Facebook login page and cache - mysql

I've got a Facebook login in my website
but I need to request permission to post in my user's wall.
I found many many examples on google that use the scope, but they're too different form mine, and I don't understand where to put it
This is the code:
<?php
session_start();
// added in v4.0.0
require_once 'autoload.php';
require 'functions.php';
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
// init app with app id and secret
FacebookSession::setDefaultApplication( 'APPID','APPSECURE' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper('http://www.bestparty.altervista.org/APP/facebook/fbconfig.php' );
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
// see if we have a session
if ( isset( $session ) ) {
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
$fbid = $graphObject->getProperty('id'); // To Get Facebook ID
$fbfullname = $graphObject->getProperty('name'); // To Get Facebook full name
$femail = $graphObject->getProperty('email');
/* ---- Session Variables -----*/
$_SESSION['FBID'] = $fbid;
$_SESSION['FULLNAME'] = $fbfullname;
$_SESSION['EMAIL'] = $femail;
checkuser($fbid,$fbfullname,$femail);
/* ---- header location after session ----*/
$cookie_name = 'FBID';
$cookie_value = $fbid;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), '/');
$cookie_name2 = 'FULLNAME';
$cookie_value2 = $fbfullname;
setcookie($cookie_name2, $cookie_value2, time() + (86400 * 30), '/');
header("Location: ../gestaccount.php");
} else {
$cookie_name = 'FBID';
$cookie_value = $fbid;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), '/');
$loginUrl = $helper->getLoginUrl();
header("Location: ".$loginUrl);
}
?>
Also:
May I save the access token in mysql to use it in future?
Why does the datas that I save in cache stays only until I close the browser?

1, You can store the access token however which way you like. As long as it's secure and you are able to update them in case of expired/updated/extended access tokens, it should be fine.
2, This is a bit unclear, are you setting and handling cookies correctly ?

Related

Is it possible to send a POST request only through HTML (without javascript)?

I want to send a newsletter through email and I would like to see who opened my email.
I send HTML in the content of the email, so I can not add javascript in there. (see here )
Is there any way to send a post request (to my server) only through HTML, every time the HTML is opened and not by pressing a button?
No.
The only HTTP requests that can be triggered by simply opening an HTML document without any JS in it are GET requests.
Tracking of HTML emails is usually achieved using GET requests from images (and usually blocked by email clients because it is intrusive).
I think you are wanting to track emails which are opened? If you are using a PHP server you can create a simple "pixel" but would need to hook it up to your database.
Inside your email you can load the pixel as an image and replace the %pixel_id%
<img src="https://yoururl/pixel.php?tid=%pixel_id%" style="width:1px;height:1px;" title="pixel">
Pixel code:
<?php
//YOU NEED TO INCLUDE YOUR DATABASE CONNECTION FILE HERE
$conn_cms=get_dbc();
$stmt = $conn_cms->prepare("SELECT * FROM `pixel_tracker` WHERE `pixel_id` = ?");
$stmt->bind_param("s", $tid);
$tid = $_GET['tid'];
$stmt->execute();
$result = $stmt->get_result();
$assoc = $result->fetch_assoc();// get the mysqli result
$stmt = $conn_cms->prepare("UPDATE `pixel_tracker` SET `seen` = ?,`seen_count` = ?,
`seen_when`= ?, `header_track`= ? WHERE `pixel_id` = ?");
$stmt->bind_param("sssss", $seen, $seen_count, $seen_when, $header_track, $pixel_id);
$seen = 1;
$seen_count = $assoc['seen_count']+1;
$seen_when = date("Y-m-d H:i:s");
if(isset($_SERVER['HTTP_REFERER'])){
$header_track = $_SERVER['HTTP_REFERER'];
} else {
$header_track = "none";
}
$pixel_id = $tid;
$stmt->execute();
$result = $stmt->get_result(); // get the mysqli result
$pixel = imagecreate(1,1);
$color = imagecolorallocate($pixel,255,255,255);
imagesetpixel($pixel,1,1,$color);
header("content-type:image/jpg");
imagejpeg($pixel);
imagedestroy($pixel);
?>
EDIT: If you are sending emails automatically from your server you can dynamically insert the pixel reference in to your database, otherwise for now you can do this manually.

Woocommerce - validate coupon with cart items & coupon data

I’m in the process of validating a coupon on cart items rather than the order as a whole. If the cart items exceeds the number of available coupon limit, the coupon errors and gives the user an error message.
The code below checks how many specific product items are in the basket, for example 5. // This works
The code below also returns data from the coupon being used. // This doesn’t work
Example of the data im looking to return so I can compare.
coupon code = 123
coupon usage_count = 1
coupon usage_limit = 3
Available usage = 2
I already have another coupon validation in place that checks whether a users facilities booking falls in between their hotel booking dates, that works fine. Anyone have any suggestions where I’m going wrong with this validation? I can’t seem to return the data from the coupon being inputted. Am I using the correct filter? Thanks
add_filter( 'woocommerce_coupon_is_valid', 'coupon_validation_quantity', 10, 2);
function coupon_validation_quantity($valid, $coupon) {
global $wpdb;
global $woocommerce;
global $product_items_in_cart;
$product_id = 493;
$product_items_in_cart = 0;
foreach ( WC()->cart->get_cart() as $cart_item ) {
$cart_product_id = $cart_item['product_id'];
if($cart_product_id == $product_id){
$product_items_in_cart++;
};
};
global $product_items_in_cart;
global $cart_coupon_code;
global $cart_coupon_count;
global $cart_coupon_limit;
global $cart_coupon_available;
$applied_coupons_code = WC()->cart->get_applied_coupons();
$coupon_in_cart = new WC_Coupon($applied_coupons_code);
$cart_coupon_code = $coupon_in_cart->get_code();
$cart_coupon_count = $coupon_in_cart->get_usage_count();
$cart_coupon_limit = $coupon_in_cart->get_usage_limit();
$cart_coupon_available = ($cart_coupon_limit - $cart_coupon_count);
print_r('products in cart -> ' . $product_items_in_cart . "\r\n"); // return correct
print_r('available -> ' . $cart_coupon_available . "\r\n"); // returns zero
if($product_items_in_cart > $cart_coupon_available){
$valid = false;
};
return $valid;
}
Coupon Error Handling
add_filter( 'woocommerce_coupon_error', 'coupon_validation_error_quantity', 10, 3);
function coupon_validation_error_quantity($err, $err_code, $coupon) {
global $wpdb;
global $woocommerce;
global $product_items_in_cart;
global $cart_coupon_available;
print_r('products in cart -> ' . $product_items_in_cart . "\r\n"); // returns correctly
print_r('available -> ' . $cart_coupon_available . "\r\n"); // returns Zero
if($product_items_in_cart > $cart_coupon_available && intval($err_code) === WC_COUPON::E_WC_COUPON_INVALID_FILTERED){
$err = __( "Coupon $cart_coupon_code exceeds available usage. You have $cart_coupon_available available ", "woocommerce" );
};
return $err;
}

Using json API pull to store in file or database

I am trying to pull data from the justin.tv API and store the echo I get in the below code in to a database or a file to be included in the sidebar of website. I am not sure on how to do this. The example of what I am trying to achieve is the live streamers list on the sidebar of teamliquid.net. Which I have done but doing it the way I have done it slows the site way down because it does about 50 json requests every time the page loads. I just need to get this in to a cached file that updates every 60 seconds or so. Any ideas?
<?php
$json_file = file_get_contents("http://api.justin.tv/api/stream/list.json?channel=colcatz");
$json_array = json_decode($json_file, true);
if ($json_array[0]['name'] == 'live_user_colcatz') echo 'coL.CatZ Live<br>';
$json_file = file_get_contents("http://api.justin.tv/api/stream/list.json?channel=coldrewbie");
$json_array = json_decode($json_file, true);
if ($json_array[0]['name'] == 'live_user_coldrewbie') echo 'coL.drewbie Live<br>';
?>
I'm not entirely sure how you would imagine this being cached, but the code below is an adaption of a block of code I've used in the past for some Twitter work. There are a few things that could probably be done better from a security perspective. Anyway, this gives you a generic way of grabbing the Feed, parsing through it, and then sending it to the database.
Warning: This assumes that there is a database connection already established within your own system.
(* Make sure you scroll to the bottom of the code window *)
/**
* Class SM
*
* Define a generic wrapper class with some system
* wide functionality. In this case we'll give it
* the ability to fetch a social media feed from
* another server for parsing and possibly caching.
*
*/
class SM {
private $api, $init, $url;
public function fetch_page_contents ($url) {
$init = curl_init();
try {
curl_setopt($init, CURLOPT_URL, $url);
curl_setopt($init, CURLOPT_HEADER, 0);
curl_setopt($init, CURLOPT_RETURNTRANSFER, 1);
} catch (Exception $e) {
error_log($e->getMessage());
}
$output = curl_exec($init);
curl_close($init);
return $output;
}
}
/**
* Class JustinTV
*
* Define a specific site wrapper for getting the
* timeline for a specific user from the JustinTV
* website. Optionally you can return the code as
* a JSON string or as a decoded PHP array with the
* $api_decode argument in the get_timeline function.
*
*/
class JustinTV extends SM {
private $timeline_document,
$api_user,
$api_format,
$api_url;
public function get_timeline ($api_user, $api_decode = 1, $api_format = 'json', $api_url = 'http://api.justin.tv/api/stream/list') {
$timeline_document = $api_url . '.' . $api_format . '?channel=' . $api_user;
$SM_init = new SM();
$decoded_json = json_decode($SM_init->fetch_page_contents($timeline_document));
// Make sure that our JSON is really JSON
if ($decoded_json === null && json_last_error() !== JSON_ERROR_NONE) {
error_log('Badly formed, dangerous, or altered JSON string detected. Exiting program.');
}
if ($api_decode == 1) {
return $decoded_json;
}
return $SM_init->fetch_page_contents($timeline_document);
}
}
/**
* Instantiation of the class
*
* Instantiate our JustinTV class, fetch a user timeline
* from JustinTV for the user colcatz. The loop through
* the results and enter each of the individual results
* into a database table called cache_sm_justintv.
*
*/
$SM_JustinTV = new JustinTV();
$user_timeline = $SM_JustinTV->get_timeline('colcatz');
foreach ($user_timeline AS $entry) {
// Here you could check whether the entry already exists in the system before you cache it, thus reducing duplicate ID's
$date = date('U');
$query = sprintf("INSERT INTO `cache_sm_justintv` (`id`, `cache_content`, `date`) VALUES (%d, '%s', )", $entry->id, $entry, $date);
$result = mysql_query($query);
// Do some other stuff and then close the MySQL Connection when your done
}

PHP + MySQL profiler

You know how vBulletin has a sql profiler when in debug mode? How would I go about building one for my own web application? It's built in procedural PHP.
Thanks.
http://dev.mysql.com/tech-resources/articles/using-new-query-profiler.html
The above link links how you can get al the sql profile information after any query.
Best way to implement it is to create a database class and have it have a "profile" flag to turn on logging of queries and the appropriate information as shown int he link above.
Example:
Class dbthing{
var $profile = false;
function __construct($profile = false){
if($profile){
$this->query('set profiling=1');
$this->profile = true;
}
...
}
function query($sql, $profile_this == false){
...
if($this->profile && !$profile_this)
$this->query("select sum(duration) as qtime from information_schema.profiling where query_id=1", true);
... // store the timing here
}
}
I use a database connection wrapper that I can place a profiling wrapper arround. This way I can discard the wrapper, or change it, without changing my base connector class.
class dbcon {
function query( $q ) {}
}
class profiled_dbcon()
{
private $dbcon;
private $thresh;
function __construct( dbcon $d, $thresh=false )
{
$this->dbcon = $d;
$this->thresh = $thresh;
}
function queury( $q )
{
$begin = microtime( true );
$result = this->dbcon->query();
$end = microtime( true );
if( $this->thresh && ($end - $begin) >= $this->thresh ) error_log( ... );
return $result;
}
}
For profiling with a 10 second threshold:
$dbc = new profiled_dbcon( new dbcon(), 10 );
I have it use error_log() what the times were. I would not log query performance back to the database server, that affects the database server performance. You'd rather have your web-heads absorb that impact.
Though late, Open PHP MyProfiler would help you achieve this, and you can extract functional sections from the code for your usage.

New Background Image on each page reload

How can I display a new background image on each page refresh on a website (using Wordpress if this helps anything)? I would also like to take into account different screen resolutions, and proper handling for this. Any help would be greatly appreciated.
Have you seen this page in the wordpress codex?
It explains how to rotate the header image. It shouldn't be too hard adapt it for your needs.
Just have your own script that randomly returns pictures each time it is accessed. I have one that I wrote in C at the URL below that returns a different pic each time.
http://www.scale18.com/cgi-bin/gpic
You can generate it in realtime with GD library
To detect screen resolution, you can use client-side javascript
screen.height
screen.width
To display a different image, you could probably use a script to generate a random number and display the image that ties to it...?
You could store the "current" imaage in the session and just check each time you generate a new random number, that it's not going to display the last....
This is what I use with Wordpress to randomly rotate the header images on my site.
Someone else wrote the code and I can't remember who. Put the php code below into a file named rotate.php, and then put rotate.php into the directory of images that are to be rotated (i.e. "headerimages"), and rotate.php will draw from them. Call rotate.php from your CSS style sheet in whatever DIV is used for your headerimage.
I don't understand what you mean by being able to handle different screen resolutions. End user screen resolutions?
<?php
/*
Call this way: <img src="http://example.com/rotate.php">
Set $folder to the full path to the location of your images.
For example: $folder = '/user/me/example.com/images/';
If the rotate.php file will be in the same folder as your
images then you should leave it set to $folder = '.';
*/
$folder = '.';
$extList = array();
$extList['gif'] = 'image/gif';
$extList['jpg'] = 'image/jpeg';
$extList['jpeg'] = 'image/jpeg';
$extList['png'] = 'image/png';
$img = null;
if (substr($folder,-1) != '/') {
$folder = $folder.'/';
}
if (isset($_GET['img'])) {
$imageInfo = pathinfo($_GET['img']);
if (
isset( $extList[ strtolower( $imageInfo['extension'] ) ] ) &&
file_exists( $folder.$imageInfo['basename'] )
) {
$img = $folder.$imageInfo['basename'];
}
} else {
$fileList = array();
$handle = opendir($folder);
while ( false !== ( $file = readdir($handle) ) ) {
$file_info = pathinfo($file);
if (
isset( $extList[ strtolower( $file_info['extension'] ) ] )
) {
$fileList[] = $file;
}
}
closedir($handle);
if (count($fileList) > 0) {
$imageNumber = time() % count($fileList);
$img = $folder.$fileList[$imageNumber];
}
}
if ($img!=null) {
$imageInfo = pathinfo($img);
$contentType = 'Content-type: '.$extList[ $imageInfo['extension'] ];
header ($contentType);
readfile($img);
} else {
if ( function_exists('imagecreate') ) {
header ("Content-type: image/png");
$im = #imagecreate (100, 100)
or die ("Cannot initialize new GD image stream");
$background_color = imagecolorallocate ($im, 255, 255, 255);
$text_color = imagecolorallocate ($im, 0,0,0);
imagestring ($im, 2, 5, 5, "IMAGE ERROR", $text_color);
imagepng ($im);
imagedestroy($im);
}
}
?>
JavaScript is probably your best bet for this one.