| Current Path : /home/bonneesp/www/administrator/components/com_tabulizer/assets/classes/dialog/ |
| Current File : /home/bonneesp/www/administrator/components/com_tabulizer/assets/classes/dialog/exportdata.php |
<?php
/**
* @version 6.5.0 tabulizer $
* @package tabulizer
* @copyright Copyright © 2011 - All rights reserved.
* @license GNU/GPL
* @author Dimitrios Mourloukos
* @author mail info@alterora.gr
* @website www.tabulizer.com
*
*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
// increase memory and execution time limits
TabulizerPerformance::increaseProcessingLimits();
class ExportData {
var $form_prefix = null;
var $export_source = null;
var $export_type = null;
var $export_output = null;
var $export_data = null;
var $export_filename = null;
var $export_email_recipients = null;
var $export_email_subject = null;
var $export_email_body = null;
var $export_dir = null;
function getExportParams(&$error_msg) {
$this->form_prefix = $_REQUEST['form_prefix'];
if (empty($this->form_prefix)) {
$error_msg = 'The form prefix is empty!';
return false;
} else {
$form_prefix = $this->form_prefix;
}
if (!empty($_REQUEST[$form_prefix . '_exportsource']))
$this->export_source = urldecode($_REQUEST[$form_prefix . '_exportsource']);
if (!empty($_REQUEST[$form_prefix . '_exporttype']))
$this->export_type = $_REQUEST[$form_prefix . '_exporttype'];
if (!empty($_REQUEST[$form_prefix . '_exportoutput']))
$this->export_output = $_REQUEST[$form_prefix . '_exportoutput'];
if (!empty($_REQUEST[$form_prefix . '_exportdata'])) {
$this->export_data = urldecode($_REQUEST[$form_prefix . '_exportdata']);
// handle magic quotes
if (get_magic_quotes_gpc()) {
$this->export_data = stripslashes($this->export_data);
}
}
if (!empty($_REQUEST[$form_prefix . '_exportfile'])) {
$this->export_filename = urldecode($_REQUEST[$form_prefix . '_exportfile']);
}
if (empty($this->export_filename)) {
if (!empty($_REQUEST[$form_prefix . '_datasourcetag'])) {
TabulizerPath::requireLib('data_source','common');
$data_source_tag = $_REQUEST[$form_prefix . '_datasourcetag'];
$data_source_user_params = $_REQUEST[$form_prefix . '_dsuserparams'];
// get header row(s) first
$errors = array();
$params = null;
$search_filters = array();
$results = TabulizerDataSource::getDataSourceContents($data_source_tag, $data_source_user_params, $search_filters, $params, $errors);
if (empty($results)) {
$this->export_data = $error_msg;
} else {
$delimiter = ',';
// open raw memory as file, no need for temp files, be careful not to run out of memory thought */
$f = fopen('php://memory', 'w');
foreach ($results['rows'] as $line) {
fputcsv($f, $line, $delimiter);
}
// rewind the "file" with the csv lines
fseek($f, 0);
$this->export_data = stream_get_contents($f);
}
// now, get the rest of the data
$server_side = empty($params['server_side'])?false:true;
if ($server_side) {
// now, get the rest of the data
$results = $this->getFilteredServerSideData($data_source_tag, $data_source_user_params, $error_msg);
if (empty($results)) {
$this->export_data = $error_msg;
} else {
$delimiter = ',';
// open raw memory as file, no need for temp files, be careful not to run out of memory thought */
$f = fopen('php://memory', 'w');
foreach ($results['rows'] as $line) {
fputcsv($f, $line, $delimiter);
}
// rewind the "file" with the csv lines
fseek($f, 0);
$this->export_data .= stream_get_contents($f);
}
} else {
$errors = array();
$params = null;
$search_filters = array('all'=>1);
$results = TabulizerDataSource::getDataSourceContents($data_source_tag, $data_source_user_params, $search_filters, $params, $errors);
if (empty($results)) {
$this->export_data = $error_msg;
} else {
$delimiter = ',';
// open raw memory as file, no need for temp files, be careful not to run out of memory thought */
$f = fopen('php://memory', 'w');
foreach ($results['rows'] as $line) {
fputcsv($f, $line, $delimiter);
}
// rewind the "file" with the csv lines
fseek($f, 0);
$this->export_data .= stream_get_contents($f);
}
}
}
}
$email_export_permissions = TabulizerPermissions::getExportDataPermissions();
$allow_recipients = $email_export_permissions['allow_recipients'];
$allow_subject = $email_export_permissions['allow_subject'];
$allow_body = $email_export_permissions['allow_body'];
if (!empty($_REQUEST[$form_prefix . '_exportemail_recipients']) && $allow_recipients) {
$this->export_email_recipients = urldecode($_REQUEST[$form_prefix . '_exportemail_recipients']);
$recipients = explode(',',$this->export_email_recipients);
$this->export_email_recipients = array();
$regex = '/^[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4}$/i';
if (!empty($recipients)) {
foreach ($recipients as $recipient) {
$recipient = trim($recipient);
if (preg_match($regex, $recipient)) $this->export_email_recipients[] = $recipient;
if (count($this->export_email_recipients)>EXPORT_TABLE_EMAIL_RECIPIENTS_MAX_NUM) break;
}
}
}
if (!empty($_REQUEST[$form_prefix . '_exportemail_subject']) && $allow_subject) {
$this->export_email_subject = urldecode($_REQUEST[$form_prefix . '_exportemail_subject']);
// handle magic quotes
if (get_magic_quotes_gpc()) {
$this->export_email_subject = stripslashes($this->export_email_subject);
}
if (mb_strlen($this->export_email_subject)>EXPORT_TABLE_EMAIL_SUBJECT_MAX_SIZE) $this->export_email_subject = mb_substr($this->export_email_subject,0,EXPORT_TABLE_EMAIL_SUBJECT_MAX_SIZE);
}
if (!empty($_REQUEST[$form_prefix . '_exportemail_body']) && $allow_body) {
$this->export_email_body = urldecode($_REQUEST[$form_prefix . '_exportemail_body']);
// handle magic quotes
if (get_magic_quotes_gpc()) {
$this->export_email_body = stripslashes($this->export_email_body);
}
if (mb_strlen($this->export_email_body)>EXPORT_TABLE_EMAIL_BODY_MAX_SIZE) $this->export_email_body = mb_substr($this->export_email_body,0,EXPORT_TABLE_EMAIL_BODY_MAX_SIZE);
}
$this->export_dir = TabulizerPath::getDirPath('temp');
// do some sanity checks on filename, if present
if (!empty($this->export_filename)) {
$filename_pattern = '/^([a-z0-9_\.]{2,128})$/i';
if (!preg_match($filename_pattern, $this->export_filename)) {
$error_msg = "Invalid filename {$this->export_filename} for the temporary export file!";
return false;
}
$export_filename = $this->export_dir . $this->export_filename;
if (!file_exists($export_filename)) {
$error_msg = "Temporary export file not found or could not be opened!";
return false;
}
$this->export_data = file_get_contents($export_filename);
if (empty($this->export_data)) {
$error_msg = "Temporary export file contained no data!";
return false;
}
}
return true;
}
function removeExportFile() {
$export_filename = $this->export_dir . $this->export_filename;
if (file_exists($export_filename)) {
@unlink($export_filename);
return true;
} else return false;
}
function getFilteredServerSideData($data_source_tag, $data_source_user_params, &$error_msg) {
TabulizerPath::requireLib('tabulizer','common');
$tab = new Tabulizer();
TabulizerPath::requireLib('server_side','common');
$server_side_helper = new ServerSideHelper($data_source_tag, $data_source_user_params);
$server_side_helper->getQueryParams($server_side_query);
$errors = array();
$params = null;
$search_filters = array('all' => 1);
if (!empty($server_side_query)) {
TabulizerPath::requireLib('data_source','common');
$results = TabulizerDataSource::getDataSourceContents($data_source_tag, $data_source_user_params, $search_filters, $params, $errors);
if (empty($results)) {
$error_msg = JText::_('COM_TABULIZER_DATA_SOURCE_ERROR_CAPTION');
return false;
} else {
if (!empty($params['consistency'])) $tab->setColumnConsistency(true);
$rows = &$results['rows'];
$total_records = $results['total_rows'];
$total_display_records = $results['total_rows'];
$offset = 0;
$length = 0;
if (!empty($server_side_query['search'])) {
$unset_keys = array();
foreach ($rows as $row_id => $row) {
$found = true;
foreach ($server_side_query['search'] as $column_id => $search_options) {
$match_op = $search_options['match'];
if ($column_id == 'all') {
$search_string = implode('~',$row);
} else if (isset($row[$column_id])) {
$search_string = $row[$column_id];
} else {
$search_string = null;
}
if (isset($search_string)) {
$search_string = trim(strip_tags($search_string));
if ($search_string == '') $search_string = null;
}
if (isset($search_string)) {
if ($match_op == 'smart') {
// smart filtering - match all values that contain the search word
if (mb_stripos($search_string,$search_options['value'])===false) { $found = false; break; }
} else if ($match_op == 'start_with') {
if (mb_stripos($search_string,$search_options['value'])!==0) { $found = false; break; }
} else if ($match_op == 'exact') {
$search_value = $search_options['value'];
$search_string = trim(strip_tags($search_string));
if (mb_stripos($search_string,$search_value)===false) { $found = false; break; }
else {
$len1 = mb_strlen($search_string);
$len2 = mb_strlen($search_value);
if ($len1 != $len2) { $found = false; break; }
}
} else if ($match_op == 'numeric_int') {
if (is_numeric($search_string)) {
$search_string = intval($search_string);
if (!self::compareMatch($search_string, $search_options)) { $found = false; break; }
} else { $found = false; break; }
} else if ($match_op == 'numeric_period') {
$search_string = str_replace(',','',$search_string);
if (is_numeric($search_string)) {
$search_string = floatval($search_string);
if (!self::compareMatch($search_string, $search_options)) { $found = false; break; }
} else { $found = false; break; }
} else if ($match_op == 'numeric_comma') {
$search_string = str_replace(',','.',str_replace('.','',$search_string));
if (is_numeric($search_string)) {
$search_string = floatval($search_string);
if (!self::compareMatch($search_string, $search_options)) { $found = false; break; }
} else { $found = false; break; }
} else if ($match_op == 'date_auto') {
$search_string = strtotime($search_string);
if (($search_string === false)||($search_string===-1)) { $found = false; break; }
else {
if (!self::compareMatch($search_string, $search_options)) { $found = false; break; }
}
} else if ($match_op == 'date_ymd') {
$parts = preg_split('#[-\.\/\\/]+#',$search_string);
if (count($parts)==3) {
$search_string = strtotime($parts[0].'-'.$parts[1].'-'.$parts[2]);
if (($search_string === false)||($search_string===-1)) { $found = false; break; }
else {
if (!self::compareMatch($search_string, $search_options)) { $found = false; break; }
}
} else { $found = false; break; }
} else if ($match_op == 'date_ydm') {
$parts = preg_split('#[-\.\/\\/]+#',$search_string);
if (count($parts)==3) {
$search_string = strtotime($parts[0].'-'.$parts[2].'-'.$parts[1]);
if (($search_string === false)||($search_string===-1)) { $found = false; break; }
else {
if (!self::compareMatch($search_string, $search_options)) { $found = false; break; }
}
} else { $found = false; break; }
} else if ($match_op == 'date_dmy') {
$parts = preg_split('#[-\.\/\\/]+#',$search_string);
if (count($parts)==3) {
$search_string = strtotime($parts[2].'-'.$parts[1].'-'.$parts[0]);
if (($search_string === false)||($search_string===-1)) { $found = false; break; }
else {
if (!self::compareMatch($search_string, $search_options)) { $found = false; break; }
}
} else { $found = false; break; }
} else if ($match_op == 'date_mdy') {
$parts = preg_split('#[-\.\/\\/]+#',$search_string);
if (count($parts)==3) {
$search_string = strtotime($parts[2].'-'.$parts[0].'-'.$parts[1]);
if (($search_string === false)||($search_string===-1)) { $found = false; break; }
else {
if (!self::compareMatch($search_string, $search_options)) { $found = false; break; }
}
} else { $found = false; break; }
} else {
// smart filtering - match all values that contain the search word
if (mb_stripos($search_string,$search_value)===false) { $found = false; break; }
}
} else {
// do not match empty values
$found = false;
}
}
if (!$found) $unset_keys[] = $row_id;
}
if (!empty($unset_keys)) {
foreach ($unset_keys as $row_id) {
unset($rows[$row_id]);
}
}
$total_display_records = count($rows);
}
if (!empty($server_side_query['order_by'])) {
$sort_helper = new SortingRowsHelper();
$sort_helper->setOrder($server_side_query['order_by']['column_id'], $server_side_query['order_by']['dir']);
usort($rows, array($sort_helper, 'compare'));
}
if (count($rows)) {
$server_data = array('rows'=>$rows);
return $server_data;
} else {
$error_msg = JText::_('COM_TABULIZER_DATA_TABLE_FILTERING_RETURNED_ZERO_RECORDS');
return false;
}
}
} else {
$error_msg = JText::_('COM_TABULIZER_SERVER_SIDE_QUERY_IS_MISSING');
return false;
}
return false;
}
function getExportData(&$error_msg) {
// remove temporary export file, its contents are already copied to export_data variable
$this->removeExportFile();
switch ($this->export_type) {
case 'csv': $content_type = 'text/csv'; break;
case 'xls': $content_type = 'application/vnd.ms-excel'; break;
case 'xlsx': $content_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; break;
case 'pdf': $content_type = 'application/pdf'; break;
case 'png': $content_type = 'image/png'; break;
case 'jpg': $content_type = 'image/jpeg'; break;
case 'gif': $content_type = 'image/gif'; break;
default:
$error_msg = "Unknown export type {$this->export_type}!";
return false;
break;
}
header('Set-Cookie: fileDownload=true; path=/');
header('Cache-Control: max-age=60, must-revalidate');
header("Content-type: {$content_type}");
header('Content-Disposition: attachment; filename="'.$this->export_filename.'"');
//header("Pragma: no-cache");
//header("Expires: 0");
jexit($this->export_data);
return true;
}
function num2alpha($n) {
$r = '';
for ($i = 1; $n >= 0 && $i < 10; $i++) {
$r = chr(0x41 + ($n % pow(26, $i) / pow(26, $i - 1))) . $r;
$n -= pow(26, $i);
}
return $r;
}
function getExcelCoord($row_id, $column_id) {
$column_alpha = $this->num2alpha($column_id-1);
return $column_alpha . $row_id;
}
function cvs2Table($contents) {
$rows = array();
$lines = explode("\n",$contents);
foreach ($lines as $line) {
if ($line != '') {
$row = TabulizerString::my_str_getcsv( $line, ',', '"');
$rows[] = $row;
}
}
return $rows;
}
function saveExportData(&$error_msg) {
switch ($this->export_type) {
case 'csv':
$this->export_filename = 'table_' . rand() . '_' . time() . '.csv';
$export_data = $this->export_data;
$export_filename = $this->export_dir . $this->export_filename;
if (file_put_contents($export_filename, $export_data)) {
return true;
} else {
$error_msg = sprintf(JText::_('COM_TABULIZER_EXPORT_ERROR_CANNOT_WRITE_EXPORT_FILE'), $this->export_dir);
return false;
}
break;
case 'xls':
case 'xlsx':
case 'pdf':
# Include path
$phpexcel_path = TabulizerPath::getDirPath('phpexcel');
set_include_path(get_include_path() . PATH_SEPARATOR . $phpexcel_path);
# PHPExcel_IOFactory
require_once($phpexcel_path.DIRECTORY_SEPARATOR.'IOFactory.php');
$this->export_filename = 'table_' . rand() . '_' . time() . '.'.$this->export_type;
$export_data = $this->export_data;
$export_filename = $this->export_dir . $this->export_filename;
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('Table');
$rows = $this->cvs2Table($export_data);
foreach ($rows as $row_id => $row) {
foreach ($row as $column_id => $cell) {
$cell_coord = $this->getExcelCoord($row_id+1, $column_id+1);
$objPHPExcel->getActiveSheet()->setCellValue($cell_coord, $cell);
}
}
switch ($this->export_type) {
case 'xls': $outputFileType = 'Excel5'; break;
case 'xlsx': $outputFileType = 'Excel2007'; break;
case 'pdf':
$rendererName = PHPExcel_Settings::PDF_RENDERER_DOMPDF;
$rendererLibraryPath = TabulizerPath::getDirPath('dompdf');
if ($rendererLibraryPath) {
set_include_path(get_include_path() . PATH_SEPARATOR . $rendererLibraryPath);
if (!PHPExcel_Settings::setPdfRenderer(
$rendererName,
$rendererLibraryPath
)) {
$error_msg = JText::_('COM_TABULIZER_EXPORT_TABLE_PDF_LIBRARY_MISSING');
return false;
}
} else {
$error_msg = JText::_('COM_TABULIZER_EXPORT_TABLE_PDF_LIBRARY_MISSING');
return false;
}
$outputFileType = 'PDF';
$objPHPExcel->getActiveSheet(0)->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
$objPHPExcel->getActiveSheet(0)->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
$objPHPExcel->getActiveSheet(0)->getPageSetup()->setFitToWidth(true);
$objPHPExcel->getActiveSheet(0)->getPageSetup()->setFitToHeight(true);
$objPHPExcel->getActiveSheet(0)->setShowGridlines(false);
break;
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $outputFileType);
$objWriter->save($export_filename);
return true;
break;
case 'png':
$this->export_filename = 'graph_' . rand() . '_' . time() . '.png';
$export_data = str_replace(' ', '+', str_replace('data:image/png;base64,','',$this->export_data));
$export_data = base64_decode($export_data);
$export_filename = $this->export_dir . $this->export_filename;
if (file_put_contents($export_filename, $export_data)) {
return true;
} else {
$error_msg = sprintf(JText::_('COM_TABULIZER_EXPORT_ERROR_CANNOT_WRITE_EXPORT_FILE'), $this->export_dir);
return false;
}
break;
case 'jpg':
// save the image first as png
$tmp_filename = $this->export_dir . 'graph_' . rand() . '_' . time() . '.png';
$export_data = str_replace(' ', '+', str_replace('data:image/png;base64,','',$this->export_data));
$export_data = base64_decode($export_data);
if (file_put_contents($tmp_filename, $export_data)) {
$image = imagecreatefrompng($tmp_filename);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = EXPORT_TABLE_IMAGE_QUALITY;
$this->export_filename = 'graph_' . rand() . '_' . time() . '.jpg';
$export_filename = $this->export_dir . $this->export_filename;
imagejpeg($bg, $export_filename, $quality);
ImageDestroy($bg);
@unlink($tmp_filename);
return true;
} else {
$error_msg = sprintf(JText::_('COM_TABULIZER_EXPORT_ERROR_CANNOT_WRITE_EXPORT_FILE'), $this->export_dir);
return false;
}
break;
case 'gif':
// save the image first as png
$tmp_filename = $this->export_dir . 'graph_' . rand() . '_' . time() . '.png';
$export_data = str_replace(' ', '+', str_replace('data:image/png;base64,','',$this->export_data));
$export_data = base64_decode($export_data);
if (file_put_contents($tmp_filename, $export_data)) {
$image = imagecreatefrompng($tmp_filename);
$this->export_filename = 'graph_' . rand() . '_' . time() . '.gif';
$export_filename = $this->export_dir . $this->export_filename;
imagegif($image, $export_filename);
imagedestroy($image);
@unlink($tmp_filename);
return true;
} else {
$error_msg = sprintf(JText::_('COM_TABULIZER_EXPORT_ERROR_CANNOT_WRITE_EXPORT_FILE'), $this->export_dir);
return false;
}
break;
default:
$error_msg = "Unknown export type {$this->export_type}!";
return false;
break;
}
}
function emailExportData(&$error_msg) {
$mailer = JFactory::getMailer();
// set sender
$sender_info = TabulizerInfo::getMailSenderInfo();
$sender = array( $sender_info['email'], $sender_info['name']);
$mailer->setSender($sender);
// set recipient
if (empty($this->export_email_recipients)) {
$user = JFactory::getUser();
if ($user->guest) {
$error_msg = JText::_('COM_TABULIZER_EXPORT_ERROR_USER_NOT_LOGGED_IN');
$this->removeExportFile();
return false;
}
$this->export_email_recipients = array($user->email);
}
$mailer->addRecipient($this->export_email_recipients);
$export_filename = $this->export_dir . $this->export_filename;
switch ($this->export_type) {
case 'csv':
case 'xls':
case 'xlsx':
case 'pdf':
$subject = empty($this->export_email_subject)?JText::_('COM_TABULIZER_EXPORT_TABLE_EMAIL_SUBJECT'):$this->export_email_subject;
$body_text = empty($this->export_email_body)?JText::_('COM_TABULIZER_EXPORT_TABLE_EMAIL_BODY'):$this->export_email_body;
$body = '<div>'.$body_text.'<br/></div>';
// Attach file
$mailer->addAttachment($export_filename);
break;
case 'png':
case 'jpg':
case 'gif':
$subject = empty($this->export_email_subject)?JText::_('COM_TABULIZER_EXPORT_IMAGE_EMAIL_SUBJECT'):$this->export_email_subject;
$body_text = empty($this->export_email_body)?JText::_('COM_TABULIZER_EXPORT_IMAGE_EMAIL_BODY'):$this->export_email_body;
$body = '<div>'.$body_text.'<br/><br/>'
. '<img src="cid:graph_id" alt="Table Graph"/></div>';
// Add embedded image
$image_type = ($this->export_type == 'jpg')?'jpeg':$this->export_type;
$mailer->AddEmbeddedImage($export_filename, 'graph_id', $this->export_filename, 'base64', 'image/'.$image_type );
break;
default:
$error_msg = "Unknown export type {$this->export_type}!";
$this->removeExportFile();
return false;
break;
}
$mailer->setSubject($subject);
$mailer->setBody($body);
$mailer->isHTML(true);
$mailer->Encoding = 'base64';
$send = $mailer->Send();
if ( $send !== true ) {
$error_msg = JText::_('COM_TABULIZER_EXPORT_ERROR_COULD_NOT_SEND_EMAIL');
$this->removeExportFile();
return false;
}
$this->removeExportFile();
return true;
}
function outputJSON($user_data, $error_flag) {
if ($error_flag) {
$output = $user_data;
} else {
$output = json_encode($user_data);
}
jexit($output);
}
function outputFile($user_msg, $error_flag = true) {
if (!$error_flag) {
header('Set-Cookie: fileDownload=true; path=/');
}
header('Cache-Control: max-age=60, must-revalidate');
header("Content-Type: text/html; charset=utf-8");
jexit($user_msg);
}
function processRequest() {
// get export params
if (!$this->getExportParams($error_msg)) {
if (empty($this->export_filename)) {
$this->outputJSON($error_msg, true);
} else {
$this->outputFile($error_msg, true);
}
return false;
}
// see if filename is set
if (empty($this->export_filename)) {
if (!$this->saveExportData($error_msg)) {
$this->outputJSON($error_msg, true);
return false;
} else {
$this->outputJSON(array('filename_tmp' => $this->export_filename), false);
return true;
}
} else {
if ($this->export_output == 'email') {
if (!$this->emailExportData($error_msg)) {
$this->outputFile($error_msg, true);
return false;
} else {
$this->outputFile(JText::_('COM_TABULIZER_EXPORT_EMAIL_SUCCESS_MESSAGE'), false);
}
} else {
if (!$this->getExportData($error_msg)) {
$this->outputFile($error_msg, true);
return false;
}
}
}
return true;
}
}
$export_controller = new ExportData();
$export_controller->processRequest();
?>