I followed this page, and the code is not working as it should in my project. I've tried to find other tutorial on how to execute what I need, however, it does not work as it should in my project either. Is anyone able to direct me to a tutorial that explains in a detailed fashion on how to use Captcha plug-in properly in CodeIgniter?
Controller:
<?php
class Prova extends Controller
{
function prova()
{
parent :: Controller();
$this -> load -> plugin( 'captcha' );
$this->load->library('validation');
$rules['user'] = "required";
$rules['captcha'] = "required|callback_captcha_check";
$this->validation->set_rules($rules);
$fields['user'] = 'Username';
$fields['captcha'] = 'codice';
$this->validation->set_fields($fields);
if ($this->validation->run() == FALSE)
{
$expiration = time()-300; // Two hour limit
$this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
$vals = array(
//'word' => 'Random word',
'img_path' => './tmp/captcha/',
'img_url' => base_url().'tmp/captcha/',
'font_path' => './system/fonts/texb.ttf',
'img_width' => '100',
'img_height' => '30',
'expiration' => '3600'
);
$cap = $this->captcha->create_captcha($vals);
//
$dati['image']= $cap['image'];
//mette nel db
$data = array(
'captcha_id' => '',
'captcha_time' => $cap['time'],
'ip_address' => $this->input->ip_address(),
'word' => $cap['word']
);
$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);
$this->load->view('captcha',$data);
}else{
echo "Captcha can't be made";
}
return $cap ['image'];
}
function captcha_check()
{
// Then see if a captcha exists:
$exp=time()-600;
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
$binds = array($this->input->post('captcha'), $this->input->ip_address(), $exp);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
$this->validation->set_message('_captcha_check', 'Codice di controllo non valido');
return FALSE;
}else{
return TRUE;
}
}
}
View:
<html>
<head>
<title>My Form</title>
</head>
<body>
<?=$this->validation->error_string; ?>
<?=form_open('XXXXXXXXX type your controller'); ?>
<h5>Username</h5>
<?=$this->validation->user_error; ?>
<input type="text" name="user" value="<?php echo ($this->validation->user) ;?>" size="50" />
<br/>
<?=$image;?>
<br/>
<?=$this->validation->captcha_error; ?>
<input type="text" name="captcha" value="" />
<br/>
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>
Captcha:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 4.3.2 or newer
*
* #package CodeIgniter
* #author ExpressionEngine Dev Team
* #copyright Copyright (c) 2008, EllisLab, Inc.
* #license http://codeigniter.com/user_guide/license.html
* #link http://codeigniter.com
* #since Version 1.0
* #filesource
*/
// ------------------------------------------------------------------------
/*
Instructions:
Load the plugin using:
$this->load->plugin('captcha');
Once loaded you can generate a captcha like this:
$vals = array(
'word' => 'Random word',
'img_path' => './captcha/',
'img_url' => 'http://example.com/captcha/',
'font_path' => './system/fonts/texb.ttf',
'img_width' => '150',
'img_height' => 30,
'expiration' => 7200
);
$cap = create_captcha($vals);
echo $cap['image'];
NOTES:
The captcha function requires the GD image library.
Only the img_path and img_url are required.
If a "word" is not supplied, the function will generate a random
ASCII string. You might put together your own word library that
you can draw randomly from.
If you do not specify a path to a TRUE TYPE font, the native ugly GD
font will be used.
The "captcha" folder must be writable (666, or 777)
The "expiration" (in seconds) signifies how long an image will
remain in the captcha folder before it will be deleted. The default
is two hours.
RETURNED DATA
The create_captcha() function returns an associative array with this data:
[array]
(
'image' => IMAGE TAG
'time' => TIMESTAMP (in microtime)
'word' => CAPTCHA WORD
)
The "image" is the actual image tag:
<img src="http://example.com/captcha/12345.jpg" width="140" height="50" />
The "time" is the micro timestamp used as the image name without the file
extension. It will be a number like this: 1139612155.3422
The "word" is the word that appears in the captcha image, which if not
supplied to the function, will be a random string.
ADDING A DATABASE
In order for the captcha function to prevent someone from posting, you will need
to add the information returned from create_captcha() function to your database.
Then, when the data from the form is submitted by the user you will need to verify
that the data exists in the database and has not expired.
Here is a table prototype:
CREATE TABLE captcha (
captcha_id bigint(13) unsigned NOT NULL auto_increment,
captcha_time int(10) unsigned NOT NULL,
ip_address varchar(16) default '0' NOT NULL,
word varchar(20) NOT NULL,
PRIMARY KEY `captcha_id` (`captcha_id`),
KEY `word` (`word`)
)
Here is an example of usage with a DB.
On the page where the captcha will be shown you'll have something like this:
$this->load->plugin('captcha');
$vals = array(
'img_path' => './captcha/',
'img_url' => 'http://example.com/captcha/'
);
$cap = create_captcha($vals);
$data = array(
'captcha_id' => '',
'captcha_time' => $cap['time'],
'ip_address' => $this->input->ip_address(),
'word' => $cap['word']
);
$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);
echo 'Submit the word you see below:';
echo $cap['image'];
echo '<input type="text" name="captcha" value="" />';
Then, on the page that accepts the submission you'll have something like this:
// First, delete old captchas
$expiration = time()-7200; // Two hour limit
$DB->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
// Then see if a captcha exists:
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND date > ?";
$binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
echo "You must submit the word that appears in the image";
}
*/
/**
|==========================================================
| Create Captcha
|==========================================================
|
*/
function create_captcha($data = '', $img_path = '', $img_url = '', $font_path = '')
{
$defaults = array('word' => '', 'img_path' => '', 'img_url' => '', 'img_width' => '150', 'img_height' => '30', 'font_path' => '', 'expiration' => 7200);
foreach ($defaults as $key => $val)
{
if ( ! is_array($data))
{
if ( ! isset($$key) OR $$key == '')
{
$$key = $val;
}
}
else
{
$$key = ( ! isset($data[$key])) ? $val : $data[$key];
}
}
if ($img_path == '' OR $img_url == '')
{
return FALSE;
}
if ( ! #is_dir($img_path))
{
return FALSE;
}
if ( ! is_really_writable($img_path))
{
return FALSE;
}
if ( ! extension_loaded('gd'))
{
return FALSE;
}
// -----------------------------------
// Remove old images
// -----------------------------------
list($usec, $sec) = explode(" ", microtime());
$now = ((float)$usec + (float)$sec);
$current_dir = #opendir($img_path);
while($filename = #readdir($current_dir))
{
if ($filename != "." and $filename != ".." and $filename != "index.html")
{
$name = str_replace(".jpg", "", $filename);
if (($name + $expiration) < $now)
{
#unlink($img_path.$filename);
}
}
}
#closedir($current_dir);
// -----------------------------------
// Do we have a "word" yet?
// -----------------------------------
if ($word == '')
{
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$str = '';
for ($i = 0; $i < 8; $i++)
{
$str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
}
$word = $str;
}
// -----------------------------------
// Determine angle and position
// -----------------------------------
$length = strlen($word);
$angle = ($length >= 6) ? rand(-($length-6), ($length-6)) : 0;
$x_axis = rand(6, (360/$length)-16);
$y_axis = ($angle >= 0 ) ? rand($img_height, $img_width) : rand(6, $img_height);
// -----------------------------------
// Create image
// -----------------------------------
// PHP.net recommends imagecreatetruecolor(), but it isn't always available
if (function_exists('imagecreatetruecolor'))
{
$im = imagecreatetruecolor($img_width, $img_height);
}
else
{
$im = imagecreate($img_width, $img_height);
}
// -----------------------------------
// Assign colors
// -----------------------------------
$bg_color = imagecolorallocate ($im, 255, 255, 255);
$border_color = imagecolorallocate ($im, 153, 102, 102);
$text_color = imagecolorallocate ($im, 204, 153, 153);
$grid_color = imagecolorallocate($im, 255, 182, 182);
$shadow_color = imagecolorallocate($im, 255, 240, 240);
// -----------------------------------
// Create the rectangle
// -----------------------------------
ImageFilledRectangle($im, 0, 0, $img_width, $img_height, $bg_color);
// -----------------------------------
// Create the spiral pattern
// -----------------------------------
$theta = 1;
$thetac = 7;
$radius = 16;
$circles = 20;
$points = 32;
for ($i = 0; $i < ($circles * $points) - 1; $i++)
{
$theta = $theta + $thetac;
$rad = $radius * ($i / $points );
$x = ($rad * cos($theta)) + $x_axis;
$y = ($rad * sin($theta)) + $y_axis;
$theta = $theta + $thetac;
$rad1 = $radius * (($i + 1) / $points);
$x1 = ($rad1 * cos($theta)) + $x_axis;
$y1 = ($rad1 * sin($theta )) + $y_axis;
imageline($im, $x, $y, $x1, $y1, $grid_color);
$theta = $theta - $thetac;
}
// -----------------------------------
// Write the text
// -----------------------------------
$use_font = ($font_path != '' AND file_exists($font_path) AND function_exists('imagettftext')) ? TRUE : FALSE;
if ($use_font == FALSE)
{
$font_size = 5;
$x = rand(0, $img_width/($length/3));
$y = 0;
}
else
{
$font_size = 16;
$x = rand(0, $img_width/($length/1.5));
$y = $font_size+2;
}
for ($i = 0; $i < strlen($word); $i++)
{
if ($use_font == FALSE)
{
$y = rand(0 , $img_height/2);
imagestring($im, $font_size, $x, $y, substr($word, $i, 1), $text_color);
$x += ($font_size*2);
}
else
{
$y = rand($img_height/2, $img_height-3);
imagettftext($im, $font_size, $angle, $x, $y, $text_color, $font_path, substr($word, $i, 1));
$x += $font_size;
}
}
// -----------------------------------
// Create the border
// -----------------------------------
imagerectangle($im, 0, 0, $img_width-1, $img_height-1, $border_color);
// -----------------------------------
// Generate the image
// -----------------------------------
$img_name = $now.'.jpg';
ImageJPEG($im, $img_path.$img_name);
$img = "<img src=\"$img_url$img_name\" width=\"$img_width\" height=\"$img_height\" style=\"border:0;\" alt=\" \" />";
ImageDestroy($im);
return array('word' => $word, 'time' => $now, 'image' => $img);
}
/* End of file captcha_pi.php */
/* Location: ./system/plugins/captcha_pi.php */
The whole tutorial is in the captcha_pi file. The captcha tutorial in the wiki works on a different script (a class).
try this, CodeIgniter Captcha User Guide
Related
I have a form where user insert their basic details and after submitting form it will redirect on view page. I trying to submit it redirect on view page without inserting data into database. I debug my code of controller I come to know that $request = $this->getRequest(); code in $request I am getting GET [ 1 ] and post is empty and in if condition here used $this->getRequest()->isPost() to check whether that post is true or false. Please find screenshot of code of controller.
Controller function
public function addAction() {
$captcha = new Zend_Session_Namespace('captcha');
$captcha->captcha = session_id();
$request = $this->getRequest();
if ($this->getRequest()->isPost()) {
if ($form->isValidPartial($request->getPost())) {
$dataform = $request->getPost();
$alphabet =
"abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1;
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
$randomPassword = implode($pass); //turn the array into a string
$dataform['password'] = $randomPassword;
if ($dataform['vercode'] != $_SESSION["vercode"]) {
$msg = "Please enter a correct code!";
$this->view->assign('errorMessage', $msg);
return FALSE;
}
if ($dataform['sessionCheck'] != $captcha->captcha) {
$this->view->assign('errorMessage', CSRF_ATTACK);
return FALSE;
}
if($dataform['name'] == 2 && $dataform['statename'] == 0){
$this->view->assign('errorMessage', 'Please select state
for the state officials!');
return;
}
$Contactusobj = new Application_Model_User;
$countdata = $Contactusobj-
>checkuserclient($dataform['username']);
$countemail = $Contactusobj-
>checkemail($dataform['email']);
if(($countdata == 0)){
$match = $Contactusobj->insertuserdetails($dataform);
$description = 'Add New User </br>';
if($dataform[name] && $dataform[name] != 0){
$rolename = $Contactusobj-
>getuserrolename($dataform[name]);
$description .= '<span>Role:
</span>'.$rolename.'</br>';
}
if($dataform[ministry_name] && $dataform[ministry_name]
!= 0){
$ministryname = $Contactusobj-
>Getministryname($dataform[ministry_name]);
$description .= '<span>Ministry:
</span>'.$ministryname .'</br>';
}
if($dataform[statename] && $dataform[statename] != 0){
$statename = $Contactusobj-
>getuserstatename($dataform[statename]);
$description .= '<span>State:
</span>'.$statename.'</br>';
}
if($dataform[cityname] && $dataform[cityname] != 0){
$cityname = $Contactusobj-
>getdistrictname($dataform[cityname]);
$description .= '<span>City:
</span>'.$cityname.'</br>';
}
$description .= '<span>User Name:
</span>'.$dataform[username].'</br>';
$description .= '<span>First Name:
</span>'.$dataform[firstname].'</br>';
$description .= '<span>Last Name:
</span>'.$dataform[lastname].'</br>';
$description .= '<span>Email:
</span>'.$dataform[email].'</br>';
$description .= '<span>Mobile:</span>'.$dataform[mobile];
$auditlog = array("uid" => $userid->userid,
"application_type" => 'User',
"description" => $description
);
$auditobj = new Application_Model_Auditlog;
$auditobj->insertauditlog($auditlog);
/***************audit log end by braj***************/
$mailObj = new Zend_Mail();
$username = $dataform['username'];
$fname = ucfirst($dataform['firstname']);
$weblink = WEB_LINK;
$body = MESSAGE_BODY;
$body = str_replace('{user_name}',$username,$body);
$body = str_replace('{fname}',$fname,$body);
$body =
str_replace('{user_password}',$dataform['password'],$body);
$body = str_replace('{web_link}',$weblink,$body);
$subject= MAIL_SUBJECT;
$to =$dataform['email'];
$from =MAIL_FROM;
$name = MAIL_NAME;
$mailObj->setSubject($subject);
$mailObj->setBodyHtml($body);
$mailObj->addTo($to, $name);
$mailObj->setFrom($from,
$name);//print_r($mailObj);die();
$mailObj->send();
$this->_redirect('/user/add?actmsg=add');
}else{
if($countdata){
$this->view->assign('errorMessage', 'Your
username is already exists in the database.');
return;
} }}}}}}}
Model User.php
public function insertuserdetails($dataform) {
$userid = new Zend_Session_Namespace('userid');
$user_table = new Zend_Db_Table('dbt_users');
$date = date("Y-m-d H:i:s");
$datainsert = "";
$datainsert = array(
'state' => $dataform['statename'],
//'cityname'=> $dataform['cityname'],
'ministry_name' => $dataform['ministry_name'],
'username' => $dataform['username'],
'password' => hash_hmac('sha256', $dataform['password'], ''),
'firstname' => $dataform['firstname'],
'lastname' => $dataform['lastname'],
'organisation' => '',
'mobile' => $dataform['mobile'],
'email' => $dataform['email'],
'telephone' => '',
'address' => '',
'role' => $dataform['name'],
'upload' => '',
'dateAdded' => $date,
'dateModify' => $date,
'status' => 1,
'created_by' => $userid->userid,
'login_time' => 1,
'tmp_password' => md5(uniqid(rand(), TRUE)) . substr(md5($dataform['username']), 2, 10),
'reset_time' => $date
);
$insertdata = $user_table->insert($datainsert);
return $insertdata; }
I am reading product sku from csv file and my csv file contains bundle product sku. I am traversing through csv data and for each bundle sku I want to add bundle items inside it which I am passing through CSV
Here is the code what I have done
ini_set('auto_detect_line_endings', TRUE);
$magentoPath = getcwd();
require_once ($magentoPath . '/includes/config.php');
require_once ($magentoPath . '/app/Mage.php');
Mage::app();
//read the csv
$bundleCsv = Mage::getBaseDir('var').'/import/bundleImport.csv';
$rows = array_map('str_getcsv', file($bundleCsv));
$header = array_shift($rows);
$csv = array();
foreach ($rows as $row) {
$csv[] = array_combine($header, $row);
}
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
echo Mage::app()->getStore()->getId(); exit;
foreach( $csv as $key => $val ){
if( !isset($val['sku']) || empty($val['sku']) || $val['sku'] == '' ){
echo 'Not Valid Sku';
continue;
}
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku',$val['sku']);
$opt = $val['bundle_options'];
$optArr = explode(':', $opt);
$bundleOptions = array();
$bundleSelections = array();
foreach ( $optArr as $key1 => $val1 ) {
$valTemp = explode( '(', $val1 );
$title = trim($valTemp[0]);
$bundleSub[$key1] = array(
'title' => $title, // option title
'option_id' => $key1,
'delete' => '',
'type' => 'select', // option type
'required' => '1', // is option required
'position' => '1' // option position
);
$skuStr = trim($valTemp[1]);
$skuStrTemp = explode( ')', $skuStr );
$skuStr = trim($skuStrTemp[0]);
$skuTemp = explode( '+', $skuStr );
foreach( $skuTemp as $key2 => $val2 ){
$product = Mage::getModel('catalog/product');
$id = Mage::getModel('catalog/product')->getResource()->getIdBySku($val2);
if( $id ){
$bundleSelectionsSub[$key2] = array ( // selection ID of the option (first product under this option (option ID) would have ID of 0, second an ID of 1, etc)
'product_id' => $id, // if of a product in selection
'delete' => '',
'selection_price_value' => '10',
'selection_price_type' => 0,
'selection_qty' => 1,
'selection_can_change_qty' => 0,
'position' => 0,
'is_default' => 1
);
$product = null;
}else{
continue;
}
}
$bundleSelections[$key1] = $bundleSelectionsSub;
}
$bundleOptions = $bundleSub;
//echo '<pre>'; print_r($bundleOptions); exit;
try{
$_product->setCanSaveCustomOptions ( true );
$_product->setCanSaveBundleSelections ( true );
$_product->setAffectBundleProductSelections ( true );
$_product->setBundleOptionsData ( $bundleOptions );
$_product->setBundleSelectionsData ( $bundleSelections );
$_product->save();
}catch ( Exception $e ) {
Mage::log ( $e->getMessage () );
echo $e->getMessage ();
}
echo 1; exit;
$_product = null;
}
But this gives me following error as
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`aero_dev`.`catalog_product_bundle_option_value`, CONSTRAINT `FK_CAT_PRD_BNDL_OPT_VAL_OPT_ID_CAT_PRD_BNDL_OPT_OPT_ID` FOREIGN KEY (`option_id`) REFERENCES `catalog_product_bundle_option` (`opt), query was: INSERT INTO `catalog_product_bundle_option_value` (`option_id`, `store_id`, `title`) VALUES (?, ?, ?)
Any help would be appreciated.
I could not get it working using above approach so I tried to write custom query to put bundle items in the existing bundle product. When I looked into db I found there are basically 3 tables involved to create bundle items. These are
catalog_product_bundle_option
catalog_product_bundle_option_value
catalog_product_bundle_selection
I went through these tables and tried to looked for what magento puts If I create bundle items from magento admin.
So after some research I have done something like -
foreach( $csv as $key => $val ){
if( !isset($val['sku']) || empty($val['sku']) || $val['sku'] == '' ){
echo 'Not Valid Sku';
continue;
}
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku',trim($val['sku']));
$_product->setCanSaveCustomOptions ( true );
$_product->setCanSaveBundleSelections ( true );
$_product->setAffectBundleProductSelections ( true );
$opt = $val['bundle_options'];
$optArr = explode(':', $opt);
//get the db write connection
$connection = Mage::getSingleton('core/resource')->getConnection('core_write');
$connection->beginTransaction();
foreach ( $optArr as $key1 => $val1 ) {
$valTemp = explode( '(', $val1 );
$title = trim($valTemp[0]);
//insert into catalog_product_bundle_option with parent product id and type
$__fields = array();
$__fields['parent_id'] = $_product->getId();
$__fields['required'] = 1;
$__fields['type'] = 'select';
$__fields['position'] = $key1+1;
$connection->insert($catalog_product_bundle_option, $__fields);
$opt_id = $connection->lastInsertId();
$connection->commit();
//inert into catalog_product_bundle_option_value with option id, store id, title
$__fields = array();
$__fields['option_id'] = $opt_id;
$__fields['store_id'] = 0;
$__fields['title'] = $title;
$connection->insert($catalog_product_bundle_option_value, $__fields);
$val_id = $connection->lastInsertId();
$connection->commit();
$skuStr = trim($valTemp[1]);
$skuStrTemp = explode( ')', $skuStr );
$skuStr = trim($skuStrTemp[0]);
$skuTemp = explode( '+', $skuStr );
$pos = 1;
foreach( $skuTemp as $key2 => $val2 ){
$id = Mage::getModel('catalog/product')->getResource()->getIdBySku($val2);
//insert into catalog_product_bundle_selection with option_id, parent product id, product id, position, is_default, selection_price_type, selection_price_value, selection_qty, selection_can_change_qty
$__fields = array();
$__fields['option_id'] = $opt_id;
$__fields['parent_product_id'] = $_product->getId();
$__fields['product_id'] = $id;
$__fields['position'] = $pos + 1;
$__fields['selection_price_type'] = 0;
$__fields['selection_price_value'] = 10;
$__fields['selection_qty'] = 1;
$__fields['selection_can_change_qty'] = 0;
$connection->insert($catalog_product_bundle_selection, $__fields);
$connection->commit();
$pos++;
}
}
//update product
$_product->save();
$_product = null;
}
my csv contains 2 columns one is sku and another is bundle options
example - sku - 12345678
bundle options - item01(ZIPLOCK18X24+ZIPLOCK16X20):item02(ZIPLOCK14X20+XEROMOCR84208X11)
in which item01 is the option title followed by simple products sku ZIPLOCK18X24, ZIPLOCK16X20 and : seperated incase of multiple options title.
I hope it may help someone.
I am trying to apply sort from remember filters on my admin function i have
if (isset($_GET[ucfirst($this->id) .'_sort'])) {
$extractSort = $_GET[ucfirst($this->id) .'_sort'];
//Yii::log($extractSort);
Yii::app()->user->setState(ucfirst($this->id) .'_sort', $extractSort);
} else if(Yii::app()->user->hasState(ucfirst($this->id) .'_sort')) {
$_GET['sort'] = Yii::app()->user->getState(ucfirst($this->id) .'_sort');
//Yii::log(Yii::app()->user->getState(ucfirst($this->id) .'_sort'));
}
On my view I have jquery which triggers n update to get the state of a model on another function. however I am having trouble applying the sort.
$model=Yii::app()->user->getState('exportModel');
$dataProvider = $model->weeklystatus(array(),false);
if(Yii::app()->user->hasState(ucfirst($this->id) .'_sort')) {
Yii::log(Yii::app()->user->getState(ucfirst($this->id) .'_sort'));
$explode = explode("Yii::app()->user->getState(ucfirst($this->id) .'_sort')" , ".");
$sort = new CSort();
$sort->attributes = array(
$explode[0]=>array(
'asc'=>$explode[0]." ASC",
'desc'=>$explode[0] . " DESC",
),
'*',
);
$sort->applyOrder($model);
$dataProvider->setSort($sort);
}
My model function search
public function weeklystatus($arr = array(),$ignore = false,$showspline = false)
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
//Yii::log(var_dump($this->getPlannedPOC()));
$criteria=new CDbCriteria;
$criteria->select='*, ((CURDATE() - StartDATE) / (ProjectEndDate - StartDATE ))*100 as PlannedPOC';
if($showspline)
$criteria->addCondition('PROJECT = "' .$this->PROJECT . '"');
else
$criteria->compare('PROJECT',$this->PROJECT,true);
$stradd = '';
if(!empty($arr) && isset($arr['PROJCODE'])){
$str = '';
foreach($arr['PROJCODE'] as $value) {
$str .= "PROJCODE = '$value' || ";
}
$criteria->addCondition(substr($str, 0, -3));
$stradd .= substr($str, 0, -3);
}else
$criteria->compare('PROJCODE',$this->PROJCODE,true);
$criteria->compare('PROJID',$this->PROJID);
$criteria->mergeWith($this->dateRangeSearchCriteria('StartDATE', $this->StartDATE));
$criteria->mergeWith($this->dateRangeSearchCriteria('ProjectEndDate', $this->ProjectEndDate));
$criteria->mergeWith($this->dateRangeSearchCriteria('ActualEndDate', $this->ActualEndDate));
$criteria->mergeWith($this->dateRangeSearchCriteria('ExpectedCompletionDate', $this->ExpectedCompletionDate));
$criteria->compare('PROCESSOR',$this->PROCESSOR,true);
if(!empty($arr) && isset($arr['OFFICE'])){
$stro = '';
foreach($arr['OFFICE'] as $value) {
$stro .= "OFFICE = '$value' || ";
}
$criteria->addCondition(substr($stro, 0, -3));
$stradd .= ") AND ( ".substr($stro, 0, -3);
}else
$criteria->compare('OFFICE',$this->OFFICE,true);
$criteria->compare('DEPTCODE',$this->DEPTCODE,true);
$criteria->compare('PERCENT',$this->PERCENT,true);
$criteria->compare('PERCENTPlanned',$this->PERCENTPlanned,true);
$criteria->compare('KM',$this->KM,true);
$criteria->compare('KMPlanned',$this->KMPlanned,true);
if(!empty($arr) && isset($arr['MC'])){
$str = '';
foreach($arr['MC'] as $value) {
$str .= "MC = '$value'";
}
$criteria->addCondition($str);
if(!empty($stradd)){
$stradd = "($stradd) AND ($str) AND ";
}
}else{
$criteria->compare('MC',$this->MC,true);
}
$criteria->compare('MCSALE',$this->MCSALE);
$criteria->compare('CATEGORY',$this->CATEGORY,true);
$criteria->compare('AREA',$this->AREA,true);
$criteria->compare('COUNTRY',$this->COUNTRY,true);
$criteria->compare('PROJINFO',$this->PROJINFO,true);
$criteria->compare('quality_timing',$this->quality_timing,true);
$criteria->compare('REGION',$this->REGION,true);
$criteria->compare('ASAAREA',$this->ASAAREA,true);
$criteria->compare('LORM',$this->LORM,true);
//$ignore = false;
//echo "1st: $ignore";
if(isset($_REQUEST['ViewWebprojectreport'])){
foreach ($_REQUEST['ViewWebprojectreport'] as $key => $value) {
//print_r($key);
//print_r($value);
if($key != "StartDATE"){
if($value != "")
$ignore = true;
}
//echo "\n";
}
}
//echo "2nd: $ignore";
if(!$ignore && !$showspline){
$date = date('Y-m-d',strtotime("-2 week"));
$criteria->addCondition("StartDATE > '".Yii::app()->params['filterStartDateonReports']."-01-01' AND (PERCENT < 100 || PERCENT is null)");
//$criteria->addCondition("(PERCENT < 100 || PERCENT is null)");
//$criteria->addCondition("StartDATE < '$date' AND PERCENT <100 || StartDATE > '$date' AND PERCENT =100 ");
$criteria->addCondition("$stradd (StartDATE > '$date' AND PERCENT =100) ","OR");
/*AND (StartDATE < '$date' AND PERCENT <100)
|| (StartDATE > '$date' AND PERCENT =100) ");*/
//$criteria->addCondition("PERCENT < 100 AND StartDATE < '$date'");
//$criteria->addCondition('StartDATE > '.$date . ' AND PERCENT > -1' );
}elseif(!$showspline){
$criteria->addCondition("StartDATE > '".Yii::app()->params['filterStartDateonReports']."-01-01'");
}
/*
if(isset($_REQUEST['ViewWebprojectreport_sort'])){
$sort = explode(".",$_REQUEST['ViewWebprojectreport_sort']);
if(isset($sort[1]))
$criteria->order = $sort[0] . " " . $sort[1];
else
$criteria->order = $_REQUEST['ViewWebprojectreport_sort'];
}elseif(Yii::app()->user->hasState("ViewWebprojectreport_sort")){
Yii::log(Yii::app()->user->getState("ViewWebprojectreport_sort"));
$sort = explode(".",Yii::app()->user->getState("ViewWebprojectreport_sort"));
if(isset($sort[1]))
$criteria->order = $sort[0] . " " . $sort[1];
else
$criteria->order = Yii::app()->user->getState("ViewWebprojectreport_sort");
}
//$criteria->order = 'id desc';
*/
$sort = new CSort();
$sort->attributes = array(
'*', // preserve sorting capability
"PROJECT"=>array(
"asc"=>"PROJECT ASC",
"desc"=>"PROJECT DESC"),
'PlannedPOC'=>array(
'asc'=>'PlannedPOC ASC',
'desc'=>'PlannedPOC DESC',
),
);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
"sort"=>$sort,
'pagination'=>array(
'pageSize'=>25,
),
));
}
I have tried which does not work
if(Yii::app()->user->hasState(ucfirst($this->id) .'_sort')) {
$explode = explode(".",Yii::app()->user->getState(ucfirst($this->id) .'_sort'));
$name = $explode[0];
$sort = new CSort();
if(count($explode)==2){
$sort->attributes = array(
/*$name => array(
"desc"=>$name . "DESC"
),*/
'defaultOrder'=>array(
$name=> CSort::SORT_DESC
),
);
}else{
$sort->attributes = array(
/*$name => array(
"asc"=>$name . " ASC",
),*/
'defaultOrder'=>array(
$name=> CSort::SORT_ASC
),
);
}
//Yii::log(print_r($explode,true));
Yii::log(print_r($sort->attributes,true));
$sort->applyOrder($model);
$dataProvider->setSort($sort);
}
following is print out of CSort
CSort Object
(
[multiSort] =>
[modelClass] => ViewWebprojectreport
[attributes] => Array
(
)
[sortVar] => sort
[descTag] => desc
[defaultOrder] => Array
(
[PROJECT] =>
)
[route] =>
[separators] => Array
(
[0] => -
[1] => .
)
[params] =>
[_directions:CSort:private] => Array
(
[PROJECT] =>
)
[_e:CComponent:private] =>
[_m:CComponent:private] =>
)
Would you try :
$model = Yii::app()->user->getState('exportModel');
$dataProvider = $model->weeklystatus(array(),false);
if(Yii::app()->user->hasState(ucfirst($this->id) .'_sort')) {
Yii::log(Yii::app()->user->getState(ucfirst($this->id) .'_sort'));
$explode = explode(Yii::app()->user->getState(ucfirst($this->id) .'_sort'), ".");
$sort = new CSort();
$sort->attributes = array(
$explode[0] => array(
'asc' => $explode[1] . " ASC",
'desc' => $explode[1] . " DESC",
),
'*',
);
$sort->applyOrder($model);
$dataProvider->setSort($sort);
}
I am using xapian as a search engine for my website.
Recently I found out it does not search words containg polish specific characters like ś, ą, ć, ę.
Anytime I am trying to search word containg one of those language-specific chars it returns no results. Are there any encoding settings in xapian?
Those are my indexing and searching functions ($document has content, id and route field).
protected function _indexDocument($document, $indexer, $database)
{
$doc = new XapianDocument();
$content = Zend_Json::encode($document);
$doc->set_data($content);
$indexer->set_document($doc);
$indexer->index_text($content);
$term = (string) md5($document['id']);
$doc->add_boolean_term($term);
$database->replace_document($term, $doc);
return true;
}
public function searchDocuments($phrase, $page = 0, $limit = 10)
{
$page = (int) $page;
$limit = (int) $limit;
$database = new XapianDatabase($this->getDatabasePath());
$enquire = new XapianEnquire($database);
$qp = new XapianQueryParser();
$stemmer = new XapianStem("english");
$qp->set_stemmer($stemmer);
$qp->set_database($database);
$qp->set_stemming_strategy(XapianQueryParser::STEM_SOME);
$query = $qp->parse_query($phrase);
$enquire->set_query($query);
$matches = $enquire->get_mset(($page-1) * $limit, $limit);
$documentCount = $matches->get_matches_estimated();
$i = $matches->begin();
$documents = array();
$rawDocuments = array();
while (!$i->equals($matches->end())) {
$n = $i->get_rank() + 1;
$data = $i->get_document()->get_data();
$documents[] = $this->_prepareDocument( Zend_Json::decode($data), $phrase );
$rawDocuments[]= Zend_Json::decode($data);
$i->next();
}
$pageCount = ceil($documentCount / $limit);
if ($page > 0) {
$prevPage = ($page - 1) * $limit;
} else {
$prevPage = 0;
}
if ($page < $pageCount) {
$nextPage = ($page + 1) * $limit;
} else {
$nextPage = $pageCount;
}
$result = array('results' => $documents, 'results-raw' => $rawDocuments, 'paginator' => array(
'page' => $page, 'limit' => $limit, 'pageCount' => $pageCount,
'prevPage' => $prevPage, 'nextPage' => $nextPage,
'documentCount' => $documentCount));
return $result;
}
I would love a script or magento extension to allow me to export all the product attributes including values for drop down attributes. Importing would be good too, I've had a look but can't seem to find anything does anyone know how this can be done?
Update: I found a working script in stackexchange and the script worked exactly as it should. All credits to the original poster. I am just copy pasting his reply here for future reference. Link to the original thread: is here.
I've done this to export all attributes and their options (if it is a dropdown attribute) from the source website:
exportAttributes.php in root directory of source website:
<?php
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
Mage::app();
$entity_type_id = Mage::getModel('catalog/product')->getResource()->getTypeId();
prepareCollection($entity_type_id);
function prepareCollection($ent_type_id){
$resource = Mage::getSingleton('core/resource');
$connection = $resource->getConnection('core_read');
$select_attribs = $connection->select()
->from(array('ea'=>$resource->getTableName('eav/attribute')))
->join(array('c_ea'=>$resource->getTableName('catalog/eav_attribute')), 'ea.attribute_id = c_ea.attribute_id');
// ->join(array('e_ao'=>$resource->getTableName('eav/attribute_option'), array('option_id')), 'c_ea.attribute_id = e_ao.attribute_id')
// ->join(array('e_aov'=>$resource->getTableName('eav/attribute_option_value'), array('value')), 'e_ao.option_id = e_aov.option_id and store_id = 0')
$select_prod_attribs = $select_attribs->where('ea.entity_type_id = '.$ent_type_id)
->order('ea.attribute_id ASC');
$product_attributes = $connection->fetchAll($select_prod_attribs);
$select_attrib_option = $select_attribs
->join(array('e_ao'=>$resource->getTableName('eav/attribute_option'), array('option_id')), 'c_ea.attribute_id = e_ao.attribute_id')
->join(array('e_aov'=>$resource->getTableName('eav/attribute_option_value'), array('value')), 'e_ao.option_id = e_aov.option_id and store_id = 0')
->order('e_ao.attribute_id ASC');
$product_attribute_options = $connection->fetchAll($select_attrib_option);
$attributesCollection = mergeCollections($product_attributes, $product_attribute_options);
prepareCsv($attributesCollection);
}
function mergeCollections($product_attributes, $product_attribute_options){
foreach($product_attributes as $key => $_prodAttrib){
$values = array();
$attribId = $_prodAttrib['attribute_id'];
foreach($product_attribute_options as $pao){
if($pao['attribute_id'] == $attribId){
$values[] = $pao['value'];
}
}
if(count($values) > 0){
$values = implode(";", $values);
$product_attributes[$key]['_options'] = $values;
}
else{
$product_attributes[$key]['_options'] = "";
}
/*
temp
*/
$product_attributes[$key]['attribute_code'] = $product_attributes[$key]['attribute_code'];
}
return $product_attributes;
}
function prepareCsv($attributesCollection, $filename = "importAttrib.csv", $delimiter = '|', $enclosure = '"'){
$f = fopen('php://memory', 'w');
$first = true;
foreach ($attributesCollection as $line) {
if($first){
$titles = array();
foreach($line as $field => $val){
$titles[] = $field;
}
fputcsv($f, $titles, $delimiter, $enclosure);
$first = false;
}
fputcsv($f, $line, $delimiter, $enclosure);
}
fseek($f, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="'.$filename.'"');
fpassthru($f);
}
This will give a csv file [actually i used "|" to separate ;)]
paste this csv file in MAGENTO_ROOT/attribImport directory of the destination website, i.e. website to which attributes need to be imported:
now put the following code in MAGENTO_ROOT/attribImport** directory
of the destination website
<?php
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/../app/Mage.php';
Mage::app();
// $fileName = MAGENTO . '/var/import/importAttrib.csv';
$fileName = 'importAttrib.csv';
// getCsv($fileName);
getAttributeCsv($fileName);
function getAttributeCsv($fileName){
// $csv = array_map("str_getcsv", file($fileName,FILE_SKIP_EMPTY_LINES));
$file = fopen($fileName,"r");
while(!feof($file)){
$csv[] = fgetcsv($file, 0, '|');
}
$keys = array_shift($csv);
foreach ($csv as $i=>$row) {
$csv[$i] = array_combine($keys, $row);
}
foreach($csv as $row){
$labelText = $row['frontend_label'];
$attributeCode = $row['attribute_code'];
if($row['_options'] != "")
$options = explode(";", $row['_options']); // add this to createAttribute parameters and call "addAttributeValue" function.
else
$options = -1;
if($row['apply_to'] != "")
$productTypes = explode(",", $row['apply_to']);
else
$productTypes = -1;
unset($row['frontend_label'], $row['attribute_code'], $row['_options'], $row['apply_to'], $row['attribute_id'], $row['entity_type_id'], $row['search_weight']);
createAttribute($labelText, $attributeCode, $row, $productTypes, -1, $options);
}
}
/**
* Create an attribute.
*
* For reference, see Mage_Adminhtml_Catalog_Product_AttributeController::saveAction().
*
* #return int|false
*/
function createAttribute($labelText, $attributeCode, $values = -1, $productTypes = -1, $setInfo = -1, $options = -1)
{
$labelText = trim($labelText);
$attributeCode = trim($attributeCode);
if($labelText == '' || $attributeCode == '')
{
echo "Can't import the attribute with an empty label or code. LABEL= [$labelText] CODE= [$attributeCode]"."<br/>";
return false;
}
if($values === -1)
$values = array();
if($productTypes === -1)
$productTypes = array();
if($setInfo !== -1 && (isset($setInfo['SetID']) == false || isset($setInfo['GroupID']) == false))
{
echo "Please provide both the set-ID and the group-ID of the attribute-set if you'd like to subscribe to one."."<br/>";
return false;
}
echo "Creating attribute [$labelText] with code [$attributeCode]."."<br/>";
//>>>> Build the data structure that will define the attribute. See
// Mage_Adminhtml_Catalog_Product_AttributeController::saveAction().
$data = array(
'is_global' => '0',
'frontend_input' => 'text',
'default_value_text' => '',
'default_value_yesno' => '0',
'default_value_date' => '',
'default_value_textarea' => '',
'is_unique' => '0',
'is_required' => '0',
'frontend_class' => '',
'is_searchable' => '1',
'is_visible_in_advanced_search' => '1',
'is_comparable' => '1',
'is_used_for_promo_rules' => '0',
'is_html_allowed_on_front' => '1',
'is_visible_on_front' => '0',
'used_in_product_listing' => '0',
'used_for_sort_by' => '0',
'is_configurable' => '0',
'is_filterable' => '0',
'is_filterable_in_search' => '0',
'backend_type' => 'varchar',
'default_value' => '',
'is_user_defined' => '0',
'is_visible' => '1',
'is_used_for_price_rules' => '0',
'position' => '0',
'is_wysiwyg_enabled' => '0',
'backend_model' => '',
'attribute_model' => '',
'backend_table' => '',
'frontend_model' => '',
'source_model' => '',
'note' => '',
'frontend_input_renderer' => '',
);
// Now, overlay the incoming values on to the defaults.
foreach($values as $key => $newValue)
if(isset($data[$key]) == false)
{
echo "Attribute feature [$key] is not valid."."<br/>";
return false;
}
else
$data[$key] = $newValue;
// Valid product types: simple, grouped, configurable, virtual, bundle, downloadable, giftcard
$data['apply_to'] = $productTypes;
$data['attribute_code'] = $attributeCode;
$data['frontend_label'] = array(
0 => $labelText,
1 => '',
3 => '',
2 => '',
4 => '',
);
//<<<<
//>>>> Build the model.
$model = Mage::getModel('catalog/resource_eav_attribute');
$model->addData($data);
if($setInfo !== -1)
{
$model->setAttributeSetId($setInfo['SetID']);
$model->setAttributeGroupId($setInfo['GroupID']);
}
$entityTypeID = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId();
$model->setEntityTypeId($entityTypeID);
$model->setIsUserDefined(1);
//<<<<
// Save.
try
{
$model->save();
}
catch(Exception $ex)
{
echo "Attribute [$labelText] could not be saved: " . $ex->getMessage()."<br/>";
return false;
}
if(is_array($options)){
foreach($options as $_opt){
addAttributeValue($attributeCode, $_opt);
}
}
$id = $model->getId();
echo "Attribute [$labelText] has been saved as ID ($id).<br/>";
// return $id;
}
function addAttributeValue($arg_attribute, $arg_value)
{
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
if(!attributeValueExists($arg_attribute, $arg_value))
{
$value['option'] = array($arg_value,$arg_value);
$result = array('value' => $value);
$attribute->setData('option',$result);
$attribute->save();
}
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
foreach($options as $option)
{
if ($option['label'] == $arg_value)
{
return $option['value'];
}
}
return false;
}
function attributeValueExists($arg_attribute, $arg_value)
{
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
foreach($options as $option)
{
if ($option['label'] == $arg_value)
{
return $option['value'];
}
}
return false;
}
NOTE: Allthough exceptions have been handled, Backup your Database
before you import these attributes, to be on safer side. Happy
Importing!
Thanks to :
Programatically create attribute in Magento, useful for the “on the fly” import system
programmatically_adding_attributes_and_attribute_sets
Magento – Programmatically insert new attribute option
I would recommend Boris's uRapidFlow: http://www.unirgy.com/products/urapidflow/ It's one of the better Data Flow Import/Export modules available. Be aware however it does require IonCube Loader, but it is well worth it if you are moving data around a lot.