MIOLO20
Carregando...
Procurando...
Nenhuma entrada encontrada
mjasperreport.class
Ir para a documentação deste ficheiro.
1<?php
2
3class MJasperReport extends MReport
4{
8 const JAVA_BIG_DECIMAL = 'java.math.BigDecimal';
9 const JAVA_BOOLEAN = 'java.lang.Boolean';
10 const JAVA_DATE = 'java.util.Date';
11 const JAVA_DOUBLE = 'java.lang.Double';
12 const JAVA_FLOAT = 'java.lang.Float';
13 const JAVA_INTEGER = 'java.lang.Integer';
14 const JAVA_LONG = 'java.lang.Long';
15 const JAVA_NUMBER = 'java.lang.Number';
16 const JAVA_SHORT = 'java.lang.Short';
17 const JAVA_STRING = 'java.lang.String';
18 const JAVA_TIME = 'java.sql.Time';
19 const JAVA_TIMESTAMP = 'java.sql.Timestamp';
20
24 const TYPE_BOOLEAN = 'boolean';
25 const TYPE_DATE = 'date';
26 const TYPE_FLOAT = 'float';
27 const TYPE_INTEGER = 'integer';
28 const TYPE_STRING = 'string';
29 const TYPE_TIME = 'time';
30 const TYPE_TIMESTAMP = 'timestamp';
31
32 public $filetype; // pdf doc xls rtf htm rpt
33 public $fileout;
34 public $fileexp;
35 public $objDb;
36 public $db;
38
39 private $arquivoRecemGerado;
40 private $javaPath;
41 private $absoluteFileOut;
42
43 const FIND_JAVA_PATH_COMMAND = 'echo $JAVA_HOME';
44
45 public function __construct($db = 'admin', $connectionType = 'local')
46 {
48
49 $this->db = $db;
50 $this->connectionType=$connectionType;
51
52 if ( $MIOLO->getConf('home.java') )
53 {
54 $this->javaPath = $MIOLO->getConf('home.java');
55 }
56 else
57 {
58 $this->javaPath = trim(shell_exec(self::FIND_JAVA_PATH_COMMAND));
59 }
60 }
61
62 public function getArquivoRecemGerado()
63 {
64 return $this->arquivoRecemGerado;
65
66 }
67
68 public function setArquivoRecemGerado($arquivoRecemGerado)
69 {
70 $this->arquivoRecemGerado = $arquivoRecemGerado;
71 }
72
73 public function execute($module, $name, $parameters = null, $filetype = 'PDF')
74 {
76 $page = $MIOLO->getPage();
77
78 $this->filetype = isset($filetype) ? $filetype : 'PDF';
79
80 $filein = addslashes($MIOLO->GetModulePath($module, 'reports/' . $name . '.jasper'));
81
82 $uniqid = uniqid(md5(uniqid("")));
83 $this->fileout= $uniqid . "." . strtolower($this->filetype);
84 $pathout = $MIOLO->getConf("home.reports") .'/'.$this->fileout;
85
86 $this->absoluteFileOut = $pathout;
87
88 $pathMJasper = $MIOLO->getConf("home.extensions")."/jasper";
89 $pathLibs = "$pathMJasper/lib/deps/*:$pathMJasper/lib/ext/*:$pathMJasper/lib/ireport/*:$pathMJasper/lib/jasperreports/*";
90 $classPath = "$pathLibs:$pathMJasper/:$this->javaPath/lib";
91
92 return $this->fill($filein, $pathout, $filetype, $parameters, $classPath);
93
94 }
95
96 public function fill($fileIn, $fileOut, $filetype, $parameters, $classPath, $download = true)
97 {
98 $this->beforeGenerateReport();
99
101 $page = $MIOLO->getPage();
102
103 if ($this->connectionType=='local')
104 {
105 //Solution without TomCat
106 $param = "";
107 if (is_array($parameters))
108 {
109 foreach ($parameters as $pn => $pv)
110 {
111 $param .= '&' . $pn . "~" . $pv;
112 }
113 }
114
115 $this->objDb = $MIOLO->GetDatabase($this->db);
116 $dbUser = $this->objDb->user;
117 $dbPass = $this->objDb->pass;
118 $dbHost = $this->objDb->host;
119 $dbName = $this->objDb->db;
120 $dbPort = $this->objDb->port;
121
122 if ( $this->objDb->system == 'postgres' )
123 {
124 $jdbcDriver = 'org.postgresql.Driver';
125 $dbPort = $dbPort ? $dbPort : '5432';
126 $jdbcDb = "jdbc:postgresql://{$dbHost}:{$dbPort}/{$dbName}";
127 }
128 elseif ( $this->objDb->system == 'mysql' )
129 {
130 $jdbcDriver = 'com.mysql.jdbc.Driver';
131 $dbPort = $dbPort ? $dbPort : '3306';
132 $jdbcDb = "jdbc:mysql://{$dbHost}:{$dbPort}/{$dbName}";
133 }
134 else
135 {
136 $jdbcDriver = 'org.postgresql.Driver';
137 $jdbcDb = "jdbc:postgresql://localhost:5432/postgres";
138 $dbUser = "postgres";
139 $dbPass = "postgres";
140 }
141
142 // Change directory to get the report images from the same place the report is located
143 $pathInfo = pathinfo($fileIn);
144 chdir(realpath($pathInfo['dirname']));
145
146 $param = "relatorio~$fileIn".$param."&fileout~".$fileOut."&filetype~".$this->filetype;
147
148 $pathLog = $MIOLO->GetConf('home.logs');
149 $fileLogTmp = '/tmp/' . uniqid(md5(uniqid(""))) . '.txt';
150 $fileLog = "mjasperreport.log";
151
152 $this->javaPath = $this->javaPath ? $this->javaPath . '/bin/java' : 'java'; //if JAVA_HOME is unsetted, get java from default path
153
154 $lang = $MIOLO->getConf('i18n.language');
155
156 // Corrige problema de acentuacao que estava ocorrendo
157 if ( !stripos($lang, 'utf') && !stripos($lang, 'iso') )
158 {
159 $lang .= '.UTF-8';
160 }
161
162 $cmd = "export LANG=$lang; " . $this->javaPath . " -Xms2g -Xmx2g -XX:-UseGCOverheadLimit -classpath $classPath MJasper \"{$pathMJasper}\" \"{$param}\" \"{$dbUser}\" \"{$dbPass}\" \"{$jdbcDriver}\" \"{$jdbcDb}\"";
163 $cmd .= " 2>> $fileLogTmp";
164 exec($cmd,$output);
165
166 //JAVA application without erros!
167 if (trim($output[0])=="end")
168 {
169 $this->afterGenerateReport();
170
171 //Break line incompatibility problem with Windows and Unix
172// if (strtoupper(trim($this->filetype))=="TXT") Mutil::unix2dos($fileOut);
173
174 // if HTML, redirects the page to the report URL to see the HTML images
175 if ( strtoupper(trim($this->filetype)) == 'HTML' )
176 {
177 $fileData = pathinfo($fileOut);
178 $fileName = $fileData['basename'];
179 $visibleFile = $MIOLO->getConf("home.html") . "/reports/$fileName";
180 copy($fileOut, $visibleFile);
181
182 // FIXME: find a way for opening the URL in another tab or window
183 if ($download)
184 {
185 $MIOLO->page->redirect($MIOLO->getConf('home.url') . "/reports/$fileName");
186 }
187 }
188 else
189 {
190 $fileDown = null;
191
192 // Quando for uma das extensoes abaixo, forca download
193 if ( in_array(strtoupper(trim($this->filetype)), array('TXT','XLS')) )
194 {
195 $fileDown = $fileOut;
196 }
197
198 if( $download )
199 {
200 $MIOLO->sendFile($fileOut, $fileDown);
201 }
202
203 }
204
205 $this->arquivoRecemGerado = $fileOut;
206
207 return 1;
208 }
209 elseif ( trim($output[0]) == 'empty' )
210 {
211 return 0;
212 }
213 else
214 {
215 $logerror .= file_get_contents($fileLogTmp);
216 $detalhes = _M("Ocorreu um erro durante a geração do relatório.");
217 $detalhes .= "<br/>Detalhes do erro:<br/> ";
218 $detalhes .= $logerror;
219 $detalhes .= trim(implode("\n",$output));
220
221 if ( $output != 'null' )
222 {
223 $file = fopen("$pathLog/$fileLog", 'a+');
224 $error = implode("\n\n", $output) . "\n" . $logerror;
225 fwrite($file, "\n\n$error");
226 fclose($file);
227 }
228
229 throw new EControlException($detalhes);
230 }
231
232 }
233 else if ($this->connectionType=='remote')
234 {
235 //TomCat
236 $this->fileout = $MIOLO->getConf("home.url_jasper"). "?bd={$this->db}&relatorio=$filein" . $param;
237 $MIOLO->getPage()->window($this->fileout);
238 }
239 }
240
251 public function executeJRXML($fileIn, $parameters=NULL, $filetype='PDF', $download = true)
252 {
254
255 $this->filetype = isset($filetype) ? $filetype : 'PDF';
256
257 $uniqid = current(explode('.', basename($fileIn)));
258 $uniqid .= '_' . uniqid(md5(uniqid(rand(), true)));
259 $pathout = null;
260
261 for ( $count = 1; ( file_exists($pathout) || ( $pathout === null ) ); $count ++ )
262 {
263 $this->fileout = $uniqid . $count . '.' . strtolower($this->filetype);
264 $pathout = $MIOLO->getConf('home.reports') . '/' . $this->fileout;
265
266 $this->absoluteFileOut = $pathout;
267 }
268
269 $pathMJasper = $MIOLO->getConf("home.extensions")."/jasper";
270 $pathLibs = "$pathMJasper/lib/deps/*:$pathMJasper/lib/ext/*:$pathMJasper/lib/ireport/*:$pathMJasper/lib/jasperreports/*";
271 $classPath = "$pathLibs:$pathMJasper/:$this->javaPath/lib";
272
273 return $this->fill($fileIn, $pathout, $this->filetype, $parameters, $classPath, $download);
274 }
275
282 private static function getTypeFromJavaType($javaType)
283 {
284 switch ( $javaType )
285 {
287 $type = self::TYPE_BOOLEAN;
288 break;
289
290 case self::JAVA_DATE:
291 $type = self::TYPE_DATE;
292 break;
293
296 case self::JAVA_FLOAT:
298 $type = self::TYPE_FLOAT;
299 break;
300
302 case self::JAVA_LONG:
303 case self::JAVA_SHORT:
304 $type = self::TYPE_INTEGER;
305 break;
306
307 case self::JAVA_TIME:
308 $type = self::TYPE_TIME;
309 break;
310
312 $type = self::TYPE_TIMESTAMP;
313 break;
314
316 default:
317 $type = self::TYPE_STRING;
318 break;
319 }
320
321 return $type;
322 }
323
343 public static function getParametersFromFile($reportFile)
344 {
345 if ( !file_exists($reportFile) )
346 {
347 return NULL;
348 }
349
350 $xml = simplexml_load_file($reportFile);
351
352 $parameters = array();
353
354 foreach ( $xml->parameter as $parameter )
355 {
356 // Create an array to represent a parameter
357 $p = array();
358 $name = (string) $parameter->attributes()->name;
359
360 // Put the simplified parameter type on "type" attribute
361 $javaType = (string) $parameter->attributes()->class;
362 $p['type'] = self::getTypeFromJavaType($javaType);
363
364 // Iterate through parameter properties to set them on the array
365 foreach ( $parameter->property as $property )
366 {
367 $key = (string) $property->attributes()->name;
368 $value = (string) $property->attributes()->value;
369 if( empty($value) )
370 {
371 $value = (string) $property;
372 }
373
374 $p[$key] = $value;
375 }
376
377 $parameters[$name] = $p;
378 }
379
380 return $parameters;
381 }
382
392 public static function getParameterFields($reportFile)
393 {
395
396 $parameters = self::getParametersFromFile($reportFile);
397 $file = pathinfo($reportFile);
398 $ids = array();
399 $validators = array();
400
401 if ( is_array($parameters) )
402 {
403 foreach ( $parameters as $id => $parameter )
404 {
405 // Put id prefixes for Jasper
406 switch ( $parameter['type'] )
407 {
409 $type = 'boo';
410 break;
411
413 $type = 'dbl';
414 break;
415
417 $type = 'int';
418 break;
419
421 $type = 'tsp';
422 break;
423
427 default:
428 $type = 'str';
429 break;
430 }
431
432 $types[$id] = $type;
433 }
434
435 foreach ( $parameters as $id => $parameter )
436 {
437 if ( strlen($parameter['nome']) )
438 {
439 $label = $parameter['nome'];
440 }
441 else
442 {
443 $label = $parameter['label'];
444 }
445
446 if ( !$label )
447 {
448 $label = ucfirst($id);
449 }
450
451 $newId = "{$types[$id]}_$id";
452
453 list($id, $field, $validator) = self::generateFieldFromParameter($newId, $id, $parameter, $label, $types);
454
455 $ids[] = $id;
456 $fields[] = $field;
457
458 if ( $validator )
459 {
460 $validators[] = $validator;
461 }
462 }
463
464 unset( $_SESSION['deleteReport']);
465 }
466 return array($ids, $fields, $validators);
467 }
468
482 public static function generateFieldFromParameter($id, $oldId, $parameter, $label, $types)
483 {
484 $field = NULL;
485 $validator = NULL;
487
488 if ( $parameter['required'] == 't' )
489 {
490 $validator = new MRequiredValidator($id, $label);
491 }
492
493 $control = strlen($parameter['tipo']) ? $parameter['tipo'] : $parameter['control'];
494
495 if ( $control )
496 {
497 switch ( $control )
498 {
499 case 'lookup':
500
501 $related = NULL;
502
503 if ( isset($parameter['related']) )
504 {
505 $related = array();
506
507 $relateds = explode(',', $parameter['related']);
508
509 foreach ( $relateds as $r )
510 {
511 if ( $r == "{$oldId}_Description" )
512 {
513 $related[] = "str_{$oldId}_Description";
514 }
515 elseif ( $types[$r] )
516 {
517 $related[] = "{$types[$r]}_$r";
518 }
519 else
520 {
521 $related[] = "str_$r";
522 }
523 }
524
525 if ( count($related) > 1 )
526 {
527 $descriptionField = "str_{$oldId}_Description";
528 }
529 else
530 {
531 $descriptionField = $related[0];
532 }
533
534 $related = implode(',', $related);
535 }
536
537 $filter = array();
538 if ( isset($parameter['filter']) )
539 {
540 $filters = explode(',', $parameter['filter']);
541
542 foreach ( $filters as $filts )
543 {
544 $filter[$filts] = 'str_' . $filts;
545 }
546 }
547
548 $module = $parameter['module'];
549 $item = $parameter['item'];
550
551 if ( $descriptionField == NULL )
552 {
553 $descriptionField = "str_{$oldId}_Description";
554 }
555
556 $field = new MLookupContainer($id, $descriptionField, NULL, $label, $related, $module, $item, $filter);
557 $field->getDescriptionField()->hint = $parameter['hint'];
558
559 if ( $parameter['required'] == 't' )
560 {
561 $field->showRequiredLabel = true;
562 }
563
564 if ( $parameter['forceAutoComplete'] == 't' )
565 {
566 $jsCode = " function forceAutoComplete()
567 {
568 var valor = document.getElementById('{$id}').value;
569 document.getElementById('{$descriptionField}').focus();
570 document.getElementById('{$id}').focus();
571
572 setTimeout(function() { document.getElementById('{$id}').value = valor; }, 500);
573 } ";
574 $MIOLO->page->addJsCode($jsCode);
575
576 // Para forçar o auto complete da lookup, quando clicado diretamente na geração do relatório sem que tenha carregado os novos filtros de busca da lookup
577 // ver ticket #41328
578 $field->addAttribute('onkeyup', " javascript:forceAutoComplete(); ");
579 }
580
581 break;
582
583 case 'escolha':
584 // este componente funciona apenas no SAGU
585 // portanto, tenha cautela ao utilizar
586
587 // obtem o nome do type utilizado (pode ser encontrado dentro de modules/MODULO/types/TYPE no SAGU)
588 $item = $parameter['item'];
589
590 // Pega as chaves do array de parâmetros
591 $keys = array_keys($parameter);
592
593 $typeArgs = array();
594
595 foreach( $keys as $key )
596 {
597 // Se é um parâmetro (identificado pelo prefixo p_)
598 if( strpos($key, "p_") === 0 )
599 {
600 $propriedade = substr($key, 2);
601
602 // Cria uma posição no array de argumentos
603 // nome da propriedade do type = valor definido no
604 // relatório
605 $typeArgs[$propriedade] = $parameter[$key];
606
607 }
608
609 }
610
611 if (isset($parameter['query']))
612 {
613 // instancia type magicamente
614 $typeInstance = new BasGenericType();
615
616 // Instancia as propriedades informadas no type
617 foreach( $typeArgs as $propriedade => $valor)
618 {
619 $typeInstance->$propriedade = $valor;
620
621 }
622
623 // instancia componente de escolha
624 $field = new sEscolha($id, NULL, $label, $typeInstance, $parameter['hint'], null, $parameter['query']);
625 }
626 else
627 {
628 // instancia type magicamente
629 $typeInstance = new $item();
630
631 // Instancia as propriedades informadas no type
632 foreach( $typeArgs as $propriedade => $valor)
633 {
634 $typeInstance->$propriedade = $valor;
635
636 }
637
638 $field = new sEscolha($id, NULL, $label, $typeInstance, $parameter['hint']);
639 }
640
641 break;
642
643 case 'combobox':
644 case 'selection':
645 if ( $parameter['query'] )
646 {
647 if ( ! $_SESSION['deleteReport'] )
648 {
649 $options = self::executarQuery($parameter['query'], $parameter['module']);
650 }
651 }
652 elseif ( $parameter['options'] )
653 {
654 foreach(explode(';',$parameter['options']) as $k=>$params)
655 {
656 $value = explode('=',trim($params));
657 if($value[1])
658 {
659 $options[$k][0] = $value[0];
660 $options[$k][1] = $value[1];
661 }
662 }
663 }
664
665 $field = ( $control == 'selection' ) ? new MSelection($id, NULL, $label, $options, false, $parameter['hint']) : new MComboBox($id, null, $label, $options, false, $parameter['hint']);
666 break;
667
668 case 'radio':
669 if ( $parameter['query'] )
670 {
671 if ( ! $_SESSION['deleteReport'] )
672 {
673 $options = self::executarQuery($parameter['query'], $parameter['module']);
674 }
675 }
676 elseif ( $parameter['options'] )
677 {
678 foreach(explode(';',$parameter['options']) as $k=>$params)
679 {
680 $value = explode('=',trim($params));
681 if($value[1])
682 {
683 $options[$k][0] = $value[1];
684 $options[$k][1] = $value[0];
685 }
686 }
687 }
688
689 $field = new MRadioButtonGroup($id, $label, $options, null, $parameter['hint']);
690 break;
691
692 case 'lista':
693 $common = $MIOLO->getConf('options.common');
694 $modulesPath = $MIOLO->getConf('home.modules');
695
696 $class = "$modulesPath/$common/classes/reportList.class";
697
698 if ( !file_exists($class) )
699 {
700 continue;
701 }
702
703 $MIOLO->uses('classes/reportList.class', $common);
704
705 $options = reportList::search($parameter['dados']);
706 $field = new MSelection($id, NULL, $label, $options, false, $parameter['hint']);
707 break;
708
709 case 'calendário':
710 case 'calendario':
711 case 'calendar':
712 $field = new MCalendarField($id, $value, $label, 20, $parameter['hint']);
713 $typeInstance = 'optional';
714 if ( $parameter['required'] == 't' )
715 {
716 $field->setIsRequired(true);
717 $typeInstance = 'required';
718 $field->validator->type = 'required';
719 }
720 $validator = new MDateDMYValidator($id, $label, $typeInstance);
721 break;
722
723 case 'boolean':
724 $listNoYes = array(
725 'f' => _M('No'),
726 't' => _M('Yes'),
727 );
728
729 $field = new MSelection($id, NULL, $label, $listNoYes, false, $parameter['hint']);
730
731 if ( $parameter['required'] == 't' )
732 {
733 $field->validator->type = 'required';
734 }
735 break;
736
737 case 'dicionarioDeCampos':
738 case 'dicionariodecampos':
739
745 try
746 {
747 list ( $field, $validator ) = SDicionarioDeCampos::obterCampo($oldId);
748 }
749 catch (Exception $ex)
750 {
751 $field = new MHiddenField('limbo');
752 }
753
754 break;
755
756 case 'text':
757 $field = new MTextField($id, NULL, $label, 10, $parameter['hint']);
758
759 break;
760
761 case 'hidden':
762 $field = new SHiddenField(substr($id, 4), $parameter['value']);
763
764 break;
765
766 default:
767 $field = new $control();
768
769 if ( property_exists($field, 'hint') )
770 {
771 $field->hint = $parameter['hint'];
772 }
773
774 if ( $parameter['required'] == 't' && method_exists($field, 'showRequiredLabel') )
775 {
776 $field->showRequiredLabel();
777 }
778
779 break;
780 }
781 }
782 else
783 {
784 switch ( $parameter['type'] )
785 {
787 $listNoYes = array(
788 'f' => _M('No'),
789 '1' => _M('Yes'),
790 );
791
792 $field = new MSelection($id, NULL, $label, $listNoYes, false, $parameter['hint']);
793 break;
794
796 $field = new MCalendarField($id, $value, $label, 20, $parameter['hint']);
797
798 if ( $parameter['required'] == 't' )
799 {
800 $field->validator->type = 'required';
801 $validator = NULL;
802 }
803 break;
804
806 $field = new MFloatField($id, NULL, $label, 10, $parameter['hint']);
807 break;
808
810 $field = new MTextField($id, NULL, $label, 10, $parameter['hint']);
811 $validatorType = $parameter['required'] == 't' ? 'required' : 'optional';
812 $validator = new MIntegerValidator($id, $label, $validatorType);
813 break;
814
818 default:
819 $field = new MTextField($id, NULL, $label, 10, $parameter['hint']);
820 break;
821 }
822 }
823
824 return array($id, $field, $validator);
825 }
826
834 public static function getParameterValues($parameters, $data)
835 {
836 $values = array();
837
838 foreach ( $parameters as $id )
839 {
840 if ( !is_null($data->$id) && $data->$id != '' )
841 {
842 $values[$id] = $data->$id;
843 }
844 }
845
846 return $values;
847 }
848
854 public function getAbsoluteFileOut()
855 {
856 return $this->absoluteFileOut;
857 }
858
859 public function setAbsoluteFileOut($absoluteFileOut)
860 {
861 $this->absoluteFileOut = $absoluteFileOut;
862 }
863
867 public function beforeGenerateReport()
868 {
869 }
870
874 public function afterGenerateReport()
875 {
876 }
877
881 public static function executarQuery($query, $module = null)
882 {
884 $isSAGU = $MIOLO->getConf('temp.is.from.sagu');
885
886 if ( $isSAGU )
887 {
888 $database = SDatabase::getInstance();
889 }
890 else
891 {
892 $dbconf = strlen($module) > 0 ? $module : 'admin';
893 $database = $MIOLO->getDatabase($dbconf);
894 }
895
896 return $database->query($query);
897 }
898}
899
900?>
static getInstance()
Definição miolo.class:134
static getParametersFromFile($reportFile)
executeJRXML($fileIn, $parameters=NULL, $filetype='PDF', $download=true)
const JAVA_BIG_DECIMAL
const FIND_JAVA_PATH_COMMAND
fill($fileIn, $fileOut, $filetype, $parameters, $classPath, $download=true)
setArquivoRecemGerado($arquivoRecemGerado)
static getParameterValues($parameters, $data)
static generateFieldFromParameter($id, $oldId, $parameter, $label, $types)
static getParameterFields($reportFile)
setAbsoluteFileOut($absoluteFileOut)
execute($module, $name, $parameters=null, $filetype='PDF')
__construct($db='admin', $connectionType='local')
static executarQuery($query, $module=null)
$lang
Definição base.php:6
$id
Definição base.php:5