Get MediaWiki session() username - php

I have statistic stored in a database. I would like Users in our MediaWiki to view only statistic that is linked to their username.
I hav e tried below but it gives me just a blank page (no errors).
My guess is that it doesn´t get the username from the session.
How should I manage to do that?
<?php
$dbtype = "mysql";
$dbhost = "localhost";
$dbname = "test";
$dbuser = "username";
$dbpassword = "passw0rd";
$conn = mysql_connect($dbhost, $dbuser, $dbpassword);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$wgHooks['UserLoginComplete'][] = 'test::onUserLoginComplete';
class test
{
public static function UserLoginComplete( $user, $password, &$retval, &$msg ) {
$dbr = wfGetDB( DB_SLAVE );
$row = $dbr->selectRow(
'coaching', // $Table
'Name', // $vars (column of the table)
array( 'Name' => $user ), // $Conitions
__METHOD__ // $fname = 'Database::select'
);
mysql_select_db($dbname, $conn);
echo '<table border="0" border-color="#CCCCCC" bgcolor="#FFFFFF"><thead><tr><td><b>ID</b></td><td><b>Namn</b></td><td><b>Datum</b></td><td><b>Score</b></td></tr></thead><tbody>';
$query = "SELECT ID, Name, Date, Score FROM coaching WHERE Name = $user";
$result = mysql_query($query) or die(mysql_error());
$color="1";
while($row = mysql_fetch_array($result)){
if($color==1){
echo '<tr bgcolor="#D0D0D0">';
$color="2";
} else {
echo '<tr bgcolor="#E0E0E0">';
$color="1";
}
echo '<td>'.$row['ID'].'</td><td>'.$row['Name'].'</td><td>'.$row['Date'].'</td><td>'.$row['Score'].'</td></tr>';
}
?>

I'm assuming you are doing this inside of a MediaWiki extension. It wasn't clear from your question if that was the case but I see you are registering a hook. Note that the hook you are registering UserLoginComplete shows a different function signature than you are defining. To get the username you need to use the instance of the $wgUser object object you are being passed and then call the getName method on that object.
Something like:
$user->getName();
$user itself is an object reference.

Your actual problem is that your class is missing a closing curly brace (}), causing a PHP syntax error. (Actually, you're missing two of them.)
To avoid and/or catch such errors, you should:
configure PHP to display error messages,
also configure PHP to log errors and warnings to a file, and make sure to check the file after testing new code, and
indent your code properly, so that you can spot such errors without having to count every brace.
Anyway, once you've fixed those issues (and the syntax error), you've still got some other problems. One, pointed out by Jamie Thingelstad, is that the parameters for your UserLoginComplete hook are wrong; they should be:
function onUserLoginComplete( &$user, &$inject_html ) {
Second, you should not echo anything in a UserLoginComplete hook (or in any MediaWiki extension code at all, really). What you can do, in this case, is append the HTML you want to output to the $inject_html parameter, like this:
$inject_html .= '<table border="0" ...';
(This output method is peculiar to this specific hook. The usual way to output something in a MediaWiki extension is using the OutputPage class, either through an instance passed to your hook — or obtained via some other object passed to it, such as anything that implements IContextSource — or, if there isn't any, using the global instance $wgOut.)
Also, you're not escaping the $user variable in your SQL query, so your code is potentially vulnerable to SQL injection. Besides, you shouldn't be using the old mysql functions anyway; they've been deprecated.
Finally, I'm not sure if UserLoginComplete is really the right hook for what you want to do, anyway. As the name suggests, it runs only when the user logs in to MediaWiki, and will not run again unless the user logs out and back in. If you would like your users to be able to view your statistics whenever you want, you should either use some hook that runs on every page view, or, perhaps better yet, make a custom special page your users can visit to see the statistics.
Ps. Also, you should never use the closing ?> tag in PHP unless you actually intend to include some HTML code after it. Having a ?> at the end of the file is nothing but an invitation for mysterious errors.

Related

PHP SQL query doesnt return a result

I have a button in a webapp that allows users to request a specially formatted number. When a user click this button 2 scripts run. The first that is fully functional, looks at a number table finds the largest number and increments it by 1. (This is not the Primary Key) the second script which is partially working gets the current date and runs a SQL query to get which period that date falls in. (Periods in this case not always equaling a full month) I know this script is at least partially working because I can access the $datetoday variable called in that script file. However it is not returning the requested data from the periods table. Anyone that could help me identify what I am doing wrong?
<?php
include 'dbh.inc.php';
$datetoday = date("Ymd");
$sql = "SELECT p_num FROM periods where '$datetoday' BETWEEN p_start AND p_end";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../quote.php?quotes=failed_to_write");
exit();
} else {
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
$pnum = $row;
mysqli_stmt_close($stmt);
}
If it helps any one I published my code to https://github.com/cwilson-vts/Quote-Appliction
So first off, I do not use msqli and never learned it. However, I believe I get the gist of what you want to do. I use PDO because I FEEL that it is easier to use, easier to read and it's also what I learned starting off. It's kinda like Apple vs. Samsung... no one product is exactly wrong or right. And each have their advantages and disadvantages. What I'm about to provide you will be in PDO form so I hope that you will be able to use this. And if you can't then no worries.
I want to first address one major thing that I saw and that is you interlacing variables directly into a mysql statement. This is not considered standard practice and is not safe due to sql injections. For reference, I would like you to read these sites:
http://php.net/manual/en/security.database.sql-injection.php
http://php.net/manual/en/pdo.prepared-statements.php
Next, I'm noticing you're using datetime as a variable name. I advise against this as this is reserved in most programming languages and can be tricky. So instead, I am going to change it something that won't be sensitive to it such as $now = "hello world data";
Also I'm not seeing where you would print the result? Or did you just not include that?
Another thing to consider: is your datetime variable the same format as what you are storing in your db? Because if not, you will return 0 results every time. Also make sure it is the right time zone too. Because that will really screw with you. And I will show you that in the code below too.
So now on to the actual code! I will be providing you with everything from the db connection code to the sql execution.
DB CONNECTION FILE:
<?php
$host = '127.0.0.1';
$user = 'root';
$pw = '';
$db = 'test'; // your db name here (replace 'test' with whatever your db name is)
try {
// this is the variable will call on later in the main file
$conn = new PDO("mysql:host=$host;dbname=$db;", $user, $pw);
} catch (PDOException $e) {
// kills the page and returns mysql error
die("Connection failed: " . $e->getMessage());
}
?>
The data file:
<?php
// calls on the db connection file
require 'dbconfig.php';
// set default date (can be whatever you need compared to your web server's timezone). For this example we will assume the web server is operating on EST.
date_default_timezone('US/Eastern');
$now = date("Ymd");
// check that the $now var is set
if(isset($now)) {
$query = $conn->prepare("SELECT p_num FROM periods WHERE p_start BETWEEN p_start AND :now AND p_end BETWEEN p_end AND :now");
$query->bindValue(':now', $now);
if($query->execute()) {
$data = $query->fetchAll(PDO::FETCH_ASSOC);
print_r($data); // checking that data is successfully being retrieved (only a troubleshooting method...you would remove this once you confirm it works)
} else {
// redirect as needed and print a user message
die("Something went wrong!");
}
$query->closeCursor();
}
?>
Another thing I want to mention is that make sure you follow due process with troubleshooting. If it's not working and I'm not getting any errors, I usually start at the querying level first. I check to make sure my query is executing properly. To do that, I go into my db and execute it manually. If that's working, then I want to check that I am actually receiving a value to the variable I'm declaring. As you can see, I check to make sure the $now variable is set. If it's not, that block of code won't even run. PHP can be rather tricky and finicky about this so make sure you check that. If you aren't sure what the variable is being set too, echo or print it with simply doing echo $now
If you have further questions please let me know. I hope this helps you!
I think I know what I was doing wrong, somebody with more PHP smarts than me will have to say for sure. In my above code I was using mysqli_stmt_store_result I believe that was clearing my variable before I intended. I changed that and reworked my query to be more simple.
<?php
include 'dbh.inc.php';
$datetoday = date("Ymd");
$sql = "SELECT p_num FROM periods WHERE p_start <= $datetoday order by p_num desc limit 1";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../quote.php?quotes=failed_to_write");
exit();
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while( $row = mysqli_fetch_assoc($result)) {
$pnum = $row['p_num'];
echo $pnum;
}
mysqli_stmt_close($stmt);
}
Thanks to #rhuntington and #nick for trying to help. Sorry I am such an idiot.

What's going on with my code?

I am using similar syntax in my blog. However, On my forum, nothing happens! This has been such an infuriating thing to tackle, as everything seems to be working exactly as my blog did. Here's my code I pass through and call the delete_post page
CHUNK FROM VIEWPOST.PHP
while($row = mysqli_fetch_array($result)){
echo '<tr>';
echo '<td class="postleft">';
echo date('F j, Y, g:i a', strtotime($row['forumpost_Date'])) . "<br>" .$row['user_Name']. "<br>" .$row['forumpost_ID'];
echo '</td>';
echo '<td class="postright">';
echo $row['forumpost_Text'];
echo '</td>';
if(isset ($_SESSION['loggedin']) && ($_SESSION['user_AuthLvl']) == 1){
echo '<td class="postright">';
echo '<a class= "btn btm-default" href="#">Edit</a>';
echo '<a class= "btn btm-default" href="delete_post.php?forumpost_ID='.$row['forumpost_ID'].'">Delete</a>';
echo '</td>';}
else if(isset ($_SESSION['loggedin']) && ($_SESSION['user_ID']) == $row['forumpost_Author']){
echo '<td class="postright">';
echo '<a class= "btn btm-default" href="#">Edit</a>';
echo '<a class= "btn btm-default" href="delete_post.php?forumpost_ID='.$row['forumpost_ID'].'">Delete</a>';
echo '</td>';}
echo '</tr>';
}echo '</table>';
DELETE POST FUNCTION
<?php
include ('header.php');
include ('dbconnect.php');
//A simple if statement page which takes the person back to the homepage
//via the header statement after a post is deleted. Kill the connection after.
if(!isset($_GET['forumpost_ID'])){
header('Location: index.php');
die();
}else{
delete('hw7_forumpost', $_GET['forumpost_ID']);
header('Location: index.php');
die();
}
/********************************************
delete function
**********************************************/
function delete($table, $forumpost_ID){
$table = mysqli_real_escape_string($connectDB, $table);
$forumpost_ID = (int)$forumpost_ID;
$sql_query = "DELETE FROM ".$table." WHERE id = ".$forumpost_ID;
$result = mysqli_query($connectDB, $sql_query);
}
?>
Now it is showing the ID's as intended, it just simply does not delete the post. It's such a simple Query, I don't know where my syntax is not matching up!
EDIT FOR DBCONNECT.PHP
<?php
/*---------------------------------------
DATABASE CONNECT PAGE
A simple connection to my database to utilize
for all of my pages!
----------------------------------------*/
$host = 'localhost';
$user = 'ad60';
$password = '4166346';
$dbname = 'ad60';
$connectDB = mysqli_connect($host, $user, $password, $dbname);
if (!$connectDB){
die('ERROR: CAN NOT CONNECT TO THE DATABASE!!!: '. mysqli_error($connectDB));
}
mysqli_select_db($connectDB,"ad60") or die("Unable to select database: ".mysqli_error($connectDB));
?>
Ok, I saw this and I would like to suggest the following:
In general
When you reuse code and copy paste it like you have done there is always the danger that you forget to edit parts that should be changed to make the code work within the new context. You should actually not use code like this.
Also you have hard coded configuration in your code. You should move up all the configuration to one central place. Never have hard coded values inside your functional code.
Learn more about this in general by reading up about code smell, programming patterns and mvc.
To find the problem
Now to fix your problem lets analyse your code starting with delete_post.php
First check if we actually end up inside delete_post.php. Just place an echo "hello world bladiebla" in top of the file and then exit. This looks stupid but since I can't see in your code if the paths match up check this please.
Now we have to make sure the required references are included properly. You start with the include functionality of php. This works of course, but when inside dbconnect.php something goes wrong while parsing your script it will continue to run. Using require would fix this. And to prevent files from loading twice you can use require_once. Check if you actually have included the dbconnect.php. You can do this by checking if the variables inside dbconnect.php exist.
Now we know we have access to the database confirm that delete_post.php received the forumpost_ID parameter. Just do print_r($_GET) and exit. Check if the field is set and if the value is set. Also check if the value is actually the correct value.
When above is all good we can go on. In your code you check if the forumpost_ID is set, but you do not check if the forumpost_ID has an actual value. In the above step we've validated this but still. Validate if your if
statement actually functions by echoing yes and no. Then test your url with different inputs.
Now we know if the code actually gets executed with all the resources that are required. You have a dedicated file that is meant to delete something. There is no need to use a function because this creates a new context and makes it necessary to make a call and check if the function context has access to all the variables you use in the upper context. In your case I would drop the function and just put the code directly within the else statement.
Then check the following:
Did you connect to the right database
Is the query correct (echo it)
Checkout the result of mysqli_query
Note! It was a while ago since I programmed with php so I assume noting from the codes behavior. This is always handy. You could check the php versions on your server for this could also be the problem. In the long run try to learn and use MVC. You can also use frameworks like codeigniter which already implemented the MVC design pattern.
You have to declare $connectDB as global in function.
function delete($table, $forumpost_ID){
global $connectDB;
$table = mysqli_real_escape_string($connectDB, $table);
$forumpost_ID = (int)$forumpost_ID;
$sql_query = "DELETE FROM ".$table." WHERE id = ".$forumpost_ID;
$result = mysqli_query($connectDB, $sql_query);
}
See the reference about variable scope here:
http://php.net/manual/en/language.variables.scope.php
please try to use below solution.
<?php
include ('header.php');
include ('dbconnect.php');
//A simple if statement page which takes the person back to the homepage
//via the header statement after a post is deleted. Kill the connection after.
if(!isset($_GET['forumpost_ID'])){
header('Location: index.php');
die();
}else{
delete('hw7_forumpost', $_GET['forumpost_ID'], $connectDB);
header('Location: index.php');
die();
}
/********************************************
delete function
**********************************************/
function delete($table, $forumpost_ID, $connectDB){
$table = mysqli_real_escape_string($connectDB, $table);
$forumpost_ID = (int)$forumpost_ID;
$sql_query = "DELETE FROM ".$table." WHERE id = ".$forumpost_ID;
$result = mysqli_query($connectDB, $sql_query);
}
?>
I wish this solution work for you best of luck!

using _GET url link to delete a record from mysql database

EDIT
Thanks for the help so far. I have edited my post to reflect the changes suggested below. I am using PDO for my database connection. The code I have now is as follows:
HTML
<a href="includes/delete-customer.php?userID='.$row->customer_id.'">
PHP
<?php
//MySQL Database Connect
include 'includes/config.php';
// confirm that the 'id' variable has been set
if (isset($_GET['userID']) && is_numeric($_GET['userID']))
{
// get the 'id' variable from the URL
$id = $_GET['userID'];
/* Delete row from the customer table */
$id = $dbh->exec("DELETE FROM customer WHERE customer_id = '$id'");
$stmt->execute();
}
?>
config.php
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'user';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=testDB", $username, $password);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
I'm pretty sure the HTML is correct now and the issue lies with the delete-customer.php file. I am currently receiving the following error: Fatal error: Call to a member function exec() on a non-object
I'm not sure of how to implement the PDO query correctly. Any further advice is much appreciated.
Your HTML section says:
<a href="includes/delete-customer.php?customer_id=$id['.$row->customer_id.']">
Is this your exact HTML syntax? This argument should be the actual numerical id, i.e. --
<a href="includes/delete-customer.php?customer_id=3">
-- either by echoing $row->customer_id (assuming it exists), or some other method of knowing that user id.
Your HTML only needs to send the actual data, not any sort of variable syntax. Your receiving PHP ($_GET['customer_id']) will interpret that for you and properly pass that to MySQL.
Your URL passes userID as the get parameter, yet in your php script you're trying to access customer_id. Try changing your code to retrieve userID and it should work
if (isset($_GET['userID']) && is_numeric($_GET['userID']))
<a href="includes/delete-customer.php?customer_id=<?php echo $id[$row->customer_id]; ?>">
assuming $id[$row->customer_id] is valid.
Plus, you really shouldn't delete from database on get var unless you're doing some admin validation / access rules and guarantee you don't have anyone on the job who will go rogue and manually type in numbers there.. That's just plain crazy.

CMS homepage in php

I am working on something it has 2 pages. One is index.php and another one is admin.php.I am making CMS page where you can edit information on the page yourself. Then it will go to the database, where the information is stored. I also have to have it where the user can update the information on the page. I am getting a little bit confused here.For instance here I am calling the database and I am starting a function called get_content:
<?php
function dbConnect(){
$hostname="localhost";
$database="blank";
$mysql_login="blank";
$mysql_password="blank";
if(!($db=mysql_connect($hostname, $mysql_login, $mysql_password))){
echo"error on connect";
}
else{
if(!(mysql_select_db($database,$db))){
echo mysql_error();
echo "<br />error on database connection. Check your settings.";
}
else{
return $db;
}
}
function get_content(){
$sql = "Select PageID,PageHeading,SubHeading,PageTitle,MetaDescription,MetaKeywords From tblContent ";
$query = mysql_query($sql) or die(mysql_error());
while ($row =mysql_fetch_assoc($query,MYSQL_ASSOC)){
$title =$row['PageID'[;
$PageHeading =$row['PageHeading'];
$SubHeading = $row['SubHeading'];
$PageTitle = $row['PageTitle'];
$MetaDescription =$row['MetaDescription'];
$MetaKeywords = $row['MetaKeywords'];
?>
And then on the index page and I am going to echo it out in the spot that someone can change:
<h2><?php echo mysql_result($row,0,"SubHeading");?>A Valid XHTML and CSS Web Design by WG.</h2>
I do know that the function is not finished I am still working on that part. What I am wondering is am I echoing it out right or I am way off. This is my first time messing with CMS in php and I am still learning it. I am working with navicat and text pad on this, yes I know it is old school but that is what I am being shown with. But my index is a form not a blog. I have seen many of CMS pages for blogs not to many to be used with forms. Any input will be considered thanks for reading my question.
Your question is a bit confusing and your code very incomplete. I'ts hard to say if you do it the right way since I don't see the rest of the script. You need to connect to the database there as well and get your data. The $row variable only exists in the while statement inside you function get_content() though.
You could complete the get_content() and use it in the index.php as well. Remember that the variables you define inside a function only is available there though. If you need the data outside that function you need to return the values you need and save them to some other variable there. Put if you do the same as you've started doing in the get_content() function in index.php, then you just have to echo the variables you define. Like this:
<h2><?php echo $SubHeading; ?></h2>
or you could also do it like this somewhere inside the php tags:
echo '<h2>{$SubHeading}</h2>';
I hope that answers your question.
EDIT:
What you need in the index.php page is exactly what you seem to be doing in the admin file. You need to connect to db using mysql_connect() and select db with mysql_select_db(). You then need to select the data from the db using the appropriate query with $query = mysql_query($sql). If it's more then one row you want to display you need to put it in a while loop otherwise (which seems to be the case here) you just need to do one $row = mysql_fetch_assoc($query). After that you can get the data using $row['column_name']. If you have more than one row you can just use $row['column_name'] in side the while loop to get each consecutive row's data.
Here is an example index.php:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password') or
die('Could not connect: ' . mysql_error());
mysql_select_db('database_name')) or die('Could not select database: ' .
mysql_error());
$sql = "SELECT SubHeading FROM tblContent WHERE PageID='1' LIMIT 1;";
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
echo '<h2>{$row[\'SubHeading\']}</h2>';
mysql_close();
?>
This is just what you need to display the SubHeading from you database. You probably also need to handle your form and save the submitted data to the database in your admin.php file.

how to get the session id

please help i have the following php code for my login session but i am trying to get the $_session['user_id'] instead of the $_session['email']. i tried print_f function to see what i can use but user_id array says 0 which cannot be right unless i read it wrong.
session_start();
$email = strip_tags($_POST['login']);
$pass = strip_tags($_POST['password']);
if ($email&&$password) {
$connect = mysql_connect("xammp","root"," ") or die (" ");
mysql_select_db("dbrun") or die ("db not found");
$query = mysql_query("SELECT email,pass FROM members WHERE login='$email'");
$numrows = mysql_num_rows($query);
if ($numrows!=0) {
// login code password check
while ($row = mysql_fetch_assoc($query)) {
$dbemail = $row['login'];
$dbpass = $row['password'];
}
// check to see if they match!
if ($login==$dbemail&&$password==$dbpass) {
echo "welcome <a href='member.php'>click to enter</a>";
$_SESSION['login']=$email;
} else {
echo (login_fail.php);
}
} else {
die ("user don't exist!");
}
//use if needed ==> echo $numrows;
} else {
die ("Please enter a valid login");
}
i am trying to get the $_session['user_id'] instead how can get this to use instead of $_session['email']. tried using $_session['user_id'] but instead i got undefined error msg.
Well, you don't define $_session['user_id'] anywhere in this script, so it's no surprise that it's not defined. You have to assign it a value before you can refer to it.
Also, note that there all kinds of security problems with this code.
You're running your MySQL connection as the root user. This is NOT a good idea.
You're trusting user input, which opens your script up to a SQL injection attack. Stripping HTML tags from the user input does not make it safe. Suppose that I came to your site, and filled in the "email" field with this:
bob#example.com'; GRANT ALL PRIVILEGES ON *.* TO 'evil_bob' IDENTIFIED BY '0wned_joo';
As currently written, your script would happily run its query as normal, and also create an account called "evil_bob" with full privileges to all the information in all of the databases on your server.
To avoid this, NEVER assume that user input is safe. Validate it. And to be extra sure, don't stick variables straight into SQL you've written. Use bound parameters instead. There are a few cases where it's hard to avoid -- for example, if you need to specify the name of a column rather than a piece of data, a bound parameter will not help and you'll have to do it some other way. However, for any piece of data you're using as part of a query, bind it.

Categories