add function in php file get Call to undefined function exception - php

I'm new on php, I'm triyng to backup a post before deleting on a mybb forum.
I edited inc/class_moderation.php adding the following function backup_post, but when the call to the function backup_post
throws
Call to undefined function backup_post() in
/membri/myforum/inc/class_moderation.php on line 485
function delete_post($pid)
{
global $mybb, $db, $cache, $plugins;
$pid = $plugins->run_hooks("class_moderation_delete_post_start", $pid);
// Get pid, uid, fid, tid, visibility, forum post count status of post
$pid = intval($pid);
$query = $db->query("
SELECT p.pid, p.uid, p.fid, p.tid, p.visible, f.usepostcounts, t.visible as threadvisible, message, p.username as p_username, p.subject, p.dateline
FROM ".TABLE_PREFIX."posts p
LEFT JOIN ".TABLE_PREFIX."threads t ON (t.tid=p.tid)
LEFT JOIN ".TABLE_PREFIX."forums f ON (f.fid=p.fid)
WHERE p.pid='$pid'
");
$post = $db->fetch_array($query);
// If post counts enabled in this forum and it hasn't already been unapproved, remove 1
if($post['usepostcounts'] != 0 && $post['visible'] != 0 && $post['threadvisible'] != 0)
{
$db->update_query("users", array("postnum" => "postnum-1"), "uid='{$post['uid']}'", 1, true);
}
if(!function_exists("remove_attachments"))
{
require MYBB_ROOT."inc/functions_upload.php";
}
// Remove attachments
remove_attachments($pid);
//Backup the post
backup_post($pid);
// Delete the post
$db->delete_query("posts", "pid='$pid'");
// Remove any reports attached to this post
$db->delete_query("reportedposts", "pid='$pid'");
$num_unapproved_posts = $num_approved_posts = 0;
// Update unapproved post count
if($post['visible'] == 0 || $post['threadvisible'] == 0)
{
++$num_unapproved_posts;
}
else
{
++$num_approved_posts;
}
$plugins->run_hooks("class_moderation_delete_post", $post['pid']);
// Update stats
$update_array = array(
"replies" => "-{$num_approved_posts}",
"unapprovedposts" => "-{$num_unapproved_posts}"
);
update_thread_counters($post['tid'], $update_array);
// Update stats
$update_array = array(
"posts" => "-{$num_approved_posts}",
"unapprovedposts" => "-{$num_unapproved_posts}"
);
update_forum_counters($post['fid'], $update_array);
return true;
}
function backup_post($pid)
{
global $mybb, $db, $cache, $plugins;
// Get pid, uid, fid, tid, visibility, forum post count status of post
$pid = intval($pid);
$query = $db->query("
SELECT p.pid, p.uid, p.fid, p.tid, p.visible, f.usepostcounts, t.visible as threadvisible, message, p.username as p_username, p.subject, p.dateline
FROM ".TABLE_PREFIX."posts p
LEFT JOIN ".TABLE_PREFIX."threads t ON (t.tid=p.tid)
LEFT JOIN ".TABLE_PREFIX."forums f ON (f.fid=p.fid)
WHERE p.pid='$pid'
");
$post = $db->fetch_array($query);
$deletedpost = array(
"username_delete" => $mybb->user['username'],
"username" => $post['p_username'],
"subject" => $post['subject'],
"message" => $post['message'],
"dateline" => TIME_NOW,
"post_dateline" => $post['dateline'],
);
$db->insert_query("posts_deleted", $deletedpost);
//14-06-20016
//ob_start();
//var_dump($mybb);
//$data = ob_get_clean();
//$fp = fopen(MYBB_ROOT."myText.txt","wb");
//fwrite($fp,$data);
//fwrite($fp, "cancellato da ".$mybb->user['username']);
//fwrite($fp, "autore ".$post['p_username']);
//fwrite($fp, "messaggio ".$post['message']);
/*
foreach ($post as $key => $value) {
fwrite($fp, $key );
}
*/
//fclose($fp);
return true;
}

You are adding functions to a class (then we tend to call them "methods" instead of "functions", but that doesn't really matter).
When you want to call a class method, you need to call it like $class_instance->method_name() instead of the usual method_name(), which works for "plain" functions.
When you are calling a method from another method in the same class, you use $this to get the same class instance.
So if you change this line:
backup_post($pid);
to:
$this->backup_post($pid);
it should work.

Related

How to debug custom plugin in Moodle

I've been asked to create a custom plugin displays course overview (course id, course name, enrolled and completed) through API. There is a report_completionoverview plugin that I can refer to and basically wanna retrieve exactly the same list via Moodle API in JSON format.
I'm trying to create a local plugin based on moodle documentation (https://docs.moodle.org/dev/Adding_a_web_service_to_a_plugin) and other default plugins, but having difficulty to debug.
* modified folder name to match plugin name *
I've Created
local/get_completion_overview/db/service.php
local/get_completion_overview/lang/en/local_get_completion_overview.php
local/get_completion_overview/externallib.php
local/get_completion_overview/version.php
Successfully installed the plugin without error in Moodle, but the plugin is not listed in the function.
I honestly think that my code is not right (and it is messy since I've copied from different sources), but don't know how to debug it.
Can anyone please let me know if you know how?
I also attach local/completionview/externallib.php (I'm sure this is causing the issue I believe).
Any help or idea or comment would be appreciated.
Thanks a lot!
<?php
require_once($CFG->libdir . "/externallib.php");
require_once("lib.php");
class local_get_completion_overview_external extends external_api {
public static function get_completion_overview_parameters() {
return new external_function_parameters(
array(
'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
id: course id
ids: comma separated course ids
shortname: course short name
idnumber: course id number
category: category id the course belongs to
', VALUE_DEFAULT, ''),
'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
)
);
}
public static function get_completion_overview($field = '', $value = ''){
global $CFG, $DB;
require_once($CFG->dirroot . '/course/lib.php');
require_once($CFG->libdir . '/filterlib.php');
$params = self::validate_parameters(self::get_completion_overview_parameters(),
array(
'field' => $field,
'value' => $value,
)
);
$sql = "SELECT DISTINCT cr.id AS courseid, cr.fullname AS coursename,
COUNT(DISTINCT ra.id ) AS enrols,
COUNT(DISTINCT cc.timecompleted) AS completed
FROM {course} cr
JOIN {context} ct ON ( ct.instanceid = cr.id )
LEFT JOIN {role_assignments} ra ON ( ra.contextid = ct.id ) and ra.roleid = 5
LEFT JOIN {course_completions} cc ON cc.course = cr.id
GROUP BY cr.fullname, cr.id
ORDER BY coursename";
$warnings = array();
if (empty($params['field'])) {
$courses = $DB->get_records_sql($sql, array());
} else {
switch ($params['field']) {
case 'id':
case 'category':
$value = clean_param($params['value'], PARAM_INT);
break;
case 'ids':
$value = clean_param($params['value'], PARAM_SEQUENCE);
break;
case 'shortname':
$value = clean_param($params['value'], PARAM_TEXT);
break;
case 'idnumber':
$value = clean_param($params['value'], PARAM_RAW);
break;
default:
throw new invalid_parameter_exception('Invalid field name');
}
if ($params['field'] === 'ids') {
$courses = $DB->get_records_list('course', 'id', explode(',', $value), 'id ASC');
} else {
$courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
}
}
if(!empty($courses)){
$coursesdata = array();
$currentcourseid = null;
$course = null;
foreach($courses as $completion) {
$context = context_course::instance($course->id);
$crs = array();
$crs['courseid'] = $completion->courseid;
$crs['coursename'] = (string)$completion->coursename;
$crs['enrols'] = $completion->enrols;
$crs['completed'] = $completion->completed;
try {
self::validate_context($context);
} catch (Exception $e) {
continue;
}
if(is_null($currentcourseid) || ($completion->courseid != $currentcourseid)) {
if(!is_null($course)) {
$coursesdata[] = $course;
}
$course = array();
$course['courseid'] = $completion->courseid;
}
$course['courseid'][] = $crs;
$currentcourseid = $completion->courseid;
}
if(!is_null($course)){
$coursesdata[] = $course;
}
$courses->close();
}
$result = array();
$result['course'] = $coursesdata;
return $result;
}
public static function get_completion_overview_returns() {
return new external_single_structure(
array(
'course' => new external_multiple_structure(self::get_completion_overview(), 'list of courses completion')
)
);
}
}
** service.php
<?php
$functions = array(
'local_get_completion_overview' =>
array('classname' => 'local_get_completion_overview_external',
'methodname' => 'get_completion_overview',
'classpath' => 'local/get_completion_overview/externallib.php',
'description' => 'Get course completion overview',
'type' => 'read',
'capabilities'=> array(), //optional, useful to let the administrator know what potential capabilities the user 'could' need
'services' => array(MOODLE_OFFICIAL_MOBILE_SERVICE),
),
);
$services = array(
'get completion overview' => array( //the name of the web service
'functions' => array ('local_get_completion_overview'), //web service functions of this service
'requiredcapability' => '', //if set, the web service user need this capability to access
//any function of this service. For example: 'some/capability:specified'
'restrictedusers' =>0, //if enabled, the Moodle administrator must link some user to this service
//into the administration
'enabled'=>1, //if enabled, the service can be reachable on a default installation
)
);
service.php should be services.php.
After fixing the filename, it appears in Moodle as function, however having an issue to load the function.
Undefined property: stdClass::$id in
/Users/lucy/Sites/moodle/local/get_completion_overview/externallib.php
on line 84
which is
$context = context_course::instance($completion->id);
in foreach block.
also,
Debug info: SELECT id,category FROM {course} WHERE id IS NULL
[array (
)]
Error code: invalidrecord
Stack trace:
line 1562 of /lib/dml/moodle_database.php: dml_missing_record_exception thrown
line 1538 of /lib/dml/moodle_database.php: call to moodle_database->get_record_select()
line 6822 of /lib/accesslib.php: call to moodle_database->get_record()
line 84 of /local/get_completion_overview/externallib.php: call to context_course::instance()
line 138 of /local/get_completion_overview/externallib.php: call to local_get_completion_overview_external::get_completion_overview()
line 124 of /lib/externallib.php: call to local_get_completion_overview_external::get_completion_overview_returns()
line 219 of /webservice/renderer.php: call to external_api::external_function_info()
line 121 of /admin/webservice/service_functions.php: call to core_webservice_renderer->admin_service_function_list()
Increment version number within version.php file. It will trigger moodle for update. Then you should do few updates in moodle. After that you shoudl see the listing
This works as expected. I've changed the permission to has_capability('moodle/site:config', $context);
I'm posting my solution in case someone runs into the same issue.
<?php
require_once('../../config.php');
require_once($CFG->libdir . "/externallib.php");
// require_once('../lib/externallib.php');
// require_once("lib.php");
class local_get_completion_overview_external extends external_api {
public static function get_completion_overview_parameters() {
return new external_function_parameters(
array(
'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
id: course id', VALUE_DEFAULT, ''),
'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
)
);
}
public static function get_completion_overview($field='', $value=''){
global $CFG, $DB;
require_once($CFG->dirroot . '/course/lib.php');
$params = self::validate_parameters(self::get_completion_overview_parameters(),
array(
'field' => $field,
'value' => $value,
)
);
$sql = "SELECT DISTINCT cr.id AS courseid,
cr.fullname AS coursename,
COUNT(DISTINCT ra.id ) AS enrols,
COUNT(DISTINCT cc.timecompleted) AS completed
FROM {course} cr
JOIN {context} ct ON ( ct.instanceid = cr.id )
LEFT JOIN {role_assignments} ra ON ( ra.contextid = ct.id ) and ra.roleid = 5
LEFT JOIN {course_completions} cc ON cc.course = cr.id
GROUP BY cr.fullname, cr.id
ORDER BY coursename";
$warnings = array();
$coursesdata = array();
$requestedcourseids = $params['value'];
if (empty($params['field'])) {
$courses = $DB->get_records_sql($sql, array());
} else {
$value = clean_param($params['id'], PARAM_INT);
if (count($value) > 0) {
$placeholders = array();
$sql_2 = "SELECT DISTINCT cr.id AS courseid,
cr.fullname AS coursename,
COUNT(DISTINCT ra.id) AS enrols,
COUNT(DISTINCT cc.timecompleted) AS completed
FROM {course} cr JOIN {context} ct ON ( ct.instanceid = cr.id )
LEFT JOIN {role_assignments} ra ON ( ra.contextid = ct.id ) and ra.roleid = 5
LEFT JOIN {course_completions} cc ON (cc.course = cr.id)
WHERE cr.id = ".$requestedcourseids." GROUP BY cr.fullname, cr.id";
$courses = $DB->get_records_sql($sql_2, $placeholders);
}
}
if(!empty($courses)) {
$currentcourseid = null;
$course = null;
foreach($courses as $completion) {
$context = context_system::instance();
has_capability('moodle/site:config', $context);
if(is_null($currentcourseid) || ($completion->courseid != $currentcourseid)) {
if(!is_null($course)) {
$coursesdata[] = $course;
}
$course = array();
$course['courseid'] = $completion->courseid;
$course['coursename'] = $completion->coursename;
$course['enrols'] = $completion->enrols;
$course['completed'] = $completion->completed;
$course['totalcourses'] = count($course);
}
$currentcourseid = $completion->courseid;
}
if(!is_null($course)){
$coursesdata[] = $course;
}
} else {
$warning = array();
$warning['item'] = 'course';
$warning['itemid'] = $requestedcourseids;
$warning['warningcode'] = '1';
$warning['message'] = 'No course found';
$warnings[] = $warning;
}
$result['course'] = $coursesdata;
$result['warnings'] = $warnings;
return $result;
}
public static function get_completion_overview_returns() {
return new external_single_structure(
array(
'course' => new external_multiple_structure(
new external_single_structure(
array(
'courseid' => new external_value(PARAM_INT, 'description'),
'coursename' => new external_value(PARAM_TEXT, ''),
'enrols' => new external_value(PARAM_INT, '', VALUE_OPTIONAL),
'completed' => new external_value(PARAM_INT, '', VALUE_OPTIONAL),
'totalcourses' => new external_value(PARAM_INT, '', VALUE_OPTIONAL),
)
)
),
'warnings' => new external_warnings()
)
);
}
}

warning messages not returning from local plugin in Moodle

I am trying to pull each course completion data through API.
Pulling all data and the course data by entering courseid working okay, but when I enter courseid doesn't exist in Moodle, it doesn't return the warning message.
courseid 5 doesn't exist and it should throw warning messages but it returns an error.
Looks like it recognises whether $courseid is empty or not and shows the right value based on entered request.
I've looked at other plugin files and saw how other people passed the warning message in their code, it looks the same and I can't figure out why this doesn't throw the error message.
Am I missing importing a class maybe?
Any help would be appreciated.
Here is my code.
class local_get_completion_overview_external extends external_api {
public static function get_completion_overview_parameters() {
return new external_function_parameters(
array(
'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
id: course id', VALUE_DEFAULT, ''),
'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
)
);
}
public static function get_completion_overview($field='', $value=''){
global $CFG, $DB;
require_once($CFG->dirroot . '/course/lib.php');
$params = self::validate_parameters(self::get_completion_overview_parameters(),
array(
'field' => $field,
'value' => $value,
)
);
$sql = "SELECT DISTINCT cr.id AS courseid,
cr.fullname AS coursename,
COUNT(DISTINCT ra.id ) AS enrols,
COUNT(DISTINCT cc.timecompleted) AS completed
FROM {course} cr
JOIN {context} ct ON ( ct.instanceid = cr.id )
LEFT JOIN {role_assignments} ra ON ( ra.contextid = ct.id ) and ra.roleid = 5
LEFT JOIN {course_completions} cc ON cc.course = cr.id
GROUP BY cr.fullname, cr.id
ORDER BY coursename";
$warnings = array();
$requestedcourseids = $params['value'];
if (empty($params['field'])) {
$courses = $DB->get_records_sql($sql, array());
} else {
$value = clean_param($params['id'], PARAM_INT);
if (count($value) > 0) {
$placeholders = array();
$sql_2 = "SELECT DISTINCT cr.id AS courseid,
cr.fullname AS coursename,
COUNT(DISTINCT ra.id) AS enrols,
COUNT(DISTINCT cc.timecompleted) AS completed
FROM {course} cr JOIN {context} ct ON ( ct.instanceid = cr.id )
LEFT JOIN {role_assignments} ra ON ( ra.contextid = ct.id ) and ra.roleid = 5
LEFT JOIN {course_completions} cc ON (cc.course = cr.id)
WHERE cr.id = ".$requestedcourseids." GROUP BY cr.fullname, cr.id";
$courses = $DB->get_records_sql($sql_2, $placeholders);
}
}
if(!empty($courses)) {
$coursesdata = array();
$currentcourseid = null;
$course = null;
foreach($courses as $completion) {
$context = context_system::instance();
has_capability('moodle/site:config', $context);
if(is_null($currentcourseid) || ($completion->courseid != $currentcourseid)) {
if(!is_null($course)) {
$coursesdata[] = $course;
}
$course = array();
$course['courseid'] = $completion->courseid;
$course['coursename'] = $completion->coursename;
$course['enrols'] = $completion->enrols;
$course['completed'] = $completion->completed;
$course['totalcourses'] = count($course);
}
$currentcourseid = $completion->courseid;
}
if(!is_null($course)){
$coursesdata[] = $course;
}
} else {
$warning = array();
$warning['item'] = 'course';
$warning['itemid'] = $requestedcourseids;
$warning['warningcode'] = '1';
$warning['message'] = 'No course found';
$warnings[] = $warning;
}
$result['course'] = $coursesdata;
$result['warnings'] = $warnings;
return $result;
}
public static function get_completion_overview_returns() {
return new external_single_structure(
array(
'course' => new external_multiple_structure(
new external_single_structure(
array(
'courseid' => new external_value(PARAM_INT, 'description'),
'coursename' => new external_value(PARAM_TEXT, ''),
'enrols' => new external_value(PARAM_INT, '', VALUE_OPTIONAL),
'completed' => new external_value(PARAM_INT, '', VALUE_OPTIONAL),
'totalcourses' => new external_value(PARAM_INT, '', VALUE_OPTIONAL),
)
)
),
'warnings' => new external_warnings()
)
);
}
}
In your code, the variable $coursesdata is only initialised as an array if at least one requested course is found in the database.
So, the line:
$result['courses'] = $coursesdata;
Will produce a warning message (if debugging is on) and set $result['courses'] to null. The expected type here is an array, so the webservice code correctly complains that the 'courses' value is not the correct type.
To fix, make sure you add:
$coursesdata = [];
Somewhere near the top of your function.

Display all categories on product page Prestashop

I need to get list of all categories and their ids on product page in Prestashop (I am using v 1.6.0.9).
I tried to do something like this:
$other_categories = $something->getCategories($this->context->language->id, 1, 100);
foreach($other_categories as something)
{
// now if the id of the category isnt "1", display name of category
if($category->id != "1") { $category->name }
}
But, this is not working.
$category->name gives me only the name of current open category, not the name of each category in the list. I don't know what to put instead of something? And it works only, when I use $category->getProducts. Here you have my shop (see "related products").
It is my third shop and I am struggling with this problem for two days.
In PS 1.6 there is a Category class, it contains some handy static methods usable in your controller: getCategories(...), getNestedCategories(...), getSimpleCategories - these are all static (and public) sou you call them like Category::funcName(...)
For your purpose I thing the best option would be getNestedCategories() which has this header:
public static function getNestedCategories(
$root_category = null,
$id_lang = false,
$active = true,
$groups = null,
$use_shop_restriction = true,
$sql_filter = '',
$sql_sort = '',
$sql_limit = ''
)
In your controller you could do something like:
$allCategories = Category::getNestedCategories(null, $this->context->language->id);
$this->context->smarty->assign( 'allCategories' , $allCategories );
Then in your template file something like
{foreach from=$allCategories item=mainCategory}
<div class="categoryBox">
<h2>{$mainCategory.name}</h2>
<p>{$mainCategory.description}</p>
</div>
{foreach from=$mainCategory.children item=subCategory}
<div class="categoryBox">
<h3>{$subCategory.name}</h3>
<p>{$subCategory.description}</p>
</div>
{/foreach}
{/foreach}
If you would like to have only subcategories of Home category, you can use getHomeCategories($id_lang, $active = true, $id_shop = false):
$allCategories = Category::getHomeCategories( $this->context->language->id );
Also handy one is static function getCategoryInformations($ids_category, $id_lang = null)
=> VERY useful when you have a list of some particular ids of categories you want to get - you just pass them as array - example of usage:
$myCustomCatIDs = array( 5 , 20 , 7);
$myCustomCats = Category::getCategoryInformations( $myCustomCatIDs );
Have a look at home categories module I tested this module with PS 1.6, it works. You can modify the module's hook to your needs. I've done some personnal modification to have the subcategories displayed too. (Sorry for bad english, not my native language)
Here is my custom php code for the module, storing the category and subcategory items in smarty, and linked to a tpl file.
class Homecategories extends Module
{
private $_html = '';
private $_postErrors = array();
function __construct()
{
$this->name = 'homecategories';
$this->tab = 'front_office_features';
$this->version = 1.3;
$this->author = 'John Stocks';
$this->need_instance = 0;
parent::__construct(); // The parent construct is required for translations
$this->page = basename(__FILE__, '.php');
$this->displayName = $this->l('Homepage Categories for v1.5');
$this->description = $this->l('Displays categories on your homepage');
}
function install()
{
return (parent::install() AND $this->registerHook('home') AND $this->registerHook('header'));
}
public function hookHeader()
{
Tools::addCSS(($this->_path).'homecategories.css', 'all');
}
function hookHome($params)
{
global $smarty, $cookie, $link;
$id_customer = (int)$params['cookie']->id_customer;
$id_group = $id_customer ? Customer::getDefaultGroupId($id_customer) : _PS_DEFAULT_CUSTOMER_GROUP_;
$id_lang = (int)$params['cookie']->id_lang;
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT c.*, cl.*
FROM `'._DB_PREFIX_.'category` c
LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (c.`id_category` = cl.`id_category` AND `id_lang` = '.$id_lang.')
LEFT JOIN `'._DB_PREFIX_.'category_group` cg ON (cg.`id_category` = c.`id_category`)
WHERE level_depth > 1 And level_depth < 3
AND c.`active` = 1
AND cg.`id_group` = '.$id_group.'
ORDER BY `level_depth` ASC, c.`position` ASC');
$category = new Category(1);
$nb = intval(Configuration::get('HOME_categories_NBR'));
global $link;
$this->context->smarty->assign(array(
'categories' => $result, Category::getRootCategories(intval($params['cookie']->id_lang), true),
'link' => $link));
$this->context->smarty->assign(array(
'category' => $category,
'lang' => Language::getIsoById(intval($params['cookie']->id_lang)),
));
$result2 = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT c.*, cl.*
FROM ps_category c
LEFT JOIN `ps_category_lang` cl ON (c.`id_category` = cl.`id_category` AND `id_lang` = '.$id_lang.')
LEFT JOIN ps_category_group cg ON (cg.`id_category` = c.`id_category`)
WHERE level_depth > 2 And level_depth < 4
AND cg.`id_group` = '.$id_group.'
AND c.`active` = 1
ORDER BY `level_depth` ASC, c.`position` ASC ');
global $link;
$this->context->smarty->assign(array(
'subcategories' => $result2, Category::getRootCategories(intval($params['cookie']->id_lang), true),
'sublink' => $link));
$this->context->smarty->assign(array(
'category' => $subcategory,
'lang' => Language::getIsoById(intval($params['cookie']->id_lang)),
));
return $this->display(__FILE__, 'homecategories.tpl');
}
}
Try-
Add in controller function-
$categoryList = Category::getCategories();
and assign the variable in smarty.
$this->smarty->assign(array(
'displayCategoryList' => $categoryList,
));
Add in tpl file-
{$displayCategoryList|#print_r}

How to grab an array from a query

I have a function getCart which has a complicated query that is merged together. I want to select only one array that is $cart['tee_times'] = array(); and place that array in another function. How can I accomplish this?
Here is a snippet of the query I am trying to pull from.
function getCart($id, DBConnection $connection) {
$query = 'SELECT * FROM cart WHERE IDCart=:cart_id LIMIT 1';
$prepared = array(
"cart_id" => $id
);
$results = $connection->fetch($query, $prepared);
$cart = !empty($results) ? $results[0] : null;
if (isset($cart)) {
$cart['IDCustomer'] = isset($cart['IDCustomer']) ? (int)$cart['IDCustomer'] : null;
$cart['IDDestination'] = isset($cart['IDDestination']) ? (int)$cart['IDDestination'] : null;
$cart['total'] = 0;
$cart['tee_times'] = array();
$cart['rooms'] = array();
$cart['cars'] = array();
$query = '
SELECT
a.*,
e. city_name,
f.IDDestination,
((CASE DATE_FORMAT(a.teetime_dt, "%w")
WHEN 0 THEN b.sun
WHEN 1 THEN b.mon
WHEN 2 THEN b.tue
WHEN 3 THEN b.wed
WHEN 4 THEN b.thu
WHEN 5 THEN b.fri
WHEN 6 THEN b.sat
ELSE 0
END) * a.no_rounds * a.no_golfers) price,
c.tax_rate
FROM cart_course_teetimes a
JOIN course_priceplan b
ON b.IDCoursePricePlan = a.IDCoursePricePlan
JOIN course_tax c
ON c.IDCourseTax = a.IDCourseTax
JOIN course d
ON d.IDCourse = b. IDCourse
JOIN vw_cities e
ON e.IDCity = d. IDCity
JOIN destinations_cities f
ON f.IDCity = e.IDCity
WHERE IDCart=:cart_id
';
$results = $connection->fetch($query, $prepared);
foreach ($results as $row) {
$formatted = array(
'IDCartTeetimes' => (int)$row['IDCartTeetimes'],
'IDCoursePricePlan' => (int)$row['IDCoursePricePlan'],
'IDCourseTax' => (int)$row['IDCourseTax'],
'teetime_date' => $row['teetime_dt'],
'num_golfers' => (int)$row['no_golfers'],
'num_rounds' => (int)$row['no_rounds'],
'price' => (float)$row['price'],
'tax_rate' => (float)$row['tax_rate'],
'city_name' => $row['city_name'],
'IDDestination' => (int)$row['IDDestination'],
);
$cart['tee_times'][] = $formatted;
$cart['total'] += $formatted['price'];
}
Here is my function and my attempt at retrieving the tee_times array
function filterCart($cart_id, DBConnection $connection) {
$cart = getCart($cart_id, $connection);
if (!isset($cart)) {
http_response_code(404);
return 'Cart does not exist.';
}
$results =$cart['tee_times'];
echo $results;
$id = null;
foreach ($results as $row){
var_dump($row['IDDestination']);
If you want to filter out courses that have more than one IDDestination, change the WHERE clause to:
WHERE IDCart = :cart_id
AND IDCart NOT IN (
SELECT IDCart
FROM course a
JOIN destinations_cities b ON b.IDCity = a.IDCity
GROUP BY IDCart
HAVING COUNT(*) > 1)

Using $this when not in object context - MyBB

So, I'm using MyBB forums, and I go to moderate a thread, and get this error.
Fatal error: Using $this when not in object context in C:\zpanel\hostdata\sdcore\public_html\forums\inc\class_moderation.php on line 642
the code on line 642 is
$this->delete_thread($mergetid);
And the surrounding code (just in case)
$db->delete_query("threadsubscriptions", "tid = '{$mergetid}'");
update_first_post($tid);
$arguments = array("mergetid" => $mergetid, "tid" => $tid, "subject" => $subject);
$plugins->run_hooks("class_moderation_merge_threads", $arguments);
$this->delete_thread($mergetid);
and the delete thread function
function delete_thread($tid)
{
global $db, $cache, $plugins;
$tid = intval($tid);
$plugins->run_hooks("class_moderation_delete_thread_start", $tid);
$thread = get_thread($tid);
$userposts = array();
// Find the pid, uid, visibility, and forum post count status
$query = $db->query("
SELECT p.pid, p.uid, p.visible, f.usepostcounts
FROM ".TABLE_PREFIX."posts p
LEFT JOIN ".TABLE_PREFIX."forums f ON (f.fid=p.fid)
WHERE p.tid='{$tid}'
");
$pids = array();
$num_unapproved_posts = $num_approved_posts = 0;
while($post = $db->fetch_array($query))
{
$pids[] = $post['pid'];
$usepostcounts = $post['usepostcounts'];
if(!function_exists("remove_attachments"))
{
require MYBB_ROOT."inc/functions_upload.php";
}
// Remove attachments
remove_attachments($post['pid']);
// If the post is unapproved, count it!
if($post['visible'] == 0 || $thread['visible'] == 0)
{
$num_unapproved_posts++;
}
else
{
$num_approved_posts++;
// Count the post counts for each user to be subtracted
++$userposts[$post['uid']];
}
}
// Remove post count from users
if($usepostcounts != 0)
{
if(is_array($userposts))
{
foreach($userposts as $uid => $subtract)
{
$db->update_query("users", array('postnum' => "postnum-{$subtract}"), "uid='".intval($uid)."'", 1, true);
}
}
}
// Delete posts and their attachments
if($pids)
{
$pids = implode(',', $pids);
$db->delete_query("posts", "pid IN ($pids)");
$db->delete_query("attachments", "pid IN ($pids)");
$db->delete_query("reportedposts", "pid IN ($pids)");
}
// Implied counters for unapproved thread
if($thread['visible'] == 0)
{
$num_unapproved_posts += $num_approved_posts;
}
// Delete threads, redirects, subscriptions, polls, and poll votes
$db->delete_query("threads", "tid='$tid'");
$db->delete_query("threads", "closed='moved|$tid'");
$db->delete_query("threadsubscriptions", "tid='$tid'");
$db->delete_query("polls", "tid='$tid'");
$db->delete_query("pollvotes", "pid='".$thread['poll']."'");
$db->delete_query("threadsread", "tid='$tid'");
$db->delete_query("threadratings", "tid='$tid'");
$updated_counters = array(
"posts" => "-{$num_approved_posts}",
"unapprovedposts" => "-{$num_unapproved_posts}"
);
if($thread['visible'] == 1)
{
$updated_counters['threads'] = -1;
}
else
{
$updated_counters['unapprovedthreads'] = -1;
}
if(substr($thread['closed'], 0, 5) != "moved")
{
// Update forum count
update_forum_counters($thread['fid'], $updated_counters);
}
$plugins->run_hooks("class_moderation_delete_thread", $tid);
return true;
}
How would I go about fixing this?

Categories