init model from controller joomla 3.1 - php

I try to call a model from one of my Joomla controller but that doesn't seem to work.
class TieraerzteControllerDatatable extends JControllerLegacy
{
/**
* display task
*
* #return void
*/
function display($cachable = false)
{
// set default view if not set
$input = JFactory::getApplication()->input;
$model = $this->getModel('datatable');
$model->getTableData('grumpi_tieraerzte', 'id', array('id','name','strasse','telefon','fax'));
die();
}
}
In my model I placed a var_dump but it is not accessed. How can I debug my model call in controller?
I try to access the models return with the following url /administrator/index.php?option=com_tieraerzte&task=datatable.display&{arguments for the model}
trying to debug my codes piece by piece seems like the model is accessed and this code is causing the problem
// Paging
$sLimit = "";
if (isset(JRequest::getVar('iDisplayStart')) && JRequest::getVar('iDisplayLength') != '-1')
{
$sLimit = "LIMIT " . intval(JRequest::getVar('iDisplayStart')) . ", " . intval(JRequest::getVar('iDisplayLength'));
}
The whole method:
public function getTableData($table, $index_column, $columns)
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
// Paging
$sLimit = "";
if (isset(JRequest::getVar('iDisplayStart')) && JRequest::getVar('iDisplayLength') != '-1')
{
$sLimit = "LIMIT " . intval(JRequest::getVar('iDisplayStart')) . ", " . intval(JRequest::getVar('iDisplayLength'));
}
// Ordering
$sOrder = "";
if (isset(JRequest::getVar('iSortCol_0')))
{
$sOrder = "ORDER BY ";
for ($i = 0; $i < intval(JRequest::getVar('iSortingCols')); $i++)
{
if (JRequest::getVar('bSortable_' . intval(JRequest::getVar('iSortCol_' . $i))) == "true")
{
$sortDir = (strcasecmp(JRequest::getVar('sSortDir_' . $i), 'ASC') == 0) ? 'ASC' : 'DESC';
$sOrder .= "`" . $columns[intval(JRequest::getVar('iSortCol_' . $i))] . "` " . $sortDir . ", ";
}
}
$sOrder = substr_replace($sOrder, "", -1);
if ($sOrder == "ORDER BY") {
$sOrder = "";
}
}
/*
* Filtering
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here, but concerned about efficiency
* on very large tables, and MySQL's regex functionality is very limited
*/
$sWhere = "";
if (isset(JRequest::getVar('sSearch')) && JRequest::getVar('sSearch') != "")
{
$like = '%' . JRequest::getVar('sSearch') . '%';
$sWhere = "WHERE (";
for ($i = 0; $i < count($columns); $i++)
{
if (isset(JRequest::getVar('bSearchable_' . $i)) && JRequest::getVar('bSearchable_' . $i) == "true")
{
$sWhere .= "`" . $columns[$i] . "` LIKE '" . $like . "' OR ";
}
}
$sWhere = substr_replace($sWhere, "", -3);
$sWhere .= ')';
}
// Individual column filtering
for ($i = 0; $i < count($columns); $i++)
{
if (isset(JRequest::getVar('bSearchable_' . $i)) && JRequest::getVar('bSearchable_' . $i) == "true" && JRequest::getVar('sSearch_' . $i) != '')
{
if ($sWhere == "")
{
$sWhere = "WHERE ";
} else {
$sWhere .= " AND ";
}
$sWhere .= "`" . $columns[$i] . "` LIKE ? " . $i . " ";
}
}
// SQL queries get data to display
$sQuery = "SELECT SQL_CALC_FOUND_ROWS `" . str_replace(" , ", " ", implode("`, `", $columns)) . "` FROM `" . $table . "` " . $sWhere . " " . $sOrder . " " . $sLimit;
$statement = $this->_db->prepare($sQuery);
// Bind parameters
if (isset(JRequest::getVar('sSearch')) && JRequest::getVar('sSearch') != "")
{
$statement->bind_param('s', $like);
}
for ($i = 0; $i < count($columns); $i++)
{
if (isset(JRequest::getVar('bSearchable_' . $i)) && JRequest::getVar('bSearchable_' . $i) == "true" && JRequest::getVar('sSearch_' . $i) != '')
{
$statement->bind_param('s' . $i, '%' . $_GET['sSearch_' . $i] . '%');
}
}
$db->setQuery($sQuery);
$res = $db->loadObjectList();
$rResult = array();
foreach ($res as $row)
{
$rResult[] = $row;
}
$iFilteredTotal = current($db->setQuery('SELECT FOUND_ROWS()')->loadResultArray());
// Get total number of rows in table
$sQuery = "SELECT COUNT(`" . $index_column . "`) FROM `" . $table . "`";
$iTotal = current($db->setQuery($sQuery));
// Output
$output = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $iTotal,
"iTotalDisplayRecords" => $iFilteredTotal,
"aaData" => array()
);
// Return array of values
foreach ($rResult as $aRow)
{
$row = array();
array_push($row, '<input type="checkbox" id="someCheckbox" name="someCheckbox" />');
for ($i = 0; $i < count($columns); $i++)
{
//var_dump($aRow->$columns[$i]);
if ($columns[$i] != '')
{
$row[] = $aRow->$columns[$i];
}
}
array_push($row, '
<div class="btn-group" id="status">
<input type="button" class="btn b1" value="On">
<input type="button" class="btn b0 btn-danger" value="Off">
</div>
');
array_push($row, '
<div class="clearfix">
<div class="label label-important" style="padding:6px 9px; margin-right:5px"><span class="icon-trash"></span></div>
<div class="label label-success" style="padding:6px 9px"><span class="icon-cog"></span></div>
</div>
');
$output['aaData'][] = $row;
}
echo json_encode($output);
}

Make sure $model inside the controller is not null. If it's not null, than the problem is somewhere in the model's method called.
if $model is null, somehow the model you are calling is not loaded. Temporary try just to include the file with require_once JPATH_COMPONENT . '/models/datatable.php'

Related

Returning JSON from a PHP function

I want to transform this PHP function.. that should return JSON data.
<?php
$query = 'SELECT * FROM `' . mix_player::table() . '` a';
if (isset($_GET['cat']) || isset($_GET['order']))
if (isset($_GET['cat'])) {
$query .= ' INNER JOIN `' . mix_player::table_cat_rel() . '` b '
. "ON (a.`id` = b.`idtrack`) WHERE `idcat` = '" . $wpdb->escape($_GET['cat']) . "'";
$random = $wpdb->get_var('SELECT `random`, `order` FROM `' . mix_player::table_categories() . "` WHERE `id` = '"
. $wpdb->escape($_GET['cat']) . "'");
if (!$random)
$order = $wpdb->get_var(NULL, 1);
}
if (isset($_GET['order']))
$order = $_GET['order'];
if ($order != '') {
if (isset($_GET['cat']))
$query .= ' AND ';
else
$query .= ' WHERE ';
$tracks = mix_player::order_list($query, $order);
}
} else {
$random = '0';
}
$query .= ' ORDER BY `id` ASC';
if (isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A))) {
// option "shuffle = true" not always working into mix. Do it our own way...
if ($random == 1) { // shuffle tracks?
list($usec, $sec) = explode(' ', microtime());
mt_srand((float) $sec + ((float) $usec * 100000));
$nrows = count($tracks);
for ($i = 0; $i < $nrows; $i++) {
$j = mt_rand(0, $nrows - 1); // pick j at random
$row = $tracks[$i]; // swap i, j
$tracks[$i] = $tracks[$j];
$tracks[$j] = $row;
}
}
foreach ($tracks as $row) {
$artist = (mix_player::entities($row['artist']));
echo ($artist);
$title = (mix_player::entities($row['title']));
echo ($title);
$url =(xspf_player::entities($row['url']));
echo ($url);
}
}
?>
to display like this json file :
{"title":"title", "artist":"artist","media":"url media.mp3","color":"#56B0E8" },
Can you help me?
Thanks in advance.
You can simply create an array and populate it with your desired values, then return it as JSON:
function tracks2json( $tracks )
{
$retval = array();
foreach( $tracks as $row )
{
$array = array();
$array['artist'] = mix_player::entities($row['artist']);
$array['title'] = mix_player::entities($row['title']);
$array['media'] = 'url '.xspf_player::entities($row['url']);
$array['color'] = '#56B0E8';
$retval[] = $array;
}
return json_encode( $retval );
}
if( isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A)) )
{
// Your MySQL routine here
$json = tracks2json( $tracks );
}
echo json_encode(array("title"=>$title,"artist"=>$artist,"url"=>$url));

Creating a php class for database insert functions

I am trying to create a class to save time on cleaning up my variables before sending them to the database to prevent sql injections. The basic systems is working now but i cant seem to get a where/or statement implemented. Does anyone know how to add this?
<?php
class Database {
private $db = '';
private $database = '';
function __construct($settings) {
$this->db = new mysqli('127.0.0.1', $settings['mysql_user']['username'], $settings['mysql_user']['password']);
$this->database = $settings['mysql_user']['database'];
print_r('Database Loaded!<br/>');
}
public function query($method, $database, $rows, $params, $where = array(), $or = array()) {
$count = 0;
$amount = count($rows);
$final_rows = '';
$final_data = '';
$bind_names = array();
$bind_names[0] = '';
$param_types = array(
"int" => "i",
"string" => "s",
"double" => "d",
"blob" => "b"
);
switch($method) {
case 'INSERT':
foreach ($rows as $row) {
$count = $count + 1;
$final_rows .= '`' . $row . '`' . ($count != $amount ? ', ' : '');
$final_data .= '?' . ($count != $amount ? ', ' : '');
}
$stmt = $this->db->prepare('INSERT INTO `' . $this->database . '`.`' . $database . '` (' . $final_rows . ') VALUES (' . $final_data . ')');
for ($i = 0; $i < count($params); $i++)
{
$bind_name = 'bind'.$i;
$$bind_name = $params[$i][1];
$bind_names[0] .= $param_types[$params[$i][0]];
$bind_names[] = &$$bind_name;
}
call_user_func_array( array ($stmt, 'bind_param'), $bind_names);
return $stmt->execute();
break;
case 'UPDATE':
foreach ($rows as $row) {
$count = $count + 1;
$final_rows .= '`' . $row . '`' . ($count != $amount ? ', ' : '');
$final_data .= '?' . ($count != $amount ? ', ' : '');
}
$stmt = $this->db->prepare('UPDATE `' . $this->database . '`.`' . $database . '` SET ' . $final_rows . '');
for ($i = 0; $i < count($params); $i++)
{
$bind_name = 'bind'.$i;
$$bind_name = $params[$i][1];
$bind_names[0] .= $param_types[$params[$i][0]];
$bind_names[] = &$$bind_name;
}
call_user_func_array( array ($stmt, 'bind_param'), $bind_names);
return $stmt->execute();
break;
case 'REPLACE':
foreach ($rows as $row) {
$count = $count + 1;
$final_rows .= '`' . $row . '`' . ($count != $amount ? ', ' : '');
$final_data .= '?' . ($count != $amount ? ', ' : '');
}
$stmt = $this->db->prepare('REPLACE INTO `' . $this->database . '`.`' . $database . '` (' . $final_rows . ') VALUES (' . $final_data . ')');
for ($i = 0; $i < count($params); $i++)
{
$bind_name = 'bind'.$i;
$$bind_name = $params[$i][1];
$bind_names[0] .= $param_types[$params[$i][0]];
$bind_names[] = &$$bind_name;
}
call_user_func_array( array ($stmt, 'bind_param'), $bind_names);
return $stmt->execute();
break;
}
}
}
?>
Going to make a few assumptions, but first I'll recommend you use an ORM before whipping up your own solution. Here's a good list of PHP libraries (I've linked to the database sections, which includes some very well done stand-alone ORMs https://github.com/ziadoz/awesome-php#database)
That being said I'm going to assume the $where and $or arrays are both for the WHERE construct and the items in $where are combined via AND and the $or is combined via OR.
Because you didn't describe what kind of output you were looking for I'm also assuming your $where and $or are key/value pairs which translates to "key=value AND key=value AND (key=value OR key=value)".
DISCLAIMER: This example is kind of hacky, but is the shortest/simplest way to get the example across.
$whereQuery = '';
foreach ($where as $key => $value) {
$whereQuery .= "$key = $value AND";
}
if ($or !== array()) {
$whereQuery .= '(';
foreach ($or as $key => $value) {
$whereQuery .= "$key = $value OR";
}
}
if ($whereQuery !== '') {
if (($temp = strlen($whereQuery) - strlen('AND')) >= 0 && strpos($whereQuery, 'AND', $temp) !== false) {
$whereQuery = substr($whereQuery, -4);
} else {
$whereQuery = substr($whereQuery, -3) . ')';
}
$whereQuery = "WHERE $whereQuery";
}
You can then stick the $whereQuery at the end of an UPDATE or SELECT. Even if $where and $or are empty it'll still work.
You could move the loops into functions and make it recursive if the $value was another array so you could create more complex WHERE statements.

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;
}
}

How To Change Numbers Based On Results

I have a follow up question on something I got help with here the other day (No Table Three Column Category Layout).
The script is as follows:
$res = mysql_query($query);
$system->check_mysql($res, $query, __LINE__, __FILE__);
$parent_node = mysql_fetch_assoc($res);
$id = (isset($parent_node['cat_id'])) ? $parent_node['cat_id'] : $id;
$catalist = '';
if ($parent_node['left_id'] != 1)
{
$children = $catscontrol->get_children_list($parent_node['left_id'], $parent_node['right_id']);
$childarray = array($id);
foreach ($children as $k => $v)
{
$childarray[] = $v['cat_id'];
}
$catalist = '(';
$catalist .= implode(',', $childarray);
$catalist .= ')';
$all_items = false;
}
$NOW = time();
/*
specified category number
look into table - and if we don't have such category - redirect to full list
*/
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE cat_id = " . $id;
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$category = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)
{
// redirect to global categories list
header ('location: browse.php?id=0');
exit;
}
else
{
// Retrieve the translated category name
$par_id = $category['parent_id'];
$TPL_categories_string = '';
$crumbs = $catscontrol->get_bread_crumbs($category['left_id'], $category['right_id']);
for ($i = 0; $i < count($crumbs); $i++)
{
if ($crumbs[$i]['cat_id'] > 0)
{
if ($i > 0)
{
$TPL_categories_string .= ' > ';
}
$TPL_categories_string .= '' . $category_names[$crumbs[$i]['cat_id']] . '';
}
}
// get list of subcategories of this category
$subcat_count = 0;
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . $id . " ORDER BY cat_name";
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$need_to_continue = 1;
$cycle = 1;
$column = 1;
$TPL_main_value = '';
while ($row = mysql_fetch_array($result))
{
++$subcat_count;
if ($cycle == 1)
{
$TPL_main_value .= '<div class="col'.$column.'"><ul>' . "\n";
}
$sub_counter = $row['sub_counter'];
$cat_counter = $row['counter'];
if ($sub_counter != 0)
{
$count_string = ' (' . $sub_counter . ')';
}
else
{
if ($cat_counter != 0)
{
$count_string = ' (' . $cat_counter . ')';
}
else
{
$count_string = '';
}
}
if ($row['cat_colour'] != '')
{
$BG = 'bgcolor=' . $row['cat_colour'];
}
else
{
$BG = '';
}
// Retrieve the translated category name
$row['cat_name'] = $category_names[$row['cat_id']];
$catimage = (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '';
$TPL_main_value .= "\t" . '<li>' . $catimage . '' . $row['cat_name'] . $count_string . '</li>' . "\n";
++$cycle;
if ($cycle == 7) // <---- here
{
$cycle = 1;
$TPL_main_value .= '</ul></div>' . "\n";
++$column;
}
}
if ($cycle >= 2 && $cycle <= 6) // <---- here minus 1
{
while ($cycle < 7) // <---- and here
{
$TPL_main_value .= ' <p> </p>' . "\n";
++$cycle;
}
$TPL_main_value .= '</ul></div>'.$number.'
' . "\n";
}
I was needing to divide the resulting links into three columns to fit my html layout.
We accomplished this by changing the numbers in the code marked with "// <---- here".
Because the amount of links returned could be different each time, I am trying to figure out how to change those numbers on the fly. I tried using
$number_a = mysql_num_rows($result);
$number_b = $number_a / 3;
$number_b = ceil($number_b);
$number_c = $number_b - 1;
and then replacing the numbers with $number_b or $number_c but that doesn't work. Any ideas?
As mentioned before, you can use the mod (%) function to do that.
Basically what it does is to get the remainder after division. So, if you say 11 % 3, you will get 2 since that is the remainder after division. You can then make use of this to check when a number is divisible by 3 (the remainder will be zero), and insert an end </div> in your code.
Here is a simplified example on how to use it to insert a newline after every 3 columns:
$cycle = 1;
$arr = range (1, 20);
$len = sizeof ($arr);
for ( ; $cycle <= $len; $cycle++)
{
echo "{$arr[$cycle - 1]} ";
if ($cycle % 3 == 0)
{
echo "\n";
}
}
echo "\n\n";

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