Error: Anonymous function expected when using a static function in PHP - php

Having some trouble with PHP static functions in my program. My code is below and I keep getting the error "Anonymous function expected". I'm using the IDE PhpStorm.
I've had a google but nothing comes up. If I remove the name of the function the error goes away but I don't know how to then call the function.
<?php
/**
* #param mysqli $conn Connection to the database.
* #param int $id The ID of the white card that is to be voted up.
*/
public static function voteUp($conn, $id){
mysqli_query($conn, 'UPDATE WhiteCards SET Ups = Ups + 1 WHERE ID = ' . $id);
}
/**
* #param mysqli $conn Connection to the database.
* #param int $id The ID of the white card that is to be voted down.
*/
public static function voteDown($conn, $id){
mysqli_query($conn, 'UPDATE WhiteCards SET Ups = Ups - 1 WHERE ID = ' . $id);
}

Just solved it, the two functions needed to be in a class.

Related

Openfire: Add user with subscription status as "both"

I am facing issue when i add user using RestApi
include "vendor/autoload.php";
$api = new Gidkom\OpenFireRestApi\OpenFireRestApi;
$api->secret = "mySecretKey";
$api->host = "HostName";
$api->port = "9090";
$api->useSSL = false;
$api->plugin = "/plugins/restapi/v1"; // plugin
For adding user to Roster i am using following code
$jid="xyz#domainname";
//Add to roster
$data=$api->addToRoster("abc", $jid);
Which points to OpenFireRestApi.php which do have function named addToRoster
/**
* Adds to this OpenFire user's roster
*
* #param string $username Username
* #param string $jid JID
* #param string|false $name Name (Optional)
* #param int|false $subscription Subscription (Optional)
* #return json|false Json with data or error, or False when something went fully wrong
*/
public function addToRoster($username, $jid, $name=false, $subscription=false)
{
$endpoint = '/users/'.$username.'/roster';
return $this->doRequest('post', $endpoint, compact('jid','name','subscription'));
}
So I've used
$data=$api->addToRoster("abc", $jid,"DummyName",3);
Where 3 is subscription type as both = 3 which is mentioned.
But when i add user shows subscription type as none only.
UPDATE
I came to know about subscription plugin
So I've installed plugin configure it
Plugin itself says it will automatically subscribe both way.
Afterwards i've again tried with
$data=$api->addToRoster("abc", $jid);
Which aspects to be working but again subscriptions is none only.
Any Help would be appreciated.
There is problem with php-openfire-restapi classes
Need to change name of parameters
So do following changes :
//Add to roster
$username = "username in which you want to add roster";
$jid = "another users JID";
$nickname= "nick name of another user";
$subscription ="3";
$result = $api->addToRoster($username, $jid,$nickname,$subscription);
and change following line in /src/Gidkom/OpenFireRestApi/OpenFireRestApi.php file
public function addToRoster($username, $jid, $name=false, $subscription=false)
{
$nickname=$name;
$subscriptionType=$subscription;
$endpoint = '/users/'.$username.'/roster';
return $this->doRequest('post', $endpoint, compact('jid','nickname','subscriptionType'));
}
Here I have changed parameter names.
Good Luck.

php - call to a member function on null [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Is there a "nullsafe operator" in PHP?
(3 answers)
Closed 2 years ago.
Apologies if this is real basic, but when PHP gets into functions I'm over my head.
I have a plug-in for a forum, which loads a flash cookie as a method to detect duplicate accounts.
The script is failing on about 0.1% of page views, causing a WSOD. The error points to this line:
return $this->registry->output->getTemplate( 'dml' )->duplicatesLoadMovie( $host, $path, $id, $md5 );
The error message is:
Fatal error: Call to a member function duplicatesLoadMovie() on null in /var/www/.../web/forums/hooks/duplicatesLoadMovie.php on line 75
To me, this reads as one of $host, $path, $id, or $md5 is returning null, but as this is not my script (and the coder is, of course, unresponsive), I would like to fix this in the simplest way possible (other than removing it, which is the fallback position).
Can I simply do something to the effect of $id = 0 if id.null? (sorry for the Rubyspeak) for each of the $variables?
Full source of the file:
class duplicatesLoadMovie
{
/**
* Registry object shortcuts
*
* #var $registry
* #var $settings
* #var $member
* #var $memberData
**/
public $registry;
public $settings;
public $member;
public $memberData;
/**
* Main function executed automatically by the controller
*
* #access public
* #return #e void
**/
public function __construct()
{
$this->registry = ipsRegistry::instance();
$this->settings =& $this->registry->fetchSettings();
$this->member = $this->registry->member();
$this->memberData =& $this->registry->member()->fetchMemberData();
}
/**
* Get the output
*
* #access public
* #return #e string
**/
public function getOutput()
{
/* Grab host URL and installation path of the community */
$host = $this->settings['board_url'];
$parsed = parse_url( $host );
$path = trim( $parsed['path'], '/' );
if( $path == '' )
{
$path = '/';
}
$host = 'host=' . $host;
$path = 'path=' . $path;
/* Determine the appropriate identification method (member_id for members and session_id for guests) */
if( $this->memberData['member_id'] )
{
$id = 'mid=' . $this->memberData['member_id'];
}
else
{
$id = 'sid=' . $this->member->session_id;
}
/* Grab the secure key for AJAX */
$md5 = 'md5=' . $this->member->form_hash;
/* Finally, call the template bit */
return $this->registry->output->getTemplate( 'dml' )->duplicatesLoadMovie( $host, $path, $id, $md5 );
}
I'd suspect that this getTemplate( 'dml' ) is not returning a value. If you do a var_dump(getTemplate( 'dml' )), does it show anything?
You might check for "null" before doing that line of code, and in your "else" statement, output an error message, or some other action suitable for that error.
Your problem is solved long time ago, but I suppose a lot of people looking for solution struggle with this error. PHP 8.0 introduces new operator nullsafe operator (?->). It's not for suppressing the error(!), but for cases when variable is allowed to be null and then we don't need to double check its value.
So in OP's question last row would look like:
return $this->registry->output->getTemplate( 'dml' )?->duplicatesLoadMovie( $host, $path, $id, $md5 );
It should be used very carefully, because it's not solution for every occurence of this kind of error!

How to get last inserted inserted row id from PDO

I am following mvc structure in PHP and I want to retrieve last inserted row ID.
I have created following sql code:
$sql = "INSERT INTO song (artist, track, link) VALUES (:artist, :track, :link)";
$query = $this->db->prepare($sql);
$query->execute(array(':artist' => $artist, ':track' => $track, ':link' => $link));
echo $query->lastInsertId(); // To retrieve last inserted row ID.
but unfortunately I ma getting this error: Fatal error: Call to undefined method PDOStatement::lastInsertId()
I have also tried this stack links but not worked for me so I will happy if you help me for retrieve ID.
I am also sharing my controller.php file here.
/**
* This is the "base controller class". All other "real" controllers extend this class.
*/
class Controller{
/**
* #var null Database Connection
*/
public $db = null;
/**
* Whenever a controller is created, open a database connection too. The idea behind is to have ONE connection
* that can be used by multiple models (there are frameworks that open one connection per model).
*/
function __construct(){
$this->openDatabaseConnection();
}
/**
* Open the database connection with the credentials from application/config/config.php
*/
private function openDatabaseConnection(){
// set the (optional) options of the PDO connection. in this case, we set the fetch mode to
// "objects", which means all results will be objects, like this: $result->user_name !
// For example, fetch mode FETCH_ASSOC would return results like this: $result["user_name] !
// #see http://www.php.net/manual/en/pdostatement.fetch.php
$options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);
// generate a database connection, using the PDO connector
// #see http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
$this->db = new PDO(DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS, $options);
}
/**
* Load the model with the given name.
* loadModel("SongModel") would include models/songmodel.php and create the object in the controller, like this:
* $songs_model = $this->loadModel('SongsModel');
* Note that the model class name is written in "CamelCase", the model's filename is the same in lowercase letters
* #param string $model_name The name of the model
* #return object model
*/
public function loadModel($model_name){
require 'application/models/' . strtolower($model_name) . '.php';
// return new model (and pass the database connection to the model)
return new $model_name($this->db);
}
}
You're almost there.
If you look at the manual page for lastInsertId, it's called on the database handle - you're currently calling it on the statement.
You just need to call:
$this->db->lastInsertId();
you can try the following -
$query = "INSERT INTO song (artist, track, link) VALUES (:artist, :track, :link)";
$stmt = $pdo->prepare($query);
$params = array(
"artist" => $artist,
"track" => $track,
"link" => $link,
);
$data = $stmt->execute($params);
$insert_id = $pdo->lastInsertId();

Joomla PHP error within page content

Warning: Parameter 3 to showBlogSection() expected to be a reference, value given in /home/smartsta/public_html/includes/Cache/Lite/Function.php on line 100
I'm getting the above error displaying within my content areas on my Joomla site all a sudden, any suggestions?
Update: No such luck finding access to defined file and directory within godaddy ftp file directory, ftp, or Joomal C-panel.
Within FTP, I cannot find access to this particular file to investigate what is on line 100.
Within the Joomla panel, in Global Configurations, I was able to toggle 'error message' to none for atleast this error to be hidden. Within the cache directory I do not see any options to get into the folder, though it displays.
I also see this at the bottom of that c-panel screen, but just links to a joomla help site, and within the fields I do not see described area to toggle 'ON or OFF'
"Following PHP Server Settings are not optimal for Security and it is recommended to change them:
PHP register_globals setting is ON instead of OFF
"
Update2!:
I've found the file in question, below is the code. Line 100 only states:
global $$object_123456789;
application/x-httpd-php Function.php
PHP script text
<?php
/**
* This class extends Cache_Lite and can be used to cache the result and output of functions/methods
*
* This class is completly inspired from Sebastian Bergmann's
* PEAR/Cache_Function class. This is only an adaptation to
* Cache_Lite
*
* There are some examples in the 'docs/examples' file
* Technical choices are described in the 'docs/technical' file
*
* #package Cache_Lite
* #version $Id: Function.php 47 2005-09-15 02:55:27Z rhuk $
* #author Sebastian BERGMANN <sb#sebastian-bergmann.de>
* #author Fabien MARTY <fab#php.net>
*/
// no direct access
defined( '_VALID_MOS' ) or die( 'Restricted access' );
require_once( $mosConfig_absolute_path . '/includes/Cache/Lite.php' );
class Cache_Lite_Function extends Cache_Lite
{
// --- Private properties ---
/**
* Default cache group for function caching
*
* #var string $_defaultGroup
*/
var $_defaultGroup = 'Cache_Lite_Function';
// --- Public methods ----
/**
* Constructor
*
* $options is an assoc. To have a look at availables options,
* see the constructor of the Cache_Lite class in 'Cache_Lite.php'
*
* Comparing to Cache_Lite constructor, there is another option :
* $options = array(
* (...) see Cache_Lite constructor
* 'defaultGroup' => default cache group for function caching (string)
* );
*
* #param array $options options
* #access public
*/
function Cache_Lite_Function($options = array(NULL))
{
if (isset($options['defaultGroup'])) {
$this->_defaultGroup = $options['defaultGroup'];
}
$this->Cache_Lite($options);
}
/**
* Calls a cacheable function or method (or not if there is already a cache for it)
*
* Arguments of this method are read with func_get_args. So it doesn't appear
* in the function definition. Synopsis :
* call('functionName', $arg1, $arg2, ...)
* (arg1, arg2... are arguments of 'functionName')
*
* #return mixed result of the function/method
* #access public
*/
function call()
{
$arguments = func_get_args();
$id = serialize($arguments); // Generate a cache id
if (!$this->_fileNameProtection) {
$id = md5($id);
// if fileNameProtection is set to false, then the id has to be hashed
// because it's a very bad file name in most cases
}
$data = $this->get($id, $this->_defaultGroup);
if ($data !== false) {
$array = unserialize($data);
$output = $array['output'];
$result = $array['result'];
} else {
ob_start();
ob_implicit_flush(false);
$target = array_shift($arguments);
if (strstr($target, '::')) { // classname::staticMethod
list($class, $method) = explode('::', $target);
$result = call_user_func_array(array($class, $method), $arguments);
} else if (strstr($target, '->')) { // object->method
// use a stupid name ($objet_123456789 because) of problems when the object
// name is the same as this var name
list($object_123456789, $method) = explode('->', $target);
global $$object_123456789;
$result = call_user_func_array(array($$object_123456789, $method), $arguments);
} else { // function
$result = call_user_func_array($target, $arguments);
}
$output = ob_get_contents();
ob_end_clean();
$array['output'] = $output;
$array['result'] = $result;
$this->save(serialize($array), $id, $this->_defaultGroup);
}
echo($output);
return $result;
}
}
?>
It is not exactly an error. It is a warning.
Suddenly? Perhaps you have upgraded/updated your PHP version. Or changed PHP configuration to "strict mode".
The message "expected to be a reference, value given" means the called function expected to receive a reference, not a value. Look:
$something = 9;
show_section($something);
// here you are passing a variable
// this will be accepted as a reference
show_section(9);
// here you are NOT passing a reference
// here you are passing a VALUE
When you pass "by reference", the function can change the variable value... in the example above:
function show_section(&$parameter) {
$parameter = 'changed!';
}
Note the ampersand symbol & before the $parameter - this is how we specify a function requires a REFERENCE.
AFTER the function call, in the example above, the variable $something value will be the changed! string.
The line throwing the error is NOT the "global" one. It is the next:
$result = call_user_func_array(array($$object_123456789, $method), $arguments);
The problem here is that the function is being called indirectly by using the "call_user_func_array" function.
A solution would be transforming all arguments into references. Suggestion:
foreach ($arguments as $count => $value)
{
$param = 'param' . $count;
$$param = $value;
$arguments[$count] = &$$param;
}
Put the code above in the beginning of the call function, right after the following line:
$id = serialize($arguments);
Give this a try!

Storing Sessions in a DB in PHP - keep getting mysql error

I want to store all my sessions in a DB and have read up on this and implemented the following class:
<?php
/**
* This class handles users sessions and stores the session in the DB rather than in a file. This way stops any
* shared host security problems that could potentially happen.
*/
class sessionHandler {
/**
* Initial constructor which takes the database object as a param, to do all the database stuff
* #param object $db The datase object
*/
public function __construct ($db) {
$this->db = $db;
$this->setHandler();
}
function setHandler() {
session_set_save_handler(array(&$this, "open"),
array(&$this, "close"),
array(&$this, "read"),
array(&$this, "write"),
array(&$this, "destroy"),
array(&$this, "clean")
);
}
/**
* Initiate a database object if necessary
*/
function open() {
$this->db->connect();
}
/**
* Write session id and data to the database
* #param string $id The hashed 32 char session id, unique to a user
* #param string $data Serialized session array from the unique session
* #return id The newly inserted ID of the database
*/
function write($id, $data) {
$access = time();
$dateAdded = date("Y-m-d G:i:s");
$this->db->wrapper->where(array("sessionId"=>$id));
$this->db->query($this->db->wrapper->delete(__CLASS__));
//fopen a file and store this in it that way we can debug
$query = $this->db->wrapper->insert(__CLASS__, array("sessionId"=>$id,"dateAdded"=>$dateAdded,"sessionData"=>$data));
$this->db->query($query);
return $this->db->insertId();
}
/**
* Retrieve the session data for a given session id
* #param string $id The hashed 32 char session id, unique to a user
* #return string The session data found for the given session id
*/
function read($id) {
$id = $this->db->wrapper->escape($id);
$row = $this->db->fetch(1, $this->db->wrapper->get_where(__CLASS__,array("sessionId"=>$id)), array(),false);
if ($row) {
return $row['data'];
}
return "";
}
/**
* Delete a session from the database by its unique session id
* #param string $id The hashed 32 char session id, unique to a user
* #return integer The number of deleted rows - should only ever be 1
*/
function destroy($id) {
$id = $this->db->wrapper->escape($id);
$this->db->wrapper->where(array("sessionId"=>$id));
$this->db->query($this->db->wrapper->delete(__CLASS__));
return $this->db->affectedRows();
}
/**
* Garage collector which deletes old records in the database, delete sessions that have expired. This is
* determined by the session.gc_maxlifetime variable in the php.ini
* #param integer $max The maximum number of seconds allowed before a session is to be considered expired
* #return integer The number of deleted rows
*/
function clean($max) {
$old = time() - $max;
$old = $this->db->wrapper->escape($old);
$this->db->wrapper->where(array("access"=>$old), "<");
$this->db->query($this->db->wrapper->delete(__CLASS__));
return $this->db->affectedRows();
}
/**
* Close the database connection once a read / write has been complete
*/
function close() {
$this->db->close();
}
/**
* End the current session and store session data.
*/
public function __destruct(){
session_write_close();
}
}
As you can see in my code, i pass the DB object into the class as a param. My bootstrap file is as follows:
$db = mogDB::init();
$sh = new sessionHandler($db);
session_start();
I have used a few of my own classes here so MogDB:init() basically creates a database connection with the right credentials. The wrapper stuff is basically so i dont have to type out sql query after sql query (me being a bit lazy i guess).
But the problem i get is this in my php error log:
08-Apr-2010 17:40:31] PHP Warning: mysql_insert_id(): 11 is not a valid MySQL-Link resource in /library/mysql.php on line 69
I have debugged this as much as i can and it seems that when it tries to write the session to the DB, it is failing. I have managed to save the query to a file and that imports fine into the database via phpmyadmin, so its not the query thats the problem.
line 69 in mysql.php is as follows:
68. public function insertId() {
69. return mysql_insert_id($this->id);
70. }
Any help would be much appreciated
Thanks
After you include the contents of the file /library/mysql.php around line 69 so we can see what is happening there, I am guessing that a small bit of your code is asking for a database handle back to call mysql_insert_id on, and instead, your db api is giving back the actual insertID already...

Categories