/**
  * 
  * @param int $id_emergencia
  */
 public function generar($id_emergencia, $mapa = true, $codigo)
 {
     $emergencia = $this->_ci->emergencia_model->getById($id_emergencia);
     if (!is_null($emergencia)) {
         $data = array("eme_ia_id" => $emergencia->eme_ia_id, "eme_c_nombre_emergencia" => $emergencia->eme_c_nombre_emergencia, "eme_c_nombre_informante" => $emergencia->eme_c_nombre_informante, "eme_d_fecha_emergencia" => ISODateTospanish($emergencia->eme_d_fecha_emergencia, false), "hora_emergencia" => ISOTimeTospanish($emergencia->eme_d_fecha_emergencia), "hora_recepcion" => ISOTimeTospanish($emergencia->eme_d_fecha_recepcion), "eme_c_lugar_emergencia" => $emergencia->eme_c_lugar_emergencia, "emisor" => $this->_ci->session->userdata('session_nombres'), "id_usuario_encargado" => $emergencia->usu_ia_id, "eme_c_descripcion" => $emergencia->eme_c_descripcion, "est_ia_id" => $emergencia->est_ia_id, "tip_ia_id" => $emergencia->tip_ia_id);
         $datos = unserialize($emergencia->eme_c_datos_tipo_emergencia);
         foreach ($datos as $key => $value) {
             $data['form_tipo_' . $key] = $value;
         }
     }
     $data['codigo'] = $codigo;
     $data['region'] = '';
     $regiones = explode(',', $this->_ci->session->userdata('session_regiones'));
     if (count($regiones) == 1) {
         if ($regiones[0] == 13) {
             $data['region'] = 'RM';
         } else {
             $data['region'] = $regiones[0] . 'º';
         }
     }
     $data['cargo'] = $this->_ci->session->userdata('session_cargo');
     $data['mapa'] = $mapa;
     $html = $this->_ci->load->view('pages/emergencia_reporte/pdf', $data, true);
     $this->_pdf->imagen_mapa = $this->_imagen;
     $this->_pdf->imagen_logo = file_get_contents(FCPATH . "/assets/img/top_logo.png");
     $this->_pdf->SetFooter($_SERVER['HTTP_HOST'] . '|{PAGENO}/{nb}|' . date('d-m-Y H:i'));
     $this->_pdf->WriteHTML($html);
     return $this->_pdf->Output('acta.pdf', 'S');
 }
Exemplo n.º 2
0
 /**
  * Return XObjects Dictionary.
  *
  * Overwritten to add additional XObjects to the resources dictionary of TCPDF
  *
  * @return string
  */
 protected function _getxobjectdict()
 {
     $out = parent::_getxobjectdict();
     foreach ($this->_tpls as $tplIdx => $tpl) {
         $out .= sprintf('%s%d %d 0 R', $this->tplPrefix, $tplIdx, $tpl['n']);
     }
     return $out;
 }
Exemplo n.º 3
0
 /**
  * Get PDF file metadata (height and width)
  * (ref: movie::get_file_metadata())
  */
 static function movie_get_file_metadata($file_path, $metadata)
 {
     if (strtolower(pathinfo($file_path, PATHINFO_EXTENSION)) == "pdf" && ($path = pdf::find_gs())) {
         // Parsing gs output properly can be a pain.  So, let's go for a reliable albeit inefficient
         // approach: re-extract the frame (into tmp) and get its image size.
         $temp_file = system::temp_filename("pdf_", "jpg");
         pdf_event::movie_extract_frame($file_path, $temp_file, null, null);
         list($metadata->height, $metadata->width) = photo::get_file_metadata($temp_file);
     }
 }
Exemplo n.º 4
0
 function _getxobjectdict()
 {
     $out = parent::_getxobjectdict();
     if (count($this->tpls)) {
         foreach ($this->tpls as $tplidx => $tpl) {
             $out .= sprintf('%s%d %d 0 R', $this->tplprefix, $tplidx, $tpl['n']);
         }
     }
     return $out;
 }
Exemplo n.º 5
0
 /**
  * Return version number of gs if found, an empty string if not.
  * (ref: movie::get_ffmpeg_version())
  */
 static function get_gs_version()
 {
     if (pdf::find_gs()) {
         $path = module::get_var("pdf", "gs_path");
         exec(escapeshellcmd($path) . " -version", $output);
         if (stristr($output[0], "ghostscript")) {
             // Found "ghostscript" in the response - it's valid.
             return $output[0];
         }
     }
     return "";
 }
Exemplo n.º 6
0
 private function _print_screen($form)
 {
     // get module parameters
     $gs_path = pdf::find_gs();
     $gs_dir = substr($gs_path, 0, strrpos($gs_path, "/"));
     $gs_version = pdf::get_gs_version();
     // make and print view
     $view = new Admin_View("admin.html");
     $view->page_title = t("PDF settings");
     $view->content = new View("admin_pdf.html");
     $view->content->form = $form;
     $view->content->gs_dir = $gs_dir;
     $view->content->gs_version = $gs_version;
     print $view;
 }
Exemplo n.º 7
0
/**
 * Outputs a certificate for some sort of completion element
 *
 * @param  string  $person_fullname  The full name of the certificate recipient
 * @param  string  $entity_name      The name of the entity that is compelted
 * @param  string  $certificatecode  The unique certificate code
 * @param  string  $date_string      Date /time the certification was achieved
 * @param  string  $curriculum_frequency the curriculum frequency
 * @param  string  $expirydate       A string representing the time that the
 * certificate expires (optional).
 */
function certificate_output_completion($person_fullname, $entity_name, $certificatecode = '', $date_string, $expirydate = '', $curriculum_frequency = '', $border = '', $seal = '', $template = '')
{
    global $CFG, $COURSE;
    //use the TCPDF library
    require_once $CFG->libdir . '/pdflib.php';
    //global settings
    $borders = 0;
    $font = 'FreeSerif';
    $large_font_size = 30;
    $small_font_size = 16;
    //create pdf
    $pdf = new pdf('L', 'in', 'Letter');
    //prevent the pdf from printing black bars
    $pdf->print_header = false;
    $pdf->print_footer = false;
    //add main (only) page
    $pdf->AddPage();
    //draw the border
    cm_certificate_check_data_path('borders');
    if (file_exists($CFG->dirroot . '/curriculum/pix/certificate/borders/' . $border)) {
        $pdf->Image($CFG->dirroot . '/curriculum/pix/certificate/borders/' . $border, 0.25, 0.25, 10.5, 8.0);
    } else {
        if (file_exists($CFG->dataroot . '/' . $COURSE->id . '/curriculum/pix/certificate/borders/' . $border)) {
            $pdf->Image($CFG->dataroot . '/' . $COURSE->id . '/curriculum/pix/certificate/borders/' . $border, 0.25, 0.25, 10.5, 8.0);
        }
    }
    //draw the seal
    cm_certificate_check_data_path('seals');
    if (file_exists($CFG->dirroot . '/curriculum/pix/certificate/seals/' . $seal)) {
        $pdf->Image($CFG->dirroot . '/curriculum/pix/certificate/seals/' . $seal, 8.0, 5.8);
    } else {
        if (file_exists($CFG->dataroot . '/' . $COURSE->id . '/curriculum/pix/certificate/seals/' . $seal)) {
            $pdf->Image($CFG->dataroot . '/' . $COURSE->id . '/curriculum/pix/certificate/seals/' . $seal, 8.0, 5.8);
        }
    }
    //include template
    cm_certificate_check_data_path('templates');
    if (file_exists($CFG->dirroot . '/curriculum/pix/certificate/templates/' . $template)) {
        include $CFG->dirroot . '/curriculum/pix/certificate/templates/' . $template;
    } else {
        if (file_exists($CFG->dataroot . '/' . $COURSE->id . '/curriculum/pix/certificate/templates/' . $template)) {
            include $CFG->dirroot . '/curriculum/pix/certificate/templates/' . $template;
        }
    }
    $pdf->Output();
}
 /**
  * printanswers::view()
  * View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'.
  * @param mixed $surveyid
  * @param bool $printableexport
  * @return
  */
 function actionView($surveyid, $printableexport = FALSE)
 {
     Yii::app()->loadHelper("frontend");
     Yii::import('application.libraries.admin.pdf');
     $iSurveyID = (int) $surveyid;
     $sExportType = $printableexport;
     Yii::app()->loadHelper('database');
     if (isset($_SESSION['survey_' . $iSurveyID]['sid'])) {
         $iSurveyID = $_SESSION['survey_' . $iSurveyID]['sid'];
     } else {
         //die('Invalid survey/session');
     }
     // Get the survey inforamtion
     // Set the language for dispay
     if (isset($_SESSION['survey_' . $iSurveyID]['s_lang'])) {
         $sLanguage = $_SESSION['survey_' . $iSurveyID]['s_lang'];
     } elseif (Survey::model()->findByPk($iSurveyID)) {
         $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $iSurveyID = 0;
         $sLanguage = Yii::app()->getConfig("defaultlang");
     }
     $clang = SetSurveyLanguage($iSurveyID, $sLanguage);
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sLanguage);
     //SET THE TEMPLATE DIRECTORY
     if (!isset($aSurveyInfo['templatedir']) || !$aSurveyInfo['templatedir']) {
         $aSurveyInfo['templatedir'] = Yii::app()->getConfig('defaulttemplate');
     }
     $sTemplate = validateTemplateDir($aSurveyInfo['templatedir']);
     //Survey is not finished or don't exist
     if (!isset($_SESSION['survey_' . $iSurveyID]['finished']) || !isset($_SESSION['survey_' . $iSurveyID]['srid'])) {
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/startpage.pstpl'), array());
         echo "<center><br />\n" . "\t<font color='RED'><strong>" . $clang->gT("Error") . "</strong></font><br />\n" . "\t" . $clang->gT("We are sorry but your session has expired.") . "<br />" . $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.") . "<br />\n" . "\t" . sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")) . "\n" . "</center><br />\n";
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/endpage.pstpl'), array());
         doFooter();
         exit;
     }
     //Fin session time out
     $sSRID = $_SESSION['survey_' . $iSurveyID]['srid'];
     //I want to see the answers with this id
     //Ensure script is not run directly, avoid path disclosure
     //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}
     if ($aSurveyInfo['printanswers'] == 'N') {
         die;
         //Die quietly if print answers is not permitted
     }
     //CHECK IF SURVEY IS ACTIVATED AND EXISTS
     $sSurveyName = $aSurveyInfo['surveyls_title'];
     $sAnonymized = $aSurveyInfo['anonymized'];
     //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
     //SHOW HEADER
     $sOutput = CHtml::form(array("printanswers/view/surveyid/{$iSurveyID}/printableexport/pdf"), 'post') . "<center><input type='submit' value='" . $clang->gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>";
     if ($sExportType == 'pdf') {
         //require (Yii::app()->getConfig('rootdir').'/application/config/tcpdf.php');
         Yii::import('application.libraries.admin.pdf', true);
         Yii::import('application.helpers.pdfHelper');
         $aPdfLanguageSettings = pdfHelper::getPdfLanguageSettings($clang->langcode);
         $oPDF = new pdf();
         $oPDF->SetTitle($clang->gT("Survey name (ID)", 'unescaped') . ": {$sSurveyName} ({$iSurveyID})");
         $oPDF->SetSubject($sSurveyName);
         $oPDF->SetDisplayMode('fullpage', 'two');
         $oPDF->setLanguageArray($aPdfLanguageSettings['lg']);
         $oPDF->setHeaderFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_MAIN));
         $oPDF->setFooterFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_DATA));
         $oPDF->SetFont($aPdfLanguageSettings['pdffont'], '', $aPdfLanguageSettings['pdffontsize']);
         $oPDF->AddPage();
         $oPDF->titleintopdf($clang->gT("Survey name (ID)", 'unescaped') . ": {$sSurveyName} ({$iSurveyID})");
     }
     $sOutput .= "\t<div class='printouttitle'><strong>" . $clang->gT("Survey name (ID):") . "</strong> {$sSurveyName} ({$iSurveyID})</div><p>&nbsp;\n";
     LimeExpressionManager::StartProcessingPage(true);
     // means that all variables are on the same page
     // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
     LimeExpressionManager::StartProcessingGroup(1, $aSurveyInfo['anonymized'] != "N", $iSurveyID);
     $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions');
     $aFullResponseTable = getFullResponseTable($iSurveyID, $sSRID, $sLanguage, $printanswershonorsconditions);
     //Get the fieldmap @TODO: do we need to filter out some fields?
     if ($aSurveyInfo['datestamp'] != "Y" || $sAnonymized == 'Y') {
         unset($aFullResponseTable['submitdate']);
     } else {
         unset($aFullResponseTable['id']);
     }
     unset($aFullResponseTable['token']);
     unset($aFullResponseTable['lastpage']);
     unset($aFullResponseTable['startlanguage']);
     unset($aFullResponseTable['datestamp']);
     unset($aFullResponseTable['startdate']);
     $sOutput .= "<table class='printouttable' >\n";
     foreach ($aFullResponseTable as $sFieldname => $fname) {
         if (substr($sFieldname, 0, 4) == 'gid_') {
             $sOutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n";
         } elseif (substr($sFieldname, 0, 4) == 'qid_') {
             $sOutput .= "\t<tr class='printanswersquestionhead'><td colspan='2'>{$fname[0]}</td></tr>\n";
         } elseif ($sFieldname == 'submitdate') {
             if ($sAnonymized != 'Y') {
                 $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
             }
         } else {
             $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>" . flattenText($fname[2]) . "</td></tr>";
         }
     }
     $sOutput .= "</table>\n";
     $sData['thissurvey'] = $aSurveyInfo;
     $sOutput = templatereplace($sOutput, array(), $sData, '', $aSurveyInfo['anonymized'] == "Y", NULL, array(), true);
     // Do a static replacement
     if ($sExportType == 'pdf') {
         $oPDF->writeHTML($sOutput);
         header("Pragma: public");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         $sExportFileName = sanitize_filename($sSurveyName);
         $oPDF->Output($sExportFileName . "-" . $iSurveyID . ".pdf", "D");
     } else {
         ob_start(function ($buffer, $phase) {
             App()->getClientScript()->render($buffer);
             App()->getClientScript()->reset();
             return $buffer;
         });
         ob_implicit_flush(false);
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/startpage.pstpl'), array(), $sData);
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/printanswers.pstpl'), array('ANSWERTABLE' => $sOutput), $sData);
         echo templatereplace(file_get_contents(getTemplatePath($sTemplate) . '/endpage.pstpl'), array(), $sData);
         echo "</body></html>";
         ob_flush();
     }
     LimeExpressionManager::FinishProcessingGroup();
     LimeExpressionManager::FinishProcessingPage();
 }
Exemplo n.º 9
0
					}
					else
						$i=$sep+1;
					$sep=-1;
					$j=$i;
					$l=0;
					$nl++;
				}
				else
					$i++;
			}
			return $nl;
		}
	}
	
	$pdf = new pdf('L','mm','A4');
	$pdf->AliasNbPages();
	$titulos = array('FECHA','F. RECEPCION','SUCURSAL','GUIA','ORIGEN','DESTINO','INCIDENTE','RECIBIO','UNIDAD','RUTA');
	$medidas = array(15,20,15,22,12,12,30,80,20,55);
	$pdf->AddPage();
	
	$pdf->SetFont('Arial','B',7);
	//Table with 20 rows and 4 columns
	
	$pdf->SetWidths($medidas);
	
	$pdf->Titulos($titulos,$medidas);
	
	$pdf->SetFont('Arial','',7);
	for($i=0;$i<count($data);$i++){
		$pdf->Row($data[$i]);
Exemplo n.º 10
0
<?php

/**
* @version		1.5.0
* @package		Fi pdf
* @copyright	Copyright (C) 2012 Fiyo Developers.
* @license		GNU/GPL, see LICENSE.txt
**/
defined('_FINDEX_') or die('Access Denied');
$pdf = new pdf();
$pdf->category(app_param('label'), Page_ID, 1);
if (isset($pdf->category)) {
    $category = $pdf->category;
    $catlink = $pdf->catlink;
    $text = $pdf->desc;
    $pagelink = $pdf->pglink;
    $link = $pdf->link;
    $perrows = $pdf->perrows;
    $author = $pdf->author;
    $title = $pdf->title;
    $title = $pdf->title;
    $labels = $pdf->labels;
    $hits = $pdf->hits;
    $date = $pdf->date;
    $label = ucfirst(app_param('label'));
    if ($title) {
        if (!empty($label)) {
            echo "<h1 class='title'>{$label}</h1>";
        } else {
            if (defined('Apps_Title')) {
                echo "<h1 class='title'>" . Apps_Title . "</h1>";
Exemplo n.º 11
0
<?php

/**
* @version		1.5.0
* @package		Fi pdf
* @copyright	Copyright (C) 2012 Fiyo Developers.
* @license		GNU/GPL, see LICENSE.txt
**/
defined('_FINDEX_') or die('Access Denied');
$pdf = new pdf();
$pdf->category(app_param('id'), Page_ID);
if (isset($pdf->category)) {
    $category = $pdf->category;
    $catlink = $pdf->catlink;
    $text = $pdf->desc;
    $pagelink = $pdf->pglink;
    $link = $pdf->link;
    $perrows = $pdf->perrows;
    $author = $pdf->author;
    $title = $pdf->title;
    $title = $pdf->title;
    $labels = $pdf->labels;
    $hits = $pdf->hits;
    $date = $pdf->date;
    $label = ucfirst(app_param('label'));
    if ($title) {
        if (!empty($label)) {
            echo "<h1 class='title'>{$label}</h1>";
        } else {
            if (defined('PageTitle')) {
                echo "<h1 class='title'>" . PageTitle . "</h1>";
Exemplo n.º 12
0
 function __construct(CController $controller)
 {
     parent::__construct();
     $this->style = $controller->render('/admin/export/quexmlpdf_view', '', true);
 }
Exemplo n.º 13
0
<?php

use App\Http\Controllers\Pdf;
$pdf = new pdf();
$pdf->load();
$dompdf = new DOMPDF();
$html = '<html><body>' . '<h2>Mario Muñoz </h2>' . '<p> Primer tutorial de composer con laravel 5</p>' . '</body></html>';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream("report.pdf");
Exemplo n.º 14
0
 public function send($filename)
 {
     $doc = new pdf($this->orientation);
     if ($this->title) {
         $doc->setHeaderData('', 0, $this->title);
         $doc->setPrintHeader(true);
     } else {
         $doc->setPrintHeader(false);
     }
     $doc->setPrintFooter(false);
     foreach ($this->pages as $page) {
         $doc->AddPage();
         if ($page->title) {
             $doc->writeHtml('<h2>' . $page->title . '</h2>');
         }
         // Find extent of the table.
         $rows = $this->get_row_count($page);
         $cols = $this->get_col_count($page);
         $relwidths = $this->compute_relative_widths($page);
         $o = html_writer::start_tag('table', array('border' => 1, 'cellpadding' => 1));
         for ($row = 0; $row < $rows; $row++) {
             $o .= html_writer::start_tag('tr');
             $col = 0;
             while ($col < $cols) {
                 $span = 1;
                 if (isset($page->mergers[$row][$col])) {
                     $mergewidth = (int) $page->mergers[$row][$col];
                     if ($mergewidth >= 1) {
                         $span = $mergewidth;
                     }
                 }
                 $opts = array();
                 if ($row == 0 && $relwidths[$col] > 0) {
                     $opts['width'] = $relwidths[$col] . '%';
                 }
                 if ($span > 1) {
                     $opts['colspan'] = $span;
                 }
                 $o .= html_writer::start_tag('td', $opts);
                 $cell = '';
                 if (isset($page->cells[$row][$col])) {
                     $cell = s($page->cells[$row][$col]);
                     if (isset($page->formats[$row][$col])) {
                         $thisformat = $page->formats[$row][$col];
                         if ($thisformat == 'header') {
                             $cell = html_writer::tag('b', $cell);
                         } else {
                             if ($thisformat == 'boldit') {
                                 $cell = html_writer::tag('i', $cell);
                             }
                         }
                     }
                 }
                 $o .= $cell;
                 $o .= html_writer::end_tag('td');
                 $col += $span;
             }
             $o .= html_writer::end_tag('tr');
         }
         $o .= html_Writer::end_tag('table');
         $doc->writeHtml($o);
     }
     $doc->Output($filename . '.pdf');
 }
Exemplo n.º 15
0
 public function __construct($settings)
 {
     parent::__construct($settings->orientation, $settings->unit, $settings->format);
     $this->_dfsettings = $settings;
 }
Exemplo n.º 16
0
 /**
  * Test that the configured path to ghostscript is correct and working.
  * @param bool $generateimage - If true - a test image will be generated to verify the install.
  * @return bool
  */
 public static function test_gs_path($generateimage = true)
 {
     global $CFG;
     $ret = (object) array('status' => self::GSPATH_OK, 'message' => null);
     $gspath = \get_config('assignfeedback_editpdf', 'gspath');
     if (empty($gspath)) {
         $ret->status = self::GSPATH_EMPTY;
         return $ret;
     }
     if (!file_exists($gspath)) {
         $ret->status = self::GSPATH_DOESNOTEXIST;
         return $ret;
     }
     if (is_dir($gspath)) {
         $ret->status = self::GSPATH_ISDIR;
         return $ret;
     }
     if (!is_executable($gspath)) {
         $ret->status = self::GSPATH_NOTEXECUTABLE;
         return $ret;
     }
     $testfile = $CFG->dirroot . '/mod/assign/feedback/editpdf/tests/fixtures/testgs.pdf';
     if (!file_exists($testfile)) {
         $ret->status = self::GSPATH_NOTESTFILE;
         return $ret;
     }
     if (!$generateimage) {
         return $ret;
     }
     $testimagefolder = \make_temp_directory('assignfeedback_editpdf_test');
     @unlink($testimagefolder . '/image_page0.png');
     // Delete any previous test images.
     $pdf = new pdf();
     $pdf->set_pdf($testfile);
     $pdf->set_image_folder($testimagefolder);
     try {
         $pdf->get_image(0);
     } catch (\moodle_exception $e) {
         $ret->status = self::GSPATH_ERROR;
         $ret->message = $e->getMessage();
     }
     return $ret;
 }
Exemplo n.º 17
0
				}
				if($c==' ')
					$sep=$i;
				$l+=$cw[$c];
				if($l>$wmax)
				{
					if($sep==-1)
					{
						if($i==$j)
							$i++;
					}
					else
						$i=$sep+1;
					$sep=-1;
					$j=$i;
					$l=0;
					$nl++;
				}
				else
					$i++;
			}
			return $nl;
		}
	}
	
	$pdf = new pdf();
	$pdf->AliasNbPages();
	$pdf->AddPage();
	$pdf->adddetalle();
	$pdf->Output();	
?>
Exemplo n.º 18
0
					}
					else
						$i=$sep+1;
					$sep=-1;
					$j=$i;
					$l=0;
					$nl++;
				}
				else
					$i++;
			}
			return $nl;
		}
	}
	
	$pdf = new pdf('L','mm','Legal');
	$pdf->AliasNbPages();
	$titulos = array('GUIA','FECHA','FLETE','DESCUENTO','FLETE NETO','COMISION','RECOLECCION','COMISION RAD','ENTREGA','COMISION EAD','COM. SOBREPESO','TOTAL','TOTAL GRAL','CONDICION','STATUS');
	$medidas = array(22,15,20,20,25,20,20,20,20,20,20,35,35,25,40);
	$pdf->AddPage();
	$pdf->SetFont('Arial','B',6);	
	
	$pdf->SetWidths($medidas);
	
	$pdf->Titulos($titulos,$medidas);
	
	$pdf->SetFont('Arial','',6);
	for($i=0;$i<count($data);$i++){
		$pdf->Row($data[$i]);
	}
	
Exemplo n.º 19
0
 /**
  * printanswers::view()
  * View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'.
  * @param mixed $surveyid
  * @param bool $printableexport
  * @return
  */
 function actionView($surveyid, $printableexport = FALSE)
 {
     global $siteadminname, $siteadminemail;
     Yii::app()->loadHelper("frontend");
     Yii::import('application.libraries.admin.pdf');
     $surveyid = (int) $surveyid;
     Yii::app()->loadHelper('database');
     if (isset($_SESSION['survey_' . $surveyid]['sid'])) {
         $surveyid = $_SESSION['survey_' . $surveyid]['sid'];
     } else {
         die('Invalid survey/session');
     }
     //Debut session time out
     if (!isset($_SESSION['survey_' . $surveyid]['finished']) || !isset($_SESSION['survey_' . $surveyid]['srid'])) {
         //require_once($rootdir.'/classes/core/language.php');
         $baselang = Survey::model()->findByPk($surveyid)->language;
         Yii::import('application.libraries.Limesurvey_lang', true);
         $clang = new Limesurvey_lang($baselang);
         //A nice exit
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath(validateTemplateDir("default")) . "/startpage.pstpl"), array(), array());
         echo "<center><br />\n" . "\t<font color='RED'><strong>" . $clang->gT("Error") . "</strong></font><br />\n" . "\t" . $clang->gT("We are sorry but your session has expired.") . "<br />" . $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.") . "<br />\n" . "\t" . sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $siteadminname, $siteadminemail) . "\n" . "</center><br />\n";
         echo templatereplace(file_get_contents(getTemplatePath(validateTemplateDir("default")) . "/endpage.pstpl"), array(), array());
         doFooter();
         exit;
     }
     //Fin session time out
     $id = $_SESSION['survey_' . $surveyid]['srid'];
     //I want to see the answers with this id
     $clang = $_SESSION['survey_' . $surveyid]['s_lang'];
     //Ensure script is not run directly, avoid path disclosure
     //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}
     // Set the language for dispay
     //require_once($rootdir.'/classes/core/language.php');  // has been secured
     if (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
         $clang = SetSurveyLanguage($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']);
         $language = $_SESSION['survey_' . $surveyid]['s_lang'];
     } else {
         $language = Survey::model()->findByPk($surveyid)->language;
         $clang = SetSurveyLanguage($surveyid, $language);
     }
     // Get the survey inforamtion
     $thissurvey = getSurveyInfo($surveyid, $language);
     //SET THE TEMPLATE DIRECTORY
     if (!isset($thissurvey['templatedir']) || !$thissurvey['templatedir']) {
         $thistpl = validateTemplateDir("default");
     } else {
         $thistpl = validateTemplateDir($thissurvey['templatedir']);
     }
     if ($thissurvey['printanswers'] == 'N') {
         die;
         //Die quietly if print answers is not permitted
     }
     //CHECK IF SURVEY IS ACTIVATED AND EXISTS
     $surveytable = "{{survey_{$surveyid}}}";
     $surveyname = $thissurvey['surveyls_title'];
     $anonymized = $thissurvey['anonymized'];
     //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
     //SHOW HEADER
     $printoutput = '';
     $printoutput .= "<form action='" . Yii::app()->getController()->createUrl('printanswers/view/surveyid/' . $surveyid . '/printableexport/pdf') . "' method='post'>\n<center><input type='submit' value='" . $clang->gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>";
     if ($printableexport == 'pdf') {
         require Yii::app()->getConfig('rootdir') . '/application/config/tcpdf.php';
         Yii::import('application.libraries.admin.pdf', true);
         $pdf = new pdf();
         $pdf->setConfig($tcpdf);
         //$pdf->SetFont($pdfdefaultfont,'',$pdffontsize);
         $pdf->AddPage();
         //$pdf->titleintopdf($clang->gT("Survey name (ID)",'unescaped').": {$surveyname} ({$surveyid})");
         $pdf->SetTitle($clang->gT("Survey name (ID)", 'unescaped') . ": {$surveyname} ({$surveyid})");
     }
     $printoutput .= "\t<div class='printouttitle'><strong>" . $clang->gT("Survey name (ID):") . "</strong> {$surveyname} ({$surveyid})</div><p>&nbsp;\n";
     LimeExpressionManager::StartProcessingPage(true);
     // means that all variables are on the same page
     // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
     LimeExpressionManager::StartProcessingGroup(1, $thissurvey['anonymized'] != "N", $surveyid);
     $aFullResponseTable = getFullResponseTable($surveyid, $id, $language, true);
     //Get the fieldmap @TODO: do we need to filter out some fields?
     unset($aFullResponseTable['id']);
     unset($aFullResponseTable['token']);
     unset($aFullResponseTable['lastpage']);
     unset($aFullResponseTable['startlanguage']);
     unset($aFullResponseTable['datestamp']);
     unset($aFullResponseTable['startdate']);
     $printoutput .= "<table class='printouttable' >\n";
     if ($printableexport == 'pdf') {
         $pdf->intopdf($clang->gT("Question", 'unescaped') . ": " . $clang->gT("Your answer", 'unescaped'));
     }
     $oldgid = 0;
     $oldqid = 0;
     foreach ($aFullResponseTable as $sFieldname => $fname) {
         if (substr($sFieldname, 0, 4) == 'gid_') {
             if ($printableexport) {
                 $pdf->intopdf(flattenText($fname[0], false, true));
                 $pdf->ln(2);
             } else {
                 $printoutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n";
             }
         } elseif (substr($sFieldname, 0, 4) == 'qid_') {
             if ($printableexport == 'pdf') {
                 $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]);
                 $pdf->ln(2);
             } else {
                 $printoutput .= "\t<tr class='printanswersquestionhead'><td  colspan='2'>{$fname[0]}</td></tr>\n";
             }
         } elseif ($sFieldname == 'submitdate') {
             if ($anonymized != 'Y') {
                 if ($printableexport == 'pdf') {
                     $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]);
                     $pdf->ln(2);
                 } else {
                     $printoutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
                 }
             }
         } else {
             if ($printableexport == 'pdf') {
                 $pdf->intopdf(flattenText($fname[0] . $fname[1], false, true) . ": " . $fname[2]);
                 $pdf->ln(2);
             } else {
                 $printoutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
             }
         }
     }
     $printoutput .= "</table>\n";
     if ($printableexport == 'pdf') {
         header("Pragma: public");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         $sExportFileName = sanitize_filename($surveyname);
         $pdf->Output($sExportFileName . "-" . $surveyid . ".pdf", "D");
     }
     //Display the page with user answers
     if (!$printableexport) {
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/startpage.pstpl'));
         echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/printanswers.pstpl'), array('ANSWERTABLE' => $printoutput));
         echo templatereplace(file_get_contents(getTemplatePath($thistpl) . '/endpage.pstpl'));
         echo "</body></html>";
     }
     LimeExpressionManager::FinishProcessingGroup();
     LimeExpressionManager::FinishProcessingPage();
 }
Exemplo n.º 20
0
	gc.colonia, gc.cp, gc.poblacion, gc.municipio, gc.estado, gc.pais, gc.celular, gc.telefono, gc.email,
	gc.precioporkg, gc.precioporcaja, gc.descuentosobreflete, gc.cantidaddescuento, gc.limitekg, gc.costo,
	gc.preciokgexcedente, gc.prepagadas, gc.consignacionkg, gc.consignacioncaja, gc.consignaciondescuento,
	gc.consignaciondescantidad, gc.valordeclarado, limite, porcada, costoextra,
	date_format(current_date, '%d/%m/%Y') as fechaactual,
	cs.estado eest, cs.municipio emun, gc.legal,
	CONCAT(day(gc.fecha),' de ', UCASE(MONTHNAME(gc.fecha)), ' de ',YEAR(gc.fecha)) fechaconvenio,
	CONCAT(day(gc.vigencia),' de ', UCASE(MONTHNAME(gc.vigencia)), ' de ',YEAR(gc.vigencia)) fechavigencia
	FROM generacionconvenio gc
	LEFT JOIN catalogosucursal cs ON gc.sucursal = cs.id
	WHERE gc.folio = '$_GET[folio]'";
	$r = mysql_query($s,$l) or die("error ".mysql_error($l)."--".$s);
	$f = mysql_fetch_object($r);
	//die($s);
	
	$pdf = new pdf();
	$pdf->AliasNbPages();
	$pdf -> AddPage();
	$pdf -> Ln(10);
	$pdf -> SetFont("Arial","",8);
	
	
	$contenido = 'Contrato de prestación de servicios que celebra por una parte ENTREGAS PUNTUALES S DE RL DE CV, a quien en lo sucesivo se le denominará "La Prestadora de Servicios", y por otra parte '.$f->ncliente.' representada por '.ucwords($f->legal).' a quien en lo sucesivo se le denominará "El Cliente".
	
	1.- La Prestadora de Servicios otorgará a "El Cliente" los siguientes servicios:
	                Guias Ventanilla                    Guias Electronicas
	                Entrega a Domicilio                 Recolección a Domicilio
	                Valor Declarado                     Acuse de Recibo
	                Entregas a Subdestinos
					
	2.- El precio del servicio de Recolección a Domicilio (RAD) y Entrega a Domicilio (EAD) es un 10% sobre el valor del flete o bien un cobro mínimo dependiendo de la Ciudad donde se origine el servicio de RAD o donde se envíe el servicio de EAD (ver tarifas).
 /**
  * Put a QR code in cerficate pdf object
  * 
  * @param pdf $pdf The pdf object
  * @param string $code The certificate code
  */
 protected function print_qrcode($pdf, $code)
 {
     global $CFG;
     $style = array('border' => 2, 'vpadding' => 'auto', 'hpadding' => 'auto', 'fgcolor' => array(0, 0, 0), 'bgcolor' => array(255, 255, 255), 'module_width' => 1, 'module_height' => 1);
     // height of a single module in points
     $codeurl = new moodle_url("{$CFG->wwwroot}/mod/simplecertificate/verify.php");
     $codeurl->param('code', $code);
     $pdf->write2DBarcode($codeurl->out(false), 'QRCODE,M', $this->get_instance()->codex, $this->get_instance()->codey, 50, 50, $style, 'N');
     $pdf->SetXY($this->get_instance()->codex, $this->get_instance()->codey + 49);
     $pdf->SetFillColor(255, 255, 255);
     $pdf->Cell(50, 0, $code, 'LRB', 0, 'C', true, '', 2);
 }
 /**
  * printanswers::view()
  * View answers at the end of a survey in one place. To export as pdf, set 'usepdfexport' = 1 in lsconfig.php and $printableexport='pdf'.
  * @param mixed $surveyid
  * @param bool $printableexport
  * @return
  */
 function actionView($surveyid, $printableexport = FALSE)
 {
     Yii::app()->loadHelper("frontend");
     Yii::import('application.libraries.admin.pdf');
     $iSurveyID = (int) $surveyid;
     $sExportType = $printableexport;
     Yii::app()->loadHelper('database');
     if (isset($_SESSION['survey_' . $iSurveyID]['sid'])) {
         $iSurveyID = $_SESSION['survey_' . $iSurveyID]['sid'];
     } else {
         //die('Invalid survey/session');
     }
     // Get the survey inforamtion
     // Set the language for dispay
     if (isset($_SESSION['survey_' . $iSurveyID]['s_lang'])) {
         $sLanguage = $_SESSION['survey_' . $iSurveyID]['s_lang'];
     } elseif (Survey::model()->findByPk($iSurveyID)) {
         $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $iSurveyID = 0;
         $sLanguage = Yii::app()->getConfig("defaultlang");
     }
     SetSurveyLanguage($iSurveyID, $sLanguage);
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sLanguage);
     $oTemplate = Template::model()->getInstance(null, $iSurveyID);
     //Survey is not finished or don't exist
     if (!isset($_SESSION['survey_' . $iSurveyID]['finished']) || !isset($_SESSION['survey_' . $iSurveyID]['srid'])) {
         sendCacheHeaders();
         doHeader();
         /// $oTemplate is a global variable defined in controller/survey/index
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/startpage.pstpl'), array());
         echo "<center><br />\n" . "\t<font color='RED'><strong>" . gT("Error") . "</strong></font><br />\n" . "\t" . gT("We are sorry but your session has expired.") . "<br />" . gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.") . "<br />\n" . "\t" . sprintf(gT("Please contact %s ( %s ) for further assistance."), Yii::app()->getConfig("siteadminname"), Yii::app()->getConfig("siteadminemail")) . "\n" . "</center><br />\n";
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/endpage.pstpl'), array());
         doFooter();
         exit;
     }
     //Fin session time out
     $sSRID = $_SESSION['survey_' . $iSurveyID]['srid'];
     //I want to see the answers with this id
     //Ensure script is not run directly, avoid path disclosure
     //if (!isset($rootdir) || isset($_REQUEST['$rootdir'])) {die( "browse - Cannot run this script directly");}
     //Ensure Participants printAnswer setting is set to true or that the logged user have read permissions over the responses.
     if ($aSurveyInfo['printanswers'] == 'N' && !Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'read')) {
         throw new CHttpException(401, 'You are not allowed to print answers.');
     }
     //CHECK IF SURVEY IS ACTIVATED AND EXISTS
     $sSurveyName = $aSurveyInfo['surveyls_title'];
     $sAnonymized = $aSurveyInfo['anonymized'];
     //OK. IF WE GOT THIS FAR, THEN THE SURVEY EXISTS AND IT IS ACTIVE, SO LETS GET TO WORK.
     //SHOW HEADER
     if ($sExportType != 'pdf') {
         $sOutput = CHtml::form(array("printanswers/view/surveyid/{$iSurveyID}/printableexport/pdf"), 'post') . "<center><input class='btn btn-default' type='submit' value='" . gT("PDF export") . "'id=\"exportbutton\"/><input type='hidden' name='printableexport' /></center></form>";
         $sOutput .= "\t<div class='printouttitle'><strong>" . gT("Survey name (ID):") . "</strong> {$sSurveyName} ({$iSurveyID})</div><p>&nbsp;\n";
         LimeExpressionManager::StartProcessingPage(true);
         // means that all variables are on the same page
         // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
         LimeExpressionManager::StartProcessingGroup(1, $aSurveyInfo['anonymized'] != "N", $iSurveyID);
         $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions');
         $aFullResponseTable = getFullResponseTable($iSurveyID, $sSRID, $sLanguage, $printanswershonorsconditions);
         //Get the fieldmap @TODO: do we need to filter out some fields?
         if ($aSurveyInfo['datestamp'] != "Y" || $sAnonymized == 'Y') {
             unset($aFullResponseTable['submitdate']);
         } else {
             unset($aFullResponseTable['id']);
         }
         unset($aFullResponseTable['token']);
         unset($aFullResponseTable['lastpage']);
         unset($aFullResponseTable['startlanguage']);
         unset($aFullResponseTable['datestamp']);
         unset($aFullResponseTable['startdate']);
         $sOutput .= "<table class='printouttable' >\n";
         foreach ($aFullResponseTable as $sFieldname => $fname) {
             if (substr($sFieldname, 0, 4) == 'gid_') {
                 $sOutput .= "\t<tr class='printanswersgroup'><td colspan='2'>{$fname[0]}</td></tr>\n";
                 $sOutput .= "\t<tr class='printanswersgroupdesc'><td colspan='2'>{$fname[1]}</td></tr>\n";
             } elseif ($sFieldname == 'submitdate') {
                 if ($sAnonymized != 'Y') {
                     $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]} {$sFieldname}</td><td class='printanswersanswertext'>{$fname[2]}</td></tr>";
                 }
             } elseif (substr($sFieldname, 0, 4) != 'qid_') {
                 $sOutput .= "\t<tr class='printanswersquestion'><td>{$fname[0]} {$fname[1]}</td><td class='printanswersanswertext'>" . flattenText($fname[2]) . "</td></tr>";
             }
         }
         $sOutput .= "</table>\n";
         $sData['thissurvey'] = $aSurveyInfo;
         $sOutput = templatereplace($sOutput, array(), $sData, '', $aSurveyInfo['anonymized'] == "Y", NULL, array(), true);
         // Do a static replacement
         ob_start(function ($buffer, $phase) {
             App()->getClientScript()->render($buffer);
             App()->getClientScript()->reset();
             return $buffer;
         });
         ob_implicit_flush(false);
         sendCacheHeaders();
         doHeader();
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/startpage.pstpl'), array(), $sData);
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/printanswers.pstpl'), array('ANSWERTABLE' => $sOutput), $sData);
         echo templatereplace(file_get_contents($oTemplate->viewPath . '/endpage.pstpl'), array(), $sData);
         echo "</body></html>";
         ob_flush();
     }
     if ($sExportType == 'pdf') {
         // Get images for TCPDF from template directory
         define('K_PATH_IMAGES', getTemplatePath($aSurveyInfo['template']) . DIRECTORY_SEPARATOR);
         Yii::import('application.libraries.admin.pdf', true);
         Yii::import('application.helpers.pdfHelper');
         $aPdfLanguageSettings = pdfHelper::getPdfLanguageSettings(App()->language);
         $oPDF = new pdf();
         $sDefaultHeaderString = $sSurveyName . " (" . gT("ID", 'unescaped') . ":" . $iSurveyID . ")";
         $oPDF->initAnswerPDF($aSurveyInfo, $aPdfLanguageSettings, Yii::app()->getConfig('sitename'), $sSurveyName, $sDefaultHeaderString);
         LimeExpressionManager::StartProcessingPage(true);
         // means that all variables are on the same page
         // Since all data are loaded, and don't need JavaScript, pretend all from Group 1
         LimeExpressionManager::StartProcessingGroup(1, $aSurveyInfo['anonymized'] != "N", $iSurveyID);
         $printanswershonorsconditions = Yii::app()->getConfig('printanswershonorsconditions');
         $aFullResponseTable = getFullResponseTable($iSurveyID, $sSRID, $sLanguage, $printanswershonorsconditions);
         //Get the fieldmap @TODO: do we need to filter out some fields?
         if ($aSurveyInfo['datestamp'] != "Y" || $sAnonymized == 'Y') {
             unset($aFullResponseTable['submitdate']);
         } else {
             unset($aFullResponseTable['id']);
         }
         unset($aFullResponseTable['token']);
         unset($aFullResponseTable['lastpage']);
         unset($aFullResponseTable['startlanguage']);
         unset($aFullResponseTable['datestamp']);
         unset($aFullResponseTable['startdate']);
         foreach ($aFullResponseTable as $sFieldname => $fname) {
             if (substr($sFieldname, 0, 4) == 'gid_') {
                 $oPDF->addGidAnswer($fname[0], $fname[1]);
             } elseif ($sFieldname == 'submitdate') {
                 if ($sAnonymized != 'Y') {
                     $oPDF->addAnswer($fname[0] . " " . $fname[1], $fname[2]);
                 }
             } elseif (substr($sFieldname, 0, 4) != 'qid_') {
                 $oPDF->addAnswer($fname[0] . " " . $fname[1], $fname[2]);
             }
         }
         header("Pragma: public");
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         $sExportFileName = sanitize_filename($sSurveyName);
         $oPDF->Output($sExportFileName . "-" . $iSurveyID . ".pdf", "D");
     }
     LimeExpressionManager::FinishProcessingGroup();
     LimeExpressionManager::FinishProcessingPage();
 }
Exemplo n.º 23
0
 /**
  * Generates statistics
  *
  * @param int $surveyid The survey id
  * @param mixed $allfields
  * @param mixed $q2show
  * @param mixed $usegraph
  * @param string $outputType Optional - Can be xls, html or pdf - Defaults to pdf
  * @param string $pdfOutput Sets the target for the PDF output: DD=File download , F=Save file to local disk
  * @param string $statlangcode Lamguage for statistics
  * @param mixed $browse  Show browse buttons
  * @return buffer
  */
 public function generate_statistics($surveyid, $allfields, $q2show = 'all', $usegraph = 0, $outputType = 'pdf', $pdfOutput = 'I', $sLanguageCode = null, $browse = true)
 {
     $aStatisticsData = array();
     //astatdata generates data for the output page's javascript so it can rebuild graphs on the fly
     //load surveytranslator helper
     Yii::import('application.helpers.surveytranslator_helper', true);
     Yii::import('application.third_party.ar-php.Arabic', true);
     $sOutputHTML = "";
     //This string carries all the actual HTML code to print.
     $sTempDir = Yii::app()->getConfig("tempdir");
     $this->pdf = array();
     //Make sure $this->pdf exists - it will be replaced with an object if a $this->pdf is actually being created
     //pick the best font file if font setting is 'auto'
     if (is_null($sLanguageCode)) {
         $sLanguageCode = getBaseLanguageFromSurveyID($surveyid);
     }
     Yii::app()->setLanguage($sLanguageCode);
     /*
      * this variable is used in the function shortencode() which cuts off a question/answer title
      * after $maxchars and shows the rest as tooltip (in html mode)
      */
     $maxchars = 13;
     //we collect all the html-output within this variable
     $sOutputHTML = '';
     /**
      * $outputType: html || pdf ||
      */
     /**
      * get/set Survey Details
      */
     //no survey ID? -> come and get one
     if (!isset($surveyid)) {
         $surveyid = returnGlobal('sid');
     }
     //Get an array of codes of all available languages in this survey
     $surveylanguagecodes = Survey::model()->findByPk($surveyid)->additionalLanguages;
     $surveylanguagecodes[] = Survey::model()->findByPk($surveyid)->language;
     $fieldmap = createFieldMap($surveyid, "full", false, false, $sLanguageCode);
     // Set language for questions and answers to base language of this survey
     $language = $sLanguageCode;
     if ($q2show == 'all') {
         $summarySql = " SELECT gid, parent_qid, qid, type " . " FROM {{questions}} WHERE parent_qid=0" . " AND sid={$surveyid} ";
         $summaryRs = Yii::app()->db->createCommand($summarySql)->query()->readAll();
         foreach ($summaryRs as $field) {
             $myField = $surveyid . "X" . $field['gid'] . "X" . $field['qid'];
             // Multiple choice get special treatment
             if ($field['type'] == "M") {
                 $myField = "M{$myField}";
             }
             if ($field['type'] == "P") {
                 $myField = "P{$myField}";
             }
             //numerical input will get special treatment (arihtmetic mean, standard derivation, ...)
             if ($field['type'] == "N") {
                 $myField = "N{$myField}";
             }
             if ($field['type'] == "|") {
                 $myField = "|{$myField}";
             }
             if ($field['type'] == "Q") {
                 $myField = "Q{$myField}";
             }
             // textfields get special treatment
             if ($field['type'] == "S" || $field['type'] == "T" || $field['type'] == "U") {
                 $myField = "T{$myField}";
             }
             //statistics for Date questions are not implemented yet.
             if ($field['type'] == "D") {
                 $myField = "D{$myField}";
             }
             if ($field['type'] == "F" || $field['type'] == "H") {
                 //Get answers. We always use the answer code because the label might be too long elsewise
                 $query = "SELECT code, answer FROM {{answers}} WHERE qid='" . $field['qid'] . "' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer";
                 $result = Yii::app()->db->createCommand($query)->query();
                 $counter2 = 0;
                 //check all the answers
                 foreach ($result->readAll() as $row) {
                     $row = array_values($row);
                     $myField = "{$myField}{$row[0]}";
                 }
                 //$myField = "{$surveyid}X{$flt[1]}X{$flt[0]}{$row[0]}[]";
             }
             if ($q2show == 'all') {
                 $summary[] = $myField;
             }
             //$allfields[]=$myField;
         }
     } else {
         // This gets all the 'to be shown questions' from the POST and puts these into an array
         if (!is_array($q2show)) {
             $summary = returnGlobal('summary');
         } else {
             $summary = $q2show;
         }
         //print_r($_POST);
         //if $summary isn't an array we create one
         if (isset($summary) && !is_array($summary)) {
             $summary = explode("+", $summary);
         }
     }
     /**
      * pdf Config
      */
     if ($outputType == 'pdf') {
         //require_once('classes/tcpdf/mypdf.php');
         Yii::import('application.libraries.admin.pdf', true);
         Yii::import('application.helpers.pdfHelper');
         $aPdfLanguageSettings = pdfHelper::getPdfLanguageSettings($language);
         // create new PDF document
         $this->pdf = new pdf();
         $surveyInfo = getSurveyInfo($surveyid, $language);
         // set document information
         $this->pdf->SetCreator(PDF_CREATOR);
         $this->pdf->SetAuthor('LimeSurvey');
         $this->pdf->SetTitle(sprintf(gT("Statistics survey %s"), $surveyid));
         $this->pdf->SetSubject($surveyInfo['surveyls_title']);
         $this->pdf->SetKeywords('LimeSurvey,' . gT("Statistics") . ', ' . sprintf(gT("Survey %s"), $surveyid));
         $this->pdf->SetDisplayMode('fullpage', 'two');
         $this->pdf->setLanguageArray($aPdfLanguageSettings['lg']);
         // set header and footer fonts
         $this->pdf->setHeaderFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_MAIN));
         $this->pdf->setFooterFont(array($aPdfLanguageSettings['pdffont'], '', PDF_FONT_SIZE_DATA));
         // set default header data
         // Since png crashes some servers (and we can not try/catch that) we use .gif (or .jpg) instead
         $headerlogo = 'statistics.gif';
         $this->pdf->SetHeaderData($headerlogo, 10, gT("Quick statistics", 'unescaped'), gT("Survey") . " " . $surveyid . " '" . flattenText($surveyInfo['surveyls_title'], false, true, 'UTF-8') . "'");
         $this->pdf->SetFont($aPdfLanguageSettings['pdffont'], '', $aPdfLanguageSettings['pdffontsize']);
         // set default monospaced font
         $this->pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
     }
     if ($outputType == 'xls') {
         /**
          * Initiate the Spreadsheet_Excel_Writer
          */
         require_once APPPATH . '/third_party/pear/Spreadsheet/Excel/Xlswriter.php';
         if ($pdfOutput == 'F') {
             $sFileName = $sTempDir . '/statistic-survey' . $surveyid . '.xls';
             $this->workbook = new Xlswriter($sFileName);
         } else {
             $this->workbook = new Xlswriter();
         }
         $this->workbook->setVersion(8);
         // Inform the module that our data will arrive as UTF-8.
         // Set the temporary directory to avoid PHP error messages due to open_basedir restrictions and calls to tempnam("", ...)
         $this->workbook->setTempDir($sTempDir);
         // Inform the module that our data will arrive as UTF-8.
         // Set the temporary directory to avoid PHP error messages due to open_basedir restrictions and calls to tempnam("", ...)
         if (!empty($sTempDir)) {
             $this->workbook->setTempDir($sTempDir);
         }
         if ($pdfOutput != 'F') {
             $this->workbook->send('statistic-survey' . $surveyid . '.xls');
         }
         // Creating the first worksheet
         $this->sheet = $this->workbook->addWorksheet(utf8_decode('results-survey' . $surveyid));
         $this->xlsPercents =& $this->workbook->addFormat();
         $this->xlsPercents->setNumFormat('0.00%');
         $this->formatBold =& $this->workbook->addFormat(array('Bold' => 1));
         $this->sheet->setInputEncoding('utf-8');
         $this->sheet->setColumn(0, 20, 20);
         $separator = "~|";
         /**XXX*/
     }
     /**
      * Start generating
      */
     $selects = buildSelects($allfields, $surveyid, $language);
     //count number of answers
     $query = "SELECT count(*) FROM {{survey_{$surveyid}}}";
     //if incompleted answers should be filtert submitdate has to be not null
     if (incompleteAnsFilterState() == "incomplete") {
         $query .= " WHERE submitdate is null";
     } elseif (incompleteAnsFilterState() == "complete") {
         $query .= " WHERE submitdate is not null";
     }
     $total = Yii::app()->db->createCommand($query)->queryScalar();
     //are there any filters that have to be taken care of?
     if (isset($selects) && $selects) {
         //Save the filters to session for use in browsing text & other features (statistics.php function listcolumn())
         Yii::app()->session['statistics_selects_' . $surveyid] = $selects;
         //filter incomplete answers?
         if (incompleteAnsFilterState() == "complete" || incompleteAnsFilterState() == "incomplete") {
             $query .= " AND ";
         } else {
             $query .= " WHERE ";
         }
         //add filter criteria to SQL
         $query .= implode(" AND ", $selects);
     }
     //get me some data Scotty
     $results = Yii::app()->db->createCommand($query)->queryScalar();
     if ($total) {
         $percent = sprintf("%01.2f", $results / $total * 100);
     }
     switch ($outputType) {
         case "xls":
             $this->xlsRow = 0;
             $this->sheet->write($this->xlsRow, 0, gT("Number of records in this query:", 'unescaped'));
             $this->sheet->writeNumber($this->xlsRow, 1, $results);
             $this->xlsRow++;
             $this->sheet->write($this->xlsRow, 0, gT("Total records in survey:", 'unescaped'));
             $this->sheet->writeNumber($this->xlsRow, 1, $total);
             if ($total) {
                 $this->xlsRow++;
                 $this->sheet->write($this->xlsRow, 0, gT("Percentage of total:", 'unescaped'));
                 $this->sheet->writeNumber($this->xlsRow, 1, $results / $total, $this->xlsPercents);
             }
             break;
         case 'pdf':
             // add summary to pdf
             $array = array(array(gT("Number of records in this query:", 'unescaped'), $results), array(gT("Total records in survey:", 'unescaped'), $total));
             if ($total) {
                 $array[] = array(gT("Percentage of total:", 'unescaped'), $percent . "%");
             }
             $this->pdf->AddPage('P', ' A4');
             $this->pdf->Bookmark(gT("Results", 'unescaped'), 0, 0);
             $this->pdf->titleintopdf(gT("Results", 'unescaped'), gT("Survey", 'unescaped') . " " . $surveyid);
             $this->pdf->tableintopdf($array);
             break;
         case 'html':
             $sOutputHTML .= "<br />\n<table class='statisticssummary' >\n" . "\t<thead><tr><th colspan='2'>" . gT("Results") . "</th></tr></thead>\n" . "\t<tr><th >" . gT("Number of records in this query:") . '</th>' . "<td>{$results}</td></tr>\n" . "\t<tr><th>" . gT("Total records in survey:") . '</th>' . "<td>{$total}</td></tr>\n";
             //only calculate percentage if $total is set
             if ($total) {
                 $percent = sprintf("%01.2f", $results / $total * 100);
                 $sOutputHTML .= "\t<tr><th align='right'>" . gT("Percentage of total:") . '</th>' . "<td>{$percent}%</td></tr>\n";
             }
             $sOutputHTML .= "</table>\n";
             break;
         default:
             break;
     }
     //put everything from $selects array into a string connected by AND
     //This string ($sql) can then be passed on to other functions so you can
     //browse these results
     if (isset($selects) && $selects) {
         $sql = implode(" AND ", $selects);
     } elseif (!empty($newsql)) {
         $sql = $newsql;
     }
     if (!isset($sql) || !$sql) {
         $sql = null;
     }
     //only continue if we have something to output
     if ($results > 0) {
         if ($outputType == 'html' && $browse === true && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'read')) {
             //add a buttons to browse results
             $sOutputHTML .= CHtml::form(array("admin/responses/sa/browse/surveyid/{$surveyid}"), 'post', array('target' => '_blank')) . "\n" . "\t\t<p>" . "\t\t\t<input type='submit' value='" . gT("Browse") . "'  />\n" . "\t\t\t<input type='hidden' name='sid' value='{$surveyid}' />\n" . "\t\t\t<input type='hidden' name='sql' value=\"{$sql}\" />\n" . "\t\t\t<input type='hidden' name='subaction' value='all' />\n" . "\t\t</p>" . "\t\t</form>\n";
         }
     }
     //end if (results > 0)
     /* Show Summary results
      * The $summary array contains each fieldname that we want to display statistics for
      *
      * */
     if (isset($summary) && $summary) {
         //let's run through the survey
         $runthrough = $summary;
         //START Chop up fieldname and find matching questions
         //loop through all selected questions
         foreach ($runthrough as $rt) {
             //Step 1: Get information about this response field (SGQA) for the summary
             $outputs = $this->buildOutputList($rt, $language, $surveyid, $outputType, $sql, $sLanguageCode);
             $sOutputHTML .= $outputs['statisticsoutput'];
             //2. Collect and Display results #######################################################################
             if (isset($outputs['alist']) && $outputs['alist']) {
                 $display = $this->displayResults($outputs, $results, $rt, $outputType, $surveyid, $sql, $usegraph, $browse, $sLanguageCode);
                 $sOutputHTML .= $display['statisticsoutput'];
                 $aStatisticsData = array_merge($aStatisticsData, $display['astatdata']);
             }
             //end if -> collect and display results
             //Delete Build Outputs data
             unset($outputs);
             unset($display);
         }
         // end foreach -> loop through all questions
         //output
         if ($outputType == 'html') {
             $sOutputHTML .= "<br />&nbsp;\n";
         }
     }
     //end if -> show summary results
     switch ($outputType) {
         case 'xls':
             $this->workbook->close();
             if ($pdfOutput == 'F') {
                 return $sFileName;
             } else {
                 return;
             }
             break;
         case 'pdf':
             $this->pdf->lastPage();
             if ($pdfOutput == 'F') {
                 // This is only used by lsrc to send an E-Mail attachment, so it gives back the filename to send and delete afterwards
                 $tempfilename = $sTempDir . "/Survey_" . $surveyid . ".pdf";
                 $this->pdf->Output($tempfilename, $pdfOutput);
                 return $tempfilename;
             } else {
                 return $this->pdf->Output(gT('Survey') . '_' . $surveyid . "_" . $surveyInfo['surveyls_title'] . '.pdf', $pdfOutput);
             }
             break;
         case 'html':
             $sGoogleMapsAPIKey = trim(Yii::app()->getConfig("googleMapsAPIKey"));
             if ($sGoogleMapsAPIKey != '') {
                 $sGoogleMapsAPIKey = '&key=' . $sGoogleMapsAPIKey;
             }
             $sSSL = '';
             if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") {
                 $sSSL = 's';
             }
             $sOutputHTML .= "<script type=\"text/javascript\" src=\"http{$sSSL}://maps.googleapis.com/maps/api/js?sensor=false{$sGoogleMapsAPIKey}\"></script>\n" . "<script type=\"text/javascript\">var site_url='" . Yii::app()->baseUrl . "';var temppath='" . Yii::app()->getConfig("tempurl") . "';var imgpath='" . Yii::app()->getConfig('adminimageurl') . "';var aStatData=" . ls_json_encode($aStatisticsData) . "</script>";
             return $sOutputHTML;
             break;
         default:
             return $sOutputHTML;
             break;
     }
 }
Exemplo n.º 24
0
 function report_download_pdf($html)
 {
     $doc = new pdf();
     //$doc->Header();
     $doc->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, 'Teleparadigm', array(), array());
     $doc->setFooterData(array(0, 64, 0), array(0, 64, 128));
     $doc->setPrintHeader(false);
     $doc->setPrintFooter(true);
     // set margins
     $doc->SetMargins(PDF_MARGIN_LEFT, 5, PDF_MARGIN_RIGHT);
     $doc->SetHeaderMargin(PDF_MARGIN_HEADER);
     $doc->SetFooterMargin(PDF_MARGIN_FOOTER);
     $doc->AddPage();
     $doc->writeHTML($html, true, false, true, false, '');
     $doc->Output();
     die;
 }
Exemplo n.º 25
0
					}
					else
						$i=$sep+1;
					$sep=-1;
					$j=$i;
					$l=0;
					$nl++;
				}
				else
					$i++;
			}
			return $nl;
		}
	}

	$pdf = new pdf();
	$pdf->AliasNbPages();
	$titulos = array('MOVIMIENTO','PAGADA-CONTADO','PAGADA-CREDITO','COBRAR-CONTADO','COBRAR-CREDITO','TOTAL');
	$medidas = array(20,35,35,35,35,35);
	$pdf->AddPage();
	$pdf->SetFont('Arial','B',6);
	//Table with 20 rows and 4 columns
	
	$pdf->SetWidths($medidas);
	
	$pdf->Titulos($titulos,$medidas);
	
	$pdf->SetFont('Arial','',7);
	for($i=0;$i<count($data);$i++){
		$pdf->Row($data[$i]);
	}
Exemplo n.º 26
0
 /**
  * Index posts stored in $this->unindexedPosts
  *
  * @since 1.0
  */
 function index()
 {
     global $wp_filesystem, $searchwp;
     $this->check_for_parallel_indexer();
     if (is_array($this->unindexedPosts) && count($this->unindexedPosts)) {
         do_action('searchwp_indexer_pre_chunk', $this->unindexedPosts);
         // all of the IDs to index have not been indexed, proceed with indexing them
         while (($unindexedPost = current($this->unindexedPosts)) !== false) {
             $this->setPost($unindexedPost);
             // log the attempt
             $count = get_post_meta($this->post->ID, '_' . SEARCHWP_PREFIX . 'attempts', true);
             if ($count == false) {
                 $count = 0;
             } else {
                 $count = intval($count);
             }
             $count++;
             // increment our counter to prevent the indexer getting stuck on a gigantic PDF
             update_post_meta($this->post->ID, '_' . SEARCHWP_PREFIX . 'attempts', $count);
             do_action('searchwp_log', 'Attempt ' . $count . ' at indexing ' . $this->post->ID);
             // if we breached the maximum number of attempts, flag it to skip
             $this->maxAttemptsToIndex = absint(apply_filters('searchwp_max_index_attempts', $this->maxAttemptsToIndex));
             if (intval($count) > $this->maxAttemptsToIndex) {
                 do_action('searchwp_log', 'Too many indexing attempts on ' . $this->post->ID . ' (' . $this->maxAttemptsToIndex . ') - skipping');
                 // flag it to be skipped
                 update_post_meta($this->post->ID, '_' . SEARCHWP_PREFIX . 'skip', true);
             } else {
                 // check to see if we're running a second pass on terms
                 $termCache = get_post_meta($this->post->ID, '_' . SEARCHWP_PREFIX . 'terms', true);
                 if (!is_array($termCache)) {
                     do_action('searchwp_index_post', $this->post);
                     // if it's an attachment, we want the permalink
                     $slug = $this->post->post_type == 'attachment' ? str_replace(get_bloginfo('wpurl'), '', get_permalink($this->post->ID)) : '';
                     // we allow users to override the extracted content from documents, if they have done so this flag is set
                     $skipDocProcessing = get_post_meta($this->post->ID, '_' . SEARCHWP_PREFIX . 'skip_doc_processing', true);
                     $omitDocProcessing = apply_filters('searchwp_omit_document_processing', false);
                     if (!$skipDocProcessing && !$omitDocProcessing) {
                         // if it's a PDF we need to populate our Custom Field with it's content
                         if ($this->post->post_mime_type == 'application/pdf') {
                             // grab the filename of the PDF
                             $filename = get_attached_file($this->post->ID);
                             // allow for external PDF content extraction
                             $pdfContent = apply_filters('searchwp_external_pdf_processing', '', $filename, $this->post->ID);
                             // only try to extract content if the external processing has not provided the PDF content we're looking for
                             if (empty($pdfContent)) {
                                 // PdfParser runs only on 5.3+ but SearchWP runs on 5.2+
                                 if (version_compare(PHP_VERSION, '5.3', '>=')) {
                                     include_once $searchwp->dir . '/vendor/pdfparser-bootloader.php';
                                 }
                                 // a wrapper class was conditionally included if we're running PHP 5.3+ so let's try that
                                 if (class_exists('SearchWP_PdfParser')) {
                                     // try PdfParser first
                                     $parser = new SearchWP_PdfParser();
                                     $parser = $parser->init();
                                     $pdf = $parser->parseFile($filename);
                                     $text = $pdf->getText();
                                     $pdfContent = trim(str_replace("\n", " ", $text));
                                 }
                                 // try PDF2Text
                                 if (empty($pdfContent)) {
                                     if (!class_exists('PDF2Text')) {
                                         include_once $searchwp->dir . '/includes/class.pdf2text.php';
                                     }
                                     $pdfParser = new PDF2Text();
                                     $pdfParser->setFilename($filename);
                                     $pdfParser->decodePDF();
                                     $pdfContent = $pdfParser->output();
                                     $pdfContent = trim(str_replace("\n", " ", $pdfContent));
                                 }
                                 // check to see if the first pass produced nothing or concatenated strings
                                 $fullContentLength = strlen($pdfContent);
                                 $numberOfSpaces = substr_count($pdfContent, ' ');
                                 if (empty($pdfContent) || $numberOfSpaces / $fullContentLength * 100 < 10) {
                                     WP_Filesystem();
                                     $filecontent = $wp_filesystem->exists($filename) ? $wp_filesystem->get_contents($filename) : '';
                                     if (false != strpos($filecontent, 'trailer')) {
                                         if (!class_exists('pdf_readstream')) {
                                             include_once $searchwp->dir . '/includes/class.pdfreadstream.php';
                                         }
                                         $pdfContent = '';
                                         $pdf = new pdf(get_attached_file($this->post->ID));
                                         $pages = $pdf->get_pages();
                                         if (!empty($pages)) {
                                             while (list($nr, $page) = each($pages)) {
                                                 $pdfContent .= $page->get_text();
                                             }
                                         }
                                     } else {
                                         // empty out the content so wacky concatenations are not indexed
                                         $pdfContent = '';
                                         // flag it for further review
                                         update_post_meta($this->post->ID, '_' . SEARCHWP_PREFIX . 'review', true);
                                         update_post_meta($this->post->ID, '_' . SEARCHWP_PREFIX . 'skip', true);
                                     }
                                 }
                             }
                             $pdfContent = trim($pdfContent);
                             if (!empty($pdfContent)) {
                                 $pdfContent = sanitize_text_field($pdfContent);
                                 delete_post_meta($this->post->ID, SEARCHWP_PREFIX . 'content');
                                 update_post_meta($this->post->ID, SEARCHWP_PREFIX . 'content', $pdfContent);
                             }
                         } elseif ($this->post->post_mime_type == 'text/plain') {
                             // if it's plain text, index it's content
                             WP_Filesystem();
                             $filename = get_attached_file($this->post->ID);
                             $textContent = $wp_filesystem->exists($filename) ? $wp_filesystem->get_contents($filename) : '';
                             $textContent = str_replace("\n", " ", $textContent);
                             if (!empty($textContent)) {
                                 $textContent = sanitize_text_field($textContent);
                                 update_post_meta($this->post->ID, SEARCHWP_PREFIX . 'content', $textContent);
                             }
                         } else {
                             // all other file types
                         }
                     }
                     $postTerms = array();
                     $postTerms['title'] = $this->indexTitle();
                     $postTerms['slug'] = $this->indexSlug(str_replace('/', ' ', $slug));
                     $postTerms['content'] = $this->indexContent();
                     $postTerms['excerpt'] = $this->indexExcerpt();
                     if (apply_filters('searchwp_index_comments', true)) {
                         $postTerms['comments'] = $this->indexComments();
                     }
                     // index taxonomies
                     $taxonomies = get_object_taxonomies($this->post->post_type);
                     if (!empty($taxonomies)) {
                         while (($taxonomy = current($taxonomies)) !== false) {
                             $terms = get_the_terms($this->post->ID, $taxonomy);
                             if (!empty($terms)) {
                                 $postTerms['taxonomy'][$taxonomy] = $this->indexTaxonomyTerms($taxonomy, $terms);
                             }
                             next($taxonomies);
                         }
                         reset($taxonomies);
                     }
                     // index custom fields
                     $customFields = apply_filters('searchwp_get_custom_fields', get_post_custom($this->post->ID), $this->post->ID);
                     if (!empty($customFields)) {
                         while (($customFieldValue = current($customFields)) !== false) {
                             $customFieldName = key($customFields);
                             // there are a few useless (when it comes to search) WordPress core custom fields, so let's exclude them by default
                             $omitWpMetadata = apply_filters('searchwp_omit_wp_metadata', array('_edit_lock', '_wp_page_template', '_edit_last', '_wp_old_slug'));
                             $excludedCustomFieldKeys = apply_filters('searchwp_excluded_custom_fields', array('_' . SEARCHWP_PREFIX . 'indexed', '_' . SEARCHWP_PREFIX . 'attempts', '_' . SEARCHWP_PREFIX . 'terms', '_' . SEARCHWP_PREFIX . 'last_index', '_' . SEARCHWP_PREFIX . 'skip', '_' . SEARCHWP_PREFIX . 'skip_doc_processing', '_' . SEARCHWP_PREFIX . 'review'));
                             // merge the two arrays of keys if possible
                             if (is_array($omitWpMetadata) && is_array($excludedCustomFieldKeys)) {
                                 $excluded_meta_keys = array_merge($omitWpMetadata, $excludedCustomFieldKeys);
                             } elseif (is_array($omitWpMetadata)) {
                                 $excluded_meta_keys = $omitWpMetadata;
                             } else {
                                 $excluded_meta_keys = $excludedCustomFieldKeys;
                             }
                             $excluded_meta_keys = is_array($excluded_meta_keys) ? array_unique($excluded_meta_keys) : array();
                             // allow developers to conditionally omit specific custom fields
                             $omit_this_custom_field = apply_filters("searchwp_omit_meta_key", false, $customFieldName, $this->post);
                             $omit_this_custom_field = apply_filters("searchwp_omit_meta_key_{$customFieldName}", $omit_this_custom_field, $this->post);
                             if (!in_array($customFieldName, $excluded_meta_keys) && !$omit_this_custom_field) {
                                 // allow devs to swap out their own content
                                 // e.g. parsing ACF Relationship fields (that store only post IDs) to actually retrieve that content at runtime
                                 $customFieldValue = apply_filters('searchwp_custom_fields', $customFieldValue, $customFieldName, $this->post);
                                 $customFieldValue = apply_filters("searchwp_custom_field_{$customFieldName}", $customFieldValue, $this->post);
                                 $postTerms['customfield'][$customFieldName] = $this->indexCustomField($customFieldName, $customFieldValue);
                             }
                             next($customFields);
                         }
                         reset($customFields);
                     }
                     // allow developer to store arbitrary information a la Custom Fields (without them actually being Custom Fields)
                     $extraMetadata = apply_filters("searchwp_extra_metadata", false, $this->post);
                     if ($extraMetadata) {
                         if (is_array($extraMetadata)) {
                             foreach ($extraMetadata as $extraMetadataKey => $extraMetadataValue) {
                                 // TODO: make sure there are no collisions?
                                 // while( isset( $postTerms['customfield'][$extraMetadataKey] ) ) {
                                 //    $extraMetadataKey .= '_';
                                 // }
                                 $postTerms['customfield'][$extraMetadataKey] = $this->indexCustomField($extraMetadataKey, $extraMetadataValue);
                             }
                         }
                     }
                     // we need to break out the terms from all of this content
                     $termCountBreakout = array();
                     if (is_array($postTerms) && count($postTerms)) {
                         foreach ($postTerms as $type => $terms) {
                             switch ($type) {
                                 case 'title':
                                 case 'slug':
                                 case 'content':
                                 case 'excerpt':
                                 case 'comments':
                                     if (is_array($terms) && count($terms)) {
                                         foreach ($terms as $term) {
                                             $termCountBreakout[$term['term']][$type] = $term['count'];
                                         }
                                     }
                                     break;
                                 case 'taxonomy':
                                 case 'customfield':
                                     if (is_array($terms) && count($terms)) {
                                         foreach ($terms as $name => $nameTerms) {
                                             if (is_array($nameTerms) && count($nameTerms)) {
                                                 foreach ($nameTerms as $nameTerm) {
                                                     $termCountBreakout[$nameTerm['term']][$type][$name] = $nameTerm['count'];
                                                 }
                                             }
                                         }
                                     }
                                     break;
                             }
                         }
                     }
                 } else {
                     $termCountBreakout = $termCache;
                     // if there was a term cache, this repeated processing doesn't count, so decrement it
                     delete_post_meta($this->post->ID, '_' . SEARCHWP_PREFIX . 'attempts');
                     delete_post_meta($this->post->ID, '_' . SEARCHWP_PREFIX . 'skip');
                 }
                 // unless the term chunk limit says otherwise, we're going to flag this as being OK to log as indexed
                 $flagAsIndexed = true;
                 // we now have a multidimensional array of terms with counts per type in $termCountBreakout
                 // if the term count is huge, we need to split up this process so as to avoid
                 // hitting upper PHP execution time limits (term insertion is heavy), so we'll chunk the array of terms
                 $termChunkMax = 500;
                 // try to set a better default based on php.ini's memory_limit
                 $memoryLimit = ini_get('memory_limit');
                 if (preg_match('/^(\\d+)(.)$/', $memoryLimit, $matches)) {
                     if ($matches[2] == 'M') {
                         $termChunkMax = (int) $matches[1] * 15;
                         // 15 terms per MB RAM
                     } else {
                         // memory was set in K...
                         $termChunkMax = 100;
                     }
                 }
                 $termChunkLimit = apply_filters('searchwp_process_term_limit', $termChunkMax);
                 if (count($termCountBreakout) > $termChunkLimit) {
                     $acceptableTermCountBreakout = array_slice($termCountBreakout, 0, $termChunkLimit);
                     // if we haven't pulled all of the terms, we can't consider this post indexed...
                     if ($termChunkLimit < count($termCountBreakout) - 1) {
                         $flagAsIndexed = false;
                         // save the term breakout so we don't have to do it again
                         $remainingTerms = array_slice($termCountBreakout, $termChunkLimit + 1);
                         update_post_meta($this->post->ID, '_' . SEARCHWP_PREFIX . 'terms', $remainingTerms);
                     }
                     // set the acceptable breakout as the main breakout
                     $termCountBreakout = $acceptableTermCountBreakout;
                 }
                 $this->recordPostTerms($termCountBreakout);
                 unset($termCountBreakout);
                 // flag the post as indexed
                 if ($flagAsIndexed) {
                     // clean up our stored term array if necessary
                     if ($termCache) {
                         delete_post_meta($this->post->ID, '_' . SEARCHWP_PREFIX . 'terms');
                     }
                     // clean up the attempt counter
                     delete_post_meta($this->post->ID, '_' . SEARCHWP_PREFIX . 'attempts');
                     delete_post_meta($this->post->ID, '_' . SEARCHWP_PREFIX . 'skip');
                     update_post_meta($this->post->ID, '_' . SEARCHWP_PREFIX . 'indexed', true);
                     update_post_meta($this->post->ID, '_' . SEARCHWP_PREFIX . 'last_index', current_time('timestamp'));
                 }
             }
             next($this->unindexedPosts);
         }
         reset($this->unindexedPosts);
         do_action('searchwp_indexer_post_chunk');
     }
 }
Exemplo n.º 27
0
 /**
  * This function takes the combined pdf and embeds all the comments and annotations.
  * @param int|\assign $assignment
  * @param int $userid
  * @param int $attemptnumber (-1 means latest attempt)
  * @return stored_file
  */
 public static function generate_feedback_document($assignment, $userid, $attemptnumber)
 {
     $assignment = self::get_assignment_from_param($assignment);
     if (!$assignment->can_view_submission($userid)) {
         \print_error('nopermission');
     }
     if (!$assignment->can_grade()) {
         \print_error('nopermission');
     }
     // Need to generate the page images - first get a combined pdf.
     $file = self::get_combined_pdf_for_attempt($assignment, $userid, $attemptnumber);
     if (!$file) {
         throw new \moodle_exception('Could not generate combined pdf.');
     }
     $tmpdir = \make_temp_directory('assignfeedback_editpdf/final/' . self::hash($assignment, $userid, $attemptnumber));
     $combined = $tmpdir . '/' . self::COMBINED_PDF_FILENAME;
     $file->copy_content_to($combined);
     // Copy the file.
     $pdf = new pdf();
     $fs = \get_file_storage();
     $stamptmpdir = \make_temp_directory('assignfeedback_editpdf/stamps/' . self::hash($assignment, $userid, $attemptnumber));
     $grade = $assignment->get_user_grade($userid, true, $attemptnumber);
     // Copy any new stamps to this instance.
     if ($files = $fs->get_area_files($assignment->get_context()->id, 'assignfeedback_editpdf', 'stamps', $grade->id, "filename", false)) {
         foreach ($files as $file) {
             $filename = $stamptmpdir . '/' . $file->get_filename();
             $file->copy_content_to($filename);
             // Copy the file.
         }
     }
     $pagecount = $pdf->set_pdf($combined);
     $grade = $assignment->get_user_grade($userid, true, $attemptnumber);
     page_editor::release_drafts($grade->id);
     for ($i = 0; $i < $pagecount; $i++) {
         $pdf->copy_page();
         $comments = page_editor::get_comments($grade->id, $i, false);
         $annotations = page_editor::get_annotations($grade->id, $i, false);
         foreach ($comments as $comment) {
             $pdf->add_comment($comment->rawtext, $comment->x, $comment->y, $comment->width, $comment->colour);
         }
         foreach ($annotations as $annotation) {
             $pdf->add_annotation($annotation->x, $annotation->y, $annotation->endx, $annotation->endy, $annotation->colour, $annotation->type, $annotation->path, $stamptmpdir);
         }
     }
     fulldelete($stamptmpdir);
     $filename = self::get_downloadable_feedback_filename($assignment, $userid, $attemptnumber);
     $filename = clean_param($filename, PARAM_FILE);
     $generatedpdf = $tmpdir . '/' . $filename;
     $pdf->save_pdf($generatedpdf);
     $record = new \stdClass();
     $record->contextid = $assignment->get_context()->id;
     $record->component = 'assignfeedback_editpdf';
     $record->filearea = self::FINAL_PDF_FILEAREA;
     $record->itemid = $grade->id;
     $record->filepath = '/';
     $record->filename = $filename;
     // Only keep one current version of the generated pdf.
     $fs->delete_area_files($record->contextid, $record->component, $record->filearea, $record->itemid);
     $file = $fs->create_file_from_pathname($record, $generatedpdf);
     // Cleanup.
     @unlink($generatedpdf);
     @unlink($combined);
     @rmdir($tmpdir);
     return $file;
 }
Exemplo n.º 28
0
 public function _getfontpath()
 {
     return parent::_getfontpath();
 }
					}
					else
						$i=$sep+1;
					$sep=-1;
					$j=$i;
					$l=0;
					$nl++;
				}
				else
					$i++;
			}
			return $nl;
		}
	}
	
	$pdf = new pdf();
	$pdf->AliasNbPages();		
	
	$s = "SELECT gv.id as guia, DATE_FORMAT(gv.fecha,'%d/%m/%Y') as fecha,
	CONCAT_WS(' ', cc.nombre,cc.paterno,cc.materno) AS cliente,
	cs.prefijo AS destino, gv.total AS importe, gv.idusuario,
	CONCAT_WS(' ',ce.nombre,ce.apellidopaterno,ce.apellidomaterno) as empleado, if(gv.ocurre=1,'Ocurre','EAD') ocurre
	FROM guiasventanilla gv
	INNER JOIN catalogosucursal cs ON gv.idsucursaldestino = cs.id	
	LEFT JOIN catalogoempleado ce ON gv.idusuario = ce.id";
	
	//1) GUIAS CONTADO
	$criterioguiascontado = " INNER JOIN catalogocliente cc ON gv.idremitente = cc.id 
	WHERE gv.id like '%A' AND gv.tipoflete = 0 AND gv.condicionpago = 0 AND gv.idsucursalorigen = ".$_GET[sucursal]." 
	AND gv.fecha BETWEEN '".cambiaf_a_mysql($_GET[fechainicio])."' AND '".cambiaf_a_mysql(((!empty($_GET[fechafin]))?$_GET[fechafin]:$_GET[fechainicio]))."'
	AND gv.estado<>'CANCELADO' ORDER BY gv.idusuario";
                    }
                } else {
                    $i = $sep + 1;
                }
                $sep = -1;
                $j = $i;
                $l = 0;
                $nl++;
            } else {
                $i++;
            }
        }
        return $nl;
    }
}
$pdf = new pdf('L', 'mm', 'A4');
$pdf->AliasNbPages();
//$titulos = array('GUIA','DESTINATARIO','DESC./CONT.','PESO','PAGADO','COBRAR','EMB','DEFECTO');
$medidas = array(25, 70, 70, 20, 22, 25, 15, 20);
$pdf->AddPage();
$pdf->SetFont('Arial', 'B', 9);
//Table with 20 rows and 4 columns
$pdf->SetWidths($medidas);
$pdf->Titulos($titulos, $medidas);
$pdf->SetFont('Arial', '', 9);
for ($i = 0; $i < count($data); $i++) {
    $pdf->Row($data[$i]);
}
$pdf->MultiCell(0, 5, 'Contrato de prestación de servicios que celebra por una parte PAQUETERIA Y MENSAJERIA EN MOVIMIENTO, S.A. DE C.V, a quien en lo sucesivo se le denominará "La Prestadora de Servicios",      y      por    otra    parte  ' . $f->ncliente . '   representada por  ' . $f->representante . ' a quien en lo sucesivo se le denominará "El Cliente".', 0, 'J');
$pdf->MultiCell(0, 5, '', 0, 'J');
$pdf->MultiCell(0, 10, '1.- La Prestadora de Servicios otorgará a "El Cliente" los siguientes servicios:', 0, 'J');