randomize default products in opencart - random

I'm using OpenCart V1.5.3.1 and am trying to randomize or shuffle the products per category on page load.
The other sort options should still work though (per price, rating, alphabetical,..).
Anybody that can give me some pointers?
Many thanks,
Steven
Code I've tried:
In controller/catalog/product/category.php
Just below
$this->data['products'][] = array(
'product_id' => $result['product_id'],
'thumb' => $image,
'name' => $result['name'],
'description' => utf8_substr(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8')), 0, 100) . '..',
'price' => $price,
'special' => $special,
'tax' => $tax,
'rating' => $result['rating'],
'reviews' => sprintf($this->language->get('text_reviews'), (int)$result['reviews']),
'href' => $this->url->link('product/product', 'path=' . $this->request->get['path'] . '&product_id=' . $result['product_id'])
);
I added:
shuffle($this->data['products']);
In stead of this I also tried this:
Just below:
$results = $this->model_catalog_product->getProducts($data);
I added:
srand((float)microtime() * 1000000);
shuffle($results);
$results = array_slice($results, 0, $data['limit']);
Both these methods unfortunately shuffle also the results when choosing another sorting option (rating, pricing, name). I only want the initial results on page load to be shuffled.

The solution:
Go to catalog/model/catalog/product.php and find the method getProducts($data).
Here change this:
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
if ($data['sort'] == 'pd.name' || $data['sort'] == 'p.model') {
$sql .= " ORDER BY LCASE(" . $data['sort'] . ")";
} else {
$sql .= " ORDER BY " . $data['sort'];
}
} else {
$sql .= " ORDER BY p.sort_order";
}
to this:
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
if ($data['sort'] == 'pd.name' || $data['sort'] == 'p.model') {
$sql .= " ORDER BY LCASE(" . $data['sort'] . ")";
} else {
$sql .= " ORDER BY " . $data['sort'];
}
} else {
$sql .= " ORDER BY RAND()";
}
(hint: only the last $sql .= ... changed)
By this simple change if there is no sorting chosen the products will always be sorted in random order.

Related

Excel file which have images in multiple columns want to import them to database to corresponding column using PHPspreadsheet

I want to import questions, options and solution from excel file which have images in multiple columns want to import them to database to corresponding column using PHPspreadsheet.
So I have column in excel named as question, option1, option2, option3, option4 and solution which will have images. I want to import them in database in respective column i.e question column image in excel will be in question column in database.
I can do it for one column but how to perform this with multiple column.
Sheet photo
enter image description here
$spreadsheet = IOFactory::load(request()->file('file'));
$i = 0;
foreach ($spreadsheet->getActiveSheet()->getDrawingCollection() as $drawing) {
if ($drawing instanceof \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing) {
ob_start();
call_user_func(
$drawing->getRenderingFunction(),
$drawing->getImageResource()
);
$imageContents = ob_get_contents();
ob_end_clean();
switch ($drawing->getMimeType()) {
case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_PNG:
$extension = 'png';
break;
case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_GIF:
$extension = 'gif';
break;
case \PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing::MIMETYPE_JPEG:
$extension = 'jpg';
break;
}
} else {
$zipReader = fopen($drawing->getPath(), 'r');
$imageContents = '';
while (!feof($zipReader)) {
$imageContents .= fread($zipReader, 1024);
}
fclose($zipReader);
$extension = $drawing->getExtension();
}
$myFileName = '<img src"images/' . '00_Image_' . ++$i . '.' . $extension . '" class="img-fluid imgresponsive">';
$savename = '00_Image_' . ++$i . '.' . $extension;
file_put_contents('images/' . $savename, $imageContents);
Question::create([
'question' => $myFileName,
'option1' => $row[1],
'option2' => $row[2],
'option3' => $row[3],
'option4' => $row[4],
'correct_ans' => $row[5],
'question_level' => $row[6],
'lesson' => $row[7],
'ans_type' => $row[8],
'range_from' => $row[9],
'range_to' => $row[10],
'solution' => $row[11],
]);
}
}
I have tried above code but this counts images in excel file and all are added in question column. What I am expecting is to count images in each column of excel file and save them to corresponding one.

Laravel - No increment method for Collection

Hello i have somes problem with collection. I want to increment a value in a row of my collection but i can't figure it. Seriously collection make me headache right now.
i want the equivalent of :
$itemcollection
->where('item_name', $itemcollected_row->first()->item_name)
->increment('quantity',1);
in that code:
//verify is the item is in the collection
$itemcollection = collect();
$itemverification = $itemcollection->where('item_name',$itemcollected_row->first()->item_name);
if ($itemverification->count() > 0) { //if the item exist in collection update it
$itemcollection->where('item_name',$itemcollected_row->first()->item_name)->increment('quantity',1);
}else { //else we need to add it to the collection
$itemcollection->push([
'item_name' => $itemcollected_row->first()->item_name,
'item_avatar' => $itemcollected_row->first()->item_avatar,
'quantity' => 1,
'badge' => '<span class="badge badge-soft-secondary">Common</span>',
]);
}
I found a way to do it. This is now working
$itemcollection = collect();
//Push the item in the collection
$itemcollection->push([
'item_id' => $itemcollected_row->first()->item_id,
'item_name' => $itemcollected_row->first()->item_name,
'item_avatar' => $itemcollected_row->first()->item_avatar,
'quantity' => 1,
'badge' => '<span class="badge badge-soft-secondary">Common</span>',
]);
//loop to display all items collected
$display = '';
foreach ($itemcollection as $itemcollected) {
$display = $itemcollected['item_name']. ' ';
$displaycount = $itemcollection->where('item_name',$itemcollected['item_name'])->count();
$display .= $displaycount . '---';
$itemcollected .= $display;
}

Front controller reached 100 router match iterations when run this www.baseurl.com/home/feed url

I am facing magento url error Front controller reached 100 router match iterations when run this www.baseurl.com/home/feed url. please help me resolve this issue.
Here is a way to find out the exact issue
Open the file
app/code/core/Mage/Core/Controller/Varien/Front.php
and find the code segment
while (!$request->isDispatched() && $i++<100) {
foreach ($this->_routers as $router) {
if ($router->match($this->getRequest())) {
break;
}
}
}
replace it with
Mage::log('----Matching routers------------------------------');
Mage::log('Total ' . count($this->_routers) . ': ' . implode(', ', array_keys($this->_routers)));
while (!$request->isDispatched() && $i++<100) {
Mage::log('- Iteration ' . $i);
$requestData = array(
'path_info' => $request->getPathInfo(),
'module' => $request->getModuleName(),
'action' => $request->getActionName(),
'controller' => $request->getControllerName(),
'controller_module' => $request->getControllerModule(),
'route' => $request->getRouteName()
);
$st = '';
foreach ($requestData as $key => $val) {
$st .= "[{$key}={$val}]";
}
Mage::log('Request: ' . $st);
foreach ($this->_routers as $name => $router) {
if ($router->match($this->getRequest())) {
Mage::log('Matched by "' . $name . '" router, class ' . get_class($router));
break;
}
}
}
Reload your site again and you can see the detailed error log at var/log/system.log

404 not found twitter api 1.1 codeginter

I've been working on upgrading from v 1 to 1.1 for a few days now. I have 100s of users that can't see their followers in my dashboard.
I followed all the steps by changing /1/ to /1.1/ still not working.
Getting error 404 (Not Found)
Controller:
function twitter_auth()
{
if ( !$this->tweet->logged_in() )
{
die('some how you are not logged in');
}
$tokens = $this->tweet->get_tokens();
$this->tweet->enable_debug(TRUE);
$user = $this->tweet->call('get', 'account/verify_credentials');
var_dump($user);
}
$options = array(
'count' => 10,
'page' => 2,
'include_entities' => 1
);
$timeline = $this->tweet->call('get', 'statuses/home_timeline');
var_dump($timeline);
}
Jobs:
function get_twitter_subscribers($args)
{
$rate = #file_get_contents('http://api.twitter.com/1.1/application/rate_limit_status.json');
$rate = #json_decode($rate);
if($rate->remaining_hits == 0):
$status = 'retask';
else:
$new_data = #file_get_contents('http://api.twitter.com/1.1/users/show.json? screen_name='.$args['account_id'].'&include_entities=true');
$new_data = #json_decode($new_data);
if(isset($new_data->followers_count)){
$insert_args = array(
'account_id' => $args['account_id'],
'metric' => 'subscribers',
'value' => $new_data->followers_count,
'platform' => 'twitter'
);
$insert = $this->CI->metrics_model->insert_metric($insert_args);
if (isset($insert)) { $status = 'complete'; }
}else{
$this->send_error_email("Function: get_twitter_subscribers - new_data->followers_count not set for account id: " . $args['account_id'] . "\r\n\r\n" . "args: " . http_build_query($args) . "\r\n\r\n" . 'http://api.twitter.com/1.1/users/show.json?screen_name='.$args['account_id'].'&include_entities=true');
}
endif;
if(!isset($status)){
$this->send_error_email("Function: get_twitter_subscribers - status not set." . "\r\n\r\n" . "args: " . http_build_query($args) . "\r\n\r\n" . 'http://api.twitter.com/1.1/users/show.json? screen_name='.$args['account_id'].'&include_entities=true');
$status = 'error';
}
return $status;
controllers:
function auth($platform)
{
if($platform == 'facebook'):
echo 'auth facebook';
elseif($platform == 'twitter'):
$this->load->library('tweet');
// current key in php page
$tokens = array(
'oauth_token' => 'xxxxxxxxxxxxx',
'oauth_token_secret' => 'xxxxxxxxxxxx'
);
$this->tweet->set_tokens($tokens);
if ( !$this->tweet->logged_in() ) :
$this->tweet->set_callback(site_url('manage/auth/twitter'));
$this->tweet->login();
else:
echo 'Twitter logged in. Return to manager';
endif;
endif;
}
What am I doing wrong?
This issue has been resolved. I created my own cURL library.
function get_twitter_subscribers($args){
$request = curl_init();
$bearer = "AAAAAAAAAAAAAAAAAAAAAJ%2xxxxxxxxxxxxxxx0000x0x0x0x0";
curl_setopt($request, CURLOPT_SSLVERSION, 1);
curl_setopt($request, CURLOPT_URL, 'https://api.twitter.com/1.1/users/show.json?screen_name='.$args['account_id'].'&include_entities=true');
curl_setopt($request, CURLOPT_HTTPHEADER, array('Authorization: Bearer '.$bearer));
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
$new_data = json_decode($file_get_contents = curl_exec($request));
curl_close($request);
if(isset($new_data->followers_count)){
$insert_args = array(
'account_id' => $args['account_id'],
'metric' => 'subscribers',
'value' => $new_data->followers_count,
'platform' => 'twitter'
);
$insert = $this->CI->metrics_model->insert_metric($insert_args);
if (isset($insert)) { $status = 'complete'; }
}else{
$this->send_error_email("Function: get_twitter_subscribers - new_data->followers_count not set for account id: " . $args['account_id'] . "\r\n\r\n" . "args: " . http_build_query($args) . "\r\n\r\n" . 'https://api.twitter.com/1.1/users/show.json?screen_name='.$args['account_id'].'&include_entities=true');
}
if(!isset($status)){
$this->send_error_email("Function: get_twitter_subscribers - status not set." . "\r\n\r\n" . "args: " . http_build_query($args) . "\r\n\r\n" . 'http://api.twitter.com/1.1/users/show.json?screen_name='.$args['account_id'].'&include_entities=true');
$status = 'error';
}
return $status;
}

multiple where condition codeigniter

How can I convert this query to active record?
"UPDATE table_user
SET email = '$email', last_ip = '$last_ip'
where username = '$username' and status = '$status'";
I tried to convert the query above to:
$data = array('email' => $email, 'last_ip' => $ip);
$this->db->where('username',$username);
$this->db->update('table_user',$data);
How about using the where clausa status?
# must i write db->where two times like this?
$this->db->where('username',$username);
$this->db->where('status',$status);
I also tried this:
$this->db->where('username',$username,'status',$status);
you can use an array and pass the array.
Associative array method:
$array = array('name' => $name, 'title' => $title, 'status' => $status);
$this->db->where($array);
// Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
Or if you want to do something other than = comparison
$array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);
$this->db->where($array);
Yes, multiple calls to where() is a perfectly valid way to achieve this.
$this->db->where('username',$username);
$this->db->where('status',$status);
http://www.codeigniter.com/user_guide/database/query_builder.html
you can try this function for multi-purpose
function ManageData($table_name='',$condition=array(),$udata=array(),$is_insert=false){
$resultArr = array();
$ci = & get_instance();
if($condition && count($condition))
$ci->db->where($condition);
if($is_insert)
{
$ci->db->insert($table_name,$udata);
return 0;
}
else
{
$ci->db->update($table_name,$udata);
return 1;
}
}
$wherecond = "( ( ( username ='" . $username . "' OR status='" . $status . "') AND (id='" . $id . "') ) )";
$this->db->where($wherecond);
If you want to add AND and OR conditions at a time. this will work.
Try this
$data = array(
'email' =>$email,
'last_ip' => $last_ip
);
$where = array('username ' => $username , 'status ' => $status);
$this->db->where($where);
$this->db->update('table_user ', $data);
it's late for this answer but i think maybe still can help, i try the both methods above, using two where conditions and the method with the array, none of those work for me i did several test and the condition was never getting executed, so i did a workaround, here is my code:
public function validateLogin($email, $password){
$password = md5($password);
$this->db->select("userID,email,password");
$query = $this->db->get_where("users", array("email" => $email));
$p = $query->row_array();
if($query->num_rows() == 1 && $password == $p['password']){
return $query->row();
}
}
you can use both use array like :
$array = array('tlb_account.crid' =>$value , 'tlb_request.sign'=> 'FALSE' );
and direct assign like:
$this->db->where('tlb_account.crid' =>$value , 'tlb_request.sign'=> 'FALSE');
I wish help you.

Resources