private function sign_pkcs7($xml)
 {
     $dataFile = $this->rwTmpFile($xml);
     $signedFile = $this->rwTmpFile();
     if (openssl_pkcs7_sign($dataFile, $signedFile, $this->CertPem, $this->PkeyPem, array(), PKCS7_NOCHAIN + PKCS7_NOCERTS)) {
         $signedData = explode("\n\n", file_get_contents($signedFile));
         return "-----BEGIN PKCS7-----\n" . $signedData[1] . "\n-----END PKCS7-----";
     }
 }
 /**
  * Sign and Envelope the passed data string, returning a PKCS7 blob that can be posted to PayPal.
  * Make sure the passed data string is seperated by UNIX linefeeds (ASCII 10, '\n').
  *
  * @param	string	The candidate for signature and encryption
  * @param	string	The file path to the EWP(merchant) certificate
  * @param	string	The file path to the EWP(merchant) private key
  * @param	string	The EWP(merchant) private key password
  * @param	string	The file path to the PayPal Certificate
  * @return	array	Contains a bool status, error_msg, error_no, and an encrypted string: encryptedData if successfull
  *
  * @access	public
  * @static
  */
 function signAndEncrypt($dataStr_, $ewpCertPath_, $ewpPrivateKeyPath_, $ewpPrivateKeyPwd_, $paypalCertPath_)
 {
     $dataStrFile = realpath(tempnam('/tmp', 'pp_'));
     $fd = fopen($dataStrFile, 'w');
     if (!$fd) {
         $error = "Could not open temporary file {$dataStrFile}.";
         return array("status" => false, "error_msg" => $error, "error_no" => 0);
     }
     fwrite($fd, $dataStr_);
     fclose($fd);
     $signedDataFile = realpath(tempnam('/tmp', 'pp_'));
     if (!@openssl_pkcs7_sign($dataStrFile, $signedDataFile, "file://{$ewpCertPath_}", array("file://{$ewpPrivateKeyPath_}", $ewpPrivateKeyPwd_), array(), PKCS7_BINARY)) {
         unlink($dataStrFile);
         unlink($signedDataFile);
         $error = "Could not sign data: " . openssl_error_string();
         return array("status" => false, "error_msg" => $error, "error_no" => 0);
     }
     unlink($dataStrFile);
     $signedData = file_get_contents($signedDataFile);
     $signedDataArray = explode("\n\n", $signedData);
     $signedData = $signedDataArray[1];
     $signedData = base64_decode($signedData);
     unlink($signedDataFile);
     $decodedSignedDataFile = realpath(tempnam('/tmp', 'pp_'));
     $fd = fopen($decodedSignedDataFile, 'w');
     if (!$fd) {
         $error = "Could not open temporary file {$decodedSignedDataFile}.";
         return array("status" => false, "error_msg" => $error, "error_no" => 0);
     }
     fwrite($fd, $signedData);
     fclose($fd);
     $encryptedDataFile = realpath(tempnam('/tmp', 'pp_'));
     if (!@openssl_pkcs7_encrypt($decodedSignedDataFile, $encryptedDataFile, file_get_contents($paypalCertPath_), array(), PKCS7_BINARY)) {
         unlink($decodedSignedDataFile);
         unlink($encryptedDataFile);
         $error = "Could not encrypt data: " . openssl_error_string();
         return array("status" => false, "error_msg" => $error, "error_no" => 0);
     }
     unlink($decodedSignedDataFile);
     $encryptedData = file_get_contents($encryptedDataFile);
     if (!$encryptedData) {
         $error = "Encryption and signature of data failed.";
         return array("status" => false, "error_msg" => $error, "error_no" => 0);
     }
     unlink($encryptedDataFile);
     $encryptedDataArray = explode("\n\n", $encryptedData);
     $encryptedData = trim(str_replace("\n", '', $encryptedDataArray[1]));
     return array("status" => true, "encryptedData" => $encryptedData);
 }
Exemple #3
0
 public function signature($manifest_path, $signature_path)
 {
     $private_key = openssl_pkey_get_private($this->certs['pkey'], $this->cert_password);
     if (file_exists(\Fuel\Core\Config::get('pass.WWDR_cert'))) {
         try {
             openssl_pkcs7_sign($manifest_path, $signature_path, $this->cert_data, $private_key, array(), PKCS7_BINARY | PKCS7_DETACHED, \Fuel\Core\Config::get('pass.WWDR_cert'));
         } catch (Exception $e) {
             $this->error = 'Certificate error.';
             return null;
         }
     } else {
         $this->error = 'WWDR Intermediate Certificate does not exist.';
         return false;
     }
     $signature = file_get_contents($signature_path);
     $signature = $this->convert_PEM2DER($signature);
     return $signature;
 }
Exemple #4
0
function SignTRA()
{
    $STATUS = openssl_pkcs7_sign("TRA.xml", "TRA.tmp", "file://" . CERT, array("file://" . PRIVATEKEY, PASSPHRASE), array(), !PKCS7_DETACHED);
    if (!$STATUS) {
        exit("ERROR generating PKCS#7 signature\n");
    }
    $inf = fopen("TRA.tmp", "r");
    $i = 0;
    $CMS = "";
    while (!feof($inf)) {
        $buffer = fgets($inf);
        if ($i++ >= 4) {
            $CMS .= $buffer;
        }
    }
    fclose($inf);
    unlink("TRA.tmp");
    return $CMS;
}
 private function sign_TRA()
 {
     $STATUS = openssl_pkcs7_sign($this->path . "xmlgenerados/TRA.xml", $this->path . "xmlgenerados/TRA.tmp", "file://" . $this->path . self::CERT, array("file://" . $this->path . self::PRIVATEKEY, self::PASSPHRASE), array(), !PKCS7_DETACHED);
     if (!$STATUS) {
         throw new Exception("ERROR generating PKCS#7 signature");
     }
     $inf = fopen($this->path . "xmlgenerados/TRA.tmp", "r");
     $i = 0;
     $CMS = "";
     while (!feof($inf)) {
         $buffer = fgets($inf);
         if ($i++ >= 4) {
             $CMS .= $buffer;
         }
     }
     fclose($inf);
     //unlink("TRA.xml");
     unlink($this->path . "xmlgenerados/TRA.tmp");
     return $CMS;
 }
 public static function SignTRA()
 {
     $STATUS = openssl_pkcs7_sign("TRA.xml", "TRA.tmp", "file://" . sfConfig::get('CERT'), array("file://" . sfConfig::get('PRIVATEKEY'), sfConfig::get('PASSPHRASE')), array(), !PKCS7_DETACHED);
     if (!$STATUS) {
         throw new WsaaException(0, "Error al intentar firmar el TRA");
     }
     $inf = fopen("TRA.tmp", "r");
     $i = 0;
     $CMS = "";
     while (!feof($inf)) {
         $buffer = fgets($inf);
         if ($i++ >= 4) {
             $CMS .= $buffer;
         }
     }
     fclose($inf);
     unlink("TRA.xml");
     unlink("TRA.tmp");
     return $CMS;
 }
function create_signature($package_dir, $cert_path, $cert_password)
{
    // Load the push notification certificate
    $pkcs12 = file_get_contents($cert_path);
    $certs = array();
    if (!openssl_pkcs12_read($pkcs12, $certs, $cert_password)) {
        return;
    }
    $signature_path = "{$package_dir}/signature";
    // Sign the manifest.json file with the private key from the certificate
    $cert_data = openssl_x509_read($certs['cert']);
    $private_key = openssl_pkey_get_private($certs['pkey'], $cert_password);
    openssl_pkcs7_sign("{$package_dir}/manifest.json", $signature_path, $cert_data, $private_key, array(), PKCS7_BINARY | PKCS7_DETACHED);
    // Convert the signature from PEM to DER
    $signature_pem = file_get_contents($signature_path);
    $matches = array();
    if (!preg_match('~Content-Disposition:[^\\n]+\\s*?([A-Za-z0-9+=/\\r\\n]+)\\s*?-----~', $signature_pem, $matches)) {
        return;
    }
    $signature_der = base64_decode($matches[1]);
    file_put_contents($signature_path, $signature_der);
}
 public function encryptData($data)
 {
     if ($this->certificateID == '' || !isset($this->certificate) || !isset($this->paypalCertificate)) {
         return FALSE;
     }
     sfContext::getInstance()->getLogger()->warning('esPaypalButton: data ...');
     $parameters = array();
     $data['cert_id'] = $this->certificateID;
     foreach ($data as $key => $value) {
         $parameters[] = "{$key}={$value}";
         sfContext::getInstance()->getLogger()->warning("{$key}={$value}");
     }
     $clearText = join("\n", $parameters);
     sfContext::getInstance()->getLogger()->warning($clearText);
     $clearFile = tempnam('/tmp', 'clear');
     $signedFile = tempnam('/tmp', 'signed');
     $encryptedFile = tempnam('/tmp', 'encrypted');
     $out = fopen($clearFile, 'wb');
     fwrite($out, $clearText);
     fclose($out);
     if (!openssl_pkcs7_sign($clearFile, $signedFile, $this->certificate, $this->privateKey, array(), PKCS7_BINARY)) {
         return FALSE;
     }
     $signedData = explode("\n\n", file_get_contents($signedFile));
     $out = fopen($signedFile, 'wb');
     fwrite($out, base64_decode($signedData[1]));
     fclose($out);
     if (!openssl_pkcs7_encrypt($signedFile, $encryptedFile, $this->paypalCertificate, array(), PKCS7_BINARY)) {
         return FALSE;
     }
     $encryptedData = explode("\n\n", file_get_contents($encryptedFile));
     $encryptedText = $encryptedData[1];
     @unlink($clearFile);
     @unlink($signedFile);
     @unlink($encryptedFile);
     return sprintf('-----BEGIN PKCS7-----%s-----END PKCS7-----', trim(str_replace("\n", "", $encryptedText)));
 }
 /**
  * Creates a package signature using the given certificate and package directory.
  *
  * @param \JWage\APNS\Certificate $certificate
  * @param \JWage\APNS\Safari\Package $package
  *
  * @return string Path of signature
  */
 public function createPackageSignature(Certificate $certificate, Package $package)
 {
     $pkcs12 = $certificate->getCertificateString();
     $certPassword = $certificate->getPassword();
     $certs = array();
     if (!openssl_pkcs12_read($pkcs12, $certs, $certPassword)) {
         throw new RuntimeException('Failed to create signature.');
     }
     $signaturePath = sprintf('%s/signature', $package->getPackageDir());
     $manifestJsonPath = sprintf('%s/manifest.json', $package->getPackageDir());
     // Sign the manifest.json file with the private key from the certificate
     $certData = openssl_x509_read($certs['cert']);
     $privateKey = openssl_pkey_get_private($certs['pkey'], $certPassword);
     openssl_pkcs7_sign($manifestJsonPath, $signaturePath, $certData, $privateKey, array(), PKCS7_BINARY | PKCS7_DETACHED);
     // Convert the signature from PEM to DER
     $signaturePem = file_get_contents($signaturePath);
     $matches = array();
     if (!preg_match('~Content-Disposition:[^\\n]+\\s*?([A-Za-z0-9+=/\\r\\n]+)\\s*?-----~', $signaturePem, $matches)) {
         throw new ErrorException('Failed to extract content from signature pem.');
     }
     $signatureDer = base64_decode($matches[1]);
     file_put_contents($signaturePath, $signatureDer);
     return $signaturePath;
 }
Exemple #10
0
 /**
  * Assembles the message body.  Returns an empty string on failure.
  * @access public
  * @throws phpmailerException
  * @return string The assembled message body
  */
 public function CreateBody()
 {
     $body = '';
     if ($this->sign_key_file) {
         $body .= $this->GetMailMIME() . $this->LE;
     }
     $this->SetWordWrap();
     switch ($this->message_type) {
         case 'inline':
             $body .= $this->GetBoundary($this->boundary[1], '', '', '');
             $body .= $this->EncodeString($this->Body, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->AttachAll("inline", $this->boundary[1]);
             break;
         case 'attach':
             $body .= $this->GetBoundary($this->boundary[1], '', '', '');
             $body .= $this->EncodeString($this->Body, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->AttachAll("attachment", $this->boundary[1]);
             break;
         case 'inline_attach':
             $body .= $this->TextLine("--" . $this->boundary[1]);
             $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
             $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
             $body .= $this->LE;
             $body .= $this->GetBoundary($this->boundary[2], '', '', '');
             $body .= $this->EncodeString($this->Body, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->AttachAll("inline", $this->boundary[2]);
             $body .= $this->LE;
             $body .= $this->AttachAll("attachment", $this->boundary[1]);
             break;
         case 'alt':
             $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
             $body .= $this->EncodeString($this->AltBody, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
             $body .= $this->EncodeString($this->Body, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->EndBoundary($this->boundary[1]);
             break;
         case 'alt_inline':
             $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
             $body .= $this->EncodeString($this->AltBody, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->TextLine("--" . $this->boundary[1]);
             $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
             $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
             $body .= $this->LE;
             $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
             $body .= $this->EncodeString($this->Body, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->AttachAll("inline", $this->boundary[2]);
             $body .= $this->LE;
             $body .= $this->EndBoundary($this->boundary[1]);
             break;
         case 'alt_attach':
             $body .= $this->TextLine("--" . $this->boundary[1]);
             $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
             $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
             $body .= $this->LE;
             $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
             $body .= $this->EncodeString($this->AltBody, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
             $body .= $this->EncodeString($this->Body, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->EndBoundary($this->boundary[2]);
             $body .= $this->LE;
             $body .= $this->AttachAll("attachment", $this->boundary[1]);
             break;
         case 'alt_inline_attach':
             $body .= $this->TextLine("--" . $this->boundary[1]);
             $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
             $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
             $body .= $this->LE;
             $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
             $body .= $this->EncodeString($this->AltBody, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->TextLine("--" . $this->boundary[2]);
             $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
             $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3] . '"');
             $body .= $this->LE;
             $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', '');
             $body .= $this->EncodeString($this->Body, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->AttachAll("inline", $this->boundary[3]);
             $body .= $this->LE;
             $body .= $this->EndBoundary($this->boundary[2]);
             $body .= $this->LE;
             $body .= $this->AttachAll("attachment", $this->boundary[1]);
             break;
         default:
             // catch case 'plain' and case ''
             $body .= $this->EncodeString($this->Body, $this->Encoding);
             break;
     }
     if ($this->IsError()) {
         $body = '';
     } elseif ($this->sign_key_file) {
         try {
             $file = tempnam('', 'mail');
             file_put_contents($file, $body);
             //TODO check this worked
             $signed = tempnam("", "signed");
             if (@openssl_pkcs7_sign($file, $signed, "file://" . $this->sign_cert_file, array("file://" . $this->sign_key_file, $this->sign_key_pass), NULL)) {
                 @unlink($file);
                 $body = file_get_contents($signed);
                 @unlink($signed);
             } else {
                 @unlink($file);
                 @unlink($signed);
                 throw new phpmailerException($this->Lang("signing") . openssl_error_string());
             }
         } catch (phpmailerException $e) {
             $body = '';
             if ($this->exceptions) {
                 throw $e;
             }
         }
     }
     return $body;
 }
Exemple #11
0
 /**
  * Assemble the message body.
  * Returns an empty string on failure.
  * @access public
  * @throws phpmailerException
  * @return string The assembled message body
  */
 public function createBody()
 {
     $body = '';
     if ($this->sign_key_file) {
         $body .= $this->getMailMIME() . $this->LE;
     }
     $this->setWordWrap();
     switch ($this->message_type) {
         case 'inline':
             $body .= $this->getBoundary($this->boundary[1], '', '', '');
             $body .= $this->encodeString($this->Body, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->attachAll('inline', $this->boundary[1]);
             break;
         case 'attach':
             $body .= $this->getBoundary($this->boundary[1], '', '', '');
             $body .= $this->encodeString($this->Body, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->attachAll('attachment', $this->boundary[1]);
             break;
         case 'inline_attach':
             $body .= $this->textLine('--' . $this->boundary[1]);
             $body .= $this->headerLine('Content-Type', 'multipart/related;');
             $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
             $body .= $this->LE;
             $body .= $this->getBoundary($this->boundary[2], '', '', '');
             $body .= $this->encodeString($this->Body, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->attachAll('inline', $this->boundary[2]);
             $body .= $this->LE;
             $body .= $this->attachAll('attachment', $this->boundary[1]);
             break;
         case 'alt':
             $body .= $this->getBoundary($this->boundary[1], '', 'text/plain', '');
             $body .= $this->encodeString($this->AltBody, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->getBoundary($this->boundary[1], '', 'text/html', '');
             $body .= $this->encodeString($this->Body, $this->Encoding);
             $body .= $this->LE . $this->LE;
             if (!empty($this->Ical)) {
                 $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
                 $body .= $this->encodeString($this->Ical, $this->Encoding);
                 $body .= $this->LE . $this->LE;
             }
             $body .= $this->endBoundary($this->boundary[1]);
             break;
         case 'alt_inline':
             $body .= $this->getBoundary($this->boundary[1], '', 'text/plain', '');
             $body .= $this->encodeString($this->AltBody, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->textLine('--' . $this->boundary[1]);
             $body .= $this->headerLine('Content-Type', 'multipart/related;');
             $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
             $body .= $this->LE;
             $body .= $this->getBoundary($this->boundary[2], '', 'text/html', '');
             $body .= $this->encodeString($this->Body, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->attachAll('inline', $this->boundary[2]);
             $body .= $this->LE;
             $body .= $this->endBoundary($this->boundary[1]);
             break;
         case 'alt_attach':
             $body .= $this->textLine('--' . $this->boundary[1]);
             $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
             $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
             $body .= $this->LE;
             $body .= $this->getBoundary($this->boundary[2], '', 'text/plain', '');
             $body .= $this->encodeString($this->AltBody, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->getBoundary($this->boundary[2], '', 'text/html', '');
             $body .= $this->encodeString($this->Body, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->endBoundary($this->boundary[2]);
             $body .= $this->LE;
             $body .= $this->attachAll('attachment', $this->boundary[1]);
             break;
         case 'alt_inline_attach':
             $body .= $this->textLine('--' . $this->boundary[1]);
             $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
             $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
             $body .= $this->LE;
             $body .= $this->getBoundary($this->boundary[2], '', 'text/plain', '');
             $body .= $this->encodeString($this->AltBody, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->textLine('--' . $this->boundary[2]);
             $body .= $this->headerLine('Content-Type', 'multipart/related;');
             $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
             $body .= $this->LE;
             $body .= $this->getBoundary($this->boundary[3], '', 'text/html', '');
             $body .= $this->encodeString($this->Body, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->attachAll('inline', $this->boundary[3]);
             $body .= $this->LE;
             $body .= $this->endBoundary($this->boundary[2]);
             $body .= $this->LE;
             $body .= $this->attachAll('attachment', $this->boundary[1]);
             break;
         default:
             // catch case 'plain' and case ''
             $body .= $this->encodeString($this->Body, $this->Encoding);
             break;
     }
     if ($this->isError()) {
         $body = '';
     } elseif ($this->sign_key_file) {
         try {
             if (!defined('PKCS7_TEXT')) {
                 throw new phpmailerException($this->lang('signing') . ' OpenSSL extension missing.');
             }
             //TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1
             $file = tempnam(sys_get_temp_dir(), 'mail');
             file_put_contents($file, $body);
             //TODO check this worked
             $signed = tempnam(sys_get_temp_dir(), 'signed');
             if (@openssl_pkcs7_sign($file, $signed, 'file://' . realpath($this->sign_cert_file), array('file://' . realpath($this->sign_key_file), $this->sign_key_pass), null)) {
                 @unlink($file);
                 $body = file_get_contents($signed);
                 @unlink($signed);
             } else {
                 @unlink($file);
                 @unlink($signed);
                 throw new phpmailerException($this->lang('signing') . openssl_error_string());
             }
         } catch (phpmailerException $e) {
             $body = '';
             if ($this->exceptions) {
                 throw $e;
             }
         }
     }
     return $body;
 }
Exemple #12
0
/**
 * To verify the signed message on the command line:
 *
 *  openssl smime -verify -in <msg file> \
 *                -CAfile /usr/share/geni-ch/CA/cacert.pem
 */
function smime_sign_message($message, $signer_cert = null, $signer_key = null)
{
    if (!is_null($signer_cert)) {
        $msg_file = writeDataToTempFile($message, "msg-");
        $out_file = tempnam(sys_get_temp_dir(), "smime-");
        $headers = null;
        $flags = PKCS7_DETACHED;
        $extracerts = writeDataToTempFile($signer_cert, "cert-");
        if (openssl_pkcs7_sign($msg_file, $out_file, $signer_cert, $signer_key, $headers, $flags, $extracerts)) {
            /* SUCCESS */
            smime_debug("smime_sign_message succeeded.");
            $message = file_get_contents($out_file);
        } else {
            /* FAILURE */
            error_log("smime_sign_message failed.");
        }
        unlink($msg_file);
        unlink($out_file);
        unlink($extracerts);
    }
    return $message;
}
Exemple #13
0
function test_openssl_pkcs7_sign()
{
    $privkey = openssl_pkey_new();
    VERIFY($privkey != null);
    $csr = openssl_csr_new(null, $privkey);
    VERIFY($csr != null);
    $scert = openssl_csr_sign($csr, null, $privkey, 365);
    $pubkey = openssl_csr_get_public_key($csr);
    VERIFY($pubkey != null);
    $data = "some secret data";
    $infile = tempnam('/tmp', 'invmtestopenssl');
    $outfile = tempnam('/tmp', 'outvmtestopenssl');
    unlink($infile);
    unlink($outfile);
    file_put_contents($infile, $data);
    VERIFY(openssl_pkcs7_sign($infile, $outfile, $scert, $privkey, array("To" => "*****@*****.**", "From" => "*****@*****.**")));
    $tmp = tempnam('/tmp', 'x509vmtestopenssl');
    unlink($tmp);
    VS(file_get_contents($tmp), false);
    VERIFY(openssl_x509_export_to_file($scert, $tmp));
    VS(openssl_pkcs7_verify($outfile, 0, $infile, (array) $tmp), true);
    unlink($infile);
    unlink($outfile);
    unlink($tmp);
}
 /**
  * Assembles the message body.  Returns an empty string on failure.
  * @access private
  * @return string
  */
 function CreateBody()
 {
     $result = '';
     if ($this->sign_key_file) {
         $result .= $this->GetMailMIME();
     }
     $this->SetWordWrap();
     switch ($this->message_type) {
         case 'plain':
             $result .= $this->EncodeString($this->Body, $this->Encoding);
             break;
         case 'inline':
             $result .= $this->GetBoundary($this->boundary[1], '', '', '');
             $result .= $this->EncodeString($this->Body, $this->Encoding);
             $result .= $this->LE . $this->LE;
             $result .= $this->AttachAll("inline", $this->boundary[1]);
             break;
         case 'attach':
             $result .= $this->GetBoundary($this->boundary[1], '', '', '');
             $result .= $this->EncodeString($this->Body, $this->Encoding);
             $result .= $this->LE . $this->LE;
             $result .= $this->AttachAll("attachment", $this->boundary[1]);
             break;
         case 'inline_attach':
             $result .= $this->TextLine("--" . $this->boundary[1]);
             $result .= $this->HeaderLine('Content-Type', 'multipart/related;');
             $result .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
             $result .= $this->LE;
             $result .= $this->GetBoundary($this->boundary[2], '', '', '');
             $result .= $this->EncodeString($this->Body, $this->Encoding);
             $result .= $this->LE . $this->LE;
             $result .= $this->AttachAll("inline", $this->boundary[2]);
             $result .= $this->LE;
             $result .= $this->AttachAll("attachment", $this->boundary[1]);
             break;
         case 'alt':
             $result .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
             $result .= $this->EncodeString($this->AltBody, $this->Encoding);
             $result .= $this->LE . $this->LE;
             $result .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
             $result .= $this->EncodeString($this->Body, $this->Encoding);
             $result .= $this->LE . $this->LE;
             $result .= $this->EndBoundary($this->boundary[1]);
             break;
         case 'alt_inline':
             $result .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
             $result .= $this->EncodeString($this->AltBody, $this->Encoding);
             $result .= $this->LE . $this->LE;
             $result .= $this->TextLine("--" . $this->boundary[1]);
             $result .= $this->HeaderLine('Content-Type', 'multipart/related;');
             $result .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
             $result .= $this->LE;
             $result .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
             $result .= $this->EncodeString($this->Body, $this->Encoding);
             $result .= $this->LE . $this->LE;
             $result .= $this->AttachAll("inline", $this->boundary[2]);
             $result .= $this->LE;
             $result .= $this->EndBoundary($this->boundary[1]);
             break;
         case 'alt_attach':
             $result .= $this->TextLine("--" . $this->boundary[1]);
             $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
             $result .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
             $result .= $this->LE;
             $result .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
             $result .= $this->EncodeString($this->AltBody, $this->Encoding);
             $result .= $this->LE . $this->LE;
             $result .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
             $result .= $this->EncodeString($this->Body, $this->Encoding);
             $result .= $this->LE . $this->LE;
             $result .= $this->EndBoundary($this->boundary[2]);
             $result .= $this->LE;
             $result .= $this->AttachAll("attachment", $this->boundary[1]);
             break;
         case 'alt_inline_attach':
             $result .= $this->TextLine("--" . $this->boundary[1]);
             $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
             $result .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
             $result .= $this->LE;
             $result .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
             $result .= $this->EncodeString($this->AltBody, $this->Encoding);
             $result .= $this->LE . $this->LE;
             $result .= $this->TextLine("--" . $this->boundary[2]);
             $result .= $this->HeaderLine('Content-Type', 'multipart/related;');
             $result .= $this->TextLine("\tboundary=\"" . $this->boundary[3] . '"');
             $result .= $this->LE;
             $result .= $this->GetBoundary($this->boundary[3], '', 'text/html', '');
             $result .= $this->EncodeString($this->Body, $this->Encoding);
             $result .= $this->LE . $this->LE;
             $result .= $this->AttachAll("inline", $this->boundary[3]);
             $result .= $this->LE;
             $result .= $this->EndBoundary($this->boundary[2]);
             $result .= $this->LE;
             $result .= $this->AttachAll("attachment", $this->boundary[1]);
             break;
     }
     if ($this->IsError()) {
         $result = '';
     } else {
         if ($this->sign_key_file) {
             $file = tempnam("", "mail");
             $fp = fopen($file, "w");
             fwrite($fp, $result);
             fclose($fp);
             $signed = tempnam("", "signed");
             if (@openssl_pkcs7_sign($file, $signed, "file://" . $this->sign_cert_file, array("file://" . $this->sign_key_file, $this->sign_key_pass), null)) {
                 $fp = fopen($signed, "r");
                 $result = fread($fp, filesize($this->sign_key_file));
                 $result = '';
                 while (!feof($fp)) {
                     $result = $result . fread($fp, 1024);
                 }
                 fclose($fp);
             } else {
                 $this->SetError('signing', openssl_error_string());
                 $result = '';
             }
             unlink($file);
             unlink($signed);
         }
     }
     return $result;
 }
 /**
  * Assemble the message body.
  * Returns an empty string on failure.
  * @access public
  * @throws phpmailerException
  * @return string The assembled message body
  */
 public function createBody()
 {
     $body = '';
     //Create unique IDs and preset boundaries
     $this->uniqueid = md5(uniqid(time()));
     $this->boundary[1] = 'b1_' . $this->uniqueid;
     $this->boundary[2] = 'b2_' . $this->uniqueid;
     $this->boundary[3] = 'b3_' . $this->uniqueid;
     if ($this->sign_key_file) {
         $body .= $this->getMailMIME() . $this->LE;
     }
     $this->setWordWrap();
     $bodyEncoding = $this->Encoding;
     $bodyCharSet = $this->CharSet;
     //Can we do a 7-bit downgrade?
     if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) {
         $bodyEncoding = '7bit';
         $bodyCharSet = 'us-ascii';
     }
     //If lines are too long, and we're not already using an encoding that will shorten them,
     //change to quoted-printable transfer encoding
     if ('base64' != $this->Encoding and self::hasLineLongerThanMax($this->Body)) {
         $this->Encoding = 'quoted-printable';
         $bodyEncoding = 'quoted-printable';
     }
     $altBodyEncoding = $this->Encoding;
     $altBodyCharSet = $this->CharSet;
     //Can we do a 7-bit downgrade?
     if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) {
         $altBodyEncoding = '7bit';
         $altBodyCharSet = 'us-ascii';
     }
     //If lines are too long, change to quoted-printable transfer encoding
     if (self::hasLineLongerThanMax($this->AltBody)) {
         $altBodyEncoding = 'quoted-printable';
     }
     //Use this as a preamble in all multipart message types
     $mimepre = "This is a multi-part message in MIME format." . $this->LE . $this->LE;
     switch ($this->message_type) {
         case 'inline':
             $body .= $mimepre;
             $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
             $body .= $this->encodeString($this->Body, $bodyEncoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->attachAll('inline', $this->boundary[1]);
             break;
         case 'attach':
             $body .= $mimepre;
             $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
             $body .= $this->encodeString($this->Body, $bodyEncoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->attachAll('attachment', $this->boundary[1]);
             break;
         case 'inline_attach':
             $body .= $mimepre;
             $body .= $this->textLine('--' . $this->boundary[1]);
             $body .= $this->headerLine('Content-Type', 'multipart/related;');
             $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
             $body .= $this->LE;
             $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
             $body .= $this->encodeString($this->Body, $bodyEncoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->attachAll('inline', $this->boundary[2]);
             $body .= $this->LE;
             $body .= $this->attachAll('attachment', $this->boundary[1]);
             break;
         case 'alt':
             $body .= $mimepre;
             $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
             $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
             $body .= $this->encodeString($this->Body, $bodyEncoding);
             $body .= $this->LE . $this->LE;
             if (!empty($this->Ical)) {
                 $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
                 $body .= $this->encodeString($this->Ical, $this->Encoding);
                 $body .= $this->LE . $this->LE;
             }
             $body .= $this->endBoundary($this->boundary[1]);
             break;
         case 'alt_inline':
             $body .= $mimepre;
             $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
             $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->textLine('--' . $this->boundary[1]);
             $body .= $this->headerLine('Content-Type', 'multipart/related;');
             $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
             $body .= $this->LE;
             $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
             $body .= $this->encodeString($this->Body, $bodyEncoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->attachAll('inline', $this->boundary[2]);
             $body .= $this->LE;
             $body .= $this->endBoundary($this->boundary[1]);
             break;
         case 'alt_attach':
             $body .= $mimepre;
             $body .= $this->textLine('--' . $this->boundary[1]);
             $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
             $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
             $body .= $this->LE;
             $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
             $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
             $body .= $this->encodeString($this->Body, $bodyEncoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->endBoundary($this->boundary[2]);
             $body .= $this->LE;
             $body .= $this->attachAll('attachment', $this->boundary[1]);
             break;
         case 'alt_inline_attach':
             $body .= $mimepre;
             $body .= $this->textLine('--' . $this->boundary[1]);
             $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
             $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
             $body .= $this->LE;
             $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
             $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->textLine('--' . $this->boundary[2]);
             $body .= $this->headerLine('Content-Type', 'multipart/related;');
             $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
             $body .= $this->LE;
             $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
             $body .= $this->encodeString($this->Body, $bodyEncoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->attachAll('inline', $this->boundary[3]);
             $body .= $this->LE;
             $body .= $this->endBoundary($this->boundary[2]);
             $body .= $this->LE;
             $body .= $this->attachAll('attachment', $this->boundary[1]);
             break;
         default:
             // catch case 'plain' and case ''
             $body .= $this->encodeString($this->Body, $bodyEncoding);
             break;
     }
     if ($this->isError()) {
         $body = '';
     } elseif ($this->sign_key_file) {
         try {
             if (!defined('PKCS7_TEXT')) {
                 throw new phpmailerException($this->lang('extension_missing') . 'openssl');
             }
             // @TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1
             $file = tempnam(sys_get_temp_dir(), 'mail');
             if (false === file_put_contents($file, $body)) {
                 throw new phpmailerException($this->lang('signing') . ' Could not write temp file');
             }
             $signed = tempnam(sys_get_temp_dir(), 'signed');
             //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
             if (empty($this->sign_extracerts_file)) {
                 $sign = @openssl_pkcs7_sign($file, $signed, 'file://' . realpath($this->sign_cert_file), array('file://' . realpath($this->sign_key_file), $this->sign_key_pass), null);
             } else {
                 $sign = @openssl_pkcs7_sign($file, $signed, 'file://' . realpath($this->sign_cert_file), array('file://' . realpath($this->sign_key_file), $this->sign_key_pass), null, PKCS7_DETACHED, $this->sign_extracerts_file);
             }
             if ($sign) {
                 @unlink($file);
                 $body = file_get_contents($signed);
                 @unlink($signed);
                 //The message returned by openssl contains both headers and body, so need to split them up
                 $parts = explode("\n\n", $body, 2);
                 $this->MIMEHeader .= $parts[0] . $this->LE . $this->LE;
                 $body = $parts[1];
             } else {
                 @unlink($file);
                 @unlink($signed);
                 throw new phpmailerException($this->lang('signing') . openssl_error_string());
             }
         } catch (phpmailerException $exc) {
             $body = '';
             if ($this->exceptions) {
                 throw $exc;
             }
         }
     }
     return $body;
 }
Exemple #16
0
 /**
  * Send the document to a given destination: string, local file or browser.
  * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
  * The method first calls Close() if necessary to terminate the document.
  * @param $name (string) The name of the file when saved. Note that special characters are removed and blanks characters are replaced with the underscore character.
  * @param $dest (string) Destination where to send the document. It can take one of the following values:<ul><li>I: send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.</li><li>D: send to the browser and force a file download with the name given by name.</li><li>F: save to a local server file with the name given by name.</li><li>S: return the document as a string (name is ignored).</li><li>FI: equivalent to F + I option</li><li>FD: equivalent to F + D option</li><li>E: return the document as base64 mime multi-part email attachment (RFC 2045)</li></ul>
  * @public
  * @since 1.0
  * @see Close()
  */
 public function Output($name = 'doc.pdf', $dest = 'I')
 {
     //Output PDF to some destination
     //Finish document if necessary
     if ($this->state < 3) {
         $this->Close();
     }
     //Normalize parameters
     if (is_bool($dest)) {
         $dest = $dest ? 'D' : 'F';
     }
     $dest = strtoupper($dest);
     if ($dest[0] != 'F') {
         $name = preg_replace('/[\\s]+/', '_', $name);
         $name = preg_replace('/[^a-zA-Z0-9_\\.-]/', '', $name);
     }
     if ($this->sign) {
         // *** apply digital signature to the document ***
         // get the document content
         $pdfdoc = $this->getBuffer();
         // remove last newline
         $pdfdoc = substr($pdfdoc, 0, -1);
         // Remove the original buffer
         if (isset($this->diskcache) and $this->diskcache) {
             // remove buffer file from cache
             unlink($this->buffer);
         }
         unset($this->buffer);
         // remove filler space
         $byterange_string_len = strlen(TCPDF_STATIC::$byterange_string);
         // define the ByteRange
         $byte_range = array();
         $byte_range[0] = 0;
         $byte_range[1] = strpos($pdfdoc, TCPDF_STATIC::$byterange_string) + $byterange_string_len + 10;
         $byte_range[2] = $byte_range[1] + $this->signature_max_length + 2;
         $byte_range[3] = strlen($pdfdoc) - $byte_range[2];
         $pdfdoc = substr($pdfdoc, 0, $byte_range[1]) . substr($pdfdoc, $byte_range[2]);
         // replace the ByteRange
         $byterange = sprintf('/ByteRange[0 %u %u %u]', $byte_range[1], $byte_range[2], $byte_range[3]);
         $byterange .= str_repeat(' ', $byterange_string_len - strlen($byterange));
         $pdfdoc = str_replace(TCPDF_STATIC::$byterange_string, $byterange, $pdfdoc);
         // write the document to a temporary folder
         $tempdoc = TCPDF_STATIC::getObjFilename('tmppdf');
         $f = fopen($tempdoc, 'wb');
         if (!$f) {
             $this->Error('Unable to create temporary file: ' . $tempdoc);
         }
         $pdfdoc_length = strlen($pdfdoc);
         fwrite($f, $pdfdoc, $pdfdoc_length);
         fclose($f);
         // get digital signature via openssl library
         $tempsign = TCPDF_STATIC::getObjFilename('tmpsig');
         if (empty($this->signature_data['extracerts'])) {
             openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED);
         } else {
             openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED, $this->signature_data['extracerts']);
         }
         unlink($tempdoc);
         // read signature
         $signature = file_get_contents($tempsign);
         unlink($tempsign);
         // extract signature
         $signature = substr($signature, $pdfdoc_length);
         $signature = substr($signature, strpos($signature, "%%EOF\n\n------") + 13);
         $tmparr = explode("\n\n", $signature);
         $signature = $tmparr[1];
         unset($tmparr);
         // decode signature
         $signature = base64_decode(trim($signature));
         // convert signature to hex
         $signature = current(unpack('H*', $signature));
         $signature = str_pad($signature, $this->signature_max_length, '0');
         // disable disk caching
         $this->diskcache = false;
         // Add signature to the document
         $this->buffer = substr($pdfdoc, 0, $byte_range[1]) . '<' . $signature . '>' . substr($pdfdoc, $byte_range[1]);
         $this->bufferlen = strlen($this->buffer);
     }
     switch ($dest) {
         case 'I':
             // Send PDF to the standard output
             if (ob_get_contents()) {
                 $this->Error('Some data has already been output, can\'t send PDF file');
             }
             if (php_sapi_name() != 'cli') {
                 // send output to a browser
                 header('Content-Type: application/pdf');
                 if (headers_sent()) {
                     $this->Error('Some data has already been output to browser, can\'t send PDF file');
                 }
                 header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
                 //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
                 header('Pragma: public');
                 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
                 // Date in the past
                 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
                 header('Content-Disposition: inline; filename="' . basename($name) . '"');
                 TCPDF_STATIC::sendOutputData($this->getBuffer(), $this->bufferlen);
             } else {
                 echo $this->getBuffer();
             }
             break;
         case 'D':
             // download PDF as file
             if (ob_get_contents()) {
                 $this->Error('Some data has already been output, can\'t send PDF file');
             }
             header('Content-Description: File Transfer');
             if (headers_sent()) {
                 $this->Error('Some data has already been output to browser, can\'t send PDF file');
             }
             header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
             //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
             header('Pragma: public');
             header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
             // Date in the past
             header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
             // force download dialog
             if (strpos(php_sapi_name(), 'cgi') === false) {
                 header('Content-Type: application/force-download');
                 header('Content-Type: application/octet-stream', false);
                 header('Content-Type: application/download', false);
                 header('Content-Type: application/pdf', false);
             } else {
                 header('Content-Type: application/pdf');
             }
             // use the Content-Disposition header to supply a recommended filename
             header('Content-Disposition: attachment; filename="' . basename($name) . '"');
             header('Content-Transfer-Encoding: binary');
             TCPDF_STATIC::sendOutputData($this->getBuffer(), $this->bufferlen);
             break;
         case 'F':
         case 'FI':
         case 'FD':
             // save PDF to a local file
             if ($this->diskcache) {
                 copy($this->buffer, $name);
             } else {
                 $f = fopen($name, 'wb');
                 if (!$f) {
                     $this->Error('Unable to create output file: ' . $name);
                 }
                 fwrite($f, $this->getBuffer(), $this->bufferlen);
                 fclose($f);
             }
             if ($dest == 'FI') {
                 // send headers to browser
                 header('Content-Type: application/pdf');
                 header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
                 //header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
                 header('Pragma: public');
                 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
                 // Date in the past
                 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
                 header('Content-Disposition: inline; filename="' . basename($name) . '"');
                 TCPDF_STATIC::sendOutputData(file_get_contents($name), filesize($name));
             } elseif ($dest == 'FD') {
                 // send headers to browser
                 if (ob_get_contents()) {
                     $this->Error('Some data has already been output, can\'t send PDF file');
                 }
                 header('Content-Description: File Transfer');
                 if (headers_sent()) {
                     $this->Error('Some data has already been output to browser, can\'t send PDF file');
                 }
                 header('Cache-Control: private, must-revalidate, post-check=0, pre-check=0, max-age=1');
                 header('Pragma: public');
                 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
                 // Date in the past
                 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
                 // force download dialog
                 if (strpos(php_sapi_name(), 'cgi') === false) {
                     header('Content-Type: application/force-download');
                     header('Content-Type: application/octet-stream', false);
                     header('Content-Type: application/download', false);
                     header('Content-Type: application/pdf', false);
                 } else {
                     header('Content-Type: application/pdf');
                 }
                 // use the Content-Disposition header to supply a recommended filename
                 header('Content-Disposition: attachment; filename="' . basename($name) . '"');
                 header('Content-Transfer-Encoding: binary');
                 TCPDF_STATIC::sendOutputData(file_get_contents($name), filesize($name));
             }
             break;
         case 'E':
             // return PDF as base64 mime multi-part email attachment (RFC 2045)
             $retval = 'Content-Type: application/pdf;' . "\r\n";
             $retval .= ' name="' . $name . '"' . "\r\n";
             $retval .= 'Content-Transfer-Encoding: base64' . "\r\n";
             $retval .= 'Content-Disposition: attachment;' . "\r\n";
             $retval .= ' filename="' . $name . '"' . "\r\n\r\n";
             $retval .= chunk_split(base64_encode($this->getBuffer()), 76, "\r\n");
             return $retval;
         case 'S':
             // returns PDF as a string
             return $this->getBuffer();
         default:
             $this->Error('Incorrect output destination: ' . $dest);
     }
     return '';
 }
Exemple #17
0
 /**
  * Creates a pkpass file
  *
  * @param  Passbook\PassInterface $pass
  * @throws FileException          If an IO error occurred
  * @return SplFileObject
  */
 public function package(PassInterface $pass)
 {
     $pass->setPassTypeIdentifier($this->passTypeIdentifier);
     $pass->setTeamIdentifier($this->teamIdentifier);
     $pass->setOrganizationName($this->organizationName);
     // Serialize pass
     $json = self::serialize($pass);
     $outputPath = rtrim($this->getOutputPath(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
     $passDir = $outputPath . $pass->getSerialNumber() . DIRECTORY_SEPARATOR;
     $passDirExists = file_exists($passDir);
     if ($passDirExists && !$this->isOverwrite()) {
         throw new FileException("Temporary pass directory already exists");
     } elseif (!$passDirExists && !mkdir($passDir, 0777, true)) {
         throw new FileException("Couldn't create temporary pass directory");
     }
     // Pass.json
     $passJSONFile = $passDir . 'pass.json';
     file_put_contents($passJSONFile, $json);
     // Images
     /** @var \Passbook\Pass\Image $image */
     foreach ($pass->getImages() as $image) {
         $fileName = $passDir . $image->getContext();
         if ($image->isHighRetina()) {
             $fileName .= '@3x';
         } else {
             if ($image->isRetina()) {
                 $fileName .= '@2x';
             }
         }
         $fileName .= '.' . $image->getExtension();
         copy($image->getPathname(), $fileName);
     }
     // Localizations
     foreach ($pass->getLocalizations() as $localization) {
         // Create dir (LANGUAGE.lproj)
         $localizationDir = $passDir . $localization->getLanguage() . '.lproj' . DIRECTORY_SEPARATOR;
         mkdir($localizationDir, 0777, true);
         // pass.strings File (Format: "token" = "value")
         $localizationStringsFile = $localizationDir . 'pass.strings';
         file_put_contents($localizationStringsFile, $localization->getStringsFileOutput());
         // Localization images
         foreach ($localization->getImages() as $image) {
             $fileName = $localizationDir . $image->getContext();
             if ($image->isHighRetina()) {
                 $fileName .= '@3x';
             } else {
                 if ($image->isRetina()) {
                     $fileName .= '@2x';
                 }
             }
             $fileName .= '.' . $image->getExtension();
             copy($image->getPathname(), $fileName);
         }
     }
     // Manifest.json - recursove, also add files in sub directories
     $manifestJSONFile = $passDir . 'manifest.json';
     $manifest = array();
     $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($passDir), RecursiveIteratorIterator::SELF_FIRST);
     foreach ($files as $file) {
         // Ignore "." and ".." folders
         if (in_array(substr($file, strrpos($file, '/') + 1), array('.', '..'))) {
             continue;
         }
         //
         $filepath = realpath($file);
         if (is_file($filepath) === true) {
             $relativePathName = str_replace($passDir, '', $file->getPathname());
             $manifest[$relativePathName] = sha1_file($filepath);
         }
     }
     file_put_contents($manifestJSONFile, json_encode($manifest, JSON_UNESCAPED_SLASHES));
     // Signature
     $signatureFile = $passDir . 'signature';
     $p12 = file_get_contents($this->p12->getRealPath());
     $certs = array();
     if (openssl_pkcs12_read($p12, $certs, $this->p12->getPassword()) == true) {
         $certdata = openssl_x509_read($certs['cert']);
         $privkey = openssl_pkey_get_private($certs['pkey'], $this->p12->getPassword());
         openssl_pkcs7_sign($manifestJSONFile, $signatureFile, $certdata, $privkey, array(), PKCS7_BINARY | PKCS7_DETACHED, $this->wwdr->getRealPath());
         // Get signature content
         $signature = @file_get_contents($signatureFile);
         // Check signature content
         if (!$signature) {
             throw new FileException("Couldn't read signature file.");
         }
         // Delimeters
         $begin = 'filename="smime.p7s"';
         $end = '------';
         // Convert signature
         $signature = substr($signature, strpos($signature, $begin) + strlen($begin));
         $signature = substr($signature, 0, strpos($signature, $end));
         $signature = base64_decode($signature);
         // Put new signature
         if (!file_put_contents($signatureFile, $signature)) {
             throw new FileException("Couldn't write signature file.");
         }
     } else {
         throw new FileException("Error reading certificate file");
     }
     // Zip pass
     $zipFile = $outputPath . $pass->getSerialNumber() . self::PASS_EXTENSION;
     $this->zip($passDir, $zipFile);
     // Remove temporary pass directory
     $this->rrmdir($passDir);
     return new SplFileObject($zipFile);
 }
 /**
  * Creates a signature and saves it
  * Parameter: json-string, manifest file
  * Return: boolean, true on succes, failse on failure
  *
  * @param $manifest
  *
  * @return bool
  */
 protected function createSignature($manifest)
 {
     $paths = $this->paths();
     file_put_contents($paths['manifest'], $manifest);
     $pkcs12 = file_get_contents($this->certPath);
     $certs = [];
     if (openssl_pkcs12_read($pkcs12, $certs, $this->certPass) == true) {
         $certdata = openssl_x509_read($certs['cert']);
         $privkey = openssl_pkey_get_private($certs['pkey'], $this->certPass);
         if (!empty($this->WWDRcertPath)) {
             if (!file_exists($this->WWDRcertPath)) {
                 $this->sError = 'WWDR Intermediate Certificate does not exist';
                 return false;
             }
             openssl_pkcs7_sign($paths['manifest'], $paths['signature'], $certdata, $privkey, [], PKCS7_BINARY | PKCS7_DETACHED, $this->WWDRcertPath);
         } else {
             openssl_pkcs7_sign($paths['manifest'], $paths['signature'], $certdata, $privkey, [], PKCS7_BINARY | PKCS7_DETACHED);
         }
         $signature = file_get_contents($paths['signature']);
         $signature = $this->convertPEMtoDER($signature);
         file_put_contents($paths['signature'], $signature);
         return true;
     } else {
         $this->sError = 'Could not read the certificate';
         return false;
     }
 }
 function process_button()
 {
     global $customer_id, $order, $sendto, $currency, $cart_PayPal_Standard_ID, $shipping, $order_total_modules;
     $total_tax = $order->info['tax'];
     // remove shipping tax in total tax value
     if (isset($shipping['cost'])) {
         $total_tax -= $order->info['shipping_cost'] - $shipping['cost'];
     }
     $process_button_string = '';
     $parameters = array('cmd' => '_cart', 'upload' => '1', 'item_name_1' => STORE_NAME, 'shipping_1' => $this->format_raw($order->info['shipping_cost']), 'business' => MODULE_PAYMENT_PAYPAL_STANDARD_ID, 'amount_1' => $this->format_raw($order->info['total'] - $order->info['shipping_cost'] - $total_tax), 'currency_code' => $currency, 'invoice' => substr($cart_PayPal_Standard_ID, strpos($cart_PayPal_Standard_ID, '-') + 1), 'custom' => $customer_id, 'no_note' => '1', 'notify_url' => tep_href_link('ext/modules/payment/paypal/standard_ipn.php', '', 'SSL', false, false), 'rm' => '2', 'return' => tep_href_link(FILENAME_CHECKOUT_PROCESS, '', 'SSL'), 'cancel_return' => tep_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL'), 'bn' => 'OSCOM23_PS', 'paymentaction' => MODULE_PAYMENT_PAYPAL_STANDARD_TRANSACTION_METHOD == 'Sale' ? 'sale' : 'authorization');
     if (defined('MODULE_PAYMENT_PAYPAL_STANDARD_TEXT_PAYPAL_RETURN_BUTTON') && tep_not_null(MODULE_PAYMENT_PAYPAL_STANDARD_TEXT_PAYPAL_RETURN_BUTTON) && strlen(MODULE_PAYMENT_PAYPAL_STANDARD_TEXT_PAYPAL_RETURN_BUTTON) <= 60) {
         $parameters['cbt'] = MODULE_PAYMENT_PAYPAL_STANDARD_TEXT_PAYPAL_RETURN_BUTTON;
     }
     if (is_numeric($sendto) && $sendto > 0) {
         $parameters['address_override'] = '1';
         $parameters['first_name'] = $order->delivery['firstname'];
         $parameters['last_name'] = $order->delivery['lastname'];
         $parameters['address1'] = $order->delivery['street_address'];
         $parameters['city'] = $order->delivery['city'];
         $parameters['state'] = tep_get_zone_code($order->delivery['country']['id'], $order->delivery['zone_id'], $order->delivery['state']);
         $parameters['zip'] = $order->delivery['postcode'];
         $parameters['country'] = $order->delivery['country']['iso_code_2'];
     } else {
         $parameters['no_shipping'] = '1';
         $parameters['first_name'] = $order->billing['firstname'];
         $parameters['last_name'] = $order->billing['lastname'];
         $parameters['address1'] = $order->billing['street_address'];
         $parameters['city'] = $order->billing['city'];
         $parameters['state'] = tep_get_zone_code($order->billing['country']['id'], $order->billing['zone_id'], $order->billing['state']);
         $parameters['zip'] = $order->billing['postcode'];
         $parameters['country'] = $order->billing['country']['iso_code_2'];
     }
     if (tep_not_null(MODULE_PAYMENT_PAYPAL_STANDARD_PAGE_STYLE)) {
         $parameters['page_style'] = MODULE_PAYMENT_PAYPAL_STANDARD_PAGE_STYLE;
     }
     $item_params = array();
     $line_item_no = 1;
     foreach ($order->products as $product) {
         if (DISPLAY_PRICE_WITH_TAX == 'true') {
             $product_price = $this->format_raw($product['final_price'] + tep_calculate_tax($product['final_price'], $product['tax']));
         } else {
             $product_price = $this->format_raw($product['final_price']);
         }
         $item_params['item_name_' . $line_item_no] = $product['name'];
         $item_params['amount_' . $line_item_no] = $product_price;
         $item_params['quantity_' . $line_item_no] = $product['qty'];
         $line_item_no++;
     }
     $items_total = $this->format_raw($order->info['subtotal']);
     $has_negative_price = false;
     // order totals are processed on checkout confirmation but not captured into a variable
     if (is_array($order_total_modules->modules)) {
         foreach ($order_total_modules->modules as $value) {
             $class = substr($value, 0, strrpos($value, '.'));
             if ($GLOBALS[$class]->enabled) {
                 for ($i = 0, $n = sizeof($GLOBALS[$class]->output); $i < $n; $i++) {
                     if (tep_not_null($GLOBALS[$class]->output[$i]['title']) && tep_not_null($GLOBALS[$class]->output[$i]['text'])) {
                         if (!in_array($GLOBALS[$class]->code, array('ot_subtotal', 'ot_shipping', 'ot_tax', 'ot_total'))) {
                             $item_params['item_name_' . $line_item_no] = $GLOBALS[$class]->output[$i]['title'];
                             $item_params['amount_' . $line_item_no] = $this->format_raw($GLOBALS[$class]->output[$i]['value']);
                             $items_total += $item_params['amount_' . $line_item_no];
                             if ($item_params['amount_' . $line_item_no] < 0) {
                                 $has_negative_price = true;
                             }
                             $line_item_no++;
                         }
                     }
                 }
             }
         }
     }
     $paypal_item_total = $items_total + $parameters['shipping_1'];
     if (DISPLAY_PRICE_WITH_TAX == 'false') {
         $item_params['tax_cart'] = $this->format_raw($total_tax);
         $paypal_item_total += $item_params['tax_cart'];
     }
     if ($has_negative_price == false && $this->format_raw($paypal_item_total) == $this->format_raw($order->info['total'])) {
         $parameters = array_merge($parameters, $item_params);
     } else {
         $parameters['tax_cart'] = $this->format_raw($total_tax);
     }
     if (MODULE_PAYMENT_PAYPAL_STANDARD_EWP_STATUS == 'True') {
         $parameters['cert_id'] = MODULE_PAYMENT_PAYPAL_STANDARD_EWP_CERT_ID;
         $random_string = rand(100000, 999999) . '-' . $customer_id . '-';
         $data = '';
         foreach ($parameters as $key => $value) {
             $data .= $key . '=' . $value . "\n";
         }
         $fp = fopen(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt', 'w');
         fwrite($fp, $data);
         fclose($fp);
         unset($data);
         if (function_exists('openssl_pkcs7_sign') && function_exists('openssl_pkcs7_encrypt')) {
             openssl_pkcs7_sign(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt', MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt', file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PUBLIC_KEY), file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PRIVATE_KEY), array('From' => MODULE_PAYMENT_PAYPAL_STANDARD_ID), PKCS7_BINARY);
             unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt');
             // remove headers from the signature
             $signed = file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt');
             $signed = explode("\n\n", $signed);
             $signed = base64_decode($signed[1]);
             $fp = fopen(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt', 'w');
             fwrite($fp, $signed);
             fclose($fp);
             unset($signed);
             openssl_pkcs7_encrypt(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt', MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt', file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PAYPAL_KEY), array('From' => MODULE_PAYMENT_PAYPAL_STANDARD_ID), PKCS7_BINARY);
             unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt');
             // remove headers from the encrypted result
             $data = file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt');
             $data = explode("\n\n", $data);
             $data = '-----BEGIN PKCS7-----' . "\n" . $data[1] . "\n" . '-----END PKCS7-----';
             unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt');
         } else {
             exec(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_OPENSSL . ' smime -sign -in ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt -signer ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PUBLIC_KEY . ' -inkey ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PRIVATE_KEY . ' -outform der -nodetach -binary > ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt');
             unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt');
             exec(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_OPENSSL . ' smime -encrypt -des3 -binary -outform pem ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PAYPAL_KEY . ' < ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt > ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt');
             unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt');
             $fh = fopen(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt', 'rb');
             $data = fread($fh, filesize(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt'));
             fclose($fh);
             unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt');
         }
         $process_button_string = tep_draw_hidden_field('cmd', '_s-xclick') . tep_draw_hidden_field('encrypted', $data);
         unset($data);
     } else {
         foreach ($parameters as $key => $value) {
             $process_button_string .= tep_draw_hidden_field($key, $value);
         }
     }
     return $process_button_string;
 }
 /**
  * @param Swift_FileStream      $outputStream
  * @param Swift_InputByteStream $inputStream
  *
  * @throws Swift_IoException
  */
 protected function messageStreamToSignedByteStream(Swift_FileStream $outputStream, Swift_InputByteStream $inputStream)
 {
     $signedMessageStream = new Swift_ByteStream_TemporaryFileByteStream();
     if (!openssl_pkcs7_sign($outputStream->getPath(), $signedMessageStream->getPath(), $this->signCertificate, $this->signPrivateKey, array(), $this->signOptions)) {
         throw new Swift_IoException(sprintf('Failed to sign S/Mime message. Error: "%s".', openssl_error_string()));
     }
     $this->copyFromOpenSSLOutput($signedMessageStream, $inputStream);
 }
Exemple #21
0
 /**
  * Renders the PDF document
  *
  * @throws Zend_Pdf_Exception
  */
 public function render($newSegmentOnly = false, $outputStream = NULL)
 {
     //the file with root certificates
     $rootCertificateFile = null;
     $matches = array();
     //render what we have for now
     $pdfDoc = parent::render();
     if (empty($this->_certificate)) {
         return $pdfDoc;
     }
     //set the modification date
     $this->properties['ModDate'] = $this->_currentTime;
     //look for the match line by line
     $pdfLines = explode("\n", $pdfDoc);
     //find the ByteRange and Signature parts that were inserted when we attached the signature object
     foreach ($pdfLines as $line) {
         if (preg_match('/.*<<.+\\/Sig.+\\/Adobe.PPKLite.+\\/ByteRange\\s*\\[(.+)\\].+\\/Contents\\s*(<\\d+>).*/', $line, $matches, PREG_OFFSET_CAPTURE) === 1) {
             break;
         }
     }
     if (count($matches) < 3) {
         throw new Zend_Pdf_Exception('No signature field match was found');
     }
     //offset from the beginning of the document
     $lineOffset = strpos($pdfDoc, $matches[0][0]);
     //[0] - body and [1] - offset
     $byteRangePart = $matches[1];
     $signaturePart = $matches[2];
     //offset where the signature starts
     $signatureStartPosition = $lineOffset + $signaturePart[1];
     //offset where the ByteRange starts
     $byteRangeStartPosition = $lineOffset + $byteRangePart[1];
     //offset where the signature ends
     $signatureEndPosition = $signatureStartPosition + strlen($signaturePart[0]);
     //position of the signature from the end of the PDF
     $signatureFromDocEndPosition = strlen($pdfDoc) - $signatureEndPosition;
     //cut out the signature part
     $pdfDoc = substr($pdfDoc, 0, $signatureStartPosition) . substr($pdfDoc, $signatureEndPosition);
     //replace the ByteRange with the positions of the signature
     $byteRangeLength = strlen($byteRangePart[0]);
     $calculatedByteRange = sprintf('0 %u %u %u', $signatureStartPosition, $signatureEndPosition, $signatureFromDocEndPosition);
     //pad with spaces to put it in the same position
     $calculatedByteRange .= str_repeat(' ', $byteRangeLength - strlen($calculatedByteRange));
     //replace the original ByteRange with the calculated ByteRange
     $pdfDoc = substr_replace($pdfDoc, $calculatedByteRange, $byteRangeStartPosition, $byteRangeLength);
     set_exception_handler('PrintDoc::handle1Exception');
     set_error_handler('PrintDoc::handle1Exception');
     //get the certificate info
     if (!function_exists('openssl_pkcs12_read')) {
         throw new Zend_Pdf_Exception('Please install the OpenSSL support for php');
     }
     $certificateInfo = array();
     $result = openssl_pkcs12_read($this->_certificate, $certificateInfo, $this->_certificatePassword);
     if (!$result) {
         throw new Zend_Pdf_Exception('Unable to open the digital certificate. Check the certificate password: '******'tmppdf');
     $f = fopen($tempDoc, 'wb');
     if (!$f) {
         throw new Zend_Pdf_Exception('Unable to create temporary file: ' . $tempDoc);
     }
     $pdfDocLength = strlen($pdfDoc);
     fwrite($f, $pdfDoc, $pdfDocLength);
     fclose($f);
     // get digital signature via openssl library
     $tempSign = tempnam(sys_get_temp_dir(), 'tmpsig');
     if (!function_exists('openssl_pkcs7_sign')) {
         throw new Zend_Pdf_Exception('Please install the OpenSSL support for php');
     }
     //create a file with extra root certificates
     if (array_key_exists('extracerts', $certificateInfo) && count($certificateInfo['extracerts']) > 0) {
         $rootCertificateFile = tempnam(sys_get_temp_dir(), 'tmproot');
         file_put_contents($rootCertificateFile, implode("\n", $certificateInfo['extracerts']));
     }
     if ($rootCertificateFile) {
         $signResult = openssl_pkcs7_sign($tempDoc, $tempSign, $certificateInfo['cert'], array($certificateInfo['pkey'], $this->_certificatePassword), array(), PKCS7_BINARY | PKCS7_DETACHED, $rootCertificateFile);
         unlink($rootCertificateFile);
     } else {
         $signResult = openssl_pkcs7_sign($tempDoc, $tempSign, $certificateInfo['cert'], array($certificateInfo['pkey'], $this->_certificatePassword), array(), PKCS7_BINARY | PKCS7_DETACHED);
     }
     if (!$signResult) {
         unlink($tempDoc);
         throw new Zend_Pdf_Exception('Cannot sign with pkcs7');
     }
     unlink($tempDoc);
     // read signature
     $signature = file_get_contents($tempSign);
     if ($signature === false) {
         unlink($tempSign);
         throw new Zend_Pdf_Exception('Cannot read the pkcs7 signed document');
     }
     unlink($tempSign);
     // extract signature
     $signature = substr($signature, $pdfDocLength);
     $signature = substr($signature, strpos($signature, "%%EOF\n\n------") + 13);
     $tmpArr = explode("\n\n", $signature);
     $signature = $tmpArr[1];
     unset($tmpArr);
     // decode signature
     $signature = base64_decode(trim($signature));
     // convert signature to hex
     $signature = current(unpack('H*', $signature));
     $signature = str_pad($signature, self::SIGNATURE_MAX_LENGTH, '0');
     // Add signature to the document
     $pdfDoc = substr($pdfDoc, 0, $signatureStartPosition) . '<' . $signature . '>' . substr($pdfDoc, $signatureStartPosition);
     return $pdfDoc;
 }
Exemple #22
0
 /**
  *   Create encrypted buttons.
  *
  *   Requires that the plugin is configured to do so, and that the key files
  *   are set up correctly.  If an error is encountered, an empty string
  *   is returned so the caller can proceed with an un-encrypted button.
  *
  *   @since  version 0.4.0
  *   @param  array   $fields     Array of data to encrypt into buttons
  *   @return string              Encrypted_value, or empty string on error
  */
 private function _encButton($fields)
 {
     global $_CONF, $_PP_CONF;
     // Make sure button encryption is enabled and needed values are set
     if ($this->config['encrypt'] != 1 || empty($this->config['prv_key']) || empty($this->config['pub_key']) || empty($this->config['pp_cert']) || $this->cert_id == '') {
         return '';
     }
     // Now check that the files exist and can be read
     foreach (array('prv_key', 'pub_key', 'pp_cert') as $idx => $name) {
         if (!is_file($this->config[$name]) || !is_readable($this->config[$name])) {
             return '';
         }
     }
     // Create a temporary file to begin storing our data.  If this fails,
     // then return.
     $dataFile = tempnam($_PP_CONF['tmpdir'], 'data');
     if (!is_writable($dataFile)) {
         return '';
     }
     $plainText = '';
     $signedText = array();
     $encText = '';
     $pub_key = @openssl_x509_read(file_get_contents($this->config['pub_key']));
     if (!$pub_key) {
         COM_errorLog("Failed reading public key from {$this->config['pub_key']}", 1);
         return '';
     }
     $prv_key = @openssl_get_privatekey(file_get_contents($this->config['prv_key']));
     if (!$prv_key) {
         COM_errorLog("Failed reading private key from {$this->config['prv_key']}", 1);
         return '';
     }
     $pp_cert = @openssl_x509_read(file_get_contents($this->config['pp_cert']));
     if (!$pp_cert) {
         COM_errorLog("Failed reading PayPal certificate from {$this->config['pp_cert']}", 1);
         return '';
     }
     //  Make sure this key and certificate belong together
     if (!openssl_x509_check_private_key($pub_key, $prv_key)) {
         COM_errorLog("Mismatched private & public keys", 1);
         return '';
     }
     //  Start off the form data with the PayPal certificate ID
     $plainText .= "cert_id=" . $this->cert_id;
     //  Create the form data by separating each value set by a new line
     //  Make sure that required fields are available.  We assume that the
     //  item_number, item_name and amount are in.
     if (!isset($fields['business'])) {
         $fields['business'] = $this->receiver_email;
     }
     if (!isset($fields['currency_code'])) {
         $fields['currency_code'] = $this->currency_code;
     }
     foreach ($fields as $key => $value) {
         $plainText .= "\n{$key}={$value}";
     }
     //  First create a file for storing the plain text values
     $fh = fopen($dataFile . '_plain.txt', 'wb');
     if ($fh) {
         fwrite($fh, $plainText);
     } else {
         return '';
     }
     @fclose($fh);
     // Now sign the plaintext values into the signed file
     //$fh = fopen($dataFile . "_signed.txt", "w+");
     if (!openssl_pkcs7_sign($dataFile . '_plain.txt', $dataFile . '_signed.txt', $pub_key, $prv_key, array(), PKCS7_BINARY)) {
         return '';
     }
     //  Parse the signed file between the header and content
     $signedText = explode("\n\n", file_get_contents($dataFile . '_signed.txt'));
     //  Save only the content but base64 decode it first
     $fh = fopen($dataFile . '_signed.txt', 'wb');
     if ($fh) {
         fwrite($fh, base64_decode($signedText[1]));
     } else {
         return '';
     }
     @fclose($fh);
     // Now encrypt the signed file we just wrote
     if (!openssl_pkcs7_encrypt($dataFile . '_signed.txt', $dataFile . '_enc.txt', $pp_cert, array(), PKCS7_BINARY)) {
         return '';
     }
     // Parse the encrypted file between header and content
     $encryptedData = explode("\n\n", file_get_contents($dataFile . "_enc.txt"));
     $encText = $encryptedData[1];
     // Delete all of our temporary files
     @unlink($dataFile);
     @unlink($dataFile . "_plain.txt");
     @unlink($dataFile . "_signed.txt");
     @unlink($dataFile . "_enc.txt");
     //  Return the now-encrypted form content
     return "-----BEGIN PKCS7-----\n" . $encText . "\n-----END PKCS7-----";
 }
    /**
     * Creates a new encrypted button HTML block
     *
     * @param array The button parameters as key/value pairs
     * @return mixed A string of HTML or a Paypal error object on failure
     */
    function encryptButton($buttonParams)
    {
        if (!is_object($this->_profile)) {
            return PayPal::raiseError("No Profile is set, cannot encrypt");
        }
        $res = $this->_profile->validate();
        if (PayPal::isError($res)) {
            return $res;
        }
        $merchant_cert = 'file://' . $this->_profile->getCertificateFile();
        $merchant_key = 'file://' . $this->_profile->getPrivateKeyFile();
        $enc_cert = 'file://' . $this->getPayPalCertificateFile($this->_profile->getEnvironment());
        $tmpin_file = tempnam('/tmp', 'paypal_');
        $tmpout_file = tempnam('/tmp', 'paypal_');
        $tmpfinal_file = tempnam('/tmp', 'paypal_');
        $rawdata = array();
        $buttonParams['cert_id'] = $this->_profile->getCertificateId();
        foreach ($buttonParams as $name => $value) {
            $rawdata[] = "{$name}={$value}";
        }
        $rawdata = implode("\n", $rawdata);
        $fp = fopen($tmpin_file, 'w');
        if (!$fp) {
            return PayPal::raiseError("Could not open temporary file '{$tmpin_file}')");
        }
        fwrite($fp, $rawdata);
        fclose($fp);
        if (!@openssl_pkcs7_sign($tmpin_file, $tmpout_file, $merchant_cert, array($merchant_key, $this->_profile->getPrivateKeyPassword()), array(), PKCS7_BINARY)) {
            return PayPal::raiseError("Could not sign encrypted data: " . openssl_error_string());
        }
        $data = file_get_contents($tmpout_file);
        $data = explode("\n\n", $data);
        $data = $data[1];
        $data = base64_decode($data);
        $fp = fopen($tmpout_file, 'w');
        if (!$fp) {
            return PayPal::raiseError("Could not open temporary file '{$tmpin_file}')");
        }
        fwrite($fp, $data);
        fclose($fp);
        if (!@openssl_pkcs7_encrypt($tmpout_file, $tmpfinal_file, $enc_cert, array(), PKCS7_BINARY)) {
            return PayPal::raiseError("Could not encrypt data:" . openssl_error_string());
        }
        $encdata = @file_get_contents($tmpfinal_file, false);
        if (!$encdata) {
            return PayPal::raiseError("Encryption and signature of data failed.");
        }
        $encdata = explode("\n\n", $encdata);
        $encdata = trim(str_replace("\n", '', $encdata[1]));
        $encdata = "-----BEGIN PKCS7-----{$encdata}-----END PKCS7-----";
        @unlink($tmpfinal_file);
        @unlink($tmpin_file);
        @unlink($tmpout_file);
        $action = $this->_profile->getUrl();
        $buttonimgurl = $this->_profile->getButtonImage();
        $retval = <<<PPHTML
<FORM ACTION="{$action}" METHOD="post">
<INPUT TYPE="hidden" NAME="cmd" VALUE="_s-xclick">
<INPUT TYPE="hidden" NAME="encrypted" VALUE="{$encdata}">
<INPUT TYPE="image" SRC="{$buttonimgurl}" BORDER="0" NAME="submit" ALT="Make Payments with PayPal -- it's fast, free and secure!">
</FORM>
PPHTML;
        return $retval;
    }
 /**
  * Creates a new encrypted button HTML block
  *
  * @param array $buttonParams The button parameters as key/value pairs
  * @return mixed A string of HTML or a Paypal error object on failure
  */
 private function encryptButton($buttonParams)
 {
     $merchant_cert = $this->paypalConfig["vendor_cert"];
     $merchant_key = $this->paypalConfig["vendor_key"];
     $end_cert = $this->paypalConfig["enc_cert"];
     $tmpin_file = tempnam('/tmp', 'paypal_');
     $tmpout_file = tempnam('/tmp', 'paypal_');
     $tmpfinal_file = tempnam('/tmp', 'paypal_');
     $rawdata = array();
     $buttonParams['cert_id'] = $this->paypalConfig["cert_id"];
     foreach ($buttonParams as $name => $value) {
         $rawdata[] = "{$name}={$value}";
     }
     $rawdata = implode("\n", $rawdata);
     $fp = fopen($tmpin_file, 'w');
     if (!$fp) {
         echo "Could not open temporary file '{$tmpin_file}')";
         return false;
         #            return PayPal::raiseError("Could not open temporary file '$tmpin_file')");
     }
     fwrite($fp, $rawdata);
     fclose($fp);
     if (!@openssl_pkcs7_sign($tmpin_file, $tmpout_file, $merchant_cert, array($merchant_key, $this->paypalConfig["private_key_password"]), array(), PKCS7_BINARY)) {
         echo "Could not sign encrypted data: " . openssl_error_string();
         return false;
         #            return PayPal::raiseError("Could not sign encrypted data: " . openssl_error_string());
     }
     $data = file_get_contents($tmpout_file);
     $data = explode("\n\n", $data);
     $data = $data[1];
     $data = base64_decode($data);
     $fp = fopen($tmpout_file, 'w');
     if (!$fp) {
         echo "Could not open temporary file '{$tmpin_file}')";
         return false;
         #            return PayPal::raiseError("Could not open temporary file '$tmpin_file')");
     }
     fwrite($fp, $data);
     fclose($fp);
     if (!@openssl_pkcs7_encrypt($tmpout_file, $tmpfinal_file, $end_cert, array(), PKCS7_BINARY)) {
         echo "Could not encrypt data:" . openssl_error_string();
         return false;
         #            return PayPal::raiseError("Could not encrypt data:" . openssl_error_string());
     }
     $encdata = @file_get_contents($tmpfinal_file, false);
     if (!$encdata) {
         echo "Encryption and signature of data failed.";
         return false;
         #            return PayPal::raiseError("Encryption and signature of data failed.");
     }
     $encdata = explode("\n\n", $encdata);
     $encdata = trim(str_replace("\n", '', $encdata[1]));
     $encdata = "-----BEGIN PKCS7-----{$encdata}-----END PKCS7-----";
     @unlink($tmpfinal_file);
     @unlink($tmpin_file);
     @unlink($tmpout_file);
     return $encdata;
 }
 /**
  * Assembles the message body.  Returns an empty string on failure.
  * @access public
  * @return string The assembled message body
  */
 public function CreateBody()
 {
     $body = '';
     if ($this->sign_key_file) {
         $body .= $this->GetMailMIME();
     }
     $this->SetWordWrap();
     switch ($this->message_type) {
         case 'alt':
             $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
             $body .= $this->EncodeString($this->AltBody, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
             $body .= $this->EncodeString($this->Body, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->EndBoundary($this->boundary[1]);
             break;
         case 'plain':
             $body .= $this->EncodeString($this->Body, $this->Encoding);
             break;
         case 'attachments':
             $body .= $this->GetBoundary($this->boundary[1], '', '', '');
             $body .= $this->EncodeString($this->Body, $this->Encoding);
             $body .= $this->LE;
             $body .= $this->AttachAll();
             break;
         case 'alt_attachments':
             $body .= sprintf("--%s%s", $this->boundary[1], $this->LE);
             $body .= sprintf("Content-Type: %s;%s" . "\tboundary=\"%s\"%s", 'multipart/alternative', $this->LE, $this->boundary[2], $this->LE . $this->LE);
             $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '') . $this->LE;
             // Create text body
             $body .= $this->EncodeString($this->AltBody, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '') . $this->LE;
             // Create the HTML body
             $body .= $this->EncodeString($this->Body, $this->Encoding);
             $body .= $this->LE . $this->LE;
             $body .= $this->EndBoundary($this->boundary[2]);
             $body .= $this->AttachAll();
             break;
     }
     if ($this->IsError()) {
         $body = '';
     } elseif ($this->sign_key_file) {
         try {
             $file = tempnam('', 'mail');
             file_put_contents($file, $body);
             //TODO check this worked
             $signed = tempnam("", "signed");
             if (@openssl_pkcs7_sign($file, $signed, "file://" . $this->sign_cert_file, array("file://" . $this->sign_key_file, $this->sign_key_pass), NULL)) {
                 @unlink($file);
                 @unlink($signed);
                 $body = file_get_contents($signed);
             } else {
                 @unlink($file);
                 @unlink($signed);
                 throw new phpmailerException($this->Lang("signing") . openssl_error_string());
             }
         } catch (phpmailerException $e) {
             $body = '';
             if ($this->exceptions) {
                 throw $e;
             }
         }
     }
     return $body;
 }
 function process_button()
 {
     global $customer_id, $order, $sendto, $currency, $cart_PayPal_Standard_ID, $shipping;
     $process_button_string = '';
     $parameters = array('cmd' => '_xclick', 'item_name' => STORE_NAME, 'shipping' => $this->format_raw($order->info['shipping_cost']), 'tax' => $this->format_raw($order->info['tax']), 'business' => MODULE_PAYMENT_PAYPAL_STANDARD_ID, 'amount' => $this->format_raw($order->info['total'] - $order->info['shipping_cost'] - $order->info['tax']), 'currency_code' => $currency, 'invoice' => substr($cart_PayPal_Standard_ID, strpos($cart_PayPal_Standard_ID, '-') + 1), 'custom' => $customer_id, 'no_note' => '1', 'notify_url' => tep_href_link('ext/modules/payment/paypal/standard_ipn.php', '', 'SSL', false, false), 'return' => tep_href_link(FILENAME_CHECKOUT_PROCESS, '', 'SSL'), 'cancel_return' => tep_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL'), 'bn' => 'osCommerce22_Default_ST', 'paymentaction' => MODULE_PAYMENT_PAYPAL_STANDARD_TRANSACTION_METHOD == 'Sale' ? 'sale' : 'authorization');
     if (is_numeric($sendto) && $sendto > 0) {
         $parameters['address_override'] = '1';
         $parameters['first_name'] = $order->delivery['firstname'];
         $parameters['last_name'] = $order->delivery['lastname'];
         $parameters['address1'] = $order->delivery['street_address'];
         $parameters['city'] = $order->delivery['city'];
         $parameters['state'] = tep_get_zone_code($order->delivery['country']['id'], $order->delivery['zone_id'], $order->delivery['state']);
         $parameters['zip'] = $order->delivery['postcode'];
         $parameters['country'] = $order->delivery['country']['iso_code_2'];
     } else {
         $parameters['no_shipping'] = '1';
         $parameters['first_name'] = $order->billing['firstname'];
         $parameters['last_name'] = $order->billing['lastname'];
         $parameters['address1'] = $order->billing['street_address'];
         $parameters['city'] = $order->billing['city'];
         $parameters['state'] = tep_get_zone_code($order->billing['country']['id'], $order->billing['zone_id'], $order->billing['state']);
         $parameters['zip'] = $order->billing['postcode'];
         $parameters['country'] = $order->billing['country']['iso_code_2'];
     }
     if (tep_not_null(MODULE_PAYMENT_PAYPAL_STANDARD_PAGE_STYLE)) {
         $parameters['page_style'] = MODULE_PAYMENT_PAYPAL_STANDARD_PAGE_STYLE;
     }
     if (MODULE_PAYMENT_PAYPAL_STANDARD_EWP_STATUS == 'True') {
         $parameters['cert_id'] = MODULE_PAYMENT_PAYPAL_STANDARD_EWP_CERT_ID;
         $random_string = rand(100000, 999999) . '-' . $customer_id . '-';
         $data = '';
         reset($parameters);
         while (list($key, $value) = each($parameters)) {
             $data .= $key . '=' . $value . "\n";
         }
         $fp = fopen(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt', 'w');
         fwrite($fp, $data);
         fclose($fp);
         unset($data);
         if (function_exists('openssl_pkcs7_sign') && function_exists('openssl_pkcs7_encrypt')) {
             openssl_pkcs7_sign(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt', MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt', file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PUBLIC_KEY), file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PRIVATE_KEY), array('From' => MODULE_PAYMENT_PAYPAL_STANDARD_ID), PKCS7_BINARY);
             unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt');
             // remove headers from the signature
             $signed = file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt');
             $signed = explode("\n\n", $signed);
             $signed = base64_decode($signed[1]);
             $fp = fopen(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt', 'w');
             fwrite($fp, $signed);
             fclose($fp);
             unset($signed);
             openssl_pkcs7_encrypt(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt', MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt', file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PAYPAL_KEY), array('From' => MODULE_PAYMENT_PAYPAL_STANDARD_ID), PKCS7_BINARY);
             unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt');
             // remove headers from the encrypted result
             $data = file_get_contents(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt');
             $data = explode("\n\n", $data);
             $data = '-----BEGIN PKCS7-----' . "\n" . $data[1] . "\n" . '-----END PKCS7-----';
             unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt');
         } else {
             exec(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_OPENSSL . ' smime -sign -in ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt -signer ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PUBLIC_KEY . ' -inkey ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PRIVATE_KEY . ' -outform der -nodetach -binary > ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt');
             unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'data.txt');
             exec(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_OPENSSL . ' smime -encrypt -des3 -binary -outform pem ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_PAYPAL_KEY . ' < ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt > ' . MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt');
             unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'signed.txt');
             $fh = fopen(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt', 'rb');
             $data = fread($fh, filesize(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt'));
             fclose($fh);
             unlink(MODULE_PAYMENT_PAYPAL_STANDARD_EWP_WORKING_DIRECTORY . '/' . $random_string . 'encrypted.txt');
         }
         $process_button_string = tep_draw_hidden_field('cmd', '_s-xclick') . tep_draw_hidden_field('encrypted', $data);
         unset($data);
     } else {
         reset($parameters);
         while (list($key, $value) = each($parameters)) {
             $process_button_string .= tep_draw_hidden_field($key, $value);
         }
     }
     return $process_button_string;
 }
 /**
  * Assembles the message body.  Returns an empty string on failure.
  * @access private
  * @return string
  */
 function CreateBody()
 {
     $result = '';
     if ($this->sign_key_file) {
         $result .= $this->GetMailMIME();
     }
     $this->SetWordWrap();
     switch ($this->message_type) {
         case 'alt':
             $result .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
             $result .= $this->EncodeString($this->AltBody, $this->Encoding);
             $result .= $this->LE . $this->LE;
             $result .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
             $result .= $this->EncodeString($this->Body, $this->Encoding);
             $result .= $this->LE . $this->LE;
             $result .= $this->EndBoundary($this->boundary[1]);
             break;
         case 'plain':
             $result .= $this->EncodeString($this->Body, $this->Encoding);
             break;
         case 'attachments':
             $result .= $this->GetBoundary($this->boundary[1], '', '', '');
             $result .= $this->EncodeString($this->Body, $this->Encoding);
             $result .= $this->LE;
             $result .= $this->AttachAll();
             break;
         case 'alt_attachments':
             $result .= sprintf("--%s%s", $this->boundary[1], $this->LE);
             $result .= sprintf("Content-Type: %s;%s" . "\tboundary=\"%s\"%s", 'multipart/alternative', $this->LE, $this->boundary[2], $this->LE . $this->LE);
             $result .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '') . $this->LE;
             // Create text body
             $result .= $this->EncodeString($this->AltBody, $this->Encoding);
             $result .= $this->LE . $this->LE;
             $result .= $this->GetBoundary($this->boundary[2], '', 'text/html', '') . $this->LE;
             // Create the HTML body
             $result .= $this->EncodeString($this->Body, $this->Encoding);
             $result .= $this->LE . $this->LE;
             $result .= $this->EndBoundary($this->boundary[2]);
             $result .= $this->AttachAll();
             break;
     }
     if ($this->IsError()) {
         $result = '';
     } else {
         if ($this->sign_key_file) {
             $file = tempnam("", "mail");
             $fp = fopen($file, "w");
             fwrite($fp, $result);
             fclose($fp);
             $signed = tempnam("", "signed");
             if (@openssl_pkcs7_sign($file, $signed, "file://" . $this->sign_cert_file, array("file://" . $this->sign_key_file, $this->sign_key_pass), null)) {
                 $fp = fopen($signed, "r");
                 $result = fread($fp, filesize($this->sign_key_file));
                 $result = '';
                 while (!feof($fp)) {
                     $result = $result . fread($fp, 1024);
                 }
                 fclose($fp);
             } else {
                 $this->SetError($this->Lang("signing") . openssl_error_string());
                 $result = '';
             }
             unlink($file);
             unlink($signed);
         }
     }
     return $result;
 }
 /**
  * Takes the body of the message and processes it with S/MIME
  * 
  * @param  string $to       The recipients being sent to
  * @param  string $subject  The subject of the email
  * @param  string $headers  The headers for the message
  * @param  string $body     The message body
  * @return array  `0` => The message headers, `1` => The message body
  */
 private function createSMIMEBody($to, $subject, $headers, $body)
 {
     if (!$this->smime_encrypt && !$this->smime_sign) {
         return array($headers, $body);
     }
     $plaintext_file = tempnam('', '__fEmail_');
     $ciphertext_file = tempnam('', '__fEmail_');
     $headers_array = array('To' => $to, 'Subject' => $subject);
     preg_match_all('#^([\\w\\-]+):\\s+([^\\n]+\\n( [^\\n]+\\n)*)#im', $headers, $header_matches, PREG_SET_ORDER);
     foreach ($header_matches as $header_match) {
         $headers_array[$header_match[1]] = trim($header_match[2]);
     }
     $body_headers = "";
     if (isset($headers_array['Content-Type'])) {
         $body_headers .= 'Content-Type: ' . $headers_array['Content-Type'] . "\r\n";
     }
     if (isset($headers_array['Content-Transfer-Encoding'])) {
         $body_headers .= 'Content-Transfer-Encoding: ' . $headers_array['Content-Transfer-Encoding'] . "\r\n";
     }
     if ($body_headers) {
         $body = $body_headers . "\r\n" . $body;
     }
     file_put_contents($plaintext_file, $body);
     file_put_contents($ciphertext_file, '');
     // Set up the neccessary S/MIME resources
     if ($this->smime_sign) {
         $senders_smime_cert = file_get_contents($this->senders_smime_cert_file);
         $senders_private_key = openssl_pkey_get_private(file_get_contents($this->senders_smime_pk_file), $this->senders_smime_pk_password);
         if ($senders_private_key === FALSE) {
             throw new fValidationException("The sender's S/MIME private key password specified does not appear to be valid for the private key");
         }
     }
     if ($this->smime_encrypt) {
         $recipients_smime_cert = file_get_contents($this->recipients_smime_cert_file);
     }
     // If we are going to sign and encrypt, the best way is to sign, encrypt and then sign again
     if ($this->smime_encrypt && $this->smime_sign) {
         openssl_pkcs7_sign($plaintext_file, $ciphertext_file, $senders_smime_cert, $senders_private_key, array());
         openssl_pkcs7_encrypt($ciphertext_file, $plaintext_file, $recipients_smime_cert, array(), NULL, OPENSSL_CIPHER_RC2_128);
         openssl_pkcs7_sign($plaintext_file, $ciphertext_file, $senders_smime_cert, $senders_private_key, $headers_array);
     } elseif ($this->smime_sign) {
         openssl_pkcs7_sign($plaintext_file, $ciphertext_file, $senders_smime_cert, $senders_private_key, $headers_array);
     } elseif ($this->smime_encrypt) {
         openssl_pkcs7_encrypt($plaintext_file, $ciphertext_file, $recipients_smime_cert, $headers_array, NULL, OPENSSL_CIPHER_RC2_128);
     }
     // It seems that the contents of the ciphertext is not always \r\n line breaks
     $message = file_get_contents($ciphertext_file);
     $message = str_replace("\r\n", "\n", $message);
     $message = str_replace("\r", "\n", $message);
     $message = str_replace("\n", "\r\n", $message);
     list($new_headers, $new_body) = explode("\r\n\r\n", $message, 2);
     $new_headers = preg_replace('#^To:[^\\n]+\\n( [^\\n]+\\n)*#mi', '', $new_headers);
     $new_headers = preg_replace('#^Subject:[^\\n]+\\n( [^\\n]+\\n)*#mi', '', $new_headers);
     $new_headers = preg_replace("#^MIME-Version: 1.0\r?\n#mi", '', $new_headers, 1);
     $new_headers = preg_replace('#^Content-Type:\\s+' . preg_quote($headers_array['Content-Type'], '#') . "\r?\n#mi", '', $new_headers);
     $new_headers = preg_replace('#^Content-Transfer-Encoding:\\s+' . preg_quote($headers_array['Content-Transfer-Encoding'], '#') . "\r?\n#mi", '', $new_headers);
     unlink($plaintext_file);
     unlink($ciphertext_file);
     if ($this->smime_sign) {
         openssl_pkey_free($senders_private_key);
     }
     return array($new_headers, $new_body);
 }
Exemple #29
0
 /**
  * @Route("/", name="home")
  * @Method({"GET"})
  * @Template
  */
 public function indexAction()
 {
     $currentDate = new \DateTime('now');
     $afipParameters = $this->container->getParameter('afip-ws');
     $tmpDir = $this->container->getParameter('tmpDir');
     $wsaa = $afipParameters['wsaa'];
     $wsfev1 = $afipParameters['wsfev1'];
     $cert = realpath($afipParameters['cert']);
     $pri = realpath($afipParameters['pri']);
     $traFile = '/tra-' . $currentDate->format("YmdHis") . '.xml';
     $traTmpFile = '/tra-' . $currentDate->format("YmdHis") . '.tmp';
     $taFIle = '/ta-' . $currentDate->format("YmdHis") . '.xml';
     // Crear tra file con el request al servicio
     $tra = new \SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>' . '<loginTicketRequest version="1.0">' . '</loginTicketRequest>');
     $tra->addChild('header');
     $tra->header->addChild('uniqueId', date('U'));
     $tra->header->addChild('generationTime', date('c', date('U') - 60));
     $tra->header->addChild('expirationTime', date('c', date('U') + 60));
     $tra->addChild('service', 'wsfe');
     $tra->asXML($tmpDir . $traFile);
     // This functions makes the PKCS#7 signature using TRA as input file, CERT and PRIVATEKEY
     $status = openssl_pkcs7_sign($tmpDir . $traFile, $tmpDir . $traTmpFile, 'file://' . $cert, array('file://' . $pri, 'umadsysadmin'), array(), !PKCS7_DETACHED);
     if (!$status) {
         exit("ERROR generating PKCS#7 signature");
     }
     $sign = fopen($tmpDir . $traTmpFile, "r");
     $i = 0;
     $cms = "";
     while (!feof($sign)) {
         $buffer = fgets($sign);
         if ($i++ >= 4) {
             $cms .= $buffer;
         }
     }
     fclose($sign);
     //unlink($tmpDir.$traFile);
     //unlink($tmpDir.$traTmpFile);
     //var_dump($cms);
     $client = new \SoapClient($wsaa, array('soap_version' => SOAP_1_2, 'trace' => 1, 'exceptions' => 0));
     $result = $client->loginCms(array('in0' => $cms));
     file_put_contents($tmpDir . '/loginCmsRequest-' . $currentDate->format("YmdHis") . '.xml', $client->__getLastRequest());
     file_put_contents($tmpDir . '/loginCmsResponse-' . $currentDate->format("YmdHis") . '.xml', $client->__getLastResponse());
     if (is_soap_fault($result)) {
         exit("SOAP Fault: " . $result->faultcode . "\n" . $result->faultstring . "\n");
     }
     file_put_contents($tmpDir . $taFIle, $result->loginCmsReturn);
     /*$ta = new \SimpleXMLElement(file_get_contents('/var/www/efact-afip.com.ar/ws-source/xml/ta-20151014163631.xml'));
             $source = $ta->header->source;
             $destination = $ta->header->destination;
             $uniqueId = $ta->header->uniqueId;
             $generationTime = $ta->header->generationTime;
             $expirationTime = $ta->header->expirationTime;
             $token = (string) $ta->credentials->token;
             $sign = (string) $ta->credentials->sign;
     
             //unlink($xmlDir.$taFIle);
     
             $clientWsfe = new \SoapClient($wsfev1, array('soap_version' => SOAP_1_2, 'trace' => 1, 'exceptions' => 0));
     
     
             $parameters = new \StdClass();
             $parameters->Auth = new \StdClass();
             $parameters->Auth->Token = $token;
             $parameters->Auth->Sign = $sign;
             $parameters->Auth->Cuit = '27953948406';
     
             $parameters->FeCAEReq = new \StdClass();
             $parameters->FeCAEReq->FeCabReq = new \StdClass();
             $parameters->FeCAEReq->FeCabReq->CantReg = 1;
             $parameters->FeCAEReq->FeCabReq->PtoVta = 12;
             $parameters->FeCAEReq->FeCabReq->CbteTipo = 1;
             $parameters->FeCAEReq->FeDetReq = new \StdClass();
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest = new \StdClass();
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->Concepto = 1;
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->DocTipo = 80;
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->DocNro = 20111111112;
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->CbteDesde = 1;
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->CbteHasta = 1;
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->CbteFch = 20100903;
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->ImpTotal = 184.05;
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->ImpTotConc = 0;
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->ImpNeto = 150;
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->ImpOpEx = 0;
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->ImpTrib = 7.8;
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->ImpIVA = 26.25;
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->FchServDesde = '';
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->FchServHasta = '';
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->FchVtoPago = '';
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->MonId = 'PES';
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->MonCotiz = 1;
                 
             $tributo1 = new \StdClass();
             $tributo1->Id = 99;
             $tributo1->Desc = 'Impuesto Municipal Matanza';
             $tributo1->BaseImp = 150;
             $tributo1->Alic = 5.2;
             $tributo1->Importe = 7.8;
     
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->Tributos = array($tributo1);
     
             $iva1 = new \StdClass();
             $iva1->Id = 5;
             $iva1->BaseImp = 100;
             $iva1->Importe = 21;
     
             $iva2 = new \StdClass();
             $iva2->Id = 4;
             $iva2->BaseImp = 50;
             $iva2->Importe = 5.25;
     
             $parameters->FeCAEReq->FeDetReq->FECAEDetRequest->Iva = array($iva1, $iva2);
     
             //var_dump($parameters);
     
     
             $feCAESolicitar = $clientWsfe->FECAESolicitar($parameters);
     
             if (is_soap_fault($feCAESolicitar)) {
                 exit("SOAP Fault: ".$feCAESolicitar->faultcode."\n".$feCAESolicitar->faultstring."\n");
             }
     
             print_r($feCAESolicitar->FECAESolicitarResult);
     
             
             //$feAuthRequest = $clientWsfe->FEAuthRequest();
     
             $feAuthRequest = $clientWsfe->__soapCall('FEAuthRequest', array('Token' => $token, 'Sign' => $sign, 'Cuit' => '27953948406'));
     
             var_dump(get_class_methods($clientWsfe));
             var_dump($clientWsfe->__getTypes()[1]);
             var_dump($clientWsfe->__getFunctions());
     
             if (is_soap_fault($feAuthRequest)) {
                 exit("SOAP Fault: ".$feAuthRequest->faultcode."\n".$feAuthRequest->faultstring."\n");
             }*/
     return array('name' => "");
 }
Exemple #30
0
 /**
  * Send the document to a given destination: string, local file or browser. 
  * In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
  * The method first calls Close() if necessary to terminate the document.
  * @param string $name The name of the file when saved. Note that special characters are removed and blanks characters are replaced with the underscore character.
  * @param string $dest Destination where to send the document. It can take one of the following values:<ul><li>I: send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.</li><li>D: send to the browser and force a file download with the name given by name.</li><li>F: save to a local file with the name given by name.</li><li>S: return the document as a string. name is ignored.</li></ul>
  * @access public
  * @since 1.0
  * @see Close()
  */
 public function Output($name = 'doc.pdf', $dest = 'I')
 {
     //Output PDF to some destination
     //Finish document if necessary
     if ($this->state < 3) {
         $this->Close();
     }
     //Normalize parameters
     if (is_bool($dest)) {
         $dest = $dest ? 'D' : 'F';
     }
     $dest = strtoupper($dest);
     if ($dest != 'F') {
         $name = preg_replace('/[\\s]+/', '_', $name);
         $name = preg_replace('/[^a-zA-Z0-9\\._-\\x{4e00}-\\x{9fa5}]/u', '', $name);
     }
     if ($this->sign) {
         // *** apply digital signature to the document ***
         // get the document content
         $pdfdoc = $this->getBuffer();
         // remove last newline
         $pdfdoc = substr($pdfdoc, 0, -1);
         // Remove the original buffer
         if (isset($this->diskcache) and $this->diskcache) {
             // remove buffer file from cache
             unlink($this->buffer);
         }
         unset($this->buffer);
         // remove filler space
         $tmppos = strpos($pdfdoc, '/ByteRange[0 ********** ********** **********]') + 58;
         $pdfdoc = substr($pdfdoc, 0, $tmppos) . substr($pdfdoc, $tmppos + $this->signature_max_lenght);
         // define the ByteRange
         $byte_range = array();
         $byte_range[0] = 0;
         $byte_range[1] = $tmppos - 1;
         $byte_range[2] = $byte_range[1] + $this->signature_max_lenght;
         $byte_range[3] = strlen($pdfdoc) - $byte_range[1];
         // replace the ByteRange
         $byterange = sprintf('/ByteRange[0 %010u %010u %010u]', $byte_range[1], $byte_range[2], $byte_range[3]);
         $pdfdoc = str_replace('/ByteRange[0 ********** ********** **********]', $byterange, $pdfdoc);
         // write the document to a temporary folder
         $tempdoc = tempnam(K_PATH_CACHE, 'tmppdf_');
         $f = fopen($tempdoc, 'wb');
         if (!$f) {
             $this->Error('Unable to create temporary file: ' . $tempdoc);
         }
         $pdfdoc_lenght = strlen($pdfdoc);
         fwrite($f, $pdfdoc, $pdfdoc_lenght);
         fclose($f);
         // get digital signature.
         // IS THE FOLLOWING PROCEDURE CORRECT? THE SIGNED DOCUMENTS ARE NOT VALID!
         $tempsign = tempnam(K_PATH_CACHE, 'tmpsig_');
         if (empty($this->signature_data['extracerts'])) {
             openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED);
         } else {
             openssl_pkcs7_sign($tempdoc, $tempsign, $this->signature_data['signcert'], array($this->signature_data['privkey'], $this->signature_data['password']), array(), PKCS7_BINARY | PKCS7_DETACHED, $this->signature_data['extracerts']);
         }
         unlink($tempdoc);
         // read signature
         $signature = file_get_contents($tempsign, false, null, $pdfdoc_lenght);
         unlink($tempsign);
         // extract signature
         $signature = substr($signature, strpos($signature, "%%EOF\n\n------") + 13);
         $tmparr = explode("\n\n", $signature);
         $signature = $tmparr[1];
         unset($tmparr);
         // decode signature
         $signature = base64_decode(trim($signature));
         // convert signature to hex
         $signature = current(unpack('H*', $signature));
         $signature = str_pad($signature, $this->signature_max_lenght, '0');
         // Add signature to the document
         $pdfdoc = substr($pdfdoc, 0, $byte_range[1]) . $signature . substr($pdfdoc, 0 - $byte_range[3]);
         $this->diskcache = false;
         $this->buffer =& $pdfdoc;
         $this->bufferlen = strlen($pdfdoc);
     }
     switch ($dest) {
         case 'I':
             // Send PDF to the standard output
             if (ob_get_contents()) {
                 $this->Error('Some data has already been output, can\'t send PDF file');
             }
             if (php_sapi_name() != 'cli') {
                 //We send to a browser
                 header('Content-Type: application/pdf');
                 if (headers_sent()) {
                     $this->Error('Some data has already been output to browser, can\'t send PDF file');
                 }
                 header('Cache-Control: public, must-revalidate, max-age=0');
                 // HTTP/1.1
                 header('Pragma: public');
                 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
                 // Date in the past
                 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
                 header('Content-Length: ' . $this->bufferlen);
                 header('Content-Disposition: inline; filename="' . basename($name) . '";');
             }
             echo $this->getBuffer();
             break;
         case 'D':
             // Download PDF as file
             if (ob_get_contents()) {
                 $this->Error('Some data has already been output, can\'t send PDF file');
             }
             header('Content-Description: File Transfer');
             if (headers_sent()) {
                 $this->Error('Some data has already been output to browser, can\'t send PDF file');
             }
             header('Cache-Control: public, must-revalidate, max-age=0');
             // HTTP/1.1
             header('Pragma: public');
             header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
             // Date in the past
             header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
             // force download dialog
             header('Content-Type: application/force-download');
             header('Content-Type: application/octet-stream', false);
             header('Content-Type: application/download', false);
             header('Content-Type: application/pdf', false);
             // use the Content-Disposition header to supply a recommended filename
             header('Content-Disposition: attachment; filename="' . basename($name) . '";');
             header('Content-Transfer-Encoding: binary');
             header('Content-Length: ' . $this->bufferlen);
             echo $this->getBuffer();
             break;
         case 'F':
             // Save PDF to a local file
             if ($this->diskcache) {
                 copy($this->buffer, $name);
             } else {
                 $f = fopen($name, 'wb');
                 if (!$f) {
                     $this->Error('Unable to create output file: ' . $name);
                 }
                 fwrite($f, $this->getBuffer(), $this->bufferlen);
                 fclose($f);
             }
             break;
         case 'S':
             // Returns PDF as a string
             return $this->getBuffer();
         default:
             $this->Error('Incorrect output destination: ' . $dest);
     }
     return '';
 }