Magento - Bad attributes when loading product? - php

I'm creating custom rules to automagically add products to categories. The below code is from my observer. The problem I encounter is that upon running this code, products without an attribute ('shirt_color' for example) get added to my category.
Can anyone shed some light as to why this is happening? For some reason, 'charcoal grey' is still being attached to the product w/o a 'shirt_color'. When compared ('charcoal grey' == 'charcoal grey') it resolves to 'true' and that is why $r == 1;
Thanks.
Example output:
#product w/ a 'shirt_color' attribute
productEntityId=628
productName=Rogue GRAY International Shirt XXL
productSKU=HW0003-XXL
string ==
product attributeSTRTOLOWER='charcoal grey'
value STRTOLOWER='charcoal grey'
r=1
#product w/o a 'shirt_color' attribute
productEntityId=629
productName=O'Neill Hyperfreak White
productSKU=
string ==
product attributeSTRTOLOWER='charcoal grey'
value STRTOLOWER='charcoal grey'
r=1
Code:
public function onCategoryRuleSave($observe)
{
$model = Mage::getModel('catalog/product');
$collection =
$model->getCollection()
->addAttributeToSelect('entity_id');
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
foreach ($collection as $product) {
echo "productEntityId=" . $product->getId() . "<br>";
$product = $product->load($product->getId());
$productAttributeValue =
$model->load($product->getId())
->getAttributeText( $observe['attribute_code'] );
$r = 0;
echo "productName=" . $product->getName() . "<br>";
echo "productSKU=" . $product->getSku() . "<br>";
if ( is_numeric($observe['value']) ) {
echo "operator= " . $observe['operator'] . "<br>";
switch($observe['operator']) {
case "<":
echo "numeric <<br>";
$r = ($productAttributeValue < $observe['value']) ? 1 : 0;
break;
case ">":
echo "numeric ><br>";
$r = ($productAttributeValue > $observe['value']) ? 1 : 0;
break;
case "<=":
echo "numeric <=<br>";
$r = ($productAttributeValue <= $observe['value']) ? 1 : 0;
break;
case ">=":
echo "numeric >=<br>";
$r = ($productAttributeValue >= $observe['value']) ? 1 : 0;
break;
case "==":
echo "numeric ==<br>";
$r = ($productAttributeValue == $observe['value']) ? 1 : 0;
break;
case "!=":
echo "numeric !=<br>";
$r = ($productAttributeValue != $observe['value']) ? 1 : 0;
break;
}
}
else {
switch($observe['operator']) {
case "==":
echo "string ==<br>";
echo "product attributeSTRTOLOWER='" . strtolower($productAttributeValue) . "'<br>";
echo "value STRTOLOWER='" . strtolower($observe['value']) . "'<br>";
$r = (
strtolower($productAttributeValue) == strtolower($observe['value'])
) ? 1 : 0;
echo "r=" . $r . "<br>";
break;
case "!=":
echo "string !=<br>";
echo "product attributeSTRTOLOWER='" . strtolower($productAttributeValue) . "'<br>";
echo "value STRTOLOWER='" . strtolower($observe['value']) . "'<br>";
$r = (
strtolower($productAttributeValue) != strtolower($observe['value'])
) ? 1 : 0;
echo "r=" . $r . "<br>";
break;
}
}
echo "<br>";
if ($r==1) {
$write->query(
"REPLACE INTO `catalog_category_product` (`category_id`, `product_id`)
VALUES (" . $observe['category_id'] . "," . $product->getId() . ")"
);
}
}
die();
}
Passed from the controller:
Mage::dispatchEvent(
'category_rule_save',
array(
'rule_id' => $id,
'attribute_code' => $data['attribute_code'],
'operator' => $data['operator'],
'value' => $data['value'],
'category_id' => $data['category'],
'store_id' => $data['store_id']
)
);

Figured out the problem. Because I declared $model = Mage::getModel('catalog/product'); earlier, something was messing up later on. Instead of
$model->load($product->getId())
I now have
Mage::getModel('catalog/product')->load($product->getId()).
I did the same for Mage::getModel('catalog/product')->getCollection().

Related

PHP: Replace ID with string, based on decoded JSON number

The custom Wordpress plugin I installed, responsible for all kind of hotel booking requests, displays a calendar containing the for- and surname of our clients in the Wordpress backend. At first I didn't get the ID of the booked apartment, but now I got that which leads me to the next problem.
Unfortunately only the ID of the booked apartment is displayed in the backend. Is there a way to convert the ID into a predefined string before the page is displayed?
Like 237 ยป Apartment 4?
I already tried it with a If-condition, but nothings happened.
if ( !empty($booked_ids) ) {
foreach( $booked_ids as $key => $val) {
echo '<tr class="sh_booking_data">';
$booking_meta = get_post_meta( $val, '_booking_meta', true );
$arr = json_decode($booking_meta["save_rooms"], true);
die($arr["Room 1"]["room_type"]);
if ( $arr["Room 1"]["room_type"] == 237 ) {
$bodytag = "Apartment 4";
echo("<script>console.log('PHP: " . $arr["Room 1"]["room_type"] . "');</script>");
}
echo '<td>#' . $val . ' ' . $booking_meta["first_name"] . ' ' . $booking_meta["last_name"] . ' ' . $arr["Room 1"]["room_type"] . '</td>';
foreach( $month_1_2_array as $key => $val) {
if ( !empty($booking_meta["booking_status"]) ) {
if ( $booking_meta["booking_status"] == 1 ) {
$booking_status_class = 'pending';
} elseif ( $booking_meta["booking_status"] == 2 ) {
$booking_status_class = 'confirmed';
} elseif ( $booking_meta["booking_status"] == 3 ) {
$booking_status_class = 'cancelled';
} else {
$booking_status_class = 'unknown';
}
} else {
$booking_status_class = 'unknown';
}
if( $booking_meta["check_in"] == $val ) {
echo '<td class="sh_first_day_' . $booking_status_class . '"> </td>';
} elseif( $booking_meta["check_out"] == $val ) {
echo '<td class="sh_last_day_' . $booking_status_class . '"> </td>';
} elseif ( sh_get_date_range_overlap($val,$val,$booking_meta["check_in"],$booking_meta["check_out"]) == true ) {
echo '<td class="sh_booking_' . $booking_status_class . '"> </td>';
} else {
echo '<td> </td>';
}
}
echo '</tr>';
}
}
I'm very new to PHP and thanks in advance!
If you got multiple IDs, then you can list all the available IDs in if-else block and assign the relevant Apartment name for the relevant ID to the $bodytag, so you can use $bodytag to print echo it.
So below is an example:
Assuming that you have 6 ID's which are 237, 27, 251, 252, 255, and 260, so you put all of them in if-else block like this and assign the relevant apartment name for the relevant ID.
$bodytag = ""; // initialize the variable
if ($arr["Room 1"]["room_type"] == 237) {
$bodytag = "Apartment 4";
}
else if ($arr["Room 1"]["room_type"] == 27) {
$bodytag = "Apartment 10";
}
else if ($arr["Room 1"]["room_type"] == 251) {
$bodytag = "Apartment 12";
}
else if ($arr["Room 1"]["room_type"] == 252) {
$bodytag = "Apartment 13";
}
else if ($arr["Room 1"]["room_type"] == 255) {
$bodytag = "Apartment 15";
}
else{
$bodytag = "Apartment 20";
}
echo '<td>#' . $val . ' ' . $booking_meta["first_name"] . ' ' . $booking_meta["last_name"] . ' ' . $bodytag . '</td>';

Array_push in for loop giving null response

Hello I am trying to push in an array using array_push but I am getting the value of the first index then after that all I am getting a null response, I am not getting where I have done a mistake.I am getting the values properly but in array_push there is some mistake which is in for loop.
Here is my code :
function actioncouponcsv_download() {
$this->layout = false;
foreach (Yii::app()->log->routes as $route) {
if ($route instanceof CWebLogRoute || $route instanceof CFileLogRoute || $route instanceof YiiDebugToolbarRoute) {
$route->enabled = false;
}
}
$dateRange = json_decode($_POST['dateRange'], true);
$start = $dateRange['start'];
$end = $dateRange['end'];
$validity = $_POST['validity'];
$limit = isset($_REQUEST['limit']) && trim($_REQUEST['limit']) ? $_REQUEST['limit'] : 0;
$studio_id = Yii::app()->user->studio_id;
if (isset($_GET['type']) && intval($_GET['type']) ==2) {
$couponobj = new CouponSubscription();
$getcouponobj = $couponobj->getcoupon_data($studio_id,$start,$end,$validity);
$k = 0;
$title_addon = "\t" . "Discount Cycle" . "\t" . "Extend free trail";
$data_addon = "\t" . $getcouponobj[$k]['discount_multiple_cycle'] . "\t" . $getcouponobj[$k]['extend_free_trail'];
} else {
$title_addon = "";
$data_addon = "";
$couponobj = new Coupon();
$getcouponobj = $couponobj->getcoupon_data($studio_id,$limit,1);
}
//$Coupon = Coupon::model()->find('studio_id=:studio_id', array(':studio_id' => $studio_id));
$dataCsv = '';
if ($getcouponobj) {
$headings = "Sl no" . "\t" . "Coupon" . "\t" . "Coupon Type" . "\t" . "Used by a single user" . "\t" . "Valid" . "\t" . "Used" . "\t" . "User" .$title_addon. "\t" . "Used Date". "\t" . "Content Category". "\t" . "Content"."\n";
$i = 1;
$dataCSV[] = Array();
$j = 0;
for ($k = 0; $k < count($getcouponobj); $k++) {
$userList = '-';
if ($getcouponobj[$k]['used_by'] != '0') {
if ($getcouponobj[$k]['coupon_type'] == 1) {
$userList = '';
$userIdList = explode(",", $getcouponobj[$k]['used_by']);
foreach ($userIdList as $userIdListKey => $userIdListVal) {
if ($userIdListKey == 0) {
$userList .= Yii::app()->webCommon->getuseremail($userIdListVal);
} else {
$userList .= " | " . Yii::app()->webCommon->getuseremail($userIdListVal);
}
}
} else {
$userList = Yii::app()->webCommon->getuseremail($getcouponobj[$k]['used_by']);
}
}
if($getcouponobj[$k]['is_all']!=1){
if($getcouponobj[$k]['content_category']==1){
$cont_cat = "Digital";
$content_str = Coupon::model()->getContentInfo($getcouponobj[$k]['specific_content']);
$cont_str = $content_str;
}else if($getcouponobj[$k]['content_category']==2){
$cont_cat = "Physical";
$content_str = Coupon::model()->getContentInfoPhysical($getcouponobj[$k]['specific_content']);
$cont_str = $content_str;
}else{
$cont_cat = "All";
$cont_str = "All";
}
}else{
$cont_cat = "All";
$cont_str = "All";
}
#echo $getcouponobj[$k]['coupon_code'];
array_push($dataCSV[$j],$i);
array_push($dataCSV[$j],$getcouponobj[$k]['coupon_code']);
array_push($dataCSV[$j],(($getcouponobj[$k]['coupon_type'] == 1) ? 'Multi-use' : 'Once-use'));
array_push($dataCSV[$j],(($getcouponobj[$k]['user_can_use'] == 1) ? 'Multiple times' : 'Once'));
array_push($dataCSV[$j],(($getcouponobj[$k]['used_by'] == 0) ? 'Yes' : 'No'));
array_push($dataCSV[$j],(($getcouponobj[$k]['used_by'] == 0) ? '-' : 'Yes'));
array_push($dataCSV[$j],$userList);
array_push($dataCSV[$j],$getcouponobj[$k]['discount_multiple_cycle']);
array_push($dataCSV[$j],$getcouponobj[$k]['extend_free_trail']);
array_push($dataCSV[$j],(($getcouponobj[$k]['cused_date'] == 0) ? '-' : $getcouponobj[$k]['cused_date']));
array_push($dataCSV[$j],$cont_cat);
array_push($dataCSV[$j],$cont_str);
$j++;
//$dataCsv .= $i . "\t" . $getcouponobj[$k]['coupon_code'] . "\t" . (($getcouponobj[$k]['coupon_type'] == 1) ? 'Multi-use' : 'Once-use') . "\t" . (($getcouponobj[$k]['user_can_use'] == 1) ? 'Multiple times' : 'Once') . "\t" . (($getcouponobj[$k]['used_by'] == 0) ? 'Yes' : 'No') . "\t" . (($getcouponobj[$k]['used_by'] == 0) ? '-' : 'Yes') . "\t" . $userList .$data_addon. "\t" . (($getcouponobj[$k]['cused_date'] == 0) ? '-' : $getcouponobj[$k]['cused_date'])."\t" .$cont_cat ."\t".$cont_str."\n";
$i = $i+1;
}
}
print_r(json_encode($dataCSV));
}
PS: I am getting the values. Any help will be highly appreciated.
Well, first thing i see wrong is the way you declare your array:
$dataCSV[] = Array();
$array[] = Means that you are adding a new value to an existing array. To declare your array you should use
$dataCSV = array();
Also, this code:
array_push($dataCSV[$j],$i);
means that you are adding a new value to your $dataCSV[$j] array, but this is never declared as an array, so first thing would be to do
$dataCSV[$j] = new array();
Your code is really long and complicated, those are only examples of issues i see in there.

CSV stock import for Prestashop 1.6

I would like to create a simple php script that I can run a stock overwrite to my products in Prestashop 1.6. It will need to reference the "product reference" which in my file is "SKU" and then update the "quantity" in Prestashop which is "Available Stock" in my spreadsheet.
At present I am updating this manually every day as I am given a csv file with live stock updates from my supplier. I have seen modules but none of them seem to work for us so hoping theres a simple maybe php script someone has created that would just overwrite the data in the db.
Thanks in advance
Here is an script i use on PS 1.6 for update stock for "product" or "product_attribute" by UPC.
the CSV file in stock/ folder look like :
product ref;stock move;id shop
4443601522;0;1
you can change this scrit to use SKU instead of UPC
<?php
include(dirname(__FILE__) . '/config/config.inc.php');
include(dirname(__FILE__) . '/init.php');
$id_shop = 1;
$id_lang = 1;
$ligne = 0;
$dossier_csv = "/home/mywebsite/public_html/stock/";
echo '<H1>MAJ PS STOCK PAR UPC</h1>';
if (($fic = fopen($dossier_csv . "stock.csv", "a+")) == FALSE) {
echo '<br>Erreur ouverture fichier stock !<br>';
} else {
echo '<h2><u>Traitement des stocks :</u></h2>';
}
while ($tab = fgetcsv($fic, 1024, ';')) {
$champs = count($tab);
$ligne++;
for ($i = 0; $i < $champs; $i++) {
if ($i == 0)
$reference = $tab[$i];
if ($i == 1 && $reference != '' && $ligne != 1) {
$quantity = $tab[$i];
$productId = getIdProductByUPC($reference);
if ($productId != false) {
$idProductAttribute = getIdByUPC($productId, $reference);
$newStock = $quantity;
StockAvailable::setQuantity($productId, $idProductAttribute, $newStock, $id_shop);
echo '<br>(' . $reference . ') : OK qte : <b>' . $quantity . '</b><br>';
} else {
$productId = Product::getIdByUPC($reference);
$product = new Product($productId);
$combination = $product->getAttributeCombinations($id_lang);
if ($productId != false && count($combination) == 0) {
$newStock = $quantity;
StockAvailable::setQuantity($productId, 0, $newStock, $id_shop);
echo '<br>(' . $reference . ') : OK qte : <b>' . $quantity . '</b><br>';
} else {
echo '<br>(' . $reference . '-' . $productId . ') : Erreur enregistrement stock <br>';
}
}
}
}
}
echo '<br><br><br><br>---MAJ TERMINEE---';
function getIdByUPC($id_product, $reference)
{
if (empty($reference)) {
return 0;
}
$query = new DbQuery();
$query->select('pa.id_product_attribute');
$query->from('product_attribute', 'pa');
$query->where('pa.upc LIKE \'%' . pSQL($reference) . '%\'');
$query->where('pa.id_product = ' . (int) $id_product);
return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query);
}
function getIdProductByUPC($reference)
{
if (empty($reference))
return 0;
$query = new DbQuery();
$query->select('pa.id_product');
$query->from('product_attribute', 'pa');
$query->where('pa.upc = \'' . pSQL($reference) . '\'');
return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query);
}
?>
I think, line $productId = Product::getIdByUPC($reference) is wrong.
The correct: $productId = getIdProductByUPC($reference)

PHP Dynamically create SQL query with AND condition

I am trying to write some PHP that fits in to a larger method so that I can dynamically create a MySQL query.
I haven't included the code to the larger method that contains this code because I think the logic of this bit is self-contained.
So, I have a multi-dimensional array:
$where=array(array('username', 'pid', 'name'), array('=','<=', '='), array('alex',2,'james'));
which when I print_r() shows this structure:
Array
(
[0] => Array
(
[0] => username
[1] => pid
[2] => name
)
[1] => Array
(
[0] => =
[1] => <=
[2] => =
)
[2] => Array
(
[0] => alex
[1] => 2
[2] => james
)
)
What I would like to do if use the first value in each second level array to build up the start of the query such as
SELECT * FROM table WHERE username = alex
and then use the other values to build up the query such as (depending upon the number of items in the arrays)
SELECT * FROM table WHERE username = alex AND pid <= 2 AND name = james
Below is the code I have written
if (is_array($where[0])){
$i=0;
$field = $where[0][$i];
$operator = $where[1][$i];
$value= $where[2][$i];
$sql= "SELECT * FROM table WHERE {$field} {$operator} {$value}";
while($i=0 ) {
print $sql;
$i++;
}
while($i>0 AND $i< sizeof($where[0]))
$field = $where[0][$i];
$operator = $where[1][$i];
$value= $where[2][$i];
print $sql .= " AND {$field} {$operator} {$value}";
$i++;
}
However this prints out just one query
SELECT * FROM table WHERE username = alex AND username = alex
I am using PDO so in reality {$value} is replaced by ? and bound elsewhere in the method. I've just shown it here in full.
$sql = 'SELECT * FROM table WHERE';
for($i = 0; $i < count($where[0]); $i++){
$sql .= " {$where[0][$i]} {$where[1][$i]} {$where[2][$i]} AND";
}
$sql = substr($sql, 0, strlen($sql) - 4);
I personally would however save your statements like this:
$array = array('username = alex', 'pid <= 2');
If you needed the different parts of the statements, you could just do
explode(' ', $array[num]);
$companyFilter = "";
$auth = getFormulaAuth();
$companyFilter = "AND company_id = {$auth['company_id']} ";
$arguments = func_get_args();
if ($WhereFilterName_xxx) {
} else {
$db = new Database();
$this_get_table_form = getFormulaFormDetails($FormName);
$tbfields_data = Formula::getTBFields($this_get_table_form["id"], $db);
$q_string = "SELECT * FROM `" . $this_get_table_form["form_table_name"] . "`";
$valid_param_check = count($arguments) - 2;
$cache_key = "*";
if ($valid_param_check >= 1 && $valid_param_check % 3 == 0) {
$found_indexes = array();
$q_string_where = " WHERE ";
$search = " (NOT EXISTS(SELECT * FROM tbtrash_bin WHERE record_id = " . $this_get_table_form["form_table_name"] . ".id
AND form_id = " . $this_get_table_form["id"] . "
AND table_name='" . $this_get_table_form["form_table_name"] . "')) AND ";
$q_string_where .= $search;
for ($i = 2; $i < count($arguments); $i+=3) {
$field_key = $arguments[$i];
$operator = $arguments[$i + 1];
$value = $arguments[$i + 2];
if ($i > 2) {
$q_string_where .= " AND ";
}
$q_string_where .= " `" . $field_key . "` " . $operator;
if (($tbfields_data["" . $field_key]["field_input_type"] == "Number" || $tbfields_data["" . $field_key]["field_input_type"] == "Currency") || strtoupper($operator) == "IN") {
$q_string_where .= " " . $value . " ";
} else {
$q_string_where .= " '" . $value . "' ";
}
$q_string_orderby .= $q_string_where;
$sort_by = isset($_GET['s']) ? $_GET['s'] : false;
switch ($sort_by) {
case $tbfields_data;
break;
default:
$sort_by = 'DateCreated';
}
$q_string_orderby .= ' ORDER BY '.$sort_by.' ';
$direction = isset($_GET['d']) ? $_GET['d'] : false;
if ($direction != 'ASC' && $direction != 'DESC')
$direction = 'DESC';
$q_string_orderby .= $direction;
$res = $db->query($q_string_orderby);
$results = array();
if ($res) {
while ($r = mysql_fetch_assoc($res)) {
$results[] = $r;
}
}
$cache_key.="::" . $field_key . "::" . $operator . "::" . $value . "::" . $q_string_orderby;
}
$q_string .= $q_string_orderby;
}
$this_record = Formula::getLookupValue("formula_lookup_where_array", $this_get_table_form, $q_string, $cache_key);
array_push($GLOBALS['formula_executed_data_collector']['collected_form_id'], array(
"form_id" => $this_get_table_form['id'],
"where" => $q_string_where,
"function_name" => "Total",
"whole_query" => $q_string
));
$rslt = array_values(array_map(function($a) use($ReturnField) {
if (gettype($ReturnField) == "array") {
$array_collector = array();
foreach ($ReturnField as $key => $value) {
$array_collector[$value] = $a[$value];
}
return $array_collector;
} else if ($ReturnField == "*") {
return $a;
} else {
return $a[$ReturnField];
}
}, $this_record));
return $rslt;
}
}

Change 'sort by' in plugin

I'm looking to edit the Gigpress code so that when events are not 'grouped by artist', they are still ordered by event date rather than artist name.
The Gigpress sidebar does this no problem so I figure that the main plugin should be able to be configured to do this somehow. Just can't get my head around this.
The plugin code is
<?php
// These two functions are for backwards-compatibility the shortcodes used in GigPress < 2.0
function gigpress_upcoming($filter = null, $content = null) {
if(!is_array($filter)) $filter = array();
$filter['scope'] = 'upcoming';
return gigpress_shows($filter, $content);
}
function gigpress_archive($filter = null, $content = null) {
if(!is_array($filter)) $filter = array();
$filter['scope'] = 'past';
return gigpress_shows($filter, $content);
}
function gigpress_shows($filter = null, $content = null) {
global $wpdb, $gpo;
$further_where = $limit = '';
extract(shortcode_atts(array(
'tour' => FALSE,
'artist' => FALSE,
'venue' => FALSE,
'limit' => FALSE,
'scope' => 'upcoming',
'sort' => FALSE,
'group_artists' => 'yes',
'artist_order' => 'custom',
'show_menu' => FALSE,
'show_menu_count' => FALSE,
'menu_sort' => FALSE,
'menu_title' => FALSE,
'year' => FALSE,
'month' => FALSE
), $filter)
);
$total_artists = $wpdb->get_var("SELECT count(*) from " . GIGPRESS_ARTISTS);
// Date conditionals and sorting based on scope
switch($scope) {
case 'upcoming':
$date_condition = "show_expire >= '" . GIGPRESS_NOW . "'";
if(empty($sort)) $sort = 'asc';
break;
case 'past':
$date_condition = "show_expire < '" . GIGPRESS_NOW . "'";
if(empty($sort)) $sort = 'desc';
break;
case 'today':
$date_condition = "show_expire >= '".GIGPRESS_NOW."' AND show_date <= '".GIGPRESS_NOW."'";
if(empty($sort)) $sort = 'asc';
break;
case 'all':
$date_condition = "show_expire != ''";
if(empty($sort)) $sort = 'desc';
break;
}
// Artist, tour and venue filtering
if($artist) $further_where .= ' AND show_artist_id = ' . $wpdb->prepare('%d', $artist);
if($tour) $further_where .= ' AND show_tour_id = ' . $wpdb->prepare('%d', $tour);
if($venue) $further_where .= ' AND show_venue_id = ' . $wpdb->prepare('%d', $venue);
// Date filtering
// Query vars take precedence over function vars
if(isset($_REQUEST['gpy'])) {
$year = $_REQUEST['gpy'];
if(isset($_REQUEST['gpm'])) {
$month = $_REQUEST['gpm'];
} else {
unset($month);
}
$no_limit = TRUE;
}
// Validate year and date parameters
if($year || $month) {
if($year) {
if(is_numeric($year) && strlen($year) == 4) {
$year = round($year);
} else {
$year = date('Y', current_time('timestamp'));
}
} else {
// We've only specified a month, so we'll assume the year is current
$year = date('Y', current_time('timestamp'));
}
if($month) {
if($month == 'current') {
$month = date('m', current_time('timestamp'));
} elseif(round($month) == 0) {
// Probably using a month name
$month = date('m', strtotime($month));
} elseif(round($month) < 10) {
// Make sure the month is padded through 09
$month = str_pad($month, 2, 0, STR_PAD_LEFT);
} elseif(round($month) < 13) {
// Between 10 and 12 we're OK
$month = $month;
} else {
// Bogus month value (not a string and > 12)
// Sorry, bailing out. Your "month" will be ignored. Dink.
$month = FALSE;
}
$start_month = $end_month = $month;
}
if(!$month) {
$start_month = '01';
$end_month = '12';
}
$start = $year.'-'.$start_month.'-01';
$end = $year.'-'.$end_month.'-31';
$further_where .= ' AND show_date BETWEEN '.$wpdb->prepare('%s', $start).' AND '.$wpdb->prepare('%s', $end);
}
$limit = ($limit && !$no_limit) ? ' LIMIT ' . $wpdb->prepare('%d', $limit) : '';
$artist_order = ($artist_order == 'custom') ? "artist_order ASC," : '';
// With the new 'all' scope, we should probably have a third message option, but I'm too lazy
// Really, there should just be one generic 'no shows' message. Oh well.
$no_results_message = ($scope == 'upcoming') ? wptexturize($gpo['noupcoming']) : wptexturize($gpo['nopast']);
ob_start();
// Are we showing our menu?
if($show_menu) {
$menu_options = array();
$menu_options['scope'] = $scope;
$menu_options['type'] = $show_menu;
if($menu_title) $menu_options['title'] = $menu_title;
if($show_menu_count) $menu_options['show_count'] = $show_menu_count;
if($menu_sort) $menu_options['sort'] = $menu_sort;
if($artist) $menu_options['artist'] = $artist;
if($tour) $menu_options['tour'] = $tour;
if($venue) $menu_options['venue'] = $venue;
include gigpress_template('before-menu');
echo gigpress_menu($menu_options);
include gigpress_template('after-menu');
}
// If we're grouping by artist, we'll unfortunately have to first get all artists
// Then make a query for each one. Looking for a better way to do this.
if($group_artists == 'yes' && !$artist && $total_artists > 1) {
$artists = $wpdb->get_results("SELECT * FROM " . GIGPRESS_ARTISTS . " ORDER BY " . $artist_order . "artist_name ASC");
foreach($artists as $artist_group) {
$shows = $wpdb->get_results("SELECT * FROM " . GIGPRESS_ARTISTS . " AS a, " . GIGPRESS_VENUES . " as v, " . GIGPRESS_SHOWS ." AS s LEFT JOIN " . GIGPRESS_TOURS . " AS t ON s.show_tour_id = t.tour_id WHERE " . $date_condition . " AND show_status != 'deleted' AND s.show_artist_id = " . $artist_group->artist_id . " AND s.show_artist_id = a.artist_id AND s.show_venue_id = v.venue_id " . $further_where . " ORDER BY s.show_date " . $sort . ",s.show_expire " . $sort . ",s.show_time ". $sort . $limit);
if($shows) {
// For each artist group
$some_results = TRUE;
$current_tour = '';
$i = 0;
$showdata = array(
'artist' => wptexturize($artist_group->artist_name),
'artist_id' => $artist_group->artist_id
);
include gigpress_template('shows-artist-heading');
include gigpress_template('shows-list-start');
foreach($shows as $show) {
// For each individual show
$showdata = gigpress_prepare($show, 'public');
if($showdata['tour'] && $showdata['tour'] != $current_tour && !$tour) {
$current_tour = $showdata['tour'];
include gigpress_template('shows-tour-heading');
}
$class = $showdata['status'];
++ $i; $class .= ($i % 2) ? '' : ' gigpress-alt';
if(!$showdata['tour'] && $current_tour) {
$current_tour = '';
$class .= ' divider';
}
$class .= ($showdata['tour'] && !$tour) ? ' gigpress-tour' : '';
include gigpress_template('shows-list');
}
include gigpress_template('shows-list-end');
}
}
if($some_results) {
// After all artist groups
include gigpress_template('shows-list-footer');
} else {
// No shows from any artist
include gigpress_template('shows-list-empty');
}
} else {
// Not grouping by artists
$shows = $wpdb->get_results("
SELECT * FROM " . GIGPRESS_ARTISTS . " AS a, " . GIGPRESS_VENUES . " as v, " . GIGPRESS_SHOWS ." AS s LEFT JOIN " . GIGPRESS_TOURS . " AS t ON s.show_tour_id = t.tour_id WHERE " . $date_condition . " AND show_status != 'deleted' AND s.show_artist_id = a.artist_id AND s.show_venue_id = v.venue_id " . $further_where . " ORDER BY s.show_date " . $sort . ",s.show_expire " . $sort . ",s.show_time " . $sort . $limit);
if($shows) {
$current_tour = '';
$i = 0;
include gigpress_template('shows-list-start');
foreach($shows as $show) {
// For each individual show
$showdata = gigpress_prepare($show, 'public');
if($showdata['tour'] && $showdata['tour'] != $current_tour && !$tour) {
$current_tour = $showdata['tour'];
include gigpress_template('shows-tour-heading');
}
$class = $showdata['status'];
++ $i; $class .= ($i % 2) ? '' : ' gigpress-alt';
if(!$showdata['tour'] && $current_tour) {
$current_tour = '';
$class .= ' divider';
}
$class .= ($showdata['tour'] && !$tour) ? ' gigpress-tour' : '';
include gigpress_template('shows-list');
}
include gigpress_template('shows-list-end');
include gigpress_template('shows-list-footer');
} else {
// No shows to display
include gigpress_template('shows-list-empty');
}
}
echo('<!-- Generated by GigPress ' . GIGPRESS_VERSION . ' -->
');
return ob_get_clean();
}
function gigpress_menu($options = null) {
global $wpdb, $wp_locale, $gpo;
extract(shortcode_atts(array(
'type' => 'monthly',
'base' => get_permalink(),
'scope' => 'upcoming',
'title' => FALSE,
'id' => 'gigpress_menu',
'show_count' => FALSE,
'artist' => FALSE,
'tour' => FALSE,
'venue' => FALSE,
'sort' => 'desc'
), $options));
$base .= (strpos($base, '?') === FALSE) ? '?' : '&';
// Date conditionals based on scope
switch($scope) {
case 'upcoming':
$date_condition = ">= '" . GIGPRESS_NOW . "'";
break;
case 'past':
$date_condition = "< '" . GIGPRESS_NOW . "'";
break;
case 'all':
$date_condition = "!= ''";
}
$further_where = '';
// Artist, tour and venue filtering
if($artist) $further_where .= ' AND show_artist_id = ' . $wpdb->prepare('%d', $artist);
if($tour) $further_where .= ' AND show_tour_id = ' . $wpdb->prepare('%d', $tour);
if($venue) $further_where .= ' AND show_venue_id = ' . $wpdb->prepare('%d', $venue);
// Variable operajigamarations based on monthly vs. yearly
switch($type) {
case 'monthly':
$sql_select_extra = 'MONTH(show_date) AS month, ';
$sql_group_extra = ', MONTH(show_date)';
$title = ($title) ? wptexturize(strip_tags($title)) : __('Select Month');
$current = (isset($_REQUEST['gpy']) && isset($_REQUEST['gpm'])) ? $_REQUEST['gpy'].$_REQUEST['gpm'] : '';
break;
case 'yearly':
$sql_select_extra = $sql_group_extra = '';
$title = ($title) ? wptexturize(strip_tags($title)) : __('Select Year');
$current = (isset($_REQUEST['gpy'])) ? $_REQUEST['gpy'] : '';
}
// Build query
$dates = $wpdb->get_results("
SELECT YEAR(show_date) AS year, " . $sql_select_extra . " count(show_id) as shows
FROM ".GIGPRESS_SHOWS."
WHERE show_status != 'deleted'
AND show_date " . $date_condition . $further_where . "
GROUP BY YEAR(show_date)" . $sql_group_extra . "
ORDER BY show_date " . $sort);
ob_start();
if($dates) : ?>
<select name="gigpress_menu" class="gigpress_menu" id="<?php echo $id; ?>">
<option value="<?php echo $base; ?>"><?php echo $title; ?></option>
<?php foreach($dates as $date) : ?>
<?php $this_date = ($type == 'monthly') ? $date->year.$date->month : $date->year; ?>
<option value="<?php echo $base.'gpy='.$date->year; if($type == 'monthly') echo '&gpm='.$date->month; ?>"<?php if($this_date == $current) : ?> selected="selected"<?php endif; ?>>
<?php if($type == 'monthly') echo $wp_locale->get_month($date->month).' '; echo $date->year; ?>
<?php if($show_count && $show_count == 'yes') : ?>(<?php echo $date->shows; ?>)<?php endif; ?>
</option>
<?php endforeach; ?>
</select>
<?php endif;
return ob_get_clean();
}
The line under // Not grouping by artists
Change from:
$shows = $wpdb->get_results("SELECT * FROM " . GIGPRESS_ARTISTS . " AS a, " . GIGPRESS_VENUES . " as v, " . GIGPRESS_SHOWS ." AS s LEFT JOIN " . GIGPRESS_TOURS . " AS t ON s.show_tour_id = t.tour_id WHERE " . $date_condition . " AND show_status != 'deleted' AND s.show_artist_id = a.artist_id AND s.show_venue_id = v.venue_id " . $further_where . " ORDER BY s.show_date " . $sort . ",s.show_expire " . $sort . ",s.show_time " . $sort . $limit);
To:
$shows = $wpdb->get_results("SELECT * FROM " . GIGPRESS_ARTISTS . " AS a, " . GIGPRESS_VENUES . " as v, " . GIGPRESS_SHOWS ." AS s LEFT JOIN " . GIGPRESS_TOURS . " AS t ON s.show_tour_id = t.tour_id WHERE " . $date_condition . " AND show_status != 'deleted' AND s.show_artist_id = a.artist_id AND s.show_venue_id = v.venue_id " . $further_where . " ORDER BY a.artist_name ASC,s.show_date " . $sort . ",s.show_expire " . $sort . ",s.show_time " . $sort . $limit);

Categories