<?php

Yii::import('application.vendors.*');
require_once('tcpdf/tcpdf.php');

/**
 * @author p6
 *
*/
class PDFTools
{

  /** 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. */
  const CREATION_MODE_INLINE = "I";

  /** D: send to the browser and force a file download with the name given by name. */
  const CREATION_MODE_DOWNLOAD = "D";

  /** F: save to a local server file with the name given by name. */
  const CREATION_MODE_SAVE = "F";

  /** S: return the document as a string (name is ignored). */
  const CREATION_MODE_STRING = "S";

  /** FI: equivalent to F + I option */
  const CREATION_MODE_INLINE_SAVE = "FI";

  /** FD: equivalent to F + D option */
  const CREATION_MODE_DOWNLOAD_SAVE = "FD";

  /** E: return the document as base64 mime multi-part email attachment (RFC 2045) */
  const CREATION_MODE_BASE64 = "E";

  /** 0 = RC4 40 bit */
  const ENCRYPTION_STRENGTH_RC40 = 0;
  /** 1 = RC4 128 bit */
  const ENCRYPTION_STRENGTH_RC128 = 1;
  /** 2 = AES 128 bit */
  const ENCRYPTION_STRENGTH_AES128 = 2;
  /** 3 = AES 256 bit */
  const ENCRYPTION_STRENGTH_AES256 = 3;

  /** 1 = No changes to the document shall be permitted; any change to the document shall invalidate the signature */
  const CERT_ACCESS_PERM_STRICT = 1;

  /** 2 = Permitted changes shall be filling in forms, instantiating page templates, and signing; other changes shall invalidate the signature */
  const CERT_ACCESS_PERM_MEDIUM = 2;

  /** 3 = Permitted changes shall be the same as for 2, as well as annotation creation, deletion, and modification; other changes shall invalidate the signature */
  const CERT_ACCESS_PERM_TOLERANT = 3;

  /** html code used by createPdfFromHtml */
  public $html = '';
  /** filename of the output pdf file */
  public $outputFilename = 'document.pdf';

  public $author = '';
  public $creator = '';
  public $subject = '';
  public $title = '';
  public $keywords = array();

  public $viewerPassword = '';
  public $adminPassword = '';
  public $encryptionStrength = PDFTools::ENCRYPTION_STRENGTH_RC40; // acrobat 3 in poi

  public $certificateFile = '';
  public $certificatePassword = '';
  public $certificateAccessPermissions = PDFTools::CERT_ACCESS_PERM_STRICT;
  public $certificatePermissions = array('print', 'modify', 'copy', 'annot-forms', 'fill-forms', 'extract', 'assemble', 'print-high');

  public $certificateExtraInfo_Name = '';
  public $certificateExtraInfo_Location = '';
  public $certificateExtraInfo_Reason = '';
  public $certificateExtraInfo_ContactInfo = '';

  public $attachments = array();

  /**
   * genera il pdf creator di base
   * @return TCPDF
   */
  public function getPdf()
  {
    $certificateFound = false;
    if(not_empty_string($this->author) && file_exists($this->certificateFile))
      $certificateFound = true;

    $pdf = new TCPDF('P', 'cm', 'A4', true, 'UTF-8');

    if(not_empty_string($this->viewerPassword) && not_empty_string($this->adminPassword))
      $pdf->SetProtection($this->certificatePermissions, $this->viewerPassword, $this->adminPassword, $this->encryptionStrength);

    if(not_empty_string($this->author))
      $pdf->SetAuthor($this->author);

    if(not_empty_string($this->creator))
      $pdf->SetCreator($this->creator);

    if(not_empty_string($this->subject))
      $pdf->SetSubject($this->subject);

    if(not_empty_string($this->title))
      $pdf->SetTitle($this->title);
     
    if(count($this->keywords) > 0)
      $pdf->SetKeywords(implode(', ',$this->keywords));
     
    foreach ($this->attachments as $file)
    if(file_exists($file))
      $pdf->Annotation(0, 0, 0, 0, $file, array('Subtype'=>'FileAttachment', 'Name' => 'PushPin', 'FS' => $file));

    if($certificateFound)
    {
      // set additional information
      $info = array(
          'Name' => $this->certificateExtraInfo_Name,
          'Location' => $this->certificateExtraInfo_Location,
          'Reason' => $this->certificateExtraInfo_Reason,
          'ContactInfo' => $this->certificateExtraInfo_ContactInfo,
      );
      
      // set document signature
      /*
       NOTES:
      - To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
      - To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
      - To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes
      */
      $pdf->setSignature($this->certificateFile, $this->certificateFile, $this->certificatePassword, '', $this->certificateAccessPermissions, $info);
    }
     
    return $pdf;
  }

  /**
   * chiama getPdf() e poi genera il pdf
   * @param string $creationMode
   * @param string $callExit
   */
  public function createPdfFromHtml($creationMode = PDFTools::CREATION_MODE_DOWNLOAD, $callExit = true)
  {
    $pdf = $this->getPdf();
     
    $pdf->AddPage();
    $pdf->writeHTML($this->html, true, false, true, false, '');

    $pdf->Output($this->outputFilename, $creationMode);
    
    if($callExit)
      exit; // test fix 
  }
}
