I'm getting a PHP fatal error on a cron script used for Commission Junction. It seems in the error_log it keeps updating with
PHP Fatal error: Call to undefined method Mage_Core_Helper_Data::getEscapedCSVData() in /home/lovescen/public_html/app/code/core/Mage/Dataflow/Model/Convert/Parser/Csv.php on line 269
The code on line 269 is
$escapedValue = Mage::helper("core")->getEscapedCSVData(array($value));
And here is the entire code in Csv.php.
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license#magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* #category Mage
* #package Mage_Dataflow
* #copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
* #license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Convert csv parser
*
* #category Mage
* #package Mage_Dataflow
* #author Magento Core Team <core#magentocommerce.com>
*/
class Mage_Dataflow_Model_Convert_Parser_Csv extends Mage_Dataflow_Model_Convert_Parser_Abstract
{
protected $_fields;
protected $_mapfields = array();
public function parse()
{
// fixed for multibyte characters
setlocale(LC_ALL, Mage::app()->getLocale()->getLocaleCode().'.UTF-8');
$fDel = $this->getVar('delimiter', ',');
$fEnc = $this->getVar('enclose', '"');
if ($fDel == '\t') {
$fDel = "\t";
}
$adapterName = $this->getVar('adapter', null);
$adapterMethod = $this->getVar('method', 'saveRow');
if (!$adapterName || !$adapterMethod) {
$message = Mage::helper('dataflow')->__('Please declare "adapter" and "method" nodes first.');
$this->addException($message, Mage_Dataflow_Model_Convert_Exception::FATAL);
return $this;
}
try {
$adapter = Mage::getModel($adapterName);
}
catch (Exception $e) {
$message = Mage::helper('dataflow')->__('Declared adapter %s was not found.', $adapterName);
$this->addException($message, Mage_Dataflow_Model_Convert_Exception::FATAL);
return $this;
}
if (!method_exists($adapter, $adapterMethod)) {
$message = Mage::helper('dataflow')->__('Method "%s" not defined in adapter %s.', $adapterMethod, $adapterName);
$this->addException($message, Mage_Dataflow_Model_Convert_Exception::FATAL);
return $this;
}
$batchModel = $this->getBatchModel();
$batchIoAdapter = $this->getBatchModel()->getIoAdapter();
if (Mage::app()->getRequest()->getParam('files')) {
$file = Mage::app()->getConfig()->getTempVarDir().'/import/'
. urldecode(Mage::app()->getRequest()->getParam('files'));
$this->_copy($file);
}
$batchIoAdapter->open(false);
$isFieldNames = $this->getVar('fieldnames', '') == 'true' ? true : false;
if (!$isFieldNames && is_array($this->getVar('map'))) {
$fieldNames = $this->getVar('map');
}
else {
$fieldNames = array();
foreach ($batchIoAdapter->read(true, $fDel, $fEnc) as $v) {
$fieldNames[$v] = $v;
}
}
$countRows = 0;
while (($csvData = $batchIoAdapter->read(true, $fDel, $fEnc)) !== false) {
if (count($csvData) == 1 && $csvData[0] === null) {
continue;
}
$itemData = array();
$countRows ++; $i = 0;
foreach ($fieldNames as $field) {
$itemData[$field] = isset($csvData[$i]) ? $csvData[$i] : null;
$i ++;
}
$batchImportModel = $this->getBatchImportModel()
->setId(null)
->setBatchId($this->getBatchModel()->getId())
->setBatchData($itemData)
->setStatus(1)
->save();
}
$this->addException(Mage::helper('dataflow')->__('Found %d rows.', $countRows));
$this->addException(Mage::helper('dataflow')->__('Starting %s :: %s', $adapterName, $adapterMethod));
$batchModel->setParams($this->getVars())
->setAdapter($adapterName)
->save();
//$adapter->$adapterMethod();
return $this;
// // fix for field mapping
// if ($mapfields = $this->getProfile()->getDataflowProfile()) {
// $this->_mapfields = array_values($mapfields['gui_data']['map'][$mapfields['entity_type']]['db']);
// } // end
//
// if (!$this->getVar('fieldnames') && !$this->_mapfields) {
// $this->addException('Please define field mapping', Mage_Dataflow_Model_Convert_Exception::FATAL);
// return;
// }
//
// if ($this->getVar('adapter') && $this->getVar('method')) {
// $adapter = Mage::getModel($this->getVar('adapter'));
// }
//
// $i = 0;
// while (($line = fgetcsv($fh, null, $fDel, $fEnc)) !== FALSE) {
// $row = $this->parseRow($i, $line);
//
// if (!$this->getVar('fieldnames') && $i == 0 && $row) {
// $i = 1;
// }
//
// if ($row) {
// $loadMethod = $this->getVar('method');
// $adapter->$loadMethod(compact('i', 'row'));
// }
// $i++;
// }
//
// return $this;
}
public function parseRow($i, $line)
{
if (sizeof($line) == 1) return false;
if (0==$i) {
if ($this->getVar('fieldnames')) {
$this->_fields = $line;
return;
} else {
foreach ($line as $j=>$f) {
$this->_fields[$j] = $this->_mapfields[$j];
}
}
}
$resultRow = array();
foreach ($this->_fields as $j=>$f) {
$resultRow[$f] = isset($line[$j]) ? $line[$j] : '';
}
return $resultRow;
}
/**
* Read data collection and write to temporary file
*
* #return Mage_Dataflow_Model_Convert_Parser_Csv
*/
public function unparse()
{
$batchExport = $this->getBatchExportModel()
->setBatchId($this->getBatchModel()->getId());
$fieldList = $this->getBatchModel()->getFieldList();
$batchExportIds = $batchExport->getIdCollection();
$io = $this->getBatchModel()->getIoAdapter();
$io->open();
if (!$batchExportIds) {
$io->write("");
$io->close();
return $this;
}
if ($this->getVar('fieldnames')) {
$csvData = $this->getCsvString($fieldList);
$io->write($csvData);
}
foreach ($batchExportIds as $batchExportId) {
$csvData = array();
$batchExport->load($batchExportId);
$row = $batchExport->getBatchData();
foreach ($fieldList as $field) {
$csvData[] = isset($row[$field]) ? $row[$field] : '';
}
$csvData = $this->getCsvString($csvData);
$io->write($csvData);
}
$io->close();
return $this;
}
public function unparseRow($args)
{
$i = $args['i'];
$row = $args['row'];
$fDel = $this->getVar('delimiter', ',');
$fEnc = $this->getVar('enclose', '"');
$fEsc = $this->getVar('escape', '\\');
$lDel = "\r\n";
if ($fDel == '\t') {
$fDel = "\t";
}
$line = array();
foreach ($this->_fields as $f) {
$v = isset($row[$f]) ? str_replace(array('"', '\\'), array($fEnc.'"', $fEsc.'\\'), $row[$f]) : '';
$line[] = $fEnc.$v.$fEnc;
}
return join($fDel, $line);
}
/**
* Retrieve csv string from array
*
* #param array $fields
* #return string
*/
public function getCsvString($fields = array()) {
$delimiter = $this->getVar('delimiter', ',');
$enclosure = $this->getVar('enclose', '');
$escapeChar = $this->getVar('escape', '\\');
if ($delimiter == '\t') {
$delimiter = "\t";
}
$str = '';
foreach ($fields as $value) {
$escapedValue = Mage::helper("core")->getEscapedCSVData(array($value));
$value = $escapedValue[0];
if (strpos($value, $delimiter) !== false ||
empty($enclosure) ||
strpos($value, $enclosure) !== false ||
strpos($value, "\n") !== false ||
strpos($value, "\r") !== false ||
strpos($value, "\t") !== false ||
strpos($value, ' ') !== false) {
$str2 = $enclosure;
$escaped = 0;
$len = strlen($value);
for ($i=0;$i<$len;$i++) {
if ($value[$i] == $escapeChar) {
$escaped = 1;
} else if (!$escaped && $value[$i] == $enclosure) {
$str2 .= $enclosure;
} else {
$escaped = 0;
}
$str2 .= $value[$i];
}
$str2 .= $enclosure;
$str .= $str2.$delimiter;
} else {
$str .= $enclosure.$value.$enclosure.$delimiter;
}
}
return substr($str, 0, -1) . "\n";
}
}
Not sure how to fix this problem. If I could get some help I'd really appreciate it.
Thanks
UPDATE
Here is the code from my app/code/core/Mage/Core/Helper/Data.php file: http://pastie.org/10815259
Does the file app/code/core/Mage/Core/Helper/Data.php have the getEscapedCSVData function in it?
It appears that this function is added by SUPEE-7405. Have you patched your store with this SUPEE?
In my case some previous programer have copy the file
from core
\app\code\core\Mage\Core\Helper\Data.php
to local
app\code\local\Mage\Core\Helper\Data.php
and then apply SUPE PATCH 7405...
it cause that all modifications made by SUPE in data.php where rewrite by the old ones in local folder...
Solution: copy the new data.php to local or made a extension of class (better solution)
Related
I've been searching around for extensions of CodeIgniter's parser class that would add the use of conditional statements in the view files. The problem is that the location that I've found it at doesn't offer any explanation on how to use it and doesn't list anything about the file's author. Could anyone perhaps share any thoughts on this code?
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 4.3.2 or newer
*
* #package CodeIgniter
* #author ExpressionEngine Dev Team
* #copyright Copyright (c) 2008, EllisLab, Inc.
* #license http://codeigniter.com/user_guide/license.html
* #link http://codeigniter.com
* #since Version 1.0
* #filesource
*/
// ------------------------------------------------------------------------
/**
* MY Parser Class
*
* #package CodeIgniter
* #subpackage Libraries
* #category Parser
* #author Haloweb Ltd
*/
class MY_Parser extends CI_Parser {
/**
* Parse a template
*
* Parses pseudo-variables contained in the specified template,
* replacing them with the data in the second param
*
* #access public
* #param string
* #param array
* #param bool
* #return string
*/
function parse($template, $data, $return = FALSE, $include = FALSE)
{
$CI =& get_instance();
if ($template == '')
{
return FALSE;
}
if ($include === FALSE)
{
$template = $CI->load->view($template, $data, TRUE);
}
if (isset($data) && $data != '')
{
foreach ($data as $key => $val)
{
if (is_array($val))
{
$template = $this->_parse_pair($key, $val, $template);
}
else
{
$template = $this->_parse_single($key, (string)$val, $template);
}
}
}
// Check for conditional statments
$template = $this->conditionals($template, $data);
// populate form tags
preg_match_all('/{form:(.+)}/i', $template, $posts);
if ($posts)
{
foreach ($posts[1] as $post => $value)
{
if ($postValue = $CI->input->post($value))
{
$template = str_replace('{form:'.$value.'}', $postValue, $template);
}
else
{
$template = str_replace('{form:'.$value.'}', '', $template);
}
}
}
//$template = preg_replace('/{(.+)}/i', '', $template);
if ($return == FALSE)
{
$CI->output->append_output($template);
}
return $template;
}
// --------------------------------------------------------------------
/**
* Parse conditional statments
*
* #access public
* #param string
* #param bool
* #return string
*/
function conditionals($template, $data)
{
if (preg_match_all('/'.$this->l_delim.'if (.+)'.$this->r_delim.'(.+)'.$this->l_delim.'\/if'.$this->r_delim.'/siU', $template, $conditionals, PREG_SET_ORDER))
{
if (count($conditionals) > 0)
{
// filter through conditionals
foreach($conditionals as $condition)
{
// get conditional and the string inside
$code = (isset($condition[0])) ? $condition[0] : FALSE;
$condString = (isset($condition[1])) ? str_replace(' ', '', $condition[1]) : FALSE;
$insert = (isset($condition[2])) ? $condition[2] : '';
// check code is valid
if (!preg_match('/('.$this->l_delim.'|'.$this->r_delim.')/', $condString, $condProblem))
{
if (!empty($code) || $condString != FALSE || !empty($insert))
{
if (preg_match("/^!(.*)$/", $condString, $matches))
{
$condVar = (#!$data[trim($matches[1])]) ? 0 : $data[trim($matches[1])];
#$result = (!$condVar) ? TRUE : FALSE;
}
elseif (preg_match("/([a-z0-9\-_:\(\)]+)(\!=|=|==|>|<)([a-z0-9\-_\/]+)/", $condString, $matches))
{
$condVar = (#!$data[$matches[1]]) ? 0 : $data[trim($matches[1])];
if ($matches[2] == '==' || $matches[2] == '=')
{
#$result = ($condVar === $matches[3]) ? TRUE : FALSE;
}
elseif ($matches[2] == '!=')
{
#$result = ($condVar !== $matches[3]) ? TRUE : FALSE;
}
elseif ($matches[2] == '>')
{
#$result = ($condVar > $matches[3]) ? TRUE : FALSE;
}
elseif ($matches[2] == '<')
{
#$result = ($condVar < $matches[3]) ? TRUE : FALSE;
}
}
else
{
// if the variable is set
if (isset($data[$condString]) && is_array($data[$condString]))
{
$result = (count($data[$condString]) > 0) ? TRUE : FALSE;
}
else
{
$result = (isset($data[$condString]) && $data[$condString] != '') ? TRUE : FALSE;
}
}
// filter for else
$insert = preg_split('/'.$this->l_delim.'else'.$this->r_delim.'/siU', $insert);
if ($result == TRUE)
{
// show the string inside
$template = str_replace($code, $insert[0], $template);
}
else
{
if (is_array($insert))
{
$insert = (isset($insert[1])) ? $insert[1] : '';
$template = str_replace($code, $insert, $template);
}
else
{
$template = str_replace($code, '', $template);
}
}
}
}
else
{
// remove any conditionals we cant process
$template = str_replace($code, '', $template);
}
}
}
//print_r($conditionals);
}
return $template;
}
// --------------------------------------------------------------------
/**
* Matches a variable pair
*
* #access private
* #param string
* #param string
* #return mixed
*/
function _match_pair($string, $variable)
{
$variable = str_replace('(', '\(', $variable);
$variable = str_replace(')', '\)', $variable);
if ( ! preg_match("|".$this->l_delim . $variable . $this->r_delim."(.+?)".$this->l_delim . '/' . $variable . $this->r_delim."|s", $string, $match))
{
return FALSE;
}
return $match;
}
}
Below, there is my code for database backup.
$this->load->database();
$this->load->dbutil();
$backup =& $this->dbutil->backup();
$prefs = array(
'format' => 'txt',
'filename' => 'mybackup.sql', );
$path=$this->config->base_url()."database/";
$this->load->helper('file');
write_file($path, $backup);
$this->load->helper('download');
force_download('mybackup.gz', $backup);
It works fine when i use
$db['default']['dbdriver'] = 'mysql';
But it gives error with
$db['default']['dbdriver'] = 'mysqli';
error:Unsupported feature of the database platform you are using.
How it will work with "mysqli" i need support mysqli in my project.
This hapend to me, then i open file "system\database\drivers\mysqli\mysqli_utility.php" and change function "_backup" to this:
/**
* MySQLi Export
*
* #access private
* #param array Preferences
* #return mixed
*/
function _backup($params = array())
{
// Currently unsupported
//---return $this->db->display_error('db_unsuported_feature');
if (count($params) == 0)
{
return FALSE;
}
// Extract the prefs for simplicity
extract($params);
// Build the output
$output = '';
foreach ((array)$tables as $table)
{
// Is the table in the "ignore" list?
if (in_array($table, (array)$ignore, TRUE))
{
continue;
}
// Get the table schema
$query = $this->db->query("SHOW CREATE TABLE `".$this->db->database.'`.`'.$table.'`');
// No result means the table name was invalid
if ($query === FALSE)
{
continue;
}
// Write out the table schema
$output .= '#'.$newline.'# TABLE STRUCTURE FOR: '.$table.$newline.'#'.$newline.$newline;
if ($add_drop == TRUE)
{
$output .= 'DROP TABLE IF EXISTS '.$table.';'.$newline.$newline;
}
$i = 0;
$result = $query->result_array();
foreach ($result[0] as $val)
{
if ($i++ % 2)
{
$output .= $val.';'.$newline.$newline;
}
}
// If inserts are not needed we're done...
if ($add_insert == FALSE)
{
continue;
}
// Grab all the data from the current table
$query = $this->db->query("SELECT * FROM $table");
if ($query->num_rows() == 0)
{
continue;
}
// Fetch the field names and determine if the field is an
// integer type. We use this info to decide whether to
// surround the data with quotes or not
$i = 0;
$field_str = '';
$is_int = array();
while ($field = mysqli_fetch_field($query->result_id))
{
// Most versions of MySQL store timestamp as a string
$is_int[$i] = (in_array(
//strtolower(mysqli_field_type($query->result_id, $i)),
strtolower($field->type),
array('tinyint', 'smallint', 'mediumint', 'int', 'bigint'), //, 'timestamp'),
TRUE)
) ? TRUE : FALSE;
// Create a string of field names
$field_str .= '`'.$field->name.'`, ';
$i++;
}
// Trim off the end comma
$field_str = preg_replace( "/, $/" , "" , $field_str);
// Build the insert string
foreach ($query->result_array() as $row)
{
$val_str = '';
$i = 0;
foreach ($row as $v)
{
// Is the value NULL?
if ($v === NULL)
{
$val_str .= 'NULL';
}
else
{
// Escape the data if it's not an integer
if ($is_int[$i] == FALSE)
{
$val_str .= $this->db->escape($v);
}
else
{
$val_str .= $v;
}
}
// Append a comma
$val_str .= ', ';
$i++;
}
// Remove the comma at the end of the string
$val_str = preg_replace( "/, $/" , "" , $val_str);
// Build the INSERT string
$output .= 'INSERT INTO '.$table.' ('.$field_str.') VALUES ('.$val_str.');'.$newline;
}
$output .= $newline.$newline;
}
return $output;
}
If you need what change....
change all "mysql_..." to "mysqli..."
and the line
strtolower(mysqli_field_type($query->result_id, $i)),
To this
strtolower($field->type),
And viola! thats WORKS great...
Here is an extension to the function to backup all databases of any size.
This code will remove the PHP memory limits on exporting databases by utilising the file system (cache folder) and SQL LIMITS.
I hope this is useful to someone.
Replacement for function _backup($params = array())
FILE: system/drivers/mysqli/mysqli_utility.php
/**
* MySQLi Export
*
* #access private
* #param array Preferences
* #return mixed
*/
function _backup_old($params = array())
{
// Currently unsupported
return $this->db->display_error('db_unsuported_feature');
}
/**
* MySQLi Export
*
* #access private
* #param array Preferences
* #return mixed
*/
function _backup($params = array())
{
// Currently unsupported
//---return $this->db->display_error('db_unsuported_feature');
if (count($params) == 0)
{
return FALSE;
}
// Extract the prefs for simplicity
extract($params);
// Build the output
$output = '';
foreach ((array)$tables as $table)
{
// Temp file to reduce change of OOM Killer
$tempfilepath = APPPATH . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
$tempfile = $tempfilepath . 'dbbkp_tmp_' . time() . '.sql';
// Is the table in the "ignore" list?
if (in_array($table, (array)$ignore, TRUE))
{
continue;
}
// Get the table schema
$query = $this->db->query("SHOW CREATE TABLE `".$this->db->database.'`.`'.$table.'`');
// No result means the table name was invalid
if ($query === FALSE)
{
continue;
}
// Write out the table schema
$output .= '#'.$newline.'# TABLE STRUCTURE FOR: '.$table.$newline.'#'.$newline.$newline;
if ($add_drop == TRUE)
{
$output .= 'DROP TABLE IF EXISTS '.$table.';'.$newline.$newline;
}
$i = 0;
$result = $query->result_array();
foreach ($result[0] as $val)
{
if ($i++ % 2)
{
$output .= $val.';'.$newline.$newline;
}
}
// Write $output to the $filename file
file_put_contents( $filename, $output, LOCK_EX );
$output = '';
// If inserts are not needed we're done...
if ($add_insert == FALSE)
{
continue;
}
// Grab all the data from the current table
//$query = $this->db->query("SELECT * FROM $table"); // OLD
$countResult = $this->db->query("SELECT COUNT(*) AS `count` FROM " . $table . ";");
$countReturn = $countResult->result_array();
$totalCount = $countReturn[0]['count'];
//if ($query->num_rows() == 0) // OLD
if ($totalCount == 0)
{
continue;
}
// Chunk Vars
$chunkSize = 10000;
$from = 0;
$resultArray = array();
if (isset($chunk_size))
{
$chunkSize = $chunk_size;
}
// Write out the table schema
$output .= '#'.$newline.'# TABLE DATA FOR: '.$table.$newline.'#'.$newline.$newline;
// Write $output to the $filename file
file_put_contents( $filename, $output, FILE_APPEND | LOCK_EX );
// Fetch the field names and determine if the field is an
// integer type. We use this info to decide whether to
// surround the data with quotes or not
$query = $this->db->query("SELECT * FROM " . $table . " LIMIT 1;");
$i = 0;
$field_str = '';
$is_int = array();
while ($field = mysqli_fetch_field($query->result_id))
{
// Most versions of MySQL store timestamp as a string
$is_int[$i] = (in_array(
//strtolower(mysqli_field_type($query->result_id, $i)),
strtolower($field->type),
array('tinyint', 'smallint', 'mediumint', 'int', 'bigint'), //, 'timestamp'),
TRUE)
) ? TRUE : FALSE;
// Create a string of field names
$field_str .= '`'.$field->name.'`, ';
$i++;
}
// Trim off the end comma
$field_str = preg_replace( "/, $/" , "" , $field_str);
// Pull the data in chunks
while($from < $totalCount)
{
// empty $output
$output = '';
// Execute a limited query:
$dataChunkQuery = $this->db->query('SELECT * FROM ' . $table . ' LIMIT ' . $from . ', ' . $chunkSize . ';');
$dataChunkRows = $dataChunkQuery->result_array();
// Increase $from:
$from += $chunkSize;
// Build the insert string
//foreach ($query->result_array() as $row) // OLD
//var_dump($resultArray); die();
foreach ($dataChunkRows as $row)
{
$val_str = '';
$i = 0;
foreach ($row as $v)
{
// Is the value NULL?
if ($v === NULL)
{
$val_str .= 'NULL';
}
else
{
// Escape the data if it's not an integer
if ($is_int[$i] == FALSE)
{
$val_str .= $this->db->escape($v);
}
else
{
$val_str .= $v;
}
}
// Append a comma
$val_str .= ', ';
$i++;
}
// Remove the comma at the end of the string
$val_str = preg_replace( "/, $/" , "" , $val_str);
// Build the INSERT string
$output .= 'INSERT INTO '.$table.' ('.$field_str.') VALUES ('.$val_str.');'.$newline;
}
// Write $output to the $filename file
file_put_contents( $filename, $output, FILE_APPEND | LOCK_EX );
sleep(1); // used to help reduce the CPU load
}
}
if( file_exists($filename) ) {
return true;
} else {
return false;
}
}
CI Model built for DB Backups
FILE: models/databasebackup_model.php
<?php
/**
* Database Backup
* - Used to make backups of the database system
* #author Adan Rehtla <adan.rehtla#aamcommercial.com.au>
*/
class Databasebackup_model extends API_Model {
private $CI;
private $lpFilePath = APPPATH . 'cache/backup/';
// Tables to ignore when doing a backup
private $laIgnoreTables = array(
'ci_sessions',
'any_other_tables_to_ignore'
);
/**
* Constructor
* #author Adan Rehtla <adan.rehtla#aamcommercial.com.au>
*/
function __construct() {
parent::__construct();
$this->CI = &get_instance();
}
/**
* Check and empty the cache location for storing the backups during transit
* #author Adan Rehtla <adan.rehtla#aamcommercial.com.au>
* #return json Result
*/
public function check_cache() {
$arrRet = false;
if( ! file_exists( $this->lpFilePath ) ) {
$arrRet = mkdir( $this->lpFilePath );
$arrRet = true;
}
$files = glob( $this->lpFilePath . '*' ); // get all file names present in folder
foreach( $files as $file ){ // iterate files
if( is_file( $file ) ) unlink( $file ); // delete the file
}
return (object) $arrRet;
}
/**
* Build a list of tables to backup
* #author Adan Rehtla <adan.rehtla#aamcommercial.com.au>
* #return json Result
*/
public function find_tables() {
$arrRet = false;
if( $this->database('db_read') ) {
$this->db_read->_protect_identifiers = FALSE;
$this->db_read->start_cache();
$this->db_read->distinct();
$this->db_read->select("table_name");
$this->db_read->from("information_schema.columns");
$this->db_read->where("table_schema", $this->db->dbprefix . $this->db->database);
$this->db_read->stop_cache();
// Get List of all tables to backup
$laTableNameResult = $this->db_read->get()->result();
$this->db_read->flush_cache();
if( !empty($laTableNameResult) ) {
foreach($laTableNameResult as $loTableName) {
if( ! in_array( $loTableName->table_name, $this->laIgnoreTables ) ) {
$arrRet[] = $loTableName->table_name;
}
}
}
$this->db_read->_protect_identifiers = TRUE;
}
return (object) $arrRet;
}
/**
* Backup the database to Amazon S3
* #author Adan Rehtla <adan.rehtla#aamcommercial.com.au>
* #param interger $lpUserId Logged in User ID
* #return json Result
*/
public function backup() {
ini_set('max_execution_time', 3600); // 3600 seconds = 60 minutes
ini_set('memory_limit', '-1'); // unlimited memory
//error_reporting(E_ALL); // show errors
//ini_set('display_errors', 1); // display errors
$arrRet = array();
$lpBackupCount = 0;
$zipNumFiles = 0;
$zipStatus = 0;
if( $this->database('db_read') ) {
$this->db->save_queries = false;
$this->load->dbutil( $this->db_read, TRUE );
$laBackupTables = $this->find_tables();
if( !empty($laBackupTables) && $this->check_cache() ) {
foreach($laBackupTables as $lpTableName) {
$lpFilename = $this->lpFilePath . 'backup-' . $lpTableName . '-' . date('Ymd-His') . '.sql';
$prefs = array(
'tables' => $lpTableName,
'format' => 'sql',
'filename' => $lpFilename,
'add_drop' => TRUE,
'add_insert' => TRUE,
'newline' => "\n",
'foreign_key_checks' => TRUE,
'chunk_size' => 1000
);
if( !file_exists( $lpFilename ) ){
if( $this->dbutil->backup( $prefs ) ) {
$lpBackupCount++;
}
}
sleep(1); // used to help reduce the CPU load
//break; // used to debug and testing to only process the first database table
}
try {
// ZIP up all the individual GZIPs
$zip = new ZipArchive();
$zip_file = $this->lpFilePath . '-' . date('Ymd-His') . '.zip';
$zip_files = glob( $this->lpFilePath . 'backup-*' ); // get all file names present in folder starting with 'backup-'
if( $zip->open( $zip_file, ZIPARCHIVE::CREATE ) !== TRUE ) {
exit("cannot open <$zip_file>\n");
}
if( !empty($zip_files) ) {
foreach( $zip_files as $file_to_zip ) { // iterate files
$zip->addFile( $file_to_zip, basename( $file_to_zip ) );
}
}
$zipNumFiles = $zip->numFiles;
$zipStatus = $zip->status;
$zip->close();
} catch (Vi_exception $e) {
print( strip_tags( $e->errorMessage() ) );
}
// Upload the file to Amazon S3
// REMOVED AWS S3 UPLOAD CODE
// REMOVED AWS S3 UPLOAD CODE
// REMOVED AWS S3 UPLOAD CODE
// Clean up cache files
$this->check_cache();
}
$this->db->save_queries = true;
}
if( !empty($lpBackupCount) && !empty($zip) && !empty($zip_file) ) {
return (object) array( 'success'=>true, 'totalTables'=>$lpBackupCount, 'zipNumFiles'=>$zipNumFiles, 'zipStatus'=>$zipStatus, 'zipFile'=>$zip_file );
} else {
return (object) array( 'success'=>false );
}
}
}
USAGE:
$this->load->model('databasebackup_model');
$laResult = $this->databasebackup_model->backup();
Your mysqli driver does n't support this feature.
Refer this:
http://ellislab.com/forums/viewthread/194645/#979255
I have found a php inventory http://inventory-management.org/ easy but was written in PHP4? and I run now on PHP5. I have found some errors that I have already managed to fix but they are keep coming up so I would like to see if I can managed to run at the end. (As it is really simple script only has 5-7 php files).
Could someone help me please how to fix this error?
Fatal error: Cannot redeclare fputcsv() in C:\xampp\htdocs\Inventory\lib\common.php on line 935
which is:
function fputcsv ($fp, $array, $deliminator=",") {
return fputs($fp, putcsv($array,$delimitator));
}#end fputcsv()
here is the full code:
<?php
/*
*/
/**
* description returns an array with filename base name and the extension
*
* #param filemane format
*
* #return array
*
* #access public
*/
function FileExt($filename) {
//checking if the file have an extension
if (!strstr($filename, "."))
return array("0"=>$filename,"1"=>"");
//peoceed to normal detection
$filename = strrev($filename);
$extpos = strpos($filename , ".");
$file = strrev(substr($filename , $extpos + 1));
$ext = strrev(substr($filename , 0 , $extpos));
return array("0"=>$file,"1"=>$ext);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function UploadFile($source, $destination , $name ="") {
$name = $name ? $name : basename($source);
$name = FileExt($name);
$name[2]= $name[0];
$counter = 0 ;
while (file_exists( $destination . $name[0] . "." . $name[1] )) {
$name[0] = $name[2] . $counter;
$counter ++;
}
copy($source , $destination . $name[0] . "." . $name[1] );
#chmod($destination . $name[0] . "." . $name[1] , 0777);
}
function UploadFileFromWeb($source, $destination , $name) {
$name = FileExt($name);
$name[2]= $name[0];
$counter = 0 ;
while (file_exists( $destination . $name[0] . "." . $name[1] )) {
$name[0] = $name[2] . $counter;
$counter ++;
}
SaveFileContents($destination . $name[0] . "." . $name[1] , $source);
#chmod($destination . $name[0] . "." . $name[1] , 0777);
}
/**
* returns the contents of a file in a string
*
* #param string $file_name name of file to be loaded
*
* #return string
*
* #acces public
*/
function GetFileContents($file_name) {
// if (!file_exists($file_name)) {
// return null;
// }
//echo "<br>:" . $file_name;
$file = fopen($file_name,"r");
//checking if the file was succesfuly opened
if (!$file)
return null;
if (strstr($file_name,"://"))
while (!feof($file))
$result .= fread($file,1024);
else
$result = #fread($file,filesize($file_name));
fclose($file);
return $result;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function SaveFileContents($file_name,$content) {
// echo $file_name;
$file = fopen($file_name,"w");
fwrite($file,$content);
fclose($file);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function Debug($what,$pre = 1,$die = 0) {
if (PB_DEBUG_EXT == 1) {
if ($pre == 1)
echo "<pre style=\"background-color:white;\">";
print_r($what);
if ($pre == 1)
echo "</pre>";
if ($die == 1)
die;
}
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function SendMail($to,$from,$subject,$message,$to_name,$from_name) {
if ($to_name)
$to = "$to_name <$to>";
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text; charset=iso-8859-1\n";
if ($from_name) {
$headers .= "From: $from_name <$from>\n";
$headers .= "Reply-To: $from_name <$from>\n";
}
else {
$headers .= "From: $from\n";
$headers .= "Reply-To: $from\n";
}
$headers .= "X-Mailer: PHP/" . phpversion();
return mail($to, $subject, $message,$headers);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function FillVars($var,$fields,$with) {
$fields = explode (",",$fields);
foreach ($fields as $field)
if (!$var[$field])
!$var[$field] = $with;
return $var;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function CleanupString($string,$strip_tags = TRUE) {
$string = addslashes(trim($string));
if ($strip_tags)
$string = strip_tags($string);
return $string;
}
define("RX_EMAIL","^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$");
define("RX_CHARS","[a-z\ ]");
define("RX_DIGITS","[0-9]");
define("RX_ALPHA","[^a-z0-9_]");
define("RX_ZIP","[0-9\-]");
define("RX_PHONE","[0-9\-\+\(\)]");
/**
* description
*
* #param
*
* #return
*
* #access
*/
function CheckString($string,$min,$max,$regexp = "",$rx_result = FALSE) {
if (get_magic_quotes_gpc() == 0)
$string = CleanupString($string);
if (strlen($string) < $min)
return 1;
elseif (($max != 0) && (strlen($string) > $max))
return 2;
elseif ($regexp != "")
if ($rx_result == eregi($regexp,$string))
return 3;
return 0;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/// FIRST_NAME:S:3:60,LAST_NAME:S...
function ValidateVars($source,$vars) {
$vars = explode(",",$vars);
foreach ($vars as $var) {
list($name,$type,$min,$max) = explode(":",$var);
switch ($type) {
case "S":
$type = RX_CHARS;
$rx_result = FALSE;
break;
case "I":
$type = RX_DIGITS;
$rx_result = TRUE;
break;
case "E":
$type = RX_EMAIL;
$rx_result = FALSE;
break;
case "P":
$type = RX_PHONE;
$rx_result = TRUE;
break;
case "Z":
$type = RX_ZIP;
$rx_result = FALSE;
break;
case "A":
$type = "";
break;
case "F":
//experimental crap
$type = RX_ALPHA;
$rx_result = TRUE;
//$source[strtolower($name)] = str_replace(" ", "" , $source[strtolower($name)] );
break;
}
//var_dump($result);
if (($result = CheckString($source[strtolower($name)],$min,$max,$type,$rx_result)) != 0)
$errors[] = $name;
}
return is_array($errors) ? $errors : 0;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function ResizeImage($source,$destination,$size) {
if (PB_IMAGE_MAGICK == 1)
system( PB_IMAGE_MAGICK_PATH . "convert $source -resize {$size}x{$size} $destination");
else
copy($source,$destination);
}
/**
* uses microtime() to return the current unix time w/ microseconds
*
* #return float the current unix time in the form of seconds.microseconds
*
* #access public
*/
function GetMicroTime() {
list($usec,$sec) = explode(" ",microtime());
return (float) $usec + (float) $sec;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GetArrayPart($input,$from,$count) {
$return = array();
$max = count($input);
for ($i = $from; $i < $from + $count; $i++ )
if ($i<$max)
$return[] = $input[$i];
return $return;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function ReplaceAllImagesPath($htmldata,$image_path) {
$htmldata = stripslashes($htmldata);
// replacing IE formating style
$htmldata = str_replace("<IMG","<img",$htmldata);
// esmth, i dont know why i'm doing
preg_match_all("'<img.*?>'si",$htmldata,$images);
//<?//ing edit plus
foreach ($images[0] as $image)
$htmldata = str_replace($image,ReplaceImagePath($image,$image_path),$htmldata);
return $htmldata;//implode("\n",$html_out);
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function ReplaceImagePath($image,$replace) {
// removing tags
$image = stripslashes($image);
$image = str_replace("<","",$image);
$image = str_replace(">","",$image);
// exploging image in proprietes
$image_arr = explode(" ",$image);
for ($i = 0;$i < count($image_arr) ;$i++ ) {
if (stristr($image_arr[$i],"src")) {
// lets it :]
$image_arr[$i] = explode("=",$image_arr[$i]);
// modifing the image path
// i doing this
// replacing ',"
$image_arr[$i][1] = str_replace("'","",$image_arr[$i][1]);
$image_arr[$i][1] = str_replace("\"","",$image_arr[$i][1]);
//getting only image name
$image_arr[$i][1] = strrev(substr(strrev($image_arr[$i][1]),0,strpos(strrev($image_arr[$i][1]),"/")));
// building the image back
$image_arr[$i][1] = "\"" . $replace . $image_arr[$i][1] . "\"";
$image_arr[$i] = implode ("=",$image_arr[$i]);
}
}
// adding tags
return "<" . implode(" ",$image_arr) . ">";
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function DowloadAllImages($images,$path) {
foreach ($images as $image)
#SaveFileContents($path ."/".ExtractFileNameFromPath($image),#implode("",#file($image)));
}
function GetAllImagesPath($htmldata) {
$htmldata = stripslashes($htmldata);
// replacing IE formating style
$htmldata = str_replace("<IMG","<img",$htmldata);
// esmth, i dont know why i'm doing
preg_match_all("'<img.*?>'si",$htmldata,$images);
//<?//ing edit plus
foreach ($images[0] as $image)
$images_path[] = GetImageName($image);
return $images_path;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GetImagePath($image) {
// removing tags
$image = stripslashes($image);
$image = str_replace("<","",$image);
$image = str_replace(">","",$image);
// exploging image in proprietes
$image_arr = explode(" ",$image);
for ($i = 0;$i < count($image_arr) ;$i++ ) {
if (stristr($image_arr[$i],"src")) {
// lets it :]
$image_arr[$i] = explode("=",$image_arr[$i]);
// modifing the image path
// i doing this
// replacing ',"
$image_arr[$i][1] = str_replace("'","",$image_arr[$i][1]);
$image_arr[$i][1] = str_replace("\"","",$image_arr[$i][1]);
return strrev(substr(strrev($image_arr[$i][1]),0,strpos(strrev($image_arr[$i][1]),"/")));;
}
}
// adding tags
return "";
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GetImageName($image) {
// removing tags
$image = stripslashes($image);
$image = str_replace("<","",$image);
$image = str_replace(">","",$image);
// exploging image in proprietes
$image_arr = explode(" ",$image);
for ($i = 0;$i < count($image_arr) ;$i++ ) {
if (stristr($image_arr[$i],"src")) {
// lets it :]
$image_arr[$i] = explode("=",$image_arr[$i]);
// modifing the image path
// i doing this
// replacing ',"
$image_arr[$i][1] = str_replace("'","",$image_arr[$i][1]);
$image_arr[$i][1] = str_replace("\"","",$image_arr[$i][1]);
return $image_arr[$i][1];
}
}
// adding tags
return "";
}
/**
* reinventing the wheel [badly]
*
* #param somthin
*
* #return erroneous
*
* #access denied
*/
function ExtractFileNameFromPath($file) {
//return strrev(substr(strrev($file),0,strpos(strrev($file),"/")));
// sau ai putea face asha. umpic mai smart ca mai sus dar tot stupid
// daca le dai path fara slashes i.e. un filename prima returneaza "" asta taie primu char
//return substr($file,strrpos($file,"/") + 1,strlen($file) - strrpos($file,"/"));
// corect ar fi cred asha [observa smart usage`u de strRpos]
//return substr($file,strrpos($file,"/") + (strstr($file,"/") ? 1 : 0),strlen($file) - strrpos($file,"/"));
// sau putem folosi tactica `nute mai caca pe tine and rtm' shi facem asha
return basename($file);
// har har :]]
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function RemoveArraySlashes($array) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = RemoveArraySlashes($item);
else
$array[$key] = stripslashes($item);
return $array;
}
function AddArraySlashes($array) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = AddArraySlashes($item);
else
$array[$key] = addslashes($item);
return $array;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function Ahtmlentities($array) {
if (is_array($array))
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = ahtmlentities($item);
else
$array[$key] = htmlentities(stripslashes($item),ENT_COMPAT);
else
return htmlentities(stripslashes($array),ENT_COMPAT);
return $array;
}
function AStripSlasshes($array) {
if (is_array($array))
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = AStripSlasshes($item);
else
$array[$key] = stripslashes($item);
else
return stripslashes($array);
return $array;
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function Ahtml_entity_decode($array) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = ahtml_entity_decode($item);
else
$array[$key] = html_entity_decode($item,ENT_COMPAT);
return $array;
}
function array2xml ($name, $value, $indent = 1)
{
$indentstring = "\t";
for ($i = 0; $i < $indent; $i++)
{
$indentstring .= $indentstring;
}
if (!is_array($value))
{
$xml = $indentstring.'<'.$name.'>'.$value.'</'.$name.'>'."\n";
}
else
{
if($indent === 1)
{
$isindex = False;
}
else
{
$isindex = True;
while (list ($idxkey, $idxval) = each ($value))
{
if ($idxkey !== (int)$idxkey)
{
$isindex = False;
}
}
}
reset($value);
while (list ($key, $val) = each ($value))
{
if($indent === 1)
{
$keyname = $name;
$nextkey = $key;
}
elseif($isindex)
{
$keyname = $name;
$nextkey = $name;
}
else
{
$keyname = $key;
$nextkey = $key;
}
if (is_array($val))
{
$xml .= $indentstring.'<'.$keyname.'>'."\n";
$xml .= array2xml ($nextkey, $val, $indent+1);
$xml .= $indentstring.'</'.$keyname.'>'."\n";
}
else
{
$xml .= array2xml ($nextkey, $val, $indent);
}
}
}
return $xml;
}
function GetPhpContent($file) {
if (file_exists($file) ) {
$data = GetFileContents($file);
//replacing special chars in content
$data = str_replace("<?php","",$data);
$data = str_replace("?>","",$data);
return $data;
}
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function KeyArray($array,$recurse = 0 , $count = 1) {
if (is_array($array)) {
foreach ($array as $key => $val) {
$array[$key]["key"] = $count ++;
if ($recurse) {
foreach ($array[$key] as $k => $val)
if (is_array($val)) {
KeyArray($array[$key][$k] , $recurse , $count);
}
}
}
}
return $count + 1;
}
function RandomWord( $passwordLength ) {
$password = "";
for ($index = 1; $index <= $passwordLength; $index++) {
// Pick random number between 1 and 62
$randomNumber = rand(1, 62);
// Select random character based on mapping.
if ($randomNumber < 11)
$password .= Chr($randomNumber + 48 - 1); // [ 1,10] => [0,9]
else if ($randomNumber < 37)
$password .= Chr($randomNumber + 65 - 10); // [11,36] => [A,Z]
else
$password .= Chr($randomNumber + 97 - 36); // [37,62] => [a,z]
}
return $password;
}
function DeleteFolder($file) {
if (file_exists($file)) {
chmod($file,0777);
if (is_dir($file)) {
$handle = opendir($file);
while($filename = readdir($handle)) {
if ($filename != "." && $filename != "..") {
DeleteFolder($file."/".$filename);
}
}
closedir($handle);
rmdir($file);
} else {
unlink($file);
}
}
}
function GenerateRecordID($array) {
$max = 0;
if (is_array($array)) {
foreach ($array as $key => $val)
$max = ($key > $max ? $key : $max);
return $max + 1;
}
else return 1;
}
/*****************************************************
Links cripting for admin
DO NOT TOUCH UNLKESS YOU KNOW WHAT YOU ARE DOING
*****************************************************/
/**
* description
*
* #param
*
* #return
*
* #access
*/
function CryptLink($link) {
if (defined("PB_CRYPT_LINKS") && (PB_CRYPT_LINKS == 1)) {
if (stristr($link,"javascript:")) {
/* if (stristr($link,"window.location=")) {
$pos = strpos($link , "window.location=");
$js = substr($link , 0 , $pos + 17 );
$final = substr($link , $pos + 17 );
$final = substr($final, 0, strlen($final) - 1 );
//well done ... crypt the link now
$url = #explode("?" , $final);
if (!is_array($url))
$url[0] = $final;
$tmp = str_replace( $url[0] . "?" , "" , $final);
$uri = urlencode(urlencode(base64_encode(str_rot13($tmp))));
$link = $js . $url[0] . "?" . $uri . md5($uri) . "'";
}
*/
} else {
$url = #explode("?" , $link);
if (!is_array($url))
$url[0] = $link;
$tmp = str_replace( $url[0] . "?" , "" , $link);
$uri = urlencode(urlencode(base64_encode(str_rot13($tmp))));
$link = $url[0] . "?" . $uri . md5($uri);
}
}
return $link;
}
/************************************************************************/
/* SOME PREINITIALISATION CRAP*/
if (defined("PB_CRYPT_LINKS") && (PB_CRYPT_LINKS == 1) ) {
$key = key($_GET);
if (is_array($_GET) && (count($_GET) == 1) && ($_GET[$key] == "")) {
$tmp = $_SERVER["QUERY_STRING"];
//do the md5 check
$md5 = substr($tmp , -32);
$tmp = substr($tmp , 0 , strlen($tmp) - 32);
if ($md5 != md5($tmp)) {
//header("index.php?action=badrequest");
//exit;
die("Please dont change the links!");
}
$tmp = str_rot13(base64_decode(urldecode(urldecode($tmp))));
$tmp_array = #explode("&" , $tmp);
$tmp_array = is_array($tmp_array) ? $tmp_array : array($tmp);
if (is_array($tmp_array)) {
foreach ($tmp_array as $key => $val) {
$tmp2 = explode("=" , $val);
$out[$tmp2[0]] = $tmp2[1];
}
} else {
$tmp2 = explode("=" , $tmp);
$out[$tmp2[0]] = $tmp2[1];
}
$_GET = $out;
}
}
/***********************************************************************/
function ArrayReplace($what , $with , $array ) {
if ($array)
foreach ($array as $key => $item)
if (is_array($item))
$array[$key] = ArrayReplace($what , $with , $item);
else
$array[$key] = str_replace($what , $with , $item);
return $array;
}
function stri_replace( $find, $replace, $string )
{
$parts = explode( strtolower($find), strtolower($string) );
$pos = 0;
foreach( $parts as $key=>$part ){
$parts[ $key ] = substr($string, $pos, strlen($part));
$pos += strlen($part) + strlen($find);
}
return( join( $replace, $parts ) );
}
/**
* description
*
* #param
*
* #return
*
* #access
*/
function GMTDate($format , $date) {
global $_GMT;
return date($format , $date - $_GMT);
}
function putcsv ($array, $deliminator=",") {
$line = "";
foreach($array as $val) {
# remove any windows new lines,
# as they interfere with the parsing at the other end
$val = str_replace("\r\n", "\n", $val);
# if a deliminator char, a double quote char or a newline
# are in the field, add quotes
if(ereg("[$deliminator\"\n\r]", $val)) {
$val = '"'.str_replace('"', '""', $val).'"';
}#end if
$line .= $val.$deliminator;
}#end foreach
# strip the last deliminator
$line = substr($line, 0, (strlen($deliminator) * -1));
# add the newline
$line .= "\n";
# we don't care if the file pointer is invalid,
# let fputs take care of it
return $line;
}#end fputcsv()
function fputcsv ($fp, $array, $deliminator=",") {
return fputs($fp, putcsv($array,$delimitator));
}#end fputcsv()
/**
* description
*
* #param
*
* #return
*
* #access
*/
function is_subaction($sub,$action) {
return (bool)($_GET["sub"] == $sub) && ($_GET["action"] == $action);
}
?>
many thanks in advance
fputcsv() is a built in PHP function. This means you cannot name your own function the same thing.
If you need this code to work with PHP4, just check to see if the function exists first, then if not, create your own.
if (!function_exists('fputcsv')) {
// Your definition here
}
I am getting this PHP fatal error message: "Fatal error: Class PT_Fieldtype contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (EE_Fieldtype::display_field) in /.../pt_fieldtype.php on line 148"
However, when I open the file and do a search, the word "abstract" is nowhere to be found at all. Thanks for the help!
Edit: Here's the code in question. My bad for not showing it before.
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
if (! defined('PT_FIELD_PACK_VER'))
{
// get the version from config.php
require PATH_THIRD.'pt_field_pack/config.php';
define('PT_FIELD_PACK_VER', $config['version']);
}
/**
* P&T Fieldtype Base Class
*
* #package P&T Field Pack
* #author Brandon Kelly <brandon#pixelandtonic.com>
* #copyright Copyright (c) 2010 Pixel & Tonic, LLC
*/
class PT_Fieldtype extends EE_Fieldtype {
/**
* PT_Fieldtype Constructor
*/
function PT_Fieldtype()
{
parent::EE_Fieldtype();
}
// --------------------------------------------------------------------
/**
* Options Setting
*/
function options_setting($options=array(), $indent = '')
{
$r = '';
foreach($options as $name => $label)
{
if ($r !== '') $r .= "\n";
// is this just a blank option?
if (! $name && ! $label) $name = $label = ' ';
$r .= $indent . htmlentities($name);
// is this an optgroup?
if (is_array($label)) $r .= "\n".$this->options_setting($label, $indent.' ');
else if ($name != $label) $r .= ' : '.$label;
}
return $r;
}
// --------------------------------------------------------------------
/**
* Save Options Setting
*/
function save_options_setting($options = '', $total_levels = 1)
{
// prepare options
$options = preg_split('/[\r\n]+/', $options);
foreach($options as &$option)
{
$option_parts = preg_split('/\s:\s/', $option, 2);
$option = array();
$option['indent'] = preg_match('/^\s+/', $option_parts[0], $matches) ? strlen(str_replace("\t", ' ', $matches[0])) : 0;
$option['name'] = trim($option_parts[0]);
$option['value'] = isset($option_parts[1]) ? trim($option_parts[1]) : $option['name'];
}
return $this->_structure_options($options, $total_levels);
}
/**
* Structure Options
*/
private function _structure_options(&$options, $total_levels, $level = 1, $indent = -1)
{
$r = array();
while ($options)
{
if ($indent == -1 || $options[0]['indent'] > $indent)
{
$option = array_shift($options);
$children = (! $total_levels OR $level < $total_levels)
? $this->_structure_options($options, $total_levels, $level+1, $option['indent']+1)
: FALSE;
$r[(string)$option['name']] = $children ? $children : (string)$option['value'];
}
else if ($options[0]['indent'] <= $indent)
{
break;
}
}
return $r;
}
// --------------------------------------------------------------------
/**
* Prep Iterators
*/
function prep_iterators(&$tagdata)
{
// find {switch} tags
$this->_switches = array();
$tagdata = preg_replace_callback('/'.LD.'switch\s*=\s*([\'\"])([^\1]+)\1'.RD.'/sU', array(&$this, '_get_switch_options'), $tagdata);
$this->_count_tag = 'count';
$this->_iterator_count = 0;
}
/**
* Get Switch Options
*/
function _get_switch_options($match)
{
global $FNS;
$marker = LD.'SWITCH['.$FNS->random('alpha', 8).']SWITCH'.RD;
$this->_switches[] = array('marker' => $marker, 'options' => explode('|', $match[2]));
return $marker;
}
/**
* Parse Iterators
*/
function parse_iterators(&$tagdata)
{
// {switch} tags
foreach($this->_switches as $i => $switch)
{
$option = $this->_iterator_count % count($switch['options']);
$tagdata = str_replace($switch['marker'], $switch['options'][$option], $tagdata);
}
// update the count
$this->_iterator_count++;
// {count} tags
$tagdata = $this->EE->TMPL->swap_var_single($this->_count_tag, $this->_iterator_count, $tagdata);
}
}
// ====================================================================
/**
* P&T Multi Fieldtype Base Class
*
* #package P&T Field Pack
* #author Brandon Kelly <brandon#pixelandtonic.com>
* #copyright Copyright (c) 2010 Pixel & Tonic, LLC
*/
class PT_Multi_Fieldtype extends PT_Fieldtype {
var $default_field_settings = array(
'options' => array(
'Option 1' => 'Option 1',
'Option 2' => 'Option 2',
'Option 3' => 'Option 3'
)
);
var $default_cell_settings = array(
'options' => array(
'Opt 1' => 'Opt 1',
'Opt 2' => 'Opt 2'
)
);
var $default_tag_params = array(
'sort' => '',
'backspace' => '0'
);
var $total_option_levels = 1;
// --------------------------------------------------------------------
/**
* Display Field Settings
*/
function display_settings($data)
{
// load the language file
$this->EE->lang->loadfile($this->class);
$options = isset($data['options']) ? $data['options'] : array();
$input_name = $this->class.'_options';
$this->EE->table->add_row(
lang($this->class.'_options', $input_name) . '<br />'
. lang('field_list_instructions') . '<br /><br />'
. lang('option_setting_examples'),
'<textarea id="'.$input_name.'" name="'.$input_name.'" rows="6">'.$this->options_setting($options).'</textarea>'
);
}
/**
* Display Cell Settings
*/
function display_cell_settings($data)
{
// load the language file
$this->EE->lang->loadfile($this->class);
$options = isset($data['options']) ? $data['options'] : array();
return array(
array(
lang($this->class.'_options'),
'<textarea class="matrix-textarea" name="options" rows="4">'.$this->options_setting($options).'</textarea>'
)
);
}
// --------------------------------------------------------------------
/**
* Save Field Settings
*/
function save_settings($data)
{
$post = $this->EE->input->post($this->class.'_options');
// replace quotes
$post = str_replace('"', '"', $post);
return array(
'options' => $this->save_options_setting($post, $this->total_option_levels)
);
}
/**
* Save Cell Settings
*/
function save_cell_settings($settings)
{
// replace quotes
$settings['options'] = str_replace('"', '"', $settings['options']);
$settings['options'] = $this->save_options_setting($settings['options'], $this->total_option_levels);
return $settings;
}
// --------------------------------------------------------------------
/**
* Prep Field Data
*
* Ensures $field_data is an array.
*/
function prep_field_data(&$data)
{
if (! is_array($data))
{
$data = array_filter(preg_split("/[\r\n]+/", $data));
}
}
// --------------------------------------------------------------------
/**
* Display Field
*/
function display_field($data)
{
if (is_string($data)) $data = html_entity_decode($data);
return $this->_display_field($data, $this->field_name);
}
/**
* Display Cell
*/
function display_cell($data)
{
return $this->_display_field($data, $this->cell_name);
}
// --------------------------------------------------------------------
/**
* Save
*/
function save($data)
{
// replace quotes
return str_replace('"', '"', $data);
}
/**
* Save Cell
*/
function save_cell($data)
{
// replace quotes
return $this->save($data);
}
// --------------------------------------------------------------------
/**
* Find Options
*/
private function _find_option($needle, $haystack)
{
foreach ($haystack as $key => $value)
{
$r = $value;
if ($needle == $key OR (is_array($value) AND (($r = $this->_find_option($needle, $value)) !== FALSE)))
{
return $r;
}
}
return FALSE;
}
// --------------------------------------------------------------------
/**
* Replace Tag
*/
function replace_tag($data, $params = array(), $tagdata = FALSE)
{
if (! isset($this->settings['options']) || ! $this->settings['options'])
{
return $data;
}
if (! $tagdata)
{
return $this->replace_ul($data, $params);
}
$this->prep_field_data($data);
$r = '';
if ($this->settings['options'] && $data)
{
// optional sorting
if (isset($params['sort']) && $params['sort'])
{
$sort = strtolower($params['sort']);
if ($sort == 'asc')
{
sort($data);
}
else if ($sort == 'desc')
{
rsort($data);
}
}
// offset and limit
if (isset($params['offset']) || isset($params['limit']))
{
$offset = isset($params['offset']) ? $params['offset'] : 0;
$limit = isset($params['limit']) ? $params['limit'] : count($data);
$data = array_splice($data, $offset, $limit);
}
// prepare for {switch} and {count} tags
$this->prep_iterators($tagdata);
foreach($data as $option_name)
{
if (($option = $this->_find_option($option_name, $this->settings['options'])) !== FALSE)
{
// copy $tagdata
$option_tagdata = $tagdata;
// simple var swaps
$option_tagdata = $this->EE->TMPL->swap_var_single('option', $option, $option_tagdata);
$option_tagdata = $this->EE->TMPL->swap_var_single('option_name', $option_name, $option_tagdata);
// parse {switch} and {count} tags
$this->parse_iterators($option_tagdata);
$r .= $option_tagdata;
}
}
if (isset($params['backspace']) && $params['backspace'])
{
$r = substr($r, 0, -$params['backspace']);
}
}
return $r;
}
// --------------------------------------------------------------------
/**
* Unordered List
*/
function replace_ul($data, $params = array())
{
return "<ul>\n"
. $this->replace_tag($data, $params, " <li>{option}</li>\n")
. '</ul>';
}
/**
* Ordered List
*/
function replace_ol($data, $params = array())
{
return "<ol>\n"
. $this->replace_tag($data, $params, " <li>{option}</li>\n")
. '</ol>';
}
// --------------------------------------------------------------------
/**
* All Options
*/
function replace_all_options($data, $params = array(), $tagdata = FALSE, $options = FALSE, $iterator_count = 0)
{
if (! $tagdata)
{
return "<ul>\n"
. $this->replace_all_options($data, $params, " <li>{option}</li>\n")
. "</ul>";
}
PT_Multi_Fieldtype::prep_field_data($data);
$r = '';
if ($options === FALSE)
{
$options = $this->settings['options'];
}
if ($options)
{
// optional sorting
if (isset($params['sort']) && $params['sort'])
{
$sort = strtolower($params['sort']);
if ($sort == 'asc')
{
asort($options);
}
else if ($sort == 'desc')
{
arsort($options);
}
}
// prepare for {switch} and {count} tags
$this->prep_iterators($tagdata);
$this->_iterator_count += $iterator_count;
foreach($options as $option_name => $option)
{
if (is_array($option))
{
$sub_params = array_merge($params, array('backspace' => '0'));
$r .= $this->replace_all_options($data, $sub_params, $tagdata, $option, $this->_iterator_count);
}
else
{
// copy $tagdata
$option_tagdata = $tagdata;
// simple var swaps
$option_tagdata = $this->EE->TMPL->swap_var_single('option', $option, $option_tagdata);
$option_tagdata = $this->EE->TMPL->swap_var_single('option_name', $option_name, $option_tagdata);
$option_tagdata = $this->EE->TMPL->swap_var_single('selected', (in_array($option_name, $data) ? 1 : 0), $option_tagdata);
// parse {switch} and {count} tags
$this->parse_iterators($option_tagdata);
$r .= $option_tagdata;
}
}
if (isset($params['backspace']) && $params['backspace'])
{
$r = substr($r, 0, -$params['backspace']);
}
}
return $r;
}
// --------------------------------------------------------------------
/**
* Is Selected?
*/
function replace_selected($data, $params = array())
{
$this->prep_field_data($data);
return (isset($params['option']) AND in_array($params['option'], $data)) ? 1 : 0;
}
/**
* Total Selections
*/
function replace_total_selections($data, $params = array())
{
$this->prep_field_data($data);
return $field_data ? (string) count($data) : '0';
}
}
The answer of your question is on line 148 of this file...
Maybe you are using a class with abstract methods without inheriting them that is rejected, make sure you implement all of them and after show us some code. ;-)
This might be quite simple but I am stumped . Here is what I am trying to do load a csv file into a an entity . I found a php plugin but couldn't figure out how to install so I downloaded the plugin and took the script to read a csv file into my bundle Acme\StoreBundle and actually placed the script (sfCsvReader.php) in the entity folder in the bundle when I attempt to run this on the web I get the following error
Fatal error: Class 'Acme\StoreBundle\Controller\sfCsvReader' not found in /home/jan/symfonysandbox/src/Acme/StoreBundle/Controller/LoadCSVController.php on line 26
My Controller file is as follows
<?php
namespace Acme\StoreBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Acme\StoreBundle\Entity\Congress;
use Acme\StoreBundle\Entity\sfCsvReader;
use Symfony\Component\HttpFoundation\Response;
class LoadCSVController extends Controller
{
/**
* #Route("/load/{name}")
* #Template()
*/
public function indexAction()
{
$congress = new Congress();
$path = '~/Documents/congress.csv';
$reader = new sfCsvReader($path);
$reader->setSelectColumns('column_A, column_B');
$reader->open();
while ($data = $reader->read())
{
$congress->setTitle($data['column_A']);
$congress->setName($data['column_B']);
$em = $this->getDoctrine()->getManager();
$em->persist($congress);
$em->flush();
return new Response('Created congress id '.$congress->getId() .'for'.$congress->getTitle().'for'.$congress->getName());
}
$reader->close();
}
}
the script its calling is
sfCsvReader
<?php
namespace Acme\StoreBundle\Controller;
/**
* sfCsvReader
* by Carlos Escribano <carlos#markhaus.com>
*
* $csv = new sfCsvReader("/path/to/a/csv/file.csv");
* $csv->open();
* $csv->setSelectColumns('field_A, field_B'); // or array('field_A', 'field_B')
* while ($data = $csv->read())
* {
* // do something with $data['field_A'] and $data['field_B']
* }
* $csv->close();
*
* --- Alternative ---
* $csv = new sfCsvReader("/path/to/a/csv/file.csv");
* $csv->setSelectColumns('field_A, field_B'); // or array('field_A', 'field_B')
* $csv->open();
* ...
* --- Alternative: NUMERICAL INDEXES ---
* $csv = new sfCsvReader("/path/to/a/csv/file.csv");
* $csv->open();
* while ($data = $csv->read())
* {
* // do something with $data[0] and $data[1]
* }
* $csv->close();
*
*
* --- CHARSET ---
* $to = 'ISO-8859-1';
* $from = 'UTF-8';
* $csv->setCharset($to);
* $csv->setCharset($to, $from);
*/
class sfCsvReader
{
private
$header;
private
$file,
$path,
$initialized;
private
$length,
$delimiter,
$enclosure,
$to,
$from;
/**
* #param string $path Path to the file to read
* #param char $delimiter Character delimiting fields (Optional)
* #param char $enclosure Character enclosing fields (Optional)
* #param integer $length PHP's fgetcsv length parameter (Optional)
*/
function __construct($path, $delimiter = ',', $enclosure = '"', $length = null)
{
$this->path = $path;
$this->length = $length;
$this->delimiter = $delimiter;
$this->enclosure = $enclosure;
$this->header = array(
'map' => null,
'selected' => array()
);
$this->initialized = false;
}
public function close()
{
if ($this->file !== null)
{
fclose($this->file);
$this->file = null;
$this->initialized = false;
}
}
public function open($path = null)
{
$this->close();
if ($path !== null)
{
$this->path = $path;
}
if (!($this->file = fopen($this->path, "r")))
{
throw new Exception("File can not be opened (".$this->path.").");
}
$this->initialized = true;
$this->map();
}
public function setSelectColumns($selected = array())
{
$this->test = true;
if (!is_array($selected))
{
$selected = explode(',', preg_replace('/\s+/', '', $selected));
}
$this->header['selected'] = $selected;
$this->map();
}
public function clearSelectColumns()
{
$this->header['selected'] = array();
$this->map();
}
private function map()
{
if ($this->initialized)
{
$this->all = false;
$x = count($this->header['selected']); // N. of selected columns
$y = 0; // N. of real columns
$z = 0; // N. of matching columns
if ($x == 0)
{ // No selection. All fields.
$this->header['map'] = null;
}
else
{
$this->header['map'] = array();
fseek($this->file, 0, SEEK_SET);
if ($line = fgetcsv($this->file, $this->length, $this->delimiter, $this->enclosure))
{
$y = count($line);
if ($y > 0)
{
$common = array_intersect($line, $this->header['selected']);
$z = count($common);
if (($y < $x) || (($x > $z) && ($z > 0)))
{ // More columns in selection than in file or less common columns than selection
throw new Exception("Too much columns or non existing columns in selection (LINE: $y, SEL: $x, COMMON: $z).");
}
if ($z == 0)
{ // Relaxed Mapping: 0 matches found, numerical.
foreach ($this->header['selected'] as $i => $name)
{
$this->header['map'][$name] = $i;
}
fseek($this->file, 0, SEEK_SET);
}
else if ($z == $x)
{ // Absolute Mapping: First line is header.
foreach ($line as $i => $name)
{
$this->header['map'][$name] = $i;
}
}
} // Has columns
} // Read line
} // N columns selected
} // Initialized
}
public function read()
{
if (!$this->initialized)
{
throw new Exception('sfCsvReader is not ready.');
}
if ($line = fgetcsv($this->file, $this->length, $this->delimiter, $this->enclosure))
{
if (is_array($this->header['map']))
{
$res = array();
foreach ($this->header['selected'] as $name)
{
if ($this->to !== null)
{
$res[$name] = $this->encode($line[$this->header['map'][$name]], $this->to, $this->from);
}
else
{
$res[$name] = $line[$this->header['map'][$name]];
}
}
return $res;
}
else
{
return $line;
}
}
else
{
return null;
}
}
private function encode($str, $to, $from = null)
{
if ($from === null)
{
$from = mb_detect_encoding($str);
}
if (function_exists('iconv'))
{
return iconv($from, $to, $str);
}
else
{
return mb_convert_encoding($str, $to, $from);
}
}
public function setCharset($to, $from = null)
{
$this->to = $to;
$this->from = $from;
}
function __destruct()
{
$this->close();
}
}
Are you loading the script before call them?
Try to add the following code to app/autoload.php inside the $loader->registerNamespaces(array(... array declaration:
'SfCsvReader' => __DIR__.'/../src/Acme/StoreBundle/Entity/sfCsvReader.php',
After that, rename the namespace inside the sfCsvReader.php file to namespace SfCsvReader\sfCsvReader; and replace the namespace requesting in your controller to use SfCsvReader\sfCsvReader;.
This should work fine, but maybe you should move your file to a more proper directory, for example in the vendor/sfCsvReader directory of the project.
You can follow the recommendations in the Symfony 2.0 documentation.
The autoloading info are in the following link The ClassLoader Component.
More info about namespaces can be found in php.net.