Why Database cache errors in Codeigniter3? - codeigniter

I am using Codeigniter 3 for my development and below is the Database configuration details. I have also enabled database session, so I can store session data in the Database.
Here is my Database configuration
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'tel',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => TRUE,
'cache_on' => TRUE,
'cachedir' => '/application/cache',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => TRUE,
'compress' => TRUE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
After enabling sessions, I get an exception
An uncaught Exception was encountered
Type: Exception
Message: Configured database connection has cache enabled. Aborting.
Filename: D:\My data\project\wamp\www\fertilize\system\libraries\Session\drivers\Session_database_driver.php
Line Number: 98
Backtrace:
File: D:\My data\project\wamp\www\fertilize\application\core\MY_Controller.php
Line: 11
Function: __construct
File: D:\My data\project\wamp\www\fertilize\application\libraries\Main_Controller.php
I am not sure what is the reason for this, please help.

Above exception is not an error but a Codeigniter 3 security feature built into the framework. If you check system/Session/drivers/Session_database_driver.php, you can see this exception in the code along with few other exceptions.
public function __construct(&$params)
{
parent::__construct($params);
$CI =& get_instance();
isset($CI->db) OR $CI->load->database();
$this->_db = $CI->db;
if ( ! $this->_db instanceof CI_DB_query_builder)
{
throw new Exception('Query Builder not enabled for the configured database. Aborting.');
}
elseif ($this->_db->pconnect)
{
throw new Exception('Configured database connection is persistent. Aborting.');
}
elseif ($this->_db->cache_on)
{
throw new Exception('Configured database connection has cache enabled. Aborting.');
}
$db_driver = $this->_db->dbdriver.(empty($this->_db->subdriver) ? '' : '_'.$this->_db->subdriver);
if (strpos($db_driver, 'mysql') !== FALSE)
{
$this->_platform = 'mysql';
}
elseif (in_array($db_driver, array('postgre', 'pdo_pgsql'), TRUE))
{
$this->_platform = 'postgre';
}
The reason for the exception is since you are enabling sessions(stored in the database) at the same time using database caching globally. By doing this, your session queries will save to cache posing a security risk. You can avoid this by using local database caching.
for more details on how to use local db cache - http://www.codeigniter.com/user_guide/database/caching.html?highlight=database%20cache
As a good practice make sure to create a folder call db under application/cache(application/cache/db) and use it for database cache, to separate file cache from Database cache.
If you still want to keep database caching global, you can use Redis or Memcache as session driver which will avoid session queries in database and fix your problem (http://www.codeigniter.com/user_guide/libraries/sessions.html?highlight=session%20class).

I solved by changing some code in Session_database_driver.php
<?php
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014 - 2018, British Columbia Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* #package CodeIgniter
* #author EllisLab Dev Team
* #copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
* #copyright Copyright (c) 2014 - 2018, British Columbia Institute of Technology (http://bcit.ca/)
* #license http://opensource.org/licenses/MIT MIT License
* #link https://codeigniter.com
* #since Version 3.0.0
* #filesource
*/
defined('BASEPATH') or exit('No direct script access allowed');
/**
* CodeIgniter Session Database Driver
*
* #package CodeIgniter
* #subpackage Libraries
* #category Sessions
* #author Andrey Andreev
* #link https://codeigniter.com/user_guide/libraries/sessions.html
*/
class CI_Session_database_driver extends CI_Session_driver implements SessionHandlerInterface
{
/**
* DB object
*
* #var object
*/
protected $_db;
/**
* Row exists flag
*
* #var bool
*/
protected $_row_exists = FALSE;
/**
* Lock "driver" flag
*
* #var string
*/
protected $_platform;
// ------------------------------------------------------------------------
/**
* Class constructor
*
* #param array $params Configuration parameters
* #return void
*/
public function __construct(&$params)
{
parent::__construct($params);
$CI = &get_instance();
isset($CI->db) or $CI->load->database();
$this->_db = $CI->db;
if (!$this->_db instanceof CI_DB_query_builder) {
throw new Exception('Query Builder not enabled for the configured database. Aborting.');
} elseif ($this->_db->pconnect) {
throw new Exception('Configured database connection is persistent. Aborting.');
} elseif ($this->_db->cache_on) {
//20210908 - MP - Removed check on cache active. Managed to disabled cache just before running session queries, reactivating cache after that
//throw new Exception('Configured database connection has cache enabled. Aborting.');
}
$db_driver = $this->_db->dbdriver . (empty($this->_db->subdriver) ? '' : '_' . $this->_db->subdriver);
if (strpos($db_driver, 'mysql') !== FALSE) {
$this->_platform = 'mysql';
} elseif (in_array($db_driver, array('postgre', 'pdo_pgsql'), TRUE)) {
$this->_platform = 'postgre';
}
// Note: BC work-around for the old 'sess_table_name' setting, should be removed in the future.
if (!isset($this->_config['save_path']) && ($this->_config['save_path'] = config_item('sess_table_name'))) {
log_message('debug', 'Session: "sess_save_path" is empty; using BC fallback to "sess_table_name".');
}
}
// ------------------------------------------------------------------------
/**
* Open
*
* Initializes the database connection
*
* #param string $save_path Table name
* #param string $name Session cookie name, unused
* #return bool
*/
public function open($save_path, $name)
{
if (empty($this->_db->conn_id) && !$this->_db->db_connect()) {
return $this->_fail();
}
return $this->_success;
}
// ------------------------------------------------------------------------
/**
* Read
*
* Reads session data and acquires a lock
*
* #param string $session_id Session ID
* #return string Serialized session data
*/
public function read($session_id)
{
if ($cache_enabled = $this->_db->cache_on) {
$this->_db->cache_off();
}
if ($this->_get_lock($session_id) !== FALSE) {
// Prevent previous QB calls from messing with our queries
$this->_db->reset_query();
// Needed by write() to detect session_regenerate_id() calls
$this->_session_id = $session_id;
$this->_db
->select('data')
->from($this->_config['save_path'])
->where('id', $session_id);
if ($this->_config['match_ip']) {
$this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']);
}
if (!($result = $this->_db->get()) or ($result = $result->row()) === NULL) {
// PHP7 will reuse the same SessionHandler object after
// ID regeneration, so we need to explicitly set this to
// FALSE instead of relying on the default ...
$this->_row_exists = FALSE;
$this->_fingerprint = md5('');
if ($cache_enabled) {
$this->_db->cache_on();
}
return '';
}
// PostgreSQL's variant of a BLOB datatype is Bytea, which is a
// PITA to work with, so we use base64-encoded data in a TEXT
// field instead.
$result = ($this->_platform === 'postgre')
? base64_decode(rtrim($result->data))
: $result->data;
$this->_fingerprint = md5($result);
$this->_row_exists = TRUE;
if ($cache_enabled) {
$this->_db->cache_on();
}
return $result;
}
$this->_fingerprint = md5('');
if ($cache_enabled) {
$this->_db->cache_on();
}
return '';
}
// ------------------------------------------------------------------------
/**
* Write
*
* Writes (create / update) session data
*
* #param string $session_id Session ID
* #param string $session_data Serialized session data
* #return bool
*/
public function write($session_id, $session_data)
{
if ($cache_enabled = $this->_db->cache_on) {
$this->_db->cache_off();
}
// Prevent previous QB calls from messing with our queries
$this->_db->reset_query();
// Was the ID regenerated?
if (isset($this->_session_id) && $session_id !== $this->_session_id) {
if (!$this->_release_lock() or !$this->_get_lock($session_id)) {
if ($cache_enabled) {
$this->_db->cache_on();
}
return $this->_fail();
}
$this->_row_exists = FALSE;
$this->_session_id = $session_id;
} elseif ($this->_lock === FALSE) {
if ($cache_enabled) {
$this->_db->cache_on();
}
return $this->_fail();
}
if ($this->_row_exists === FALSE) {
$insert_data = array(
'id' => $session_id,
'ip_address' => $_SERVER['REMOTE_ADDR'],
'timestamp' => time(),
'data' => ($this->_platform === 'postgre' ? base64_encode($session_data) : $session_data)
);
if ($this->_db->insert($this->_config['save_path'], $insert_data)) {
$this->_fingerprint = md5($session_data);
$this->_row_exists = TRUE;
if ($cache_enabled) {
$this->_db->cache_on();
}
return $this->_success;
}
if ($cache_enabled) {
$this->_db->cache_on();
}
return $this->_fail();
}
$this->_db->where('id', $session_id);
if ($this->_config['match_ip']) {
$this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']);
}
$update_data = array('timestamp' => time());
if ($this->_fingerprint !== md5($session_data)) {
$update_data['data'] = ($this->_platform === 'postgre')
? base64_encode($session_data)
: $session_data;
}
if ($this->_db->update($this->_config['save_path'], $update_data)) {
$this->_fingerprint = md5($session_data);
if ($cache_enabled) {
$this->_db->cache_on();
}
return $this->_success;
}
if ($cache_enabled) {
$this->_db->cache_on();
}
return $this->_fail();
}
// ------------------------------------------------------------------------
/**
* Close
*
* Releases locks
*
* #return bool
*/
public function close()
{
return ($this->_lock && !$this->_release_lock())
? $this->_fail()
: $this->_success;
}
// ------------------------------------------------------------------------
/**
* Destroy
*
* Destroys the current session.
*
* #param string $session_id Session ID
* #return bool
*/
public function destroy($session_id)
{
if ($cache_enabled = $this->_db->cache_on) {
$this->_db->cache_off();
}
if ($this->_lock) {
// Prevent previous QB calls from messing with our queries
$this->_db->reset_query();
$this->_db->where('id', $session_id);
if ($this->_config['match_ip']) {
$this->_db->where('ip_address', $_SERVER['REMOTE_ADDR']);
}
if (!$this->_db->delete($this->_config['save_path'])) {
if ($cache_enabled) {
$this->_db->cache_on();
}
return $this->_fail();
}
}
if ($this->close() === $this->_success) {
$this->_cookie_destroy();
if ($cache_enabled) {
$this->_db->cache_on();
}
return $this->_success;
}
if ($cache_enabled) {
$this->_db->cache_on();
}
return $this->_fail();
}
// ------------------------------------------------------------------------
/**
* Garbage Collector
*
* Deletes expired sessions
*
* #param int $maxlifetime Maximum lifetime of sessions
* #return bool
*/
public function gc($maxlifetime)
{
if ($cache_enabled = $this->_db->cache_on) {
$this->_db->cache_off();
}
// Prevent previous QB calls from messing with our queries
$this->_db->reset_query();
$ret = $this->_db->delete($this->_config['save_path'], 'timestamp < ' . (time() - $maxlifetime));
if ($cache_enabled) {
$this->_db->cache_on();
}
return ($ret)
? $this->_success
: $this->_fail();
}
// ------------------------------------------------------------------------
/**
* Get lock
*
* Acquires a lock, depending on the underlying platform.
*
* #param string $session_id Session ID
* #return bool
*/
protected function _get_lock($session_id)
{
if ($cache_enabled = $this->_db->cache_on) {
$this->_db->cache_off();
}
if ($this->_platform === 'mysql') {
$arg = md5($session_id . ($this->_config['match_ip'] ? '_' . $_SERVER['REMOTE_ADDR'] : ''));
if ($this->_db->query("SELECT GET_LOCK('" . $arg . "', 300) AS ci_session_lock")->row()->ci_session_lock) {
$this->_lock = $arg;
if ($cache_enabled) {
$this->_db->cache_on();
}
return TRUE;
}
if ($cache_enabled) {
$this->_db->cache_on();
}
return FALSE;
} elseif ($this->_platform === 'postgre') {
$arg = "hashtext('" . $session_id . "')" . ($this->_config['match_ip'] ? ", hashtext('" . $_SERVER['REMOTE_ADDR'] . "')" : '');
if ($this->_db->simple_query('SELECT pg_advisory_lock(' . $arg . ')')) {
$this->_lock = $arg;
if ($cache_enabled) {
$this->_db->cache_on();
}
return TRUE;
}
if ($cache_enabled) {
$this->_db->cache_on();
}
return FALSE;
}
if ($cache_enabled) {
$this->_db->cache_on();
}
return parent::_get_lock($session_id);
}
// ------------------------------------------------------------------------
/**
* Release lock
*
* Releases a previously acquired lock
*
* #return bool
*/
protected function _release_lock()
{
if (!$this->_lock) {
return TRUE;
}
if ($cache_enabled = $this->_db->cache_on) {
$this->_db->cache_off();
}
if ($this->_platform === 'mysql') {
if ($this->_db->query("SELECT RELEASE_LOCK('" . $this->_lock . "') AS ci_session_lock")->row()->ci_session_lock) {
$this->_lock = FALSE;
if ($cache_enabled) {
$this->_db->cache_on();
}
return TRUE;
}
return FALSE;
} elseif ($this->_platform === 'postgre') {
if ($this->_db->simple_query('SELECT pg_advisory_unlock(' . $this->_lock . ')')) {
$this->_lock = FALSE;
if ($cache_enabled) {
$this->_db->cache_on();
}
return TRUE;
}
if ($cache_enabled) {
$this->_db->cache_on();
}
return FALSE;
}
if ($cache_enabled) {
$this->_db->cache_on();
}
return parent::_release_lock();
}
}

Simply, just go to config/database.php and set $db['default']['pconnect'] = FALSE;

Related

Phalcon 4 messageEmpty File Validation

Does anyone know how to modify the messageEmpty in the file validator on Phalcon 4. I tried using the same method as in Phalcon 3 but it doesn't work.
This is my Validator:
$field->addValidator(new \Phalcon\Validation\Validator\File([
"allowedTypes" => [
"text/plain"
],
"messageEmpty" => 'Message empty',
"messageType" => _('Please upload a txt file')
]));
$field->setLabel(_('Upload List'));
This is the message i get after run $this->form->isValid($_FILES)
object(Phalcon\Messages\Messages)#192 (2) {
["position":protected]=>
int(0)
["messages":protected]=>
array(1) {
[0]=>
object(Phalcon\Messages\Message)#191 (5) {
["code":protected]=>
int(0)
["field":protected]=>
string(8) "robinson"
["message":protected]=>
string(32) "Field robinson must not be empty"
["type":protected]=>
string(42) "Phalcon\Validation\Validator\File\MimeType"
["metaData":protected]=>
array(0) {
}
}
}
}
Finally, I created a custom validator:
/**
* Class FileValidator
* #package Api\Forms\Core\Validators\File
* #author Iulian Gafiu <julian#clickmedia.es>
*/
class FileValidator extends AbstractValidator {
/**
* #var array
*/
protected $params;
/**
* IsEmpty constructor.
* #param array $options
*/
public function __construct(array $options = []){
$this->params = $options;
parent::__construct($options);
}
/**
* #inheritDoc
*/
public function validate(\Phalcon\Validation $validation, $field): bool{
if($_FILES[$field]['size'] <= 0){
if(!isset($this->params['messageEmpty']) || empty($this->params['messageEmpty'])){
$this->params['messageEmpty'] = sprintf(_('%s cannot be empty'), $field);
}
$validation->appendMessage(
new Message($this->params['messageEmpty'], $field, 'FileEmpty')
);
return false;
}else{
if(isset($this->params['maxSize']) && !empty($this->params['maxSize'])){
if($this->human2byte(strtolower($this->params['maxSize'])) < $_FILES[$field]['size']){
$validation->appendMessage(
new Message($this->params['messageMaxSize'], $field, 'MaxSize')
);
return false;
}
}
if(isset($this->params['allowedTypes']) && !empty($this->params['allowedTypes'])){
if(!in_array($_FILES[$field]['type'], $this->params['allowedTypes'])){
$validation->appendMessage(
new Message($this->params['messageType'], $field, 'allowedTypes')
);
return false;
}
}
}
return true;
}
/**
* #param $value
* #return string|string[]|null
* #author Eugene Kuzmenko
* #see https://stackoverflow.com/questions/11807115/php-convert-kb-mb-gb-tb-etc-to-bytes
*/
public function human2byte($value) {
return preg_replace_callback('/^\s*(\d+)\s*(?:([kmgt]?)b?)?\s*$/i', function ($m) {
switch (strtolower($m[2])) {
case 't': $m[1] *= 1024;
case 'g': $m[1] *= 1024;
case 'm': $m[1] *= 1024;
case 'k': $m[1] *= 1024;
}
return $m[1];
}, $value);
}
}
Then I use it on my form:
$field->addValidator(new FileValidator([
'maxSize' => '112M',
'allowedTypes' => [
"text/plain"
],
'messageEmpty' => _('Please upload a file'),
'messageMaxSize' => _('File size exceeds the max permitted'),
'messageType' => _('Please upload a formated txt file')
]));

CodeIgniter Unable to connect to database

when i open CodeIgniter project than it can display not able to connect to database
Error message
A Database Error Occurred
Unable to connect to your database server using the provided settings.
Filename: C:\wamp\www\CodeIgniter-Standard-Project-master\system\database\DB_driver.php
Line Number: 76
DB_driver.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class CI_DB_driver {
var $username = 'root';
var $password = '';
var $hostname = 'localhost';
var $database = 'groups';
var $dbdriver = 'mysql';
var $dbprefix = '';
var $char_set = 'utf8';
var $dbcollat = 'utf8_general_ci';
var $autoinit = TRUE; // Whether to automatically initialize the DB
var $swap_pre = '';
var $port = '';
var $pconnect = true;
var $conn_id = FALSE;
var $result_id = FALSE;
var $db_debug = true;
var $benchmark = 0;
var $query_count = 0;
var $bind_marker = '?';
var $save_queries = TRUE;
var $queries = array();
var $query_times = array();
var $data_cache = array();
var $trans_enabled = TRUE;
var $trans_strict = TRUE;
var $_trans_depth = 0;
var $_trans_status = TRUE; // Used with transactions to determine if a rollback should occur
var $cache_on = FALSE;
var $cachedir = '';
var $cache_autodel = FALSE;
var $CACHE; // The cache class object
var $_protect_identifiers = TRUE;
var $_reserved_identifiers = array('*'); // Identifiers that should NOT be escaped
// These are use with Oracle
var $stmt_id;
var $curs_id;
var $limit_used;
function __construct($params)
{
if (is_array($params))
{
foreach ($params as $key => $val)
{
$this->$key = $val;
}
}
log_message('debug', 'Database Driver Class Initialized');
}
function initialize()
{
// If an existing connection resource is available
// there is no need to connect and select the database
if (is_resource($this->conn_id) OR is_object($this->conn_id))
{
return TRUE;
}
$this->conn_id = ($this->pconnect == FALSE) ? $this->db_connect() : $this->db_pconnect();
// No connection resource? Throw an error
if ( ! $this->conn_id)
{
log_message('error', 'Unable to connect to the database');
if ($this->db_debug)
{
$this->display_error('db_unable_to_connect');
}
return FALSE;
}
// ----------------------------------------------------------------
// Select the DB... assuming a database name is specified in the config file
if ($this->database != '')
{
if ( ! $this->db_select())
{
log_message('error', 'Unable to select database: '.$this->database);
if ($this->db_debug)
{
$this->display_error('db_unable_to_select', $this->database);
}
return FALSE;
}
else
{
// We've selected the DB. Now we set the character set
if ( ! $this->db_set_charset($this->char_set, $this->dbcollat))
{
return FALSE;
}
return TRUE;
}
}
return TRUE;
}
// --------------------------------------------------------------------
function db_set_charset($charset, $collation)
{
if ( ! $this->_db_set_charset($this->char_set, $this->dbcollat))
{
log_message('error', 'Unable to set database connection charset: '.$this->char_set);
if ($this->db_debug)
{
$this->display_error('db_unable_to_set_charset', $this->char_set);
}
return FALSE;
}
return TRUE;
}
function platform()
{
return $this->dbdriver;
}
function version()
{
if (FALSE === ($sql = $this->_version()))
{
if ($this->db_debug)
{
return $this->display_error('db_unsupported_function');
}
return FALSE;
}
$driver_version_exceptions = array('oci8', 'sqlite', 'cubrid');
if (in_array($this->dbdriver, $driver_version_exceptions))
{
return $sql;
}
else
{
$query = $this->query($sql);
return $query->row('ver');
}
}
// --------------------------------------------------------------------
function query($sql, $binds = FALSE, $return_object = TRUE)
{
if ($sql == '')
{
if ($this->db_debug)
{
log_message('error', 'Invalid query: '.$sql);
return $this->display_error('db_invalid_query');
}
return FALSE;
}
// Verify table prefix and replace if necessary
if ( ($this->dbprefix != '' AND $this->swap_pre != '') AND ($this->dbprefix != $this->swap_pre) )
{
$sql = preg_replace("/(\W)".$this->swap_pre."(\S+?)/", "\\1".$this->dbprefix."\\2", $sql);
}
if ($this->cache_on == TRUE AND stristr($sql, 'SELECT'))
{
if ($this->_cache_init())
{
$this->load_rdriver();
if (FALSE !== ($cache = $this->CACHE->read($sql)))
{
return $cache;
}
}
}
// Compile binds if needed
if ($binds !== FALSE)
{
$sql = $this->compile_binds($sql, $binds);
}
// Save the query for debugging
if ($this->save_queries == TRUE)
{
$this->queries[] = $sql;
}
// Start the Query Timer
$time_start = list($sm, $ss) = explode(' ', microtime());
// Run the Query
if (FALSE === ($this->result_id = $this->simple_query($sql)))
{
if ($this->save_queries == TRUE)
{
$this->query_times[] = 0;
}
// This will trigger a rollback if transactions are being used
$this->_trans_status = FALSE;
if ($this->db_debug)
{
// grab the error number and message now, as we might run some
// additional queries before displaying the error
$error_no = $this->_error_number();
$error_msg = $this->_error_message();
// We call this function in order to roll-back queries
// if transactions are enabled. If we don't call this here
// the error message will trigger an exit, causing the
// transactions to remain in limbo.
$this->trans_complete();
// Log and display errors
log_message('error', 'Query error: '.$error_msg);
return $this->display_error(
array(
'Error Number: '.$error_no,
$error_msg,
$sql
)
);
}
return FALSE;
}
// Stop and aggregate the query time results
$time_end = list($em, $es) = explode(' ', microtime());
$this->benchmark += ($em + $es) - ($sm + $ss);
if ($this->save_queries == TRUE)
{
$this->query_times[] = ($em + $es) - ($sm + $ss);
}
// Increment the query counter
$this->query_count++;
// Was the query a "write" type?
// If so we'll simply return true
if ($this->is_write_type($sql) === TRUE)
{
// If caching is enabled we'll auto-cleanup any
// existing files related to this particular URI
if ($this->cache_on == TRUE AND $this->cache_autodel == TRUE AND $this->_cache_init())
{
$this->CACHE->delete();
}
return TRUE;
}
// Return TRUE if we don't need to create a result object
// Currently only the Oracle driver uses this when stored
// procedures are used
if ($return_object !== TRUE)
{
return TRUE;
}
// Load and instantiate the result driver
$driver = $this->load_rdriver();
$RES = new $driver();
$RES->conn_id = $this->conn_id;
$RES->result_id = $this->result_id;
if ($this->dbdriver == 'oci8')
{
$RES->stmt_id = $this->stmt_id;
$RES->curs_id = NULL;
$RES->limit_used = $this->limit_used;
$this->stmt_id = FALSE;
}
// oci8 vars must be set before calling this
$RES->num_rows = $RES->num_rows();
// Is query caching enabled? If so, we'll serialize the
// result object and save it to a cache file.
if ($this->cache_on == TRUE AND $this->_cache_init())
{
$CR = new CI_DB_result();
$CR->num_rows = $RES->num_rows();
$CR->result_object = $RES->result_object();
$CR->result_array = $RES->result_array();
// Reset these since cached objects can not utilize resource IDs.
$CR->conn_id = NULL;
$CR->result_id = NULL;
$this->CACHE->write($sql, $CR);
}
return $RES;
}
function load_rdriver()
{
$driver = 'CI_DB_'.$this->dbdriver.'_result';
if ( ! class_exists($driver))
{
include_once(BASEPATH.'database/DB_result.php');
include_once(BASEPATH.'database/drivers/'.$this->dbdriver.'/'.$this->dbdriver.'_result.php');
}
return $driver;
}
function simple_query($sql)
{
if ( ! $this->conn_id)
{
$this->initialize();
}
return $this->_execute($sql);
}
function trans_off()
{
$this->trans_enabled = FALSE;
}
function trans_strict($mode = TRUE)
{
$this->trans_strict = is_bool($mode) ? $mode : TRUE;
}
function trans_start($test_mode = FALSE)
{
if ( ! $this->trans_enabled)
{
return FALSE;
}
// When transactions are nested we only begin/commit/rollback the outermost ones
if ($this->_trans_depth > 0)
{
$this->_trans_depth += 1;
return;
}
$this->trans_begin($test_mode);
}
function trans_complete()
{
if ( ! $this->trans_enabled)
{
return FALSE;
}
// When transactions are nested we only begin/commit/rollback the outermost ones
if ($this->_trans_depth > 1)
{
$this->_trans_depth -= 1;
return TRUE;
}
// The query() function will set this flag to FALSE in the event that a query failed
if ($this->_trans_status === FALSE)
{
$this->trans_rollback();
// If we are NOT running in strict mode, we will reset
// the _trans_status flag so that subsequent groups of transactions
// will be permitted.
if ($this->trans_strict === FALSE)
{
$this->_trans_status = TRUE;
}
log_message('debug', 'DB Transaction Failure');
return FALSE;
}
$this->trans_commit();
return TRUE;
}
function trans_status()
{
return $this->_trans_status;
}
function compile_binds($sql, $binds)
{
if (strpos($sql, $this->bind_marker) === FALSE)
{
return $sql;
}
if ( ! is_array($binds))
{
$binds = array($binds);
}
// Get the sql segments around the bind markers
$segments = explode($this->bind_marker, $sql);
// The count of bind should be 1 less then the count of segments
// If there are more bind arguments trim it down
if (count($binds) >= count($segments)) {
$binds = array_slice($binds, 0, count($segments)-1);
}
// Construct the binded query
$result = $segments[0];
$i = 0;
foreach ($binds as $bind)
{
$result .= $this->escape($bind);
$result .= $segments[++$i];
}
return $result;
}
function is_write_type($sql)
{
if ( ! preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD DATA|COPY|ALTER|GRANT|REVOKE|LOCK|UNLOCK)\s+/i', $sql))
{
return FALSE;
}
return TRUE;
}
function elapsed_time($decimals = 6)
{
return number_format($this->benchmark, $decimals);
}
function total_queries()
{
return $this->query_count;
}
function last_query()
{
return end($this->queries);
}
function escape($str)
{
if (is_string($str))
{
$str = "'".$this->escape_str($str)."'";
}
elseif (is_bool($str))
{
$str = ($str === FALSE) ? 0 : 1;
}
elseif (is_null($str))
{
$str = 'NULL';
}
return $str;
}
function escape_like_str($str)
{
return $this->escape_str($str, TRUE);
}
function primary($table = '')
{
$fields = $this->list_fields($table);
if ( ! is_array($fields))
{
return FALSE;
}
return current($fields);
}
function list_tables($constrain_by_prefix = FALSE)
{
// Is there a cached result?
if (isset($this->data_cache['table_names']))
{
return $this->data_cache['table_names'];
}
if (FALSE === ($sql = $this->_list_tables($constrain_by_prefix)))
{
if ($this->db_debug)
{
return $this->display_error('db_unsupported_function');
}
return FALSE;
}
$retval = array();
$query = $this->query($sql);
if ($query->num_rows() > 0)
{
foreach ($query->result_array() as $row)
{
if (isset($row['TABLE_NAME']))
{
$retval[] = $row['TABLE_NAME'];
}
else
{
$retval[] = array_shift($row);
}
}
}
$this->data_cache['table_names'] = $retval;
return $this->data_cache['table_names'];
}
// --------------------------------------------------------------------
/**
* Determine if a particular table exists
* #access public
* #return boolean
*/
function table_exists($table_name)
{
return ( ! in_array($this->_protect_identifiers($table_name, TRUE, FALSE, FALSE), $this->list_tables())) ? FALSE : TRUE;
}
// --------------------------------------------------------------------
/**
* Fetch MySQL Field Names
*
* #access public
* #param string the table name
* #return array
*/
function list_fields($table = '')
{
// Is there a cached result?
if (isset($this->data_cache['field_names'][$table]))
{
return $this->data_cache['field_names'][$table];
}
if ($table == '')
{
if ($this->db_debug)
{
return $this->display_error('db_field_param_missing');
}
return FALSE;
}
if (FALSE === ($sql = $this->_list_columns($table)))
{
if ($this->db_debug)
{
return $this->display_error('db_unsupported_function');
}
return FALSE;
}
$query = $this->query($sql);
$retval = array();
foreach ($query->result_array() as $row)
{
if (isset($row['COLUMN_NAME']))
{
$retval[] = $row['COLUMN_NAME'];
}
else
{
$retval[] = current($row);
}
}
$this->data_cache['field_names'][$table] = $retval;
return $this->data_cache['field_names'][$table];
}
// --------------------------------------------------------------------
/**
* Determine if a particular field exists
* #access public
* #param string
* #param string
* #return boolean
*/
function field_exists($field_name, $table_name)
{
return ( ! in_array($field_name, $this->list_fields($table_name))) ? FALSE : TRUE;
}
// --------------------------------------------------------------------
/**
* Returns an object with field data
*
* #access public
* #param string the table name
* #return object
*/
function field_data($table = '')
{
if ($table == '')
{
if ($this->db_debug)
{
return $this->display_error('db_field_param_missing');
}
return FALSE;
}
$query = $this->query($this->_field_data($this->_protect_identifiers($table, TRUE, NULL, FALSE)));
return $query->field_data();
}
// --------------------------------------------------------------------
/**
* Generate an insert string
*
* #access public
* #param string the table upon which the query will be performed
* #param array an associative array data of key/values
* #return string
*/
function insert_string($table, $data)
{
$fields = array();
$values = array();
foreach ($data as $key => $val)
{
$fields[] = $this->_escape_identifiers($key);
$values[] = $this->escape($val);
}
return $this->_insert($this->_protect_identifiers($table, TRUE, NULL, FALSE), $fields, $values);
}
// --------------------------------------------------------------------
/**
* Generate an update string
*
* #access public
* #param string the table upon which the query will be performed
* #param array an associative array data of key/values
* #param mixed the "where" statement
* #return string
*/
function update_string($table, $data, $where)
{
if ($where == '')
{
return false;
}
$fields = array();
foreach ($data as $key => $val)
{
$fields[$this->_protect_identifiers($key)] = $this->escape($val);
}
if ( ! is_array($where))
{
$dest = array($where);
}
else
{
$dest = array();
foreach ($where as $key => $val)
{
$prefix = (count($dest) == 0) ? '' : ' AND ';
if ($val !== '')
{
if ( ! $this->_has_operator($key))
{
$key .= ' =';
}
$val = ' '.$this->escape($val);
}
$dest[] = $prefix.$key.$val;
}
}
return $this->_update($this->_protect_identifiers($table, TRUE, NULL, FALSE), $fields, $dest);
}
// --------------------------------------------------------------------
/**
* Tests whether the string has an SQL operator
*
* #access private
* #param string
* #return bool
*/
function _has_operator($str)
{
$str = trim($str);
if ( ! preg_match("/(\s|<|>|!|=|is null|is not null)/i", $str))
{
return FALSE;
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Enables a native PHP function to be run, using a platform agnostic wrapper.
*
* #access public
* #param string the function name
* #param mixed any parameters needed by the function
* #return mixed
*/
function call_function($function)
{
$driver = ($this->dbdriver == 'postgre') ? 'pg_' : $this->dbdriver.'_';
if (FALSE === strpos($driver, $function))
{
$function = $driver.$function;
}
if ( ! function_exists($function))
{
if ($this->db_debug)
{
return $this->display_error('db_unsupported_function');
}
return FALSE;
}
else
{
$args = (func_num_args() > 1) ? array_splice(func_get_args(), 1) : null;
return call_user_func_array($function, $args);
}
}
// --------------------------------------------------------------------
/**
* Set Cache Directory Path
*
* #access public
* #param string the path to the cache directory
* #return void
*/
function cache_set_path($path = '')
{
$this->cachedir = $path;
}
// --------------------------------------------------------------------
/**
* Enable Query Caching
*
* #access public
* #return void
*/
function cache_on()
{
$this->cache_on = TRUE;
return TRUE;
}
// --------------------------------------------------------------------
/**
* Disable Query Caching
*
* #access public
* #return void
*/
function cache_off()
{
$this->cache_on = FALSE;
return FALSE;
}
// --------------------------------------------------------------------
/**
* Delete the cache files associated with a particular URI
*
* #access public
* #return void
*/
function cache_delete($segment_one = '', $segment_two = '')
{
if ( ! $this->_cache_init())
{
return FALSE;
}
return $this->CACHE->delete($segment_one, $segment_two);
}
// --------------------------------------------------------------------
/**
* Delete All cache files
*
* #access public
* #return void
*/
function cache_delete_all()
{
if ( ! $this->_cache_init())
{
return FALSE;
}
return $this->CACHE->delete_all();
}
// --------------------------------------------------------------------
/**
* Initialize the Cache Class
*
* #access private
* #return void
*/
function _cache_init()
{
if (is_object($this->CACHE) AND class_exists('CI_DB_Cache'))
{
return TRUE;
}
if ( ! class_exists('CI_DB_Cache'))
{
if ( ! #include(BASEPATH.'database/DB_cache.php'))
{
return $this->cache_off();
}
}
$this->CACHE = new CI_DB_Cache($this); // pass db object to support multiple db connections and returned db objects
return TRUE;
}
// --------------------------------------------------------------------
/**
* Close DB Connection
*
* #access public
* #return void
*/
function close()
{
if (is_resource($this->conn_id) OR is_object($this->conn_id))
{
$this->_close($this->conn_id);
}
$this->conn_id = FALSE;
}
// --------------------------------------------------------------------
/**
* Display an error message
*
* #access public
* #param string the error message
* #param string any "swap" values
* #param boolean whether to localize the message
* #return string sends the application/error_db.php template
*/
function display_error($error = '', $swap = '', $native = FALSE)
{
$LANG =& load_class('Lang', 'core');
$LANG->load('db');
$heading = $LANG->line('db_error_heading');
if ($native == TRUE)
{
$message = $error;
}
else
{
$message = ( ! is_array($error)) ? array(str_replace('%s', $swap, $LANG->line($error))) : $error;
}
// Find the most likely culprit of the error by going through
// the backtrace until the source file is no longer in the
// database folder.
$trace = debug_backtrace();
foreach ($trace as $call)
{
if (isset($call['file']) && strpos($call['file'], BASEPATH.'database') === FALSE)
{
// Found it - use a relative path for safety
$message[] = 'Filename: '.str_replace(array(BASEPATH, APPPATH), '', $call['file']);
$message[] = 'Line Number: '.$call['line'];
break;
}
}
$error =& load_class('Exceptions', 'core');
echo $error->show_error($heading, $message, 'error_db');
exit;
}
// --------------------------------------------------------------------
/**
* Protect Identifiers
*
* This function adds backticks if appropriate based on db type
*
* #access private
* #param mixed the item to escape
* #return mixed the item with backticks
*/
function protect_identifiers($item, $prefix_single = FALSE)
{
return $this->_protect_identifiers($item, $prefix_single);
}
function _protect_identifiers($item, $prefix_single = FALSE, $protect_identifiers = NULL, $field_exists = TRUE)
{
if ( ! is_bool($protect_identifiers))
{
$protect_identifiers = $this->_protect_identifiers;
}
if (is_array($item))
{
$escaped_array = array();
foreach ($item as $k => $v)
{
$escaped_array[$this->_protect_identifiers($k)] = $this->_protect_identifiers($v);
}
return $escaped_array;
}
// Convert tabs or multiple spaces into single spaces
$item = preg_replace('/[\t ]+/', ' ', $item);
// If the item has an alias declaration we remove it and set it aside.
// Basically we remove everything to the right of the first space
$alias = '';
if (strpos($item, ' ') !== FALSE)
{
$alias = strstr($item, " ");
$item = substr($item, 0, - strlen($alias));
}
// This is basically a bug fix for queries that use MAX, MIN, etc.
// If a parenthesis is found we know that we do not need to
// escape the data or add a prefix. There's probably a more graceful
// way to deal with this, but I'm not thinking of it -- Rick
if (strpos($item, '(') !== FALSE)
{
return $item.$alias;
}
// Break the string apart if it contains periods, then insert the table prefix
// in the correct location, assuming the period doesn't indicate that we're dealing
// with an alias. While we're at it, we will escape the components
if (strpos($item, '.') !== FALSE)
{
$parts = explode('.', $item);
// Does the first segment of the exploded item match
// one of the aliases previously identified? If so,
// we have nothing more to do other than escape the item
if (in_array($parts[0], $this->ar_aliased_tables))
{
if ($protect_identifiers === TRUE)
{
foreach ($parts as $key => $val)
{
if ( ! in_array($val, $this->_reserved_identifiers))
{
$parts[$key] = $this->_escape_identifiers($val);
}
}
$item = implode('.', $parts);
}
return $item.$alias;
}
// Is there a table prefix defined in the config file? If not, no need to do anything
if ($this->dbprefix != '')
{
// We now add the table prefix based on some logic.
// Do we have 4 segments (hostname.database.table.column)?
// If so, we add the table prefix to the column name in the 3rd segment.
if (isset($parts[3]))
{
$i = 2;
}
// Do we have 3 segments (database.table.column)?
// If so, we add the table prefix to the column name in 2nd position
elseif (isset($parts[2]))
{
$i = 1;
}
// Do we have 2 segments (table.column)?
// If so, we add the table prefix to the column name in 1st segment
else
{
$i = 0;
}
// This flag is set when the supplied $item does not contain a field name.
// This can happen when this function is being called from a JOIN.
if ($field_exists == FALSE)
{
$i++;
}
// Verify table prefix and replace if necessary
if ($this->swap_pre != '' && strncmp($parts[$i], $this->swap_pre, strlen($this->swap_pre)) === 0)
{
$parts[$i] = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $parts[$i]);
}
// We only add the table prefix if it does not already exist
if (substr($parts[$i], 0, strlen($this->dbprefix)) != $this->dbprefix)
{
$parts[$i] = $this->dbprefix.$parts[$i];
}
// Put the parts back together
$item = implode('.', $parts);
}
if ($protect_identifiers === TRUE)
{
$item = $this->_escape_identifiers($item);
}
return $item.$alias;
}
// Is there a table prefix? If not, no need to insert it
if ($this->dbprefix != '')
{
// Verify table prefix and replace if necessary
if ($this->swap_pre != '' && strncmp($item, $this->swap_pre, strlen($this->swap_pre)) === 0)
{
$item = preg_replace("/^".$this->swap_pre."(\S+?)/", $this->dbprefix."\\1", $item);
}
// Do we prefix an item with no segments?
if ($prefix_single == TRUE AND substr($item, 0, strlen($this->dbprefix)) != $this->dbprefix)
{
$item = $this->dbprefix.$item;
}
}
if ($protect_identifiers === TRUE AND ! in_array($item, $this->_reserved_identifiers))
{
$item = $this->_escape_identifiers($item);
}
return $item.$alias;
}
}
If you have wampp server use this configuration.
If you have xampp use htdocx instead of www
C/wampp/www/Your-project-folder/application/config/database.php
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => DB_HOST,
'username' => DB_USER,
'password' => DB_PASSWORD,
'database' => DB_NAME,
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
Uncomment #mysql_connect($this->hostname, $this->username, $this->password, TRUE);
on system/database/mysql/mysql_driver in db_connect method delete the # from #mysql_connect($this->hostname, $this->username, $this->password, TRUE);
This will show you the connection error and post result here
PHP 5 or above and CI 3 supports only mysqli
EDIT
$db['default'] = array(
'dsn' => '',
'hostname' => DB_HOST,
'username' => DB_USER,
'password' => DB_PASSWORD,
'database' => DB_NAME,
'dbdriver' => 'mysqli',
Refer
Edit: application/database/config.php

Magento admin : Fatal error: Call to a member function toOptionArray() on a non-object

I am getting error in admin panel after adding plugin.
Error :
Fatal error: Call to a member function toOptionArray() on a non-object in /var/lib/openshift/5374ca8999fc775bdc00009d/app-root/runtime/repo/php/app/code/core/Mage/Adminhtml/Block/System/Config/Form.php on line 463
Here is the code :
public function toOptionArray() {
return array(
array('value'=>'0', 'label'=>'No Credit'),
array('value'=>'1', 'label'=>'Credit Only Invited Customer'),
array('value'=>'2', 'label'=>'Credit Only Customer who invite'),
array('value'=>'3', 'label'=>'Credit Both Customer')
);
Form.php file :
<?php
class Mage_Adminhtml_Block_System_Config_Form extends Mage_Adminhtml_Block_Widget_Form
{
const SCOPE_DEFAULT = 'default';
const SCOPE_WEBSITES = 'websites';
const SCOPE_STORES = 'stores';
/**
* Config data array
*
* #var array
*/
protected $_configData;
/**
* Adminhtml config data instance
*
* #var Mage_Adminhtml_Model_Config_Data
*/
protected $_configDataObject;
/**
* Enter description here...
*
* #var Varien_Simplexml_Element
*/
protected $_configRoot;
/**
* Enter description here...
*
* #var Mage_Adminhtml_Model_Config
*/
protected $_configFields;
/**
* Enter description here...
*
* #var Mage_Adminhtml_Block_System_Config_Form_Fieldset
*/
protected $_defaultFieldsetRenderer;
/**
* Enter description here...
*
* #var Mage_Adminhtml_Block_System_Config_Form_Field
*/
protected $_defaultFieldRenderer;
/**
* Enter description here...
*
* #var array
*/
protected $_fieldsets = array();
/**
* Translated scope labels
*
* #var array
*/
protected $_scopeLabels = array();
/**
* Enter description here...
*
*/
public function __construct()
{
parent::__construct();
$this->_scopeLabels = array(
self::SCOPE_DEFAULT => Mage::helper('adminhtml')->__('[GLOBAL]'),
self::SCOPE_WEBSITES => Mage::helper('adminhtml')->__('[WEBSITE]'),
self::SCOPE_STORES => Mage::helper('adminhtml')->__('[STORE VIEW]'),
);
}
/**
* Enter description here...
*
* #return Mage_Adminhtml_Block_System_Config_Form
*/
protected function _initObjects()
{
/** #var $_configDataObject Mage_Adminhtml_Model_Config_Data */
$this->_configDataObject = Mage::getSingleton('adminhtml/config_data');
$this->_configRoot = $this->_configDataObject->getConfigRoot();
$this->_configData = $this->_configDataObject->load();
$this->_configFields = Mage::getSingleton('adminhtml/config');
$this->_defaultFieldsetRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_fieldset');
$this->_defaultFieldRenderer = Mage::getBlockSingleton('adminhtml/system_config_form_field');
return $this;
}
/**
* Enter description here...
*
* #return Mage_Adminhtml_Block_System_Config_Form
*/
public function initForm()
{
$this->_initObjects();
$form = new Varien_Data_Form();
$sections = $this->_configFields->getSection(
$this->getSectionCode(),
$this->getWebsiteCode(),
$this->getStoreCode()
);
if (empty($sections)) {
$sections = array();
}
foreach ($sections as $section) {
/* #var $section Varien_Simplexml_Element */
if (!$this->_canShowField($section)) {
continue;
}
foreach ($section->groups as $groups){
$groups = (array)$groups;
usort($groups, array($this, '_sortForm'));
foreach ($groups as $group){
/* #var $group Varien_Simplexml_Element */
if (!$this->_canShowField($group)) {
continue;
}
$this->_initGroup($form, $group, $section);
}
}
}
$this->setForm($form);
return $this;
}
/**
* Init config group
*
* #param Varien_Data_Form $form
* #param Varien_Simplexml_Element $group
* #param Varien_Simplexml_Element $section
* #param Varien_Data_Form_Element_Fieldset|null $parentElement
*/
protected function _initGroup($form, $group, $section, $parentElement = null)
{
if ($group->frontend_model) {
$fieldsetRenderer = Mage::getBlockSingleton((string)$group->frontend_model);
} else {
$fieldsetRenderer = $this->_defaultFieldsetRenderer;
}
$fieldsetRenderer->setForm($this)
->setConfigData($this->_configData);
if ($this->_configFields->hasChildren($group, $this->getWebsiteCode(), $this->getStoreCode())) {
$helperName = $this->_configFields->getAttributeModule($section, $group);
$fieldsetConfig = array('legend' => Mage::helper($helperName)->__((string)$group->label));
if (!empty($group->comment)) {
$fieldsetConfig['comment'] = Mage::helper($helperName)->__((string)$group->comment);
}
if (!empty($group->expanded)) {
$fieldsetConfig['expanded'] = (bool)$group->expanded;
}
$fieldset = new Varien_Data_Form_Element_Fieldset($fieldsetConfig);
$fieldset->setId($section->getName() . '_' . $group->getName())
->setRenderer($fieldsetRenderer)
->setGroup($group);
if ($parentElement) {
$fieldset->setIsNested(true);
$parentElement->addElement($fieldset);
} else {
$form->addElement($fieldset);
}
$this->_prepareFieldOriginalData($fieldset, $group);
$this->_addElementTypes($fieldset);
$this->_fieldsets[$group->getName()] = $fieldset;
if ($group->clone_fields) {
if ($group->clone_model) {
$cloneModel = Mage::getModel((string)$group->clone_model);
} else {
Mage::throwException($this->__('Config form fieldset clone model required to be able to clone fields'));
}
foreach ($cloneModel->getPrefixes() as $prefix) {
$this->initFields($fieldset, $group, $section, $prefix['field'], $prefix['label']);
}
} else {
$this->initFields($fieldset, $group, $section);
}
}
}
/**
* Return dependency block object
*
* #return Mage_Adminhtml_Block_Widget_Form_Element_Dependence
*/
protected function _getDependence()
{
if (!$this->getChild('element_dependense')){
$this->setChild('element_dependense',
$this->getLayout()->createBlock('adminhtml/widget_form_element_dependence'));
}
return $this->getChild('element_dependense');
}
/**
* Init fieldset fields
*
* #param Varien_Data_Form_Element_Fieldset $fieldset
* #param Varien_Simplexml_Element $group
* #param Varien_Simplexml_Element $section
* #param string $fieldPrefix
* #param string $labelPrefix
* #return Mage_Adminhtml_Block_System_Config_Form
*/
public function initFields($fieldset, $group, $section, $fieldPrefix='', $labelPrefix='')
{
if (!$this->_configDataObject) {
$this->_initObjects();
}
// Extends for config data
$configDataAdditionalGroups = array();
foreach ($group->fields as $elements) {
$elements = (array)$elements;
// sort either by sort_order or by child node values bypassing the sort_order
if ($group->sort_fields && $group->sort_fields->by) {
$fieldset->setSortElementsByAttribute(
(string)$group->sort_fields->by,
$group->sort_fields->direction_desc ? SORT_DESC : SORT_ASC
);
} else {
usort($elements, array($this, '_sortForm'));
}
foreach ($elements as $element) {
if (!$this->_canShowField($element)) {
continue;
}
if ((string)$element->getAttribute('type') == 'group') {
$this->_initGroup($fieldset->getForm(), $element, $section, $fieldset);
continue;
}
/**
* Look for custom defined field path
*/
$path = (string)$element->config_path;
if (empty($path)) {
$path = $section->getName() . '/' . $group->getName() . '/' . $fieldPrefix . $element->getName();
} elseif (strrpos($path, '/') > 0) {
// Extend config data with new section group
$groupPath = substr($path, 0, strrpos($path, '/'));
if (!isset($configDataAdditionalGroups[$groupPath])) {
$this->_configData = $this->_configDataObject->extendConfig(
$groupPath,
false,
$this->_configData
);
$configDataAdditionalGroups[$groupPath] = true;
}
}
$data = $this->_configDataObject->getConfigDataValue($path, $inherit, $this->_configData);
if ($element->frontend_model) {
$fieldRenderer = Mage::getBlockSingleton((string)$element->frontend_model);
} else {
$fieldRenderer = $this->_defaultFieldRenderer;
}
$fieldRenderer->setForm($this);
$fieldRenderer->setConfigData($this->_configData);
$helperName = $this->_configFields->getAttributeModule($section, $group, $element);
$fieldType = (string)$element->frontend_type ? (string)$element->frontend_type : 'text';
$name = 'groups[' . $group->getName() . '][fields][' . $fieldPrefix.$element->getName() . '][value]';
$label = Mage::helper($helperName)->__($labelPrefix) . ' '
. Mage::helper($helperName)->__((string)$element->label);
$hint = (string)$element->hint ? Mage::helper($helperName)->__((string)$element->hint) : '';
if ($element->backend_model) {
$model = Mage::getModel((string)$element->backend_model);
if (!$model instanceof Mage_Core_Model_Config_Data) {
Mage::throwException('Invalid config field backend model: '.(string)$element->backend_model);
}
$model->setPath($path)
->setValue($data)
->setWebsite($this->getWebsiteCode())
->setStore($this->getStoreCode())
->afterLoad();
$data = $model->getValue();
}
$comment = $this->_prepareFieldComment($element, $helperName, $data);
$tooltip = $this->_prepareFieldTooltip($element, $helperName);
$id = $section->getName() . '_' . $group->getName() . '_' . $fieldPrefix . $element->getName();
if ($element->depends) {
foreach ($element->depends->children() as $dependent) {
/* #var $dependent Mage_Core_Model_Config_Element */
if (isset($dependent->fieldset)) {
$dependentFieldGroupName = (string)$dependent->fieldset;
if (!isset($this->_fieldsets[$dependentFieldGroupName])) {
$dependentFieldGroupName = $group->getName();
}
} else {
$dependentFieldGroupName = $group->getName();
}
$dependentFieldNameValue = $dependent->getName();
$dependentFieldGroup = $dependentFieldGroupName == $group->getName()
? $group
: $this->_fieldsets[$dependentFieldGroupName]->getGroup();
$dependentId = $section->getName()
. '_' . $dependentFieldGroupName
. '_' . $fieldPrefix
. $dependentFieldNameValue;
$shouldBeAddedDependence = true;
$dependentValue = (string)(isset($dependent->value) ? $dependent->value : $dependent);
if (isset($dependent['separator'])) {
$dependentValue = explode((string)$dependent['separator'], $dependentValue);
}
$dependentFieldName = $fieldPrefix . $dependent->getName();
$dependentField = $dependentFieldGroup->fields->$dependentFieldName;
/*
* If dependent field can't be shown in current scope and real dependent config value
* is not equal to preferred one, then hide dependence fields by adding dependence
* based on not shown field (not rendered field)
*/
if (!$this->_canShowField($dependentField)) {
$dependentFullPath = $section->getName()
. '/' . $dependentFieldGroupName
. '/' . $fieldPrefix
. $dependent->getName();
$dependentValueInStore = Mage::getStoreConfig($dependentFullPath, $this->getStoreCode());
if (is_array($dependentValue)) {
$shouldBeAddedDependence = !in_array($dependentValueInStore, $dependentValue);
} else {
$shouldBeAddedDependence = $dependentValue != $dependentValueInStore;
}
}
if ($shouldBeAddedDependence) {
$this->_getDependence()
->addFieldMap($id, $id)
->addFieldMap($dependentId, $dependentId)
->addFieldDependence($id, $dependentId, $dependentValue);
}
}
}
$sharedClass = '';
if ($element->shared && $element->config_path) {
$sharedClass = ' shared shared-' . str_replace('/', '-', $element->config_path);
}
$requiresClass = '';
if ($element->requires) {
$requiresClass = ' requires';
foreach (explode(',', $element->requires) as $groupName) {
$requiresClass .= ' requires-' . $section->getName() . '_' . $groupName;
}
}
$field = $fieldset->addField($id, $fieldType, array(
'name' => $name,
'label' => $label,
'comment' => $comment,
'tooltip' => $tooltip,
'hint' => $hint,
'value' => $data,
'inherit' => $inherit,
'class' => $element->frontend_class . $sharedClass . $requiresClass,
'field_config' => $element,
'scope' => $this->getScope(),
'scope_id' => $this->getScopeId(),
'scope_label' => $this->getScopeLabel($element),
'can_use_default_value' => $this->canUseDefaultValue((int)$element->show_in_default),
'can_use_website_value' => $this->canUseWebsiteValue((int)$element->show_in_website),
));
$this->_prepareFieldOriginalData($field, $element);
if (isset($element->validate)) {
$field->addClass($element->validate);
}
if (isset($element->frontend_type)
&& 'multiselect' === (string)$element->frontend_type
&& isset($element->can_be_empty)
) {
$field->setCanBeEmpty(true);
}
$field->setRenderer($fieldRenderer);
if ($element->source_model) {
// determine callback for the source model
$factoryName = (string)$element->source_model;
$method = false;
if (preg_match('/^([^:]+?)::([^:]+?)$/', $factoryName, $matches)) {
array_shift($matches);
list($factoryName, $method) = array_values($matches);
}
$sourceModel = Mage::getSingleton($factoryName);
if ($sourceModel instanceof Varien_Object) {
$sourceModel->setPath($path);
}
if ($method) {
if ($fieldType == 'multiselect') {
$optionArray = $sourceModel->$method();
} else {
$optionArray = array();
foreach ($sourceModel->$method() as $value => $label) {
$optionArray[] = array('label' => $label, 'value' => $value);
}
}
} else {
$optionArray = $sourceModel->toOptionArray($fieldType == 'multiselect');
}
$field->setValues($optionArray);
}
}
}
return $this;
}
/**
* Return config root node for current scope
*
* #return Varien_Simplexml_Element
*/
public function getConfigRoot()
{
if (empty($this->_configRoot)) {
$this->_configRoot = Mage::getSingleton('adminhtml/config_data')->getConfigRoot();
}
return $this->_configRoot;
}
/**
* Set "original_data" array to the element, composed from nodes with scalar values
*
* #param Varien_Data_Form_Element_Abstract $field
* #param Varien_Simplexml_Element $xmlElement
*/
protected function _prepareFieldOriginalData($field, $xmlElement)
{
$originalData = array();
foreach ($xmlElement as $key => $value) {
if (!$value->hasChildren()) {
$originalData[$key] = (string)$value;
}
}
$field->setOriginalData($originalData);
}
/**
* Support models "getCommentText" method for field note generation
*
* #param Mage_Core_Model_Config_Element $element
* #param string $helper
* #return string
*/
protected function _prepareFieldComment($element, $helper, $currentValue)
{
$comment = '';
if ($element->comment) {
$commentInfo = $element->comment->asArray();
if (is_array($commentInfo)) {
if (isset($commentInfo['model'])) {
$model = Mage::getModel($commentInfo['model']);
if (method_exists($model, 'getCommentText')) {
$comment = $model->getCommentText($element, $currentValue);
}
}
} else {
$comment = Mage::helper($helper)->__($commentInfo);
}
}
return $comment;
}
/**
* Prepare additional comment for field like tooltip
*
* #param Mage_Core_Model_Config_Element $element
* #param string $helper
* #return string
*/
protected function _prepareFieldTooltip($element, $helper)
{
if ($element->tooltip) {
return Mage::helper($helper)->__((string)$element->tooltip);
} elseif ($element->tooltip_block) {
return $this->getLayout()->createBlock((string)$element->tooltip_block)->toHtml();
}
return '';
}
/**
* Append dependence block at then end of form block
*
*
*/
protected function _afterToHtml($html)
{
if ($this->_getDependence()) {
$html .= $this->_getDependence()->toHtml();
}
$html = parent::_afterToHtml($html);
return $html;
}
/**
* Enter description here...
*
* #param Varien_Simplexml_Element $a
* #param Varien_Simplexml_Element $b
* #return boolean
*/
protected function _sortForm($a, $b)
{
return (int)$a->sort_order < (int)$b->sort_order ? -1 : ((int)$a->sort_order > (int)$b->sort_order ? 1 : 0);
}
/**
* Enter description here...
*
* #param Varien_Simplexml_Element $field
* #return boolean
*/
public function canUseDefaultValue($field)
{
if ($this->getScope() == self::SCOPE_STORES && $field) {
return true;
}
if ($this->getScope() == self::SCOPE_WEBSITES && $field) {
return true;
}
return false;
}
/**
* Enter description here...
*
* #param Varien_Simplexml_Element $field
* #return boolean
*/
public function canUseWebsiteValue($field)
{
if ($this->getScope() == self::SCOPE_STORES && $field) {
return true;
}
return false;
}
/**
* Checking field visibility
*
* #param Varien_Simplexml_Element $field
* #return bool
*/
protected function _canShowField($field)
{
$ifModuleEnabled = trim((string)$field->if_module_enabled);
if ($ifModuleEnabled && !Mage::helper('Core')->isModuleEnabled($ifModuleEnabled)) {
return false;
}
switch ($this->getScope()) {
case self::SCOPE_DEFAULT:
return (int)$field->show_in_default;
break;
case self::SCOPE_WEBSITES:
return (int)$field->show_in_website;
break;
case self::SCOPE_STORES:
return (int)$field->show_in_store;
break;
}
return true;
}
/**
* Retrieve current scope
*
* #return string
*/
public function getScope()
{
$scope = $this->getData('scope');
if (is_null($scope)) {
if ($this->getStoreCode()) {
$scope = self::SCOPE_STORES;
} elseif ($this->getWebsiteCode()) {
$scope = self::SCOPE_WEBSITES;
} else {
$scope = self::SCOPE_DEFAULT;
}
$this->setScope($scope);
}
return $scope;
}
/**
* Retrieve label for scope
*
* #param Mage_Core_Model_Config_Element $element
* #return string
*/
public function getScopeLabel($element)
{
if ($element->show_in_store == 1) {
return $this->_scopeLabels[self::SCOPE_STORES];
} elseif ($element->show_in_website == 1) {
return $this->_scopeLabels[self::SCOPE_WEBSITES];
}
return $this->_scopeLabels[self::SCOPE_DEFAULT];
}
/**
* Get current scope code
*
* #return string
*/
public function getScopeCode()
{
$scopeCode = $this->getData('scope_code');
if (is_null($scopeCode)) {
if ($this->getStoreCode()) {
$scopeCode = $this->getStoreCode();
} elseif ($this->getWebsiteCode()) {
$scopeCode = $this->getWebsiteCode();
} else {
$scopeCode = '';
}
$this->setScopeCode($scopeCode);
}
return $scopeCode;
}
/**
* Get current scope code
*
* #return int|string
*/
public function getScopeId()
{
$scopeId = $this->getData('scope_id');
if (is_null($scopeId)) {
if ($this->getStoreCode()) {
$scopeId = Mage::app()->getStore($this->getStoreCode())->getId();
} elseif ($this->getWebsiteCode()) {
$scopeId = Mage::app()->getWebsite($this->getWebsiteCode())->getId();
} else {
$scopeId = '';
}
$this->setScopeId($scopeId);
}
return $scopeId;
}
/**
* Enter description here...
*
* #return array
*/
protected function _getAdditionalElementTypes()
{
return array(
'export' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_export'),
'import' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_import'),
'allowspecific' => Mage::getConfig()
->getBlockClassName('adminhtml/system_config_form_field_select_allowspecific'),
'image' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_image'),
'file' => Mage::getConfig()->getBlockClassName('adminhtml/system_config_form_field_file')
);
}
/**
* Temporary moved those $this->getRequest()->getParam('blabla') from the code accross this block
* to getBlala() methods to be later set from controller with setters
*/
/**
* Enter description here...
*
* #TODO delete this methods when {^see above^} is done
* #return string
*/
public function getSectionCode()
{
return $this->getRequest()->getParam('section', '');
}
/**
* Enter description here...
*
* #TODO delete this methods when {^see above^} is done
* #return string
*/
public function getWebsiteCode()
{
return $this->getRequest()->getParam('website', '');
}
/**
* Enter description here...
*
* #TODO delete this methods when {^see above^} is done
* #return string
*/
public function getStoreCode()
{
return $this->getRequest()->getParam('store', '');
}
}
Guide me how to resolve this.
Thanks in advance
Since you did not provide any code I can break down the basics.
That error means the object is empty.
If your code looked like this for example.
$results->toOptionArray()
Then the error is telling you $results is not an instance of an object.

Magento - Apply Tax On Custom Quote Totals Field

I have created a surcharge module for Magento which adds a custom total field to the quote. The surcharge is input into Magento including tax. I have successfully got the module adding the surcharge to the quote and the grand total is correct on the checkout page.
My issue comes when trying to apply tax to the surcharge so that it gets included and displayed in the tax field on the checkout page. Currently it only includes the tax for the products and the shipping.
I have managed to calculate the tax for the surcharge but cant't get the tax applied to the quote so that it is displayed in the tax field but also don't think my approach is quite correct either. Any help would be much appreciated.
class ********_Deposits_Model_Quote_Address_Total_Surcharge extends Mage_Sales_Model_Quote_Address_Total_Abstract {
protected $_config = null;
public function __construct()
{
$this->setCode('surcharge_price');
$this->_config = Mage::getSingleton('tax/config');
$this->_store = Mage::app()->getStore();
}
protected function _calculateTax(Mage_Sales_Model_Quote_Address $address)
{
$calculator = Mage::getSingleton('tax/calculation');
$inclTax = $this->_config->priceIncludesTax($this->_store);
$taxRateRequest = $calculator->getRateRequest(
$address,
$address->getQuote()->getBillingAddress(),
$address->getQuote()->getCustomerTaxClassId(),
$this->_store
);
$taxRateRequest->setProductClassId(Mage::getStoreConfig('********/surcharges/tax_class', $this->_store));
$rate = $calculator->getRate($taxRateRequest);
$baseTax = $tax = $calculator->calcTaxAmount($address->getBaseSurchargePriceAmount(), $rate, $inclTax, true);
}
/**
* Collect address subtotal
*
* #param ********_Surcharges_Model_Quote_Address $address
* #return ********_Surcharges_Model_Quote_Address_Total_Surcharge
*/
public function collect(Mage_Sales_Model_Quote_Address $address)
{
parent::collect($address);
$this->_setAmount(0)->_setBaseAmount(0);
// If Surcharges Is Enabled Then Calculate Away :-)
if(Mage::getStoreConfig('********/surcharges/surcharge_enabled')) {
$items = $this->_getAddressItems($address);
if (!count($items)) {
return $this;
}
// Calculate Total Surcharge For Items In Quote (Base Prices!)
$surcharge = 0.0;
foreach ($items as $item) {
$price = $item->getData('base_surcharge_price', null);
if(isset($price)) {
$surcharge += $item->getData('base_surcharge_price') * $item->getQty();
}
}
$this->_setAmount($surcharge);
$this->_setBaseAmount($surcharge);
$this->_calculateTax($address);
}
return $this;
}
public function fetch(Mage_Sales_Model_Quote_Address $address)
{
if(Mage::getStoreConfig('********/surcharges/surcharge_enabled')) {
$surcharge = $address->getSurchargePriceAmount();
if(isset($surcharge) && $surcharge > 0) {
$address->addTotal(array(
'code' => $this->getCode(),
'title' => Mage::getStoreConfig('********/surcharges/surcharge_label'),
'value' => $surcharge
));
}
}
return $this;
}
public function getLabel()
{
return Mage::getStoreConfig('********/surcharges/surcharge_label');
}
I managed to solve this this using the following code. Not the best solution but spent hours trying to do it and didn't get anywhere fast. Asterix's need to be replaced.
class *****_Deposits_Model_Quote_Address_Total_Surcharge extends Mage_Sales_Model_Quote_Address_Total_Abstract {
protected $_taxConfig = null;
public function __construct()
{
$this->setCode('surcharge_price');
$this->_taxConfig = Mage::getSingleton('tax/config');
$this->_store = Mage::app()->getStore();
}
protected function _calculateTax(Mage_Sales_Model_Quote_Address $address)
{
$calculator = Mage::getSingleton('tax/calculation');
$calculator->setCustomer($address->getQuote()->getCustomer());
$inclTax = $this->_taxConfig->priceIncludesTax($this->_store);
$taxRateRequest = $calculator->getRateRequest(
$address,
$address->getQuote()->getBillingAddress(),
$address->getQuote()->getCustomerTaxClassId(),
$this->_store
);
$taxRateRequest->setProductClassId(Mage::getStoreConfig('*****/surcharges/tax_class', $this->_store));
$rate = $calculator->getRate($taxRateRequest);
if($rate > 0.0) {
$baseTax = $calculator->calcTaxAmount($address->getBaseSurchargePriceAmount(), $rate, $inclTax, true);
$tax = $address->getQuote()->getStore()->convertPrice($baseTax, false);
$address->addTotalAmount('tax', $tax);
$address->addBaseTotalAmount('tax', $baseTax);
$rates = array();
foreach ($address->getAppliedTaxes() as $rate) {
$rate['amount'] = $rate['amount'] + $tax;
$rate['base_amount'] = $rate['base_amount'] + $baseTax;
$rates[] = $rate;
}
$address->setAppliedTaxes($rates);
if($inclTax) {
$address->setGrandTotal($address->getGrandTotal() - $tax);
$address->setBaseGrandTotal($address->getBaseGrandTotal() - $baseTax);
}
}
}
/**
* Collect address subtotal
*
* #param *****_Surcharges_Model_Quote_Address $address
* #return *****_Surcharges_Model_Quote_Address_Total_Surcharge
*/
public function collect(Mage_Sales_Model_Quote_Address $address)
{
parent::collect($address);
// Clear Cached Values As Multiple Addresses Causes Values To Be Added Twice Otherwise!
$this->_setAmount(0)->_setBaseAmount(0);
// If Surcharges Is Enabled Then Calculate Away :-)
if(Mage::getStoreConfig('*****/surcharges/surcharge_enabled')) {
$items = $this->_getAddressItems($address);
if (!count($items)) {
return $this;
}
// Calculate Total Surcharge For Items In Quote (Base Prices!)
$surcharge = 0.0;
foreach ($items as $item) {
$price = $item->getData('base_surcharge_price', null);
if(isset($price)) {
$surcharge += $item->getData('base_surcharge_price') * $item->getQty();
}
}
$this->_setAmount($address->getQuote()->getStore()->convertPrice($surcharge, false));
$this->_setBaseAmount($surcharge);
$this->_calculateTax($address);
}
return $this;
}
/**
* Assign subtotal amount and label to address object
*
* #param *****_Surcharges_Model_Quote_Address $address
* #return *****_Surcharges_Model_Quote_Address_Total_Surcharge
*/
public function fetch(Mage_Sales_Model_Quote_Address $address)
{
if(Mage::getStoreConfig('*****/surcharges/surcharge_enabled')) {
$surcharge = $address->getSurchargePriceAmount();
if(isset($surcharge) && $surcharge > 0) {
$address->addTotal(array(
'code' => $this->getCode(),
'title' => Mage::getStoreConfig('*****/surcharges/surcharge_label'),
'value' => $surcharge
));
}
}
return $this;
}
/**
* Get Surcharge label
*
* #return string
*/
public function getLabel()
{
return Mage::getStoreConfig('*****/surcharges/surcharge_label');
}
}

Fatal error: Call to a member function getId() on a non-object in... Magento Problem

I'm trying to setup ZetaPrint on a website. On one of the last steps, I have to do ZetaPrints templates synchronization profile, on System > Import/Export > Advanced Profiles
But When I do the "Add new profile" I get this error:
Fatal error: Call to a member function getId() on a non-object in /nfs/c06/h02/mnt/93577/domains/cannafresh.com/html/store/app/code/core/Mage/Adminhtml/controllers/System/Convert/ProfileController.php on line 117
The file is the original one from magento, I can't figure out the error... can anyone help me? Here's the whole code below:
<?php
/**
* Convert Advanced admin controller
*
* #category Mage
* #package Mage_Adminhtml
* #author Magento Core Team
*/
class Mage_Adminhtml_System_Convert_ProfileController extends Mage_Adminhtml_Controller_Action
{
protected function _initProfile($idFieldName = 'id')
{
$this->_title($this->__('System'))
->_title($this->__('Import and Export'))
->_title($this->__('Profiles'));
$profileId = (int) $this->getRequest()->getParam($idFieldName);
$profile = Mage::getModel('dataflow/profile');
if ($profileId) {
$profile->load($profileId);
if (!$profile->getId()) {
Mage::getSingleton('adminhtml/session')->addError('The profile you are trying to save no longer exists');
$this->_redirect('*/*');
return false;
}
}
Mage::register('current_convert_profile', $profile);
return $this;
}
/**
* Profiles list action
*/
public function indexAction()
{
$this->_title($this->__('System'))
->_title($this->__('Import and Export'))
->_title($this->__('Advanced Profiles'));
if ($this->getRequest()->getQuery('ajax')) {
$this->_forward('grid');
return;
}
$this->loadLayout();
/**
* Set active menu item
*/
$this->_setActiveMenu('system/convert');
/**
* Append profiles block to content
*/
$this->_addContent(
$this->getLayout()->createBlock('adminhtml/system_convert_profile', 'convert_profile')
);
/**
* Add breadcrumb item
*/
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Import/Export'), Mage::helper('adminhtml')->__('Import/Export Advanced'));
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Advanced Profiles'), Mage::helper('adminhtml')->__('Advanced Profiles'));
$this->renderLayout();
}
public function gridAction()
{
$this->getResponse()->setBody($this->getLayout()->createBlock('adminhtml/system_convert_profile_grid')->toHtml());
}
/**
* Profile edit action
*/
public function editAction()
{
$this->_initProfile();
$this->loadLayout();
$profile = Mage::registry('current_convert_profile');
// set entered data if was error when we do save
$data = Mage::getSingleton('adminhtml/session')->getConvertProfileData(true);
if (!empty($data)) {
$profile->addData($data);
}
$this->_title($profile->getId() ? $profile->getName() : $this->__('New Profile'));
$this->_setActiveMenu('system/convert');
$this->_addContent(
$this->getLayout()->createBlock('adminhtml/system_convert_profile_edit')
);
/**
* Append edit tabs to left block
*/
$this->_addLeft($this->getLayout()->createBlock('adminhtml/system_convert_profile_edit_tabs'));
$this->renderLayout();
}
/**
* Create new profile action
*/
public function newAction()
{
$this->_forward('edit');
}
/**
* Delete profile action
*/
public function deleteAction()
{
$this->_initProfile();
$profile = Mage::registry('current_convert_profile');
if ($profile->getId()) {
try {
$profile->delete();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('The profile has been deleted.'));
}
catch (Exception $e){
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
}
}
$this->_redirect('*/*');
}
/**
* Save profile action
*/
public function saveAction()
{
if ($data = $this->getRequest()->getPost()) {
if (!$this->_initProfile('profile_id')) {
return ;
}
$profile = Mage::registry('current_convert_profile');
// Prepare profile saving data
if (isset($data)) {
$profile->addData($data);
}
try {
$profile->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('The profile has been saved.'));
}
catch (Exception $e){
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setConvertProfileData($data);
$this->getResponse()->setRedirect($this->getUrl('*/*/edit', array('id'=>$profile->getId())));
return;
}
if ($this->getRequest()->getParam('continue')) {
$this->_redirect('*/*/edit', array('id'=>$profile->getId()));
} else {
$this->_redirect('*/*');
}
}
else {
Mage::getSingleton('adminhtml/session')->addError($this->__('Invalid POST data (please check post_max_size and upload_max_filesize settings in your php.ini file).'));
$this->_redirect('*/*');
}
}
public function runAction()
{
$this->_initProfile();
$this->loadLayout();
$this->renderLayout();
}
public function batchRunAction()
{
if ($this->getRequest()->isPost()) {
$batchId = $this->getRequest()->getPost('batch_id',0);
$rowIds = $this->getRequest()->getPost('rows');
$batchModel = Mage::getModel('dataflow/batch')->load($batchId);
/* #var $batchModel Mage_Dataflow_Model_Batch */
if (!$batchModel->getId()) {
//exit
return ;
}
if (!is_array($rowIds) || count($rowIds) < 1) {
//exit
return ;
}
if (!$batchModel->getAdapter()) {
//exit
return ;
}
$batchImportModel = $batchModel->getBatchImportModel();
$importIds = $batchImportModel->getIdCollection();
$adapter = Mage::getModel($batchModel->getAdapter());
$adapter->setBatchParams($batchModel->getParams());
$errors = array();
$saved = 0;
foreach ($rowIds as $importId) {
$batchImportModel->load($importId);
if (!$batchImportModel->getId()) {
$errors[] = Mage::helper('dataflow')->__('Skip undefined row.');
continue;
}
try {
$importData = $batchImportModel->getBatchData();
$adapter->saveRow($importData);
}
catch (Exception $e) {
$errors[] = $e->getMessage();
continue;
}
$saved ++;
}
$result = array(
'savedRows' => $saved,
'errors' => $errors
);
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
}
}
public function batchFinishAction()
{
if ($batchId = $this->getRequest()->getParam('id')) {
$batchModel = Mage::getModel('dataflow/batch')->load($batchId);
/* #var $batchModel Mage_Dataflow_Model_Batch */
if ($batchModel->getId()) {
$result = array();
try {
$batchModel->beforeFinish();
}
catch (Mage_Core_Exception $e) {
$result['error'] = $e->getMessage();
}
catch (Exception $e) {
$result['error'] = Mage::helper('adminhtml')->__('An error occurred while finishing process. Please refresh the cache');
}
$batchModel->delete();
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
}
}
}
/**
* Customer orders grid
*
*/
public function historyAction() {
$this->_initProfile();
$this->getResponse()->setBody($this->getLayout()->createBlock('adminhtml/system_convert_profile_edit_tab_history')->toHtml());
}
protected function _isAllowed()
{
// switch ($this->getRequest()->getActionName()) {
// case 'index':
// $aclResource = 'admin/system/convert/profiles';
// break;
// case 'grid':
// $aclResource = 'admin/system/convert/profiles';
// break;
// case 'run':
// $aclResource = 'admin/system/convert/profiles/run';
// break;
// default:
// $aclResource = 'admin/system/convert/profiles/edit';
// break;
// }
return Mage::getSingleton('admin/session')->isAllowed('admin/system/convert/profiles');
}
}
Thanks Luis

Resources