How to get comment from facebook comment plugin - javascript

I followed this guide to trigger a function when a comment is made. I am currently able to make an ajax call to interact with my DB when a comment is made.
FB Comments Plugin - Detect comment on page
What i want to do is save a copy of the comment in my own DB each time a comment is made. Im not sure i want to use facebook comments forever so id like to have all the data saved in my DB incase i revert to the original comment system i had.
Ive tried using jquery to get the value from the textbox and the username from the span.
var comment = $('.mentionsTextarea').val();
var username = $('.commentasName').html();
This code does not get the data. Im guessing its because its inside an iframe. Im wondering if its possible to get the data from the actual object when the comment commit is triggered. So when the event is triggered i can get the data from the comment object? Something like this.
FB.Event.subscribe('comment.create',
function(response) {
var comment = comment.text();
var username = comment.username.text();
}

I dont have the answer i wanted, but i do have a solution to this. This will get the latest comment made for a particular url.
$comments = file_get_contents('https://graph.facebook.com/comments/?ids='.$url);
$comments = json_decode($comments, true);
$comments = $comments[$url]['comments']['data'];
$latestComment = $comments[0];
$username = $latestComment['from']['name'];
$message = $latestComment['message'];
echo $username ." - ".$message;

Related

Check if a $_SESSION variable is set from Javascript

I'm building a message system to learn how it works, and I've already got
pretty much everything. I can log in and make a post on a board, but now I would like to be able to edit it. The back-end is ready, it receives a POST request
Basically what I need to do is check if the currently logged in user is the author of a certain post from Javascript to show or hide the edit button. I know how to tell if the user is logged in from PHP so that it blocks requests if you aren't the author, but I can't hide or show the buttons as the posts are dinamically generated from a <template> using JS.
Login snippet:
$_SESSION["userid"] = $userid;
Edit check PHP snippet (kinda pseudo-code):
if ($_POST["action"] == "modifypost" && isset($_POST["postid"]) && isset($_POST["content"]))
{
$post = get_post($_POST["postid"]);
if ($post.userid != $_SESSION["userid"])
{
die("you are not allowed");
}
//MySQL queries
}
Post dynamic generation (abbreviated):
function add_post(post) {
var t = document.querySelector('#historypost');
t.content.querySelector(".content").innerHTML = post.content;
var clone = document.importNode(t.content, true);
document.body.appendChild(clone);
}
I had originally thought of setting a variable with the user ID from HTML with <script> and <?php ?>, but then the user would be able to manually set that variable from the console and show the buttons.
I had originally thought of setting a variable with the user ID from HTML with <script> and <?php ?>
Yes, this is one correct approach. Basically, use PHP to tell JavaScript which posts actually belong to the current user.
but then the user would be able to manually set that variable from the console and show the buttons
True. There is no way to secure information from user-meddling once you've sent it to the browser. This is because the user is in control of what gets executed in the browser. Instead of thinking of the button visibility as a security feature, think of it as a convenience -- something to make the user experience more pleasing.
Application security is really enforced on the server. Just make sure that one user is not allowed to edit another user's posts, and do not trust what comes from the browser. Verify inputs.
Ideally, I would prefer to put the post rendering logic inside the server-side.
But as your solution is focused in javascript, an option makes PHP render a javascript variable that tells if the user is the post author.
Example:
Inside your PHP file, in the HTML render part you can do this:
<script>var isAuthor = '<?php echo ($post.userid == $_SESSION["userid"])'; ?></script>
Doing this you will have javascript script variable called isAuthor, that will have value "1" is the user is the author.
-
But as I said, this doesn't look like a good approach to solve the problem. It's something that PHP can handle better, without expose your logic to the client.

How to hide my API key between PHP and Javascript?

This is a challenge I am facing in Reactjs, though I don't believe that it is necessarily attributed to it. I am trying to make an API call in React. And while it works, the code also reveals my API key, which below is indicated by my javascript variable sting. When I preview the code in my browser, sting quite clearly shows my API key.
render: function() {
if (this.state.trial) {
return this.iftroo();
}
}
});
var Troo = React.createClass({
render: function() {
var sting = "<?php
$con = mysqli_connect('localhost', 'root', '', 'worldly') or die("Trying");
$query = "select * from testi";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result)){
echo $row["userName"];}
?>";
var weather = new XMLHttpRequest();
weather.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London,uk&units=imperial&appid="+sting, false);
weather.send(null);
var r = JSON.parse(weather.response);
var tempurature = r.main.temp;
return (
<p>
{tempurature}
</p>
I understand that in order to get this to work, I will likely have to embed my javascript code inside my PHP. However, doing so leads to errors, such as PHP not recognizing javascript var characters.
What measures can I take to hide my API keys from the browser?
If you want to hide the API key from the browser then you must simply never give it to the browser.
You can't use the API key from client side JavaScript and keep it hidden from the client.
Make any HTTP request that needs to use it from your server (e.g. using PHP's cURL library).
You could generate one-time jwt api keys, for a special user, with expiration time, and what ever information assigned it.
edit
OK, now I see, that the api key is for an external service. Don't know how the policy for the weather service is, but.. I think this is not the right way to go, you should make this request on the server.

User Cant See Name of Users Entered Before Him (websocket PHP)

Basically I am making a websocket chatting application in PHP and i have made a div that shows all online users.But the problem with my code is when a new user enters the room , he just can see the names of the users entering the room after him and cant see the name of users entered be4 him.
For instance , if Batman,Joker and Robin entered the room respectively then Joker can see robin's name but cant see Batman's Name in the userList.
Here is my code:
Client Side:
<div style="height:760px; width:200px; margin-left:450px;border-style:solid;"id='userlist'>
</div>
This is the DIV element where i want my userlist.
JS code:
var msg = {
name: myname,
color : '<?php echo $colours[$user_colour]; ?>'
};
websocket.send(JSON.stringify(msg));
Then server recieve this data and Heres the part of the server side code:
$tst_msg = json_decode($received_text); //json decode
$user_name = $tst_msg->name; //sender name
$response_text = mask(json_encode(array('name'=>$user_name)));
send_message($response_text); //function to send data to the client side
Now heres the client side code for recieving the data:
websocket.onmessage = function(ev) {
var msg = JSON.parse(ev.data);
var uname = msg.name; //user name
//code to check if same name doesnt appear twice
if(!$('#userlist:has(li.'+uname+')').length>0){
$('#userlist').append('<li class="'+uname+'" >'+uname+'</li>');
}
};
What can be a workaround to solve this problem? Any ideas? Hope I made sense.
With your current code this is what is happening
Batman enters room - script fires to append current users to list - noone is there so nothing is appended.
Joker enters room - script is fired and it is appended to batman - but the script has fired to add batman already so Joker doesn't know batman is there.
A script will not store temporary information
i.e. if you EXPLICITLY declare users = batman, robin, joker - the script knows this.
BUT if you fire a script and store them in a array or similar in that script the second the script has finished running it forgets what you have stored.
Hope that helps - just remember 'SCRIPTS CANNOT REMEMBER ANYTHING I TELL THEM WITHOUT HELP' - it will make it more obvious that you need a storage mecahnism for temporary stuff.
Hope that helps and good luck!

how to fetch the current user data in phpfox

Topic: Fetch current user(some particular fields) data from the DB and display it on the Welcome Screen.
Explaination of UI : On the Registration Page, A dropdown would appear. As the user selects an option, it would trigger an event to fetch user image to show on the welcome page.
I have put following code in (pages.process) module
function getUserId($iUserId)
{
$aRows = $this->database()->select('p.image_path')->from($this->_sTable, 'p')
->Join(Phpfox::getT('user') , 'u', ' p.page_id = u.college_name') ->
where('u.college_name = p.page_id AND u.user_id = ' .
(int)$iUserId)->execute('getRows');
return $aRows;
}
The data will selected from User & Pages Table, and will be used to show the user image. Please suggest.
There is a service to get user details by is
$user_id = Phpfox::getUserId();
$aRow = Phpfox::getService('user')->getUser($user_id);
This will give you user details
For performance, check if the page you are altering already has the information you need, maybe you dont need to query the database in ajax if the page, when being created, already has that info and you can store it in javascript.
Since you mentioned an ajax situation (trigger an event on drop down to query the database), then you need to include a JS file (my suggestion since you can do this from a plugin), there are other ways but this is the best in my opinion.
Please read my article about plugins if you need help with writing one. My suggestion is to write a plugin to include your JS file in the page.
In the JS file you can call a "controller function" like this:
$.ajaxCall('mymodule.myfunction', 'param1=value1&param2=value2');
this would run the function "myfunction" in the file /module/mymodule/include/component/ajax/ajax.class.php
From this ajax file you can call "service functions" and send code to the browser, for example:
$value = Phpfox::getService('mmodule')->someOtherFunction();
$this->call('alert("' . $value . '");');
Hope it helps

How to generate an ID for Contact Form?

I'm using PHP for a simple Contact Form. I'm trying to generate an unique ID for each form submitted. For example, the first email is #001, the second #002, 3th #003 etc.
I'll use the ID in the autoreply (or autoresponse?) e-mail: "You are the #016 person to make contact.", for example.
Can be with PHP or JavaScript (can it be with JS? I don't know! But I prefer PHP!). But I have no idea about how I can do this.
I'm not using a database.
Since you're (probably) going to store received information in a kind of database, you generate id on insertion into database. Autoincrement ID field should do the trick.
edit: It also sounds reasonable to reuse google forms
You can use php's uniqid() function to generate unique id each time.
Update 1:
It's a very useful function. The probability of generating same id is really minimum. For more information please visit the link
Update 2:
You can use simple text file/csv to store one line at a time to keep track of it. When the user submit the form you generate unique id each time and reply to client and at the same time you store it to a normal text file if you like. Hope this will help.
There are several ways to do this. The most simple of those is to create a file which will store the number of form filled and you can increase its value for each form filled.
Here is the example copied from: Read and write to a file while keeping lock
//Open the File Stream
$handle = fopen("file.txt","r+");
//Lock File, error if unable to lock
if(flock($handle, LOCK_EX)) {
$count = fread($handle, filesize("file.txt")); //Get Current Hit Count
$count = $count + 1; //Increment Hit Count by 1
ftruncate($handle, 0); //Truncate the file to 0
fwrite($handle, $count); //Write the new Hit Count
flock($handle, LOCK_UN); //Unlock File
} else {
echo "Could not Lock File!";
}
//Close Stream
fclose($handle);

Categories

Resources