Code Igniter overriden DB Active Record - php

I want to override the Active Record class (some functions of it at least). And I made a file called spj_DB_active_rec.php in a folder named "database" in my "application" folder but it does not work.
class name is spj_DB_active_record
<?php
class spj_DB_active_record extends CI_DB_active_record {
function update($table = '', $set = NULL, $where = NULL, $limit = NULL) {
if (is_array($set) && empty($set['modified'])) {
$this->load->helper('date');
$data['modified'] = date('Y-m-d H:i:s',now());
}
log_message('debug','TEST UPDATE '.date('Y-m-d H:i:s',time()));
return parent::update($table, $set, $where, $limit);
}
function insert($table = '', $set = NULL) {
if (is_array($set) && empty($set['modified'])) {
$this->load->helper('date');
$data['modified'] = date('Y-m-d H:i:s',now());
}
if (is_array($set) && empty($set['created'])) {
$this->load->helper('date');
$data['created'] = date('Y-m-d H:i:s',now());
}
log_message('debug','TEST INSERT '.date('Y-m-d H:i:s',time()));
return parent::insert($table, $set);
}
}

Probably that's news to you, but CodeIgniter 2.0 doesn’t officially support extending the core Active Record class. So what you want to do is (unfortunately) not "just possible" by placing a class extending from it somewhere on disk.
But you can try this workaround.

Related

Query log in codeigniter using hook

I need to create a query log in my project. So I created a post_controller hook. It saves all the executed queries in both a text file and a database. But it works only for SELECT queries. I know it is repeated question, but after a lot of search, I couldn't find solution.
Here is my code:
config/hooks.php:
$hook['post_controller'] = array(
'class' => 'LogQueryHook',
'function' => 'log_queries',
'filename' => 'log_queries.php',
'filepath' => 'hooks'
);
hooks/log_queries.php
class LogQueryHook {
function log_queries() {
$CI =& get_instance();
$times = $CI->db->query_times;
//$dbs = array();
$output = NULL;
$queries = $CI->db->queries;
//print_r($queries);
if (count($queries) == 0){
$output .= "no queries\n";
}else{
foreach ($queries as $key=>$query){
$took = round(doubleval($times[$key]), 3);
$CI->db->query('INSERT INTO queryLog_tbl(`query`, `executedTime`, `timeTaken`, `executedBy`) VALUES ("'.$query.'", "'.date('Y-m-d h:i:s').'", "'.$took.'","'.$CI->session->userdata('UserID').'")');
$output .= $query . "\n";
$output .= "===[took:{$took}]\n\n";
}
}
$CI->load->helper('file');
if ( ! write_file(APPPATH . "/logs/queries.log.txt", $output, 'a+')){
log_message('debug','Unable to write query the file');
}
}
}
and hooks enabled in my config.php : $config['enable_hooks'] = TRUE;
You need to check your internal redirection after any modification query(Insert, Update or delete query) executed. If you put any redirect statement after modification query then it will overtake hook execution.
You can do it by overwriting the query() method in system/database/DB_driver.php
Or
Create library and call it from relevant controllers.
My code skipping all queries other than SELECT because of internal redirection. So I created a library for this. I am attaching my code here. It may help someone else
application/libraries/Querylog.php
class Querylog {
protected $CI;
public function __construct() {
$this->CI =& get_instance();
}
function save_query_in_db() {
$query = $this->CI->db->last_query();
$times = $this->CI->db->query_times;
$time = round(doubleval($times[2]), 5);
$this->CI->db->query('INSERT INTO queryLog_tbl(`query`, `executedTime`, `timeTaken`, `executedBy`) '
. 'VALUES ("'.$query.'", "'.date('Y-m-d h:i:s').'", "'.$time.'","'.$this->CI->session->userdata('UserID').'")');
}
}
load this library in your controller or autoload.php
and call save_query_in_db() where ever you want
eg: in model :
$this->db->set('status', 1);
$this->db->where('UserID', $this->session->userdata('UserID'));
$this->db->update('user_tbl');
$this->querylog->save_query_in_db();

PHP set parent class property works but subsequent if statement doesn't

I am building a genetics calculator, and have reduced my code to a simple format to explain my issue.
I basically have this line which instantiates a hatch object:
$hatch = new Hatch($maleGeneticsPOST, $femaleGeneticsPOST, 'leopardGecko', true);
This takes a form post for the parent genetics and sets the species type. Below is my Parent class and Child class to show how this essentially works:
class Genetics
{
public $species = '';
public $dominants = [];
public $recessives = [];
public $snows = [];
public $wildtypes = [];
function __construct($species)
{
$this->species = $species;
echo $species; // returns leopardGecko as expected
}
}
class Hatch extends Genetics
{
function __construct($father, $mother, $species, $autoHatch = true, $hatchMethod = "punnett")
{
parent::__construct($species);
// Other code for $father, $mother etc.
}
}
On the face of it, those 2 classes are working well with each other, I can set the species type in the object and Hatch will set the parent to it.
However, what I am struggling to do is to then use the $species property in the parent to set the genetics, based off of the species selected/set; here's an example:
class Genetics
{
public $species = '';
public $dominants = [];
public $recessives = [];
public $snows = [];
public $wildtypes = [];
function __construct($species)
{
$this->species = $species;
echo $species; // returns leopardGecko as expected
if($species === "leopardGecko"){
$this->dominants = ['NN', 'BB', 'TT'];
$this->recessives = ['Bb', 'Tt', 'Rr'];
$this->snows = ['Mm', 'Gg'];
$this->wildtypes = ['QQ', 'Qq'];
}
}
}
And when I try and use them further down in my Hatch class, they just return empty arrays:
foreach ($alleles as $allele) {
//echo $this->allGenetics[$allele].' ';
if (in_array($allele, $this->dominants, true)) {
//echo $this->allGenetics[$allele].' ';
array_push($geckoGenetics['Gecko']['Dominants'], $this->allGenetics[$allele]);
array_push($geckoGenetics['Gene']['Dominants'], $allele);
} elseif (in_array($allele, $this->recessives, true)) {
//echo $this->allGenetics[$allele].' ';
array_push($geckoGenetics['Gecko']['Recessives'], $this->allGenetics[$allele]);
array_push($geckoGenetics['Gene']['Recessives'], $allele);
} elseif (in_array($allele, $this->wildtypes, true)) {
//echo $this->allGenetics[$allele].' ';
array_push($geckoGenetics['Gecko']['Wildtypes'], $this->allGenetics[$allele]);
array_push($geckoGenetics['Gecko']['Recessives'], $this->allGenetics[$allele]);
array_push($geckoGenetics['Gene']['Wildtypes'], $allele);
array_push($geckoGenetics['Gene']['Recessives'], $allele);
} elseif (in_array($allele, $this->snows, true)) {
array_push($geckoGenetics['Gecko']['Snows'], $this->allGenetics[$allele]);
array_push($geckoGenetics['Gene']['Snows'], $allele);
}
}
Please note: The rest of that code works fine, I'm just talking about the $this->dominants, $this->recessives, $this->wildtypes & $this->snows variables - they return empty.
Am I missing something obvious? This is my first proper go at OOP and it's going well, apart from this bit!
'There is a difference in how you're calling the field $species and how you're trying to do so with $dominants. If you want to access fields outside of the scope of your function, you'll need to call them using $this->.
So in the constructor, if you replace the following:
public $dominants = ['NN', 'BB', 'TT'];
public $recessives = ['Bb', 'Tt', 'Rr'];
public $snows = ['Mm', 'Gg];
public $wildtypes = ['QQ', 'Qq'];
with:
$this->dominants = ['NN', 'BB', 'TT'];
$this->recessives = ['Bb', 'Tt', 'Rr'];
$this->snows = ['Mm', 'Gg'];
$this->wildtypes = ['QQ', 'Qq'];
It should work.

want to pass variable to aftersave() method after save(false) in yii

Actually,
as you see below code,
in model two functions are calling
$this->sendMailtoTutor(),$this->sendMailtoLearner()
i want to check a condition in model that if that condition will true then only these both function will call otherwise not. Is there any way to pass attributes or variable so that i can check condition in aftersave().
my code is as below
in controller
public function actionBooking()
{
$booking_temp = new BookingTemp();
$this->performAjaxValidation($booking_temp);
if (Yii::app()->request->isPostRequest && Yii::app()->request->getPost('BookingTemp'))
{
$booking_temp->attributes = Yii::app()->request->getPost('BookingTemp');
//echo '<pre>';print_r($booking_temp->attributes);exit;
if ($booking_temp->validate())
{
$extra_price = 0;
$post_data = Yii::app()->request->getPost('BookingTemp');
$cam = Cam::model()->findByPk($post_data['temp_cam_id']);
$data = array();
$data = $post_data;
$data['temp_book_user_id'] = Yii::app()->user->id;
$data['temp_book_cam_price'] = $cam->cam_price;
$data['temp_book_duration'] = $cam->cam_duration;
if ($post_data['temp_book_session'] == 2) {
$data['temp_book_cam_price'] = 2 * $cam->cam_price;
$data['temp_book_duration'] = 2 * $cam->cam_duration;
}
if ($post_data['temp_book_is_extra'] == "Y") {
$extra_price = $cam->camExtras->extra_price;
$data['temp_book_extra_price'] = $extra_price;
}
$price_calculation = CamBooking::price_calculation(Yii::app()->user->country_id, $data['temp_book_cam_price'], $extra_price);
$data['temp_book_processing_fees'] = $price_calculation['processing_fees'];
$data['temp_book_service_tax'] = $price_calculation['service_tax'];
$data['temp_book_total_price'] = $price_calculation['total_price'];
$booking_temp->temp_value = serialize($data);
$booking_temp->user_id = Yii::app()->user->id;
$booking_temp->tutor_id = $cam->tutor_id;
$booking_temp_variable = 'check_aftersave';
$booking_temp->save(false, $booking_temp_variable);
//$booking_temp->saveAttributes(array('tutor_id', 'user_id', 'temp_value'));
$created_at = Yii::app()->localtime->fromUTC($booking_temp->created_at);
$created_at_time = strtotime($created_at);
$end_time = $created_at_time + (60 * 3); // 3 min greater from created
$end_time_format = date("Y/m/d H:i:s", $end_time);
echo json_encode(array(
'status' => 'success',
'temp_guid' => $booking_temp->temp_guid,
'end_time_format' => $end_time_format,
), JSON_UNESCAPED_SLASHES);
Yii::app()->end();
} else {
$error = CActiveForm::validate($booking_temp);
if ($error != '[]')
echo $error;
Yii::app()->end();
}
}
}
in model
protected function afterSave()
{
if ($this->isNewRecord)
{
$this->sendMailtoTutor();
$this->sendMailtoLearner();
if ($this->is_message == 'Y' && !empty($this->book_message))
{
Message::insertMessage($this->book_message, $this->book_user_id, $this->cam->tutor_id, $this->cam_id);
}
$user_profile_link = CHtml::link($this->bookUser->fullname, array("/site/user/profile", "slug" => $this->bookUser->slug));
$cam_link = CHtml::link($this->cam->cam_title, array("/site/cam/view", "slug" => $this->cam->slug));
$message = "You have a new booking from {$user_profile_link} for your {$cam_link}";
Notification::insertNotification($this->cam->tutor_id, $message, 'book', $this->book_id);
}
return parent::afterSave();
}
How can I perform this?
Hi See if you want to do it in the afterSave() of BookingTemp Model;. Then you can define a variable in that model like
like
class BookingTemp extends CActiveRecord
{
public $booking_temp_variable;
............
}
now assign this variable before saving your model in actionBooking();
as
$booking_temp->booking_temp_variable = 'check_aftersave';
$booking_temp->save(false);// no need to pass a varible
now in your aftersave function you can easily get it like
protected function afterSave()
{
if ($this->isNewRecord)
{
$this->booking_temp_variable; // this has your value
}
return parent::afterSave();
}
Don't forget to keep it in rules as safe
public function rules(){
// your rules
array('booking_temp_variable','safe');
}
What exacly you want to do?
At first you have to know, that when you are calling save() method and u pass there two args - false and, $booking_temp_variable . The first arg says that you do not run validation, the second one is (should be) array of attributes.
http://www.yiiframework.com/doc/api/1.1/CActiveRecord#save-detail

How can I use callback functions in groceryCrud for the view record page?

I do not know how to set a callback function for the view record page in codeigniter.
I use the callback_column function and it does what I need in the grid view, but on the view record page it does not work.
I searched their site and forum and did not found anything that could help me.
My code looks like:
$zeus = new grocery_CRUD();
$zeus->set_theme('bootstrap');
// $zeus->set_language('romanian');
$zeus->set_table('programari');
$zeus->columns(array('id_client', 'id_sala', 'denumire', 'numar_persoane', 'observatii'));
$zeus->callback_column('id_sala',array($this,'_test_function'));
$cod = $zeus->render();
$this->_afiseaza_panou($cod);
public function _test_function($row, $value)
{
return '0';
}
write this lines in \libraries\Grocery_CRUD.php
at line number 3530
protected $callback_read_field = array();
than put this function after constructor call
public function callback_read_field($field, $callback = null)
{
$this->callback_read_field[$field] = $callback;
return $this;
}
//Now update this function to manage the field outputs using callbacks if they are defined for the same
protected function get_read_input_fields($field_values = null)
{
$read_fields = $this->get_read_fields();
$this->field_types = null;
$this->required_fields = null;
$read_inputs = array();
foreach ($read_fields as $field) {
if (!empty($this->change_field_type)
&& isset($this->change_field_type[$field->field_name])
&& $this->change_field_type[$field->field_name]->type == 'hidden') {
continue;
}
$this->field_type($field->field_name, 'readonly');
}
$fields = $this->get_read_fields();
$types = $this->get_field_types();
$input_fields = array();
foreach($fields as $field_num => $field)
{
$field_info = $types[$field->field_name];
if(isset($field_info->db_type) && ($field_info->db_type == 'tinyint' || ($field_info->db_type == 'int' && $field_info->db_max_length == 1))) {
$field_value = $this->get_true_false_readonly_input($field_info, $field_values->{$field->field_name});
} else {
$field_value = !empty($field_values) && isset($field_values->{$field->field_name}) ? $field_values->{$field->field_name} : null;
}
if(!isset($this->callback_read_field[$field->field_name]))
{
$field_input = $this->get_field_input($field_info, $field_value);
}
else
{
$primary_key = $this->getStateInfo()->primary_key;
$field_input = $field_info;
$field_input->input = call_user_func($this->callback_read_field[$field->field_name], $field_value, $primary_key, $field_info, $field_values);
}
switch ($field_info->crud_type) {
case 'invisible':
unset($this->read_fields[$field_num]);
unset($fields[$field_num]);
continue;
break;
case 'hidden':
$this->read_hidden_fields[] = $field_input;
unset($this->read_fields[$field_num]);
unset($fields[$field_num]);
continue;
break;
}
$input_fields[$field->field_name] = $field_input;
}
return $input_fields;
}
than call same as other callback functions
As far as I'm aware GroceryCRUD doesn't provide callbacks or another means of overriding the default output in the view state.
The solution to customising this would be to create a custom view to which you will insert the data from your record. This way you can customise the layout and other presentation.
What you would then do is unset the default read view with:
$crud->unset_read();
And add a new action where there are details on how to do this here.
What to do with the new action is point it to a URL that you map in routes.php if necessary and handle it with a new function in your controller. You'll either have to write a model function to retrieve the data since this isn't passed from GC or you can use the action to target a callback and feed $row to it via POST or something so that the data for the record is accessible in the view. (Look at the example in the link above).

Custom PHP SessionHandler class Write issue

I'm creating my own custom SessionHandler to store my session information in a postgresql 9.3 database and I'm having a problem where the session data passed to the write() method isn't being written to the database, but the session name is??
Things that I know for a fact
My custom class is handling the sessions when session_start() is called - as tested with echoing output from the various methods and no session files are being created in /tmp
The $session_data arg in write() contains the proper serialized string as shown by echoing the contents in the write() method.
$session_name is being written to the database just fine and so is a BLANK serialized string a:0:{}.
Things I'm confused about:
Echoing the contents of $_SESSION['test_var1'] shows the correct value stored, even if read() is empty or returning no value??
If the session name is saved in the DB just fine, why isn't the session data?
Server Configuration
OS: Gentoo
Database: Postgresql 9.3
Web Server: NGINX 1.7.6
PHP 5.5.18 connected to NGINX via FPM
PHP ini session settings
session.save_handler = user
session.use_strict_mode = 1
session.use_cookies = 1
session.cookie_secure = 1
session.use_only_cookies = 1
session.name = _g
session.auto_start = 0
session.serialize_handler = php_serialize
class SessionManagement implements SessionHandlerInterface {
private $_id = '';
private $_link = null;
public function __construct() {
session_set_save_handler(
[$this, 'open'],
[$this, 'close'],
[$this, 'read'],
[$this, 'write'],
[$this, 'destroy'],
[$this, 'gc']
);
}
public function open($save_path, $session_id) {
echo 'open called<br/>';
$this->_id = $session_id;
$this->_link = new PDO('pgsql:host=' . $_SERVER['DB_HOST'] . ';dbname=' . $_SERVER['DB_DB'],
$_SERVER['DB_USER'],
$_SERVER['DB_PASS']);
}
public function close() {
echo 'close called<br/>';
}
public function destroy($session_id) {
echo 'destroying '.$session_id, '<br/>';
}
public function gc($maxlifetime) {
echo 'GC called<br/>';
}
public function read($session_name) {
$name = $this->_id.'_'.$session_name;
$sql = 'SELECT session_data FROM sessions WHERE session_name = :name';
if ($rel = $this->_link->prepare($sql)) {
if ($rel->execute([':name' => $name])) {
return $rel->fetch(PDO::FETCH_ASSOC)['session_data'];
} else {
return false;
}
} else {
return false;
}
return '';
}
public function write($session_name, $session_data) {
echo 'Session data: '.$session_data.'<br/>';
$name = $this->_id . '_' . $session_name;
$data = $session_data;
$sql = "SELECT 1 FROM sessions WHERE session_name = :name";
if ($rel = $this->_link->prepare($sql)) {
if ($rel->execute([':name' => $name])) {
if ($rel->rowCount()) {
echo 'Updating...<br/>';
$sql = 'UPDATE sessions SET session_data = :data WHERE session_name = :name';
if ($rel = $this->_link->prepare($sql)) {
if ($rel->execute([':name' => $name, ':data' => $data])) {
echo 'Update success...<br/>';
} else {
echo 'Update failed...<br/>';
var_dump($rel->errorInfo());
}
}
} else {
echo 'Inserting...<br/>';
$sql = 'INSERT INTO sessions (session_name, session_data) ';
$sql .= 'VALUES(:name, :data)';
if ($rel = $this->_link->prepare($sql)) {
if ($rel->execute([':name' => $name, ':data' => $data])) {
echo 'Insert success...<br/>';
} else {
echo 'Insert failed...<br/>';
var_dump($rel->errorInfo());
}
}
}
}
}
}
}
Test code:
new SessionManagement();
session_start();
$_SESSION['test_var1'] = 'some test data';
session_write_close(); // Making sure writing is finished
echo $_SESSION['test_var1'];
Output via test page
open called
Session data: a:1:{s:9:"test_var1";s:14:"some test data";}
Inserting...
Insert success...
close called
some test data
Relevant database fields
session_name: _g_h8m64bsb7a72dpj56vgojn6f4k3ncdf97leihcqfupg2qtvpbo20
session_data: a:0:{}
I'm not sure if this is a database issue or a PHP issue. I've been messing with this for a few days now and decided it was time to ask the community. Hopefully someone has some insight as to what the problem is.
I think you must initialize PDO object outside of the Open function handler and the class itself
try to access to your PDO Object with a Global value or through a static variable.
This is my implementation with MYSQL for my project :
class Core_DB_SessionHandler implements SessionHandlerInterface
{
protected $options = array(); // Options de la session
protected static $db = NULL; // Acceder a la BDD
public function __construct($options, $pdo) {
$this->options = $options;
self::$db = $pdo;
}
public function open($savePath, $sessionName) {
$now = time();
$req = self::$db->prepare("DELETE FROM tbl_sessions WHERE expire < '{1}' ");
$req->execute(array($now));
return TRUE;
}
public function close() {
$this->gc(ini_get('session.gc_maxlifetime'));
}
public function read($id) {
$now = time();
$stmt = self::$db->query("SELECT data FROM tbl_sessions WHERE sid = '$id AND expire < '$now'");
$result = $stmt->fetchColumn();
return $result;
}
public function write($id, $data) {
if (array_key_exists('TIMEOUT', $_SESSION)) {
$newExp = $_SESSION['TIMEOUT'];
}
else {
$newExp = time() + $this->options['time_limiter'];
}
try {
$req = self::$db->prepare('INSERT INTO tbl_sessions (sid, data, expire) VALUES (:sid, :data, :expire)
ON DUPLICATE KEY UPDATE data = :data, expire = :expire');
$vals = array('sid' => $id, 'data' => $data, 'expire' => $newExp);
$req->execute($vals);
return TRUE;
}
catch (PDOException $e) {
throw new Core_Exception(sprintf('PDOException was thrown when trying to write the session data: %s', $e->getMessage()), 0, $e);
}
}
public function destroy($id) {
$stmt = self::$db->prepare("DELETE FROM tbl_sessions WHERE sid = '{1}'");
$stmt->execute(array($id));
//return ($stmt->rowCount() === 1) ? true : false;
return TRUE;
}
public function gc($maxlifetime) {
$now = time();
$req = self::$db->prepare("DELETE FROM tbl_sessions WHERE expire < '{1}' ");
$req->execute(array($now));
return TRUE;
}
}
and i initialize handler like this :
$handler = new Core_DB_SessionHandler($MyOptions, $MyPDO);
if (PHP5) {
if (!session_set_save_handler($handler, TRUE)) {
throw new Core_Exception('Erreur lors de l\'init des sessions !');
}
}
nb : In your Table structure don't use autoincrement for ID
Well, I've solved my problem, but it's hard to say if this fix was actually the problem in the first place.
In the read method, I changed the follow:
return $rel->fetch(PDO::FETCH_ASSOC)['session_data'];
to
$data $rel->fetch(PDO::FETCH_ASSOC)['session_data'];
return $data;
After this the session was writing $session_data to the database without any problem. That's all well and dandy, but it doesn't explain why it didn't work in the first place. I mainly say this because upon switching the statement back everything continued to work. As in, I can't reproduce the issue now. So it's hard for me to even say that this was the problem in the first place.
Hopefully this helps someone. I've been unable to find more information about it, but it something does show up I'll be sure to add it here.

Categories