codeigniter3 : Listing all directory and files from azure blob storage? - codeigniter-3

I have account name, account key and other necessary information of azure blob storage for connect to azure blob storage. I want to list all directories and files from azure blob storage. I searched and found links but not understanding that how to integrate from start in CodeIgniter.
I search this library https://github.com/Azure/azure-sdk-for-php#readme
Can someone provide me link or tell me how to integrate in codeigniter from start?

If you want to list blobs under a container or some directory by cURL, just try the code below:
<?php
function generateSharedAccessSignature($accountName,
$storageKey,
$signedPermissions,
$signedService,
$signedResourceType,
$signedStart,
$signedExpiry,
$signedIP,
$signedProtocol,
$signedVersion){
if(empty($accountName)){
trigger_error("The account name is required.");
return;
}
if(empty($storageKey)){
trigger_error("The account key is required.");
return;
}
if(empty($signedPermissions)){
trigger_error("The permissions are required.");
return;
}
if(empty($signedService)){
trigger_error("The services are required.");
return;
}
if(empty($signedResourceType)){
trigger_error("The resource types are required.");
return;
}
if(empty($signedExpiry)){
trigger_error("The expiration time is required.");
return;
}
if(empty($signedVersion)){
trigger_error("The service version is required.");
return;
}
// generate the string to sign
$_toSign = urldecode($accountName) . "\n" .
urldecode($signedPermissions) . "\n" .
urldecode($signedService) . "\n" .
urldecode($signedResourceType) . "\n" .
urldecode($signedStart) . "\n" .
urldecode($signedExpiry) . "\n" .
urldecode($signedIP) . "\n" .
urldecode($signedProtocol) . "\n" .
urldecode($signedVersion) . "\n";
// sign the string using hmac sha256 and get a base64 encoded version_compare
$_signature = base64_encode(hash_hmac("sha256", utf8_encode($_toSign), base64_decode($storageKey), true));
return $_signature;
}
$key= "";
$storageAccount = "";
$containerName = "";
$directoryName = ""; //leave it empty if list all blobs in container
$_signedPermissions = "rl"; //read and list permission
$_signedService = "b"; // for blob service
$_signedResourceType = "c"; //only for access container
$_signedStart = "2021-05-31T00:00:00Z"; //sas token start time
$_signedExpiry = "2021-06-05T00:00:00Z"; //sas token expairy time
$_signedIP = NULL; // no IP limit
$_signedProtocol = "https";
$_signedVersion = "2020-02-10";
$_signature = generateSharedAccessSignature($storageAccount,
$key,
$_signedPermissions,
$_signedService,
$_signedResourceType,
$_signedStart,
$_signedExpiry,
$_signedIP,
$_signedProtocol,
$_signedVersion);
$sig = urlencode($_signature);
$destinationURL = "https://$storageAccount.blob.core.windows.net/$containerName?restype=container&comp=list&prefix=$directoryName&sp=$_signedPermissions&srt=$_signedResourceType&ss=$_signedService&st=$_signedStart&se=$_signedExpiry&sv=$_signedVersion&spr=$_signedProtocol&sig=$sig";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $destinationURL);
$content = curl_exec($ch);
echo $content;
?>
Result:

Consider reading this example https://learn.microsoft.com/en-us/azure/storage/blobs/storage-upload-process-images?tabs=dotnet it is quite informative and should be able to helo you , incase you have any further questions i will be happy to assist you

Here is an link about codeigniter-azure, you can take a look at it.
There is also an SO issue about it.

Related

Zend Calendar Zend_Gdata_App_HttpException' with message 'Expected response code 200, got 401

I want inteface this script with google calendar using Zend Framework.
This code works locally but doesn't works on altervista.
The error is
Fatal error: Uncaught exception 'Zend_Gdata_App_HttpException' with
message 'Expected response code 200, got 401
<?php
require_once "Zend/Loader.php";
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Calendar');
$user = "xxx#gmail.com";
$pass = "xxxxx";
$title= "Evento ";
$content="evento presso nome associaizone";
$where="luogo";
$service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
try {
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, 'cl');
} catch (Zend_Gdata_App_CaptchaRequiredException $cre) {
echo 'URL of CAPTCHA image: ' . $cre->getCaptchaUrl() . "\n";
echo 'Token ID: ' . $cre->getCaptchaToken() . "\n";
} catch (Zend_Gdata_App_AuthException $ae) {
echo 'Problem authenticating: ' . $ae->exception() . "\n";
}
$service = new Zend_Gdata_Calendar($client);
//
// Create a new entry using the calendar service's magic factory method
$event= $service->newEventEntry();
// Populate the event with the desired information
// Note that each attribute is crated as an instance of a matching class
$event->title = $service->newTitle($title);
$event->content= $service->newContent($content);
$event->where = array($service->newWhere($where));
// Set the date using RFC 3339 format.
$startDate = "2014-03-18";
$startTime = "14:00";
$endDate = "2014-03-19";
$endTime = "16:00";
$tzOffset = "-08";
$when = $service->newWhen();
$when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
$when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
$event->when = array($when);
// Upload the event to the calendar server
// A copy of the event as it is recorded on the server is returned
$newEvent = $service->insertEvent($event);
?>
Zend_Gdata and ZendGData are out of maintenance.
Instead the recomendation is migrate to the official Google SDK https://code.google.com/p/google-api-php-client/

Extract facebook data from access token

I'm trying to use this site https://www.oneall.com/ to add social login to a test site. After setting up the code and the login I still don't know how to extract user data from access token. Here's the link I get:
http://MYACCOUNT.api.oneall.com/socialize/redirect.html?provider_connection_token=ACCESS TOKEN HERE
I get this code by the call back page like this
if ( ! empty ($_POST['connection_token']))
{
echo "Connection token received: ".$_POST['connection_token'];
}
else
{
echo "No connection token received";
}
if ( ! empty ($_POST['connection_token']))
{
$token = $_POST['connection_token'];
$site_subdomain = 'myaccountname';
$site_public_key = 'public key';
$site_private_key = 'private key';
$site_domain = $site_subdomain.'.api.oneall.com';
$resource_uri = 'https://'.$site_domain.'/connections/'.$token .'.json';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $resource_uri);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_USERPWD, $site_public_key . ":" . $site_private_key);
curl_setopt($curl, CURLOPT_TIMEOUT, 15);
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($curl, CURLOPT_FAILONERROR, 0);
$result_json = curl_exec($curl);
if ($result_json === false)
{
echo 'Curl error: ' . curl_error($curl). '<br />';
echo 'Curl info: ' . curl_getinfo($curl). '<br />';
curl_close($curl);
}
else
{
curl_close($curl);
$json = json_decode ($result_json);
$data = $json->response->result->data;
if ($data->plugin->key == 'social_login')
{
if ($data->plugin->data->status == 'success')
{
$user_token = $data->user->user_token;
$user_id = GetUserIdForUserToken($user_token);
if ($user_id === null)
{
LinkUserTokenToUserId ($user_token, $user_id);
}
else
{
}
}
}
}
}
I need to learn how to extract data now and a little example about extracting the user name by this code.
You can use the access token to get the connection details from oneall using their api
You use the connection_token to get the connection details (including
the user's Facebook profile data).
example
http://MYACCOUNT.api.oneall.com/connections/ACCESS TOKEN HERE.json -->>for json formatted data
oneall docs
Once you get the user's token, you then need to make a API call to Facebook, e.g. https://graph.facebook.com/me/?access_token={$access_token}
If the $access_token is correct, Facebook should return the user's details, including name, username and any other details you've asked for.

cURL throws an exception at Facebook API SDK

I'm trying to post an image as the user from my Facebook application.
Currently, this feature is still under development, and when I'm trying to test it using WAMP server on localhost, one of the cURL functions in the Facebook API SDK class, throws an exception error:
{"error_code":60,"error":{"message":"SSL certificate problem, verify
that the CA cert is OK. Details:\nerror:14090086:SSL
routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify
failed","type":"CurlException"}}null0.90752005577087
145684992172054|e259ec293812a5276a61d3181c395077
I have checked, and I have the correct settings at php.ini both at the Apache and PHP directories.
I tried to run this Both on Easy PHP with PHP 5.4 and on WAMP with PHP 5.3. (cURL extension enabled).
I have open SSL installed on both of the local servers.
I understand that you can solve this by changing the configuration of the CURL_opt, but modifying a Facebook base class, and compromising the security of my application (middle man attack), is really a last resort for me.
Thanks in advance for any help!.
My code:
test.php:
<?php
session_start();
require 'FB_auth.php';
require 'includes.php';
require 'functions_fb.php';
$start = (float) array_sum(explode(' ',microtime()));
//echo json_encode(photoToFacebook(299, 402, 134));
// echo json_encode(photoToFacebook(724, 402, 165));
// postToFacebook($db, 402, 134);
$end = (float) array_sum(explode(' ',microtime()));
$duration = ($end-$start);
echo $duration;
echo "<br/>" . $facebook->getAccessToken();
?>
functions_fb.php
<?php
function photoToFacebook($hr_id, $user_id, $job_id){
global $db, $FEED_PATH, $JOB_IMAGES_FOLDER , $facebook;
$path = $_SERVER['DOCUMENT_ROOT'] . "/";
$JOB_IMAGES_FOLDER = "images/job_images/";
$company = $db->getCompany($hr_id);
// perapre the job photo.
$photo = $db->getJobPhoto($job_id);
if (empty($photo)){
$photo = $db->getLogo($hr_id);
}
else{
$photo = $JOB_IMAGES_FOLDER . $photo;
}
try{
// At the time of writing it is necessary to enable upload support in the Facebook SDK, you do this with the line:
$facebook->setFileUploadSupport(true);
// Get album id if exists.
$album_uid = $db->getAlbumId($user_id);
$fb_user_id = $db->getFBUserId($user_id);
if (empty($album_uid)){
// Create an album
$album_details = array(
'message'=> 'Check out my company\'s job opportunities',
'name'=> "Job opportunities at {$company}"
);
$create_album = $facebook->api("/{$fb_user_id}/albums", 'post', $album_details);
echo json_encode($create_album);
$album_uid = $create_album["id"];
$db->saveAlbumId($user_id, $create_album["id"]);
}
$job_title = $db->getJobTitle($job_id);
$link = Bitly::make_bitly_url($FEED_PATH . "show_job.php?jid={$job_id}&th_uid={$user_id}&tp=1&pc=1", BITLY_APP_USERNAME,BITLY_APP_KEY,'json');
$photo_details = array(
'message'=> $job_title . "!\n" . $company . " is looking for you.\nOpen the link for details and apply.\n" . $link
);
$path .= $photo;
$photo_details['image'] = '#' . $path; //realpath($file);
// echo $album_uid;
$upload_photo = $facebook->api("{$fb_user_id}/photos", 'post', $photo_details);
// $db->updateAutoPostActivity($user_id, $job_id,1, json_encode($upload_photo));
// $db->updateAutoPostJob($job_id, $user_id);
return $upload_photo;
}
catch (FacebookApiException $e) {
echo "error:" . json_encode($e->getResult());
// $db->updateAutoPostActivity($user_id, $job_id,1, json_encode($e->getResult()));
// AtavMail::SendRichedMail(null , "", "Error on auto process - posting photo to FB", "Where - Job Id: {$job_id} , User Id: {$user_id}", json_encode($e->getResult()));
}
}
?>
I solved this by adding the following line into the base_facebook.php file:
public static $CURL_OPTS = array(
//
//
//
CURLOPT_SSL_VERIFYPEER => false,
);
Please notice that this is an development - environment solution only, and using this on your actual application can cause a security risk.
Please take the time to review the fullp proper solution on this link:
http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/
Setting SSL verification to false defeats the purpose of SSL.
A proper solution is to set the CA certs for CURL.
Solution 1 (Changes to PHP.ini):
Download CA bundle (cacert.pem) from http://curl.haxx.se/docs/caextract.html
Place it on your local system (for eg: C:\xampp\cacert.pem)
Open your php.ini
Set the curl.ca_info options to point to the location of the cacert.pem
Example: curl.ca_info="C:\xampp\cacert.pem"
Restart Apache
Solution 2 (Set options before each CURL call)
Download CA bundle (cacert.pem) from http://curl.haxx.se/docs/caextract.html
Place it on your local system (for eg: C:\xampp\cacert.pem)
Write the following code:
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt ($ch, CURLOPT_CAINFO, "pathto\cacert.pem");
Source: http://tumblr.wehavefaces.net/post/52114563111/environment-windows-xampp-curl-library

Read Facebook page post and token expiration

I need to read, from a server, the stream of a specific fan page.
I tried to read the graph api
https://graph.facebook.com//feed?access_token=&limit=100
and it works.
What I need is to understand if the token will expire and how to renew it programmatically.
Now I generate my token through the http://developers.facebook.com/tools/explorer/ app.
Can you please help me?
I'm using the PHP sdk
thanks,
a.
You can read the facebook page using below codes and you can also get the specified fields
https://graph.facebook.com/$page_id/?fields=link,etc&access_token=page_access_token
or
$response = $fb->api($page_id . '/?fields=link,etc&'. $access_token, 'GET')
Below is the solution for four scenarios
1.The token expires after expires time (2 hours is the default).
2.The user changes her password which invalidates the access token.
3.The user de-authorizes your app.
4.The user logs out of Facebook.
To ensure the best experience for your users, your app needs to be prepared to catch errors for the above scenarios. The following PHP code shows you how to handle these errors and retrieve a new access token.
When you redirect the user to the auth dialog, the user is not prompted for permissions if the user has already authorized your application. Facebook will return you a valid access token without any user facing dialog. However if the user has de-authorized your application then the user will need to re-authorize your application for you to get the access_token.
<?php
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$my_url = "YOUR_POST_LOGIN_URL";
// known valid access token stored in a database
$access_token = "YOUR_STORED_ACCESS_TOKEN";
$code = $_REQUEST["code"];
// If we get a code, it means that we have re-authed the user
//and can get a valid access_token.
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}
// Attempt to query the graph:
$graph_url = "https://graph.facebook.com/me?"
. "access_token=" . $access_token;
$response = curl_get_file_contents($graph_url);
$decoded_response = json_decode($response);
//Check for errors
if ($decoded_response->error) {
// check to see if this is an oAuth error:
if ($decoded_response->error->type== "OAuthException") {
// Retrieving a valid access token.
$dialog_url= "https://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode($my_url);
echo("<script> top.location.href='" . $dialog_url
. "'</script>");
}
else {
echo "other error has happened";
}
}
else {
// success
echo("success" . $decoded_response->name);
echo($access_token);
}
// note this wrapper function exists in order to circumvent PHP’s
//strict obeying of HTTP error codes. In this case, Facebook
//returns error code 400 which PHP obeys and wipes out
//the response.
function curl_get_file_contents($URL) {
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
$err = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}
?>
for more details info you can visit this link
Thanks

Graph API: How to grab current user's information?

I'm trying to get some basic information about a user in a PHP script (id and name).
I have tried the following methods:
$retrieve = curl_init("https://graph.facebook.com/me?access_token=$accesstoken");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($retrieve, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($retrieve);
curl_close($retrieve);
and
$user = json_decode(file_get_contents(
"https://graph.facebook.com/me?access_token=$accesstoken"))->me;
The cURL method (former) just times out. The file_get_contents (latter) method just doesn't return anything at all...
What could be causing this? Am I using cURL correctly?
for graph api you can use graph api methods rahter than curl
the following code grabs information of current user
define('FACEBOOK_APP_ID', 'Your API ID');
define('FACEBOOK_SECRET', 'YOUR SECRET');
function get_facebook_cookie($app_id, $application_secret)
{
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value)
{
if ($key != 'sig')
{
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig'])
{
return null;
}
return $args;
}
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
$user=json_decode(file_get_contents('https://graph.facebook.com/me?access_token='.$cookie['access_token']));
its prettey easy
Facebook will not let you use curl. They have the api for that.
copy your link and paste it to browser. It will work. In Mozilla you will see the result in browser, IE will save the result as a file. So it is not about invalid access token etc. It is just because Facebook does not respond to your query when it does not come 1-from a web browser, 2-from Facebook APIs.
here is the relevant PHP call to Facebook.
$attachment = array('access_token' => $access_token);
$result=$facebook->api('/me', 'GET', $attachment);
$id = $result['id'];
$name=$result['name'];