Codeigniter delay on data after insert - php

I'm running:
- debian-linux-gnu
- codeigniter 2.2.0
- No physical links in db (legacy)
- version: 5.5.41-MariaDB-1~precise-log
Problem:
I'm writing a blog system for a webshop. After filling in the form (with ckeditor for the actual blog), I do a redirect to the reading page/view:
redirect("/blog/read/" . $blog_id, "refresh"); Only no data is found. When I refresh the page manualy imediatly after, the blog shows just fine.
I tried to sleep the process, but this didn't help. So I think it is not a db issue. Since the view is new for this particular post, no caching.
controller:
public function add_do() {
//Image handling
if (!empty($_FILES['blog_file_img'])) {
$path = $_FILES['blog_file_img']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
$fileData = $this->upload('blog_file_img', $this->now . '.' . $ext);
$fileNames = $this->resize($fileData);
}
//Create blog
$blog_data = array(
"blog_img_original" => $fileData['file_name'],
"blog_img_small" => $fileNames["small"],
"blog_img_medium" => $fileNames['medium'],
"blog_img_big" => $fileNames['big'],
"blog_date_added" => $this->now,
"blog_date_modified" => $this->now,
"blog_created_by" => $this->user['userid'],
"blog_modified_by" => $this->user['userid']
);
//Create blog description
$blog_description_data = array(
'language_id' => 1,
'blog_title' => $this->input->post('blog_title', true),
'blog_desc' => $this->input->post('blog_desc', true),
'blog_text' => $this->input->post('blog_text', false)
);
$data = array_merge($blog_data, $blog_description_data);
$blog_id = $this->blog_model->blog_new($data);
redirect("/blog/read/" . $blog_id, "refresh");
}
read controller:
public function read($id){
$this->_get_message();
$blog_data = $this->blog_model->blog_entry($id);
$this->load->view('header', $this->data_view);
$this->load->view('blog/blog_entry', array('blog_data' => $blog_data));
$this->load->view('blog/blog_right', array('blog_stats' => $this->blog_model->blog_most_popular()));
$this->load->view('footer');
$this->_debug();
}
model for add
public function blog_new($data) {
$this->db->trans_start();
//Blog data extraction
$blog_data = array(
"blog_img_original" => $data['blog_img_original'],
"blog_img_small" => $data["blog_img_small"],
"blog_img_medium" => $data['blog_img_medium'],
"blog_img_big" => $data['blog_img_big'],
"blog_date_added" => $data['blog_date_added'],
"blog_date_modified" => $data['blog_date_modified'],
"blog_created_by" => $data['blog_created_by'],
"blog_modified_by" => $data['blog_modified_by']
);
$blog_id = $this->new_blog($blog_data);
//Blog description extraction
$blog_description_data = array(
'blog_id' => $blog_id,
'language_id' => 1,
'blog_title' => $data['blog_title'],
'blog_desc' => $data['blog_desc'],
'blog_text' => $data['blog_text']
);
$this->new_blog_description($blog_description_data);
$this->db->trans_complete();
return $blog_id;
}
private function new_blog($data) {
$this->initialise('blog', 'blog_id');
return $blog_id = $this->create($data);
}
private function new_blog_description($data) {
$this->initialise('blog_description', 'blog_description_id');
return $blog_description_id = $this->create($data);
}
model for read
public function blog_entry($id) {
$this->db->select("*");
$this->db->from("blog");
$this->db->join("blog_description", "blog.blog_id = blog_description.blog_id");
$this->db->join("blog_stats", "blog.blog_id = blog_stats.blog_id");
$this->db->where("blog.blog_id", $id);
$query = $this->db->get();
//Add to views stats
$this->blog_add_view($id);
return $query->result_array();
}

Related

Upload CSV File in Admin Controller - Custom module

I'm trying to create an Admin Controller with a csv file uploader to process it like an array.
I can't find an efficient way to do it, I tried to use $this-> fields_form, but nothing is showing up.
Then I did a tpl file with an input file, called in initContent, but I don't know how to retrieve my file in the controller.
I need to create multiple object of different classes that I made, thanks to the csv file.
Does somebody have some documentation that could help me, I've already search through prestashop dev doc, stack overflow, ect but I've didn't see anything that could help me (maybe I didn't search the good way ?)
Waiting for your help guys !
Update :
Update :
Just found a way to upload my file, but it's upload as .tmp and can't be processed as a csv file, how can I convert a tmp file to a csv ?
Here is my code :
public function __construct()
{
parent::__construct();
// Base
$this->bootstrap = true; // use Bootstrap CSS
$this->fields_options = array(
'general' => array(
'title' => $this->l('Upload DB'),
'fields' => array(
'DB_BULB_DATA' => array(
'title' => $this->l('Upload DB'),
'type' => 'file',
'name' => 'DB_BULB_DATA'
),
),
'submit' => array('title' => $this->trans('Save', array(), 'Admin.Actions')),
),
);
if(isset($_FILES['DB_BULB_DATA'])){
$headers = fgetcsv(fopen($_FILES['DB_BULB_DATA']['tmp_name'], "r+"));
print_r($headers);
}
}
There is no file type name csvfile , you need to use filed type file and then hadel the csv file after upload, check file extension then process the data.
Just find out how to do it, I feel dummy 😅
I just needed to save my tmp file as a csv to be able to use it then.
Here is the full code :
<?php
class Admin<YourModuleName>Upload<YourThings>DatabaseController extends ModuleAdminController
{
public function __construct()
{
parent::__construct();
// Base
$this->bootstrap = true; // use Bootstrap CSS
$this->name = "Admin<YourModuleName>Upload<YourThings>Database";
$this->fields_options = array(
'general' => array(
'title' => $this->l('Upload DB'),
'fields' => array(
'DB_<YourThings>_DATA' => array(
'title' => $this->l('Upload DB'),
'type' => 'file',
'name' => 'DB_<YourThings>_DATA'
),
),
'submit' => array('title' => $this->l('Save')),
),
);
}
public function initContent()
{
parent::initContent();
unset($_FILES);
}
public function postProcess()
{
$fileName = '<YourThings>Db.csv';
if (!file_exists(_PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName)) {
if (isset($_FILES['DB_<YourThings>_DATA'])) {
$tmpPath = $_FILES['DB_<YourThings>_DATA']["tmp_name"];
move_uploaded_file($tmpPath, _PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName);
$uploadCsv = file(_PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName, FILE_SKIP_EMPTY_LINES);
$Db = array_map("str_getcsv", $uploadCsv, array_fill(0, count($uploadCsv), ';'));
$keys = array_shift($Db);
foreach ($Db as $i => $row) {
$Db[$i] = array_combine($keys, $row);
}
print_r($Db);
}
} else {
$uploadCsv = file(_PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName, FILE_SKIP_EMPTY_LINES);
$Db = array_map("str_getcsv", $uploadCsv, array_fill(0, count($uploadCsv), ';'));
$keys = array_shift($Db);
foreach ($Db as $i => $row) {
$Db[$i] = array_combine($keys, $row);
}
print_r($Db);
}
unset($_FILES['DB_<YourThings>_DATA']);
}
}

Cannot insert data barcode with $id_barcode on codeigniter

I tried to create a barcode using zend_barcode library , when I try to run perfectly but when I try to do a project there is a problem , I try to create a barcode based on $id_barcode I input when I insert does not work .
This my Controllers
function insert() {
$barcode = $this->input->post('id_barcode');
$imageResource = Zend_Barcode::factory('code128', 'image', array('text'=>$barcode), array())->draw();
$imageName = $barcode.'.jpg';
$imagePath = './result/';
if (!is_dir($imagePath)) {
mkdir ($imagePath, 777, TRUE);
}
$createbarcode = imagejpeg($imageResource, $imagePath.$imageName);
$this->product_m->insert_produk($createbarcode);
redirect('admin/product');
}
this my Models
function insert_produk($createbarcode){
$data = array(
'id_barcode' => $this->input->post('id_barcode'),
'reseller_produk'=> $this->input->post('reseller_produk'),
'nama_produk' => $this->input->post('nama_produk'),
'jenis_produk' => $this->input->post('jenis_produk'),
'harga_produk' => $this->input->post('harga_produk'),
'stock_produk' => $this->input->post('stock_produk'),
'date' => $this->input->post('date'),
'image' => $createbarcode);
$this->db->insert('tb_produk', $data);
}

Prestashop error "invalid security token"

im creating a new module for prestashop 1.5.6 and im having some problems with it.
The module has to send sms to the costumers and it has to be an option of the back-Office menu.
I have created the module with the install and uninstall functions and added the tabs to the back-office menu, but im a newbie in prestashop so i don´t know how to make the AdminMyModuleController.php and when i try to click the tab of the module it says "INVALID SECURITY TOKEN", i don´t know how resolve this issue because i don´t know much of security.
If someone can add me on facebook or whatever to help me would be amazing.
Here is the code of the mymodule.php:
private function _createTab()
{
// Tab Raiz
$data = array(
'id_tab' => '',
'id_parent' => 0,
'class_name' => 'Empty',
'module' => 'mymodule',
'position' => 14, 'active' => 1
);
/* Insert the data to the tab table*/
$res = Db::getInstance()->insert('tab', $data);
//Get last insert id from db which will be the new tab id
$id_tabP = Db::getInstance()->Insert_ID();
//Define tab multi language data
$data_lang = array(
'id_tab' => $id_tabP,
'id_lang' => Configuration::get('PS_LANG_DEFAULT'),
'name' => 'SMS a clientes'
);
// Now insert the tab lang data
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
// Tab Configuracion
$data = array(
'id_tab' => '',
'id_parent' => $id_tabP,
'class_name' => 'AdminMymodule',
'module' => 'mymodule',
'position' => 1, 'active' => 1
);
$res = Db::getInstance()->insert('tab', $data);
$id_tab = Db::getInstance()->Insert_ID();
$data_lang = array(
'id_tab' => $id_tab,
'id_lang' => Configuration::get('PS_LANG_DEFAULT'),
'name' => 'Configuracion'
);
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
// Tab Enviar Sms
$data = array(
'id_tab' => '',
'id_parent' => $id_tabP,
'class_name' => 'AdminEnviar',
'module' => 'mymodule',
'position' => 1, 'active' => 1
);
$res = Db::getInstance()->insert('tab', $data);
$id_tab = Db::getInstance()->Insert_ID();
$data_lang = array(
'id_tab' => $id_tab,
'id_lang' => Configuration::get('PS_LANG_DEFAULT'),
'name' => 'Enviar SMS'
);
$res &= Db::getInstance()->insert('tab_lang', $data_lang);
return true;
}
Thanks
As Lliw said, you must use InstallModuleTab function.
private function installModuleTab($tabClass, $tabName, $idTabParent)
{
$pass = true;
$tab = new Tab();
$tab->name = $tabName;
$tab->class_name = $tabClass;
$tab->module = $this->name; // defined in __construct() function
$tab->id_parent = $idTabParent;
$pass = $tab->save();
return($pass);
}
You can put all in your Install function. For example for your first tab:
public function install()
{
if(!parent::install()
|| !$this->installModuleTab('Empty', array(1 => 'SMS a clientes'), $idTabParent = 0))
return false;
return true;
}
You can set languages with the following array:
array(1 => 'SMS a clientes', 2 => 'Language 2', 3 => 'Language 3')
Then you must create the AdminMyModuleController.php file
It's the wrong way to create a module tab. You should use this function in your install() :
$this->installModuleTab('AdminMyModule', array(1 => 'Attribute description'), $idTabParent = 9);
Then create an AdminMyModuleController.php in your module folder/controllers/admin/AdminMyModuleController.php
But you will need to set some function to see something displayed, i'll make a tutorial for that but until i do it, you can look in another admincontroller from the prestashop core and do the same.

Trackback not working in Codeigniter

I have two controllers:
test.php
public function trackback()
{
$this->load->library('trackback');
$tb_data = array(
'ping_url' => 'http://www.citest.com/addtrackback/receive/777',
'url' => 'http://www.citest.com/test/trackback/',
'title' => 'Заголовок',
'excerpt' => 'Текст.',
'blog_name' => 'Название блога',
'charset' => 'utf-8'
);
if ( ! $this->trackback->send($tb_data))
{
echo $this->trackback->display_errors();
}
else
{
echo 'Trackback успешно отправлен!';
}
}
function trackback() sends the trackback information
addtrackback.php
public function receive()
{
$this->load->library('trackback');
if ($this->uri->segment(3) == FALSE)
{
$this->trackback->send_error("Не указан ID записи ");
}
if ( ! $this->trackback->receive())
{
$this->trackback->send_error("Trackback содержит некорректные данные!");
}
$data = array(
'tb_id' => '',
'entry_id' => $this->uri->segment(3),
'url' => $this->trackback->data('url'),
'title' => $this->trackback->data('title'),
'excerpt' => $this->trackback->data('excerpt'),
'blog_name' => $this->trackback->data('blog_name'),
'tb_date' => time(),
'ip_address' => $this->input->ip_address()
);
$sql = $this->db->insert_string('trackbacks', $data);
$this->db->query($sql);
$this->trackback->send_success();
}
function receive() gets trackback and writes it into a table called 'trackbacks' in the database.
But when I try to view the page, it results in the following error:
An unknown error was encountered.
What's causing this error?
are you referencing the library or the function you're in? if ( ! $this->trackback->send($tb_data))
try changing it to something like
public function trackback(){
$this->load->library('trackbackLibrary');
what are you trying to accomplish because it seems like you're attempting to do an if statement for the same process.
if ($this->uri->segment(3) == FALSE)
{
$this->trackback->send_error("Не указан ID записи ");
}
if ( ! $this->trackback->receive())
{
$this->trackback->send_error("Trackback содержит некорректные данные!");
}
Also,
Check your error_log file to see what the actual error its throwing. /var/log or some other places. Depending on your OS

Facebook Dashboard API.... fail to use it :|

This question is about Dashboard.addNews and Dashboard.publishActivity
Facebook has told the public about its new Dashboard API, however it hasn't provided any updates on its library to use the new code.
So I followed the advice in this link
http://forum.developers.facebook.com/viewtopic.php?pid=197753
to add the new functions to the facebookapi_php5_restlib.php
//dashboard functions
public function dashboard_addNews($uid, $news, $image = null) {
return $this->call_method('facebook.dashboard.addNews',
array('uid' => $uid,
'news' => $news,
'image' => $image));
}
public function dashboard_multiAddNews($uids, $news, $image = null) {
return $this->call_method('facebook.dashboard.multiAddNews',
array('uids' => $uids ? json_encode($uids) : null,
'news' => $news,
'image' => $image));
}
public function dashboard_addGlobalNews($news, $image = null) {
return $this->call_method('facebook.dashboard.addGlobalNews',
array('news' => $news,
'image' => $image));
}
public function dashboard_publishActivity($activity, $image = null) {
return $this->call_method('facebook.dashboard.publishActivity',
array('activity' => $activity,
'image' => $image));
}
public function dashboard_multiIncrementCount($uids) {
return $this->call_method(
'facebook.dashboard.multiIncrementCount', array('uids' => json_encode($uids)));
}
public function dashboard_removeActivity($activity_ids) {
return $this->call_method(
'facebook.dashboard.removeActivity', array('activity_ids' => json_encode($activity_ids)));
}
public function dashboard_setCount($uid, $count) {
return $this->call_method('facebook.dashboard.setCount',
array('uid' => $uid,
'count' => $count));
}
But now when I follow the sample code at
http://wiki.developers.facebook.com/index.php/Dashboard.addNews
$image = 'http://www.martialdevelopment.com/wordpress/wp-content/images/cheezburger-or-dim-mak.jpg';
$news = array(array('message' => 'Your friend #:563683308 just sent you a present!', 'action_link' => array('text' => 'Get Your Gift', 'href' => 'http://www.example.com/gifts?id=5878237')));
$facebook->api_client->dashboard_addNews($user_id, $news, $image);
However it will prompt this error:
[Wed Jan 27 03:42:27 2010] [error] [client 127.0.0.1] PHP Notice: Array to string conversion in /var/local/site/webroot/xxxx/facebookapi_php5_restlib.php on line 2009
the code at that php line is
if (is_array($val)) $val = implode(',', $val);
pls notice that I haven't altered the facebookapi_php5_restlib.php except pasting those suggested dashboard function code.
and when I follow the instruction at http://wiki.developers.facebook.com/index.php/Dashboard.publishActivity and try to use it:
$image = 'http://www.martialdevelopment.com/wordpress/wp-content/images/cheezburger-or-dim-mak.jpg';
$activity = array(array('message' => '{*actor*} just sponsored #:563683308!', 'action_link' => array('text' => 'Sponsor this cause', 'href' => 'http://www.example.com/games?id=5878237')));
$facebook->api_client->dashboard_publishActivity($activity, $image);
it throws out the same error too about "Array to string conversion"
Any suggestion to actually use the new Facebook Dashboard API?
If you don't assign into the same variable, the warning will likely go away:
if (is_array($val)) $stringval = implode(',', $val);
Okay, I found that no need to modify the php class at all.
All we need to do is use the call_method
$news = array(array('message' => 'There is a new level in the dungeon!', 'action_link' => array('text' => 'Play now.', 'href' => 'http://www.example.com/gifts?id=5878237')));
$facebook->api_client->call_method('facebook.dashboard.addGlobalNews', array('news' => $news));

Categories