I'm using this php class for box.com
https://github.com/golchha21/BoxPHPAPI
I have made my own function to share a folder like this
public function share_folder($folder_id) {
$url = $this->build_url("/folders/".$folder_id);
$params = array('shared_link' => array('access' => 'open', 'permissions' =>
array('can_download' => 'true', 'can_preview' => 'true')));
return json_decode($this->post($url, json_encode($params)), true);
}
I'm having the same issue as this post.
Access denied error message when trying to create a shared link to a folder in Box
Does anyone have a fix for this or know why it's happening?
Update
I figured it out:
public function share_folder($folder_id) {
$url = $this->build_url("/folders/".$folder_id);
$params = array('shared_link' => array('access' => 'open', 'permissions' =>
array('can_download' => true, 'can_preview' => true)));
return json_decode($this->put($url, $params), true);
I have to change it to put and take off the json_encode
Hope this help someone else
The API is now updated with the sharing function.
<?php
include('library/BoxAPI.class.php');
$client_id = 'CLIENT ID';
$client_secret = 'CLIENT SECRET';
$redirect_uri = 'REDIRECT URL';
$box = new Box_API($client_id, $client_secret, $redirect_uri);
if(!$box->load_token()){
if(isset($_GET['code'])){
$token = $box->get_token($_GET['code'], true);
if($box->write_token($token, 'file')){
$box->load_token();
}
} else {
$box->get_code();
}
}
// Share folder
$params['shared_link']['access'] = 'ACCESS TYPE'; //open|company|collaborators
print_r($box->share_folder('FOLDER ID', $params));
// Share file
$params['shared_link']['access'] = 'ACCESS TYPE'; //open|company|collaborators
print_r($box->share_file('File ID', $params);
?>
Have a look here
Download: BoxPHPAPI
Related
I'm trying to create a copy of a document using the Google Docs Api, and then edit it that copy by inserting text into it. So, I've looked at the documentation and seemingly implemented it exactly the way it says.
<?php
//That is, if this is just a regular login
//Personal Files
require("loginManager.php");
require("globals.php");
require("googleDrive.php");
//Moodle files
require("../config.php");
require("../my/lib.php");
require("../files/renderer.php");
require("../course/lib.php");
//Google Docs
$CREDENTIALS_PATH = "../../" . "vendor/autoload.php";
require ($CREDENTIALS_PATH);
//Example code
$copyTitle = 'Copy Title';
$documentId = "1vYyeGLbadFi0sl9g2LEJSZCB4YiGOpCb";
$copy = new Google_Service_Drive_DriveFile(array(
'name' => $copyTitle
));
//Initialize necessary client variables
$desiredPath = "../../credentials.json";
$authCode = (isset($_GET["code"]) ? $_GET["code"]:"");
GoogleDrive::setAuthCode($authCode);
$client = GoogleDrive::getClient($desiredPath, $FULLSCRIPT);
$docServices = new Google_Service_Docs($client);
$driveServices = new Google_Service_Drive($client);
$files = $driveServices->files;
$documents = $docServices->documents;
$driveResponse = $files->copy($documentId, $copy);
$documentCopyId = $driveResponse->id;
//Create desiredRequests
$desiredRequests = array(new Google_Service_Docs_Request(array(
'insertText' => array(
'text' => 'Hello world!',
'location' => array(
'index' => 25)))));
$batchUpdateRequests = new Google_Service_Docs_BatchUpdateDocumentRequest(array(
'requests' => $desiredRequests));
$docChangeResponse = $documents->batchUpdate($documentCopyId, $batchUpdateRequests);
echo $OUTPUT->header();
echo $OUTPUT->custom_block_region('content');
echo $OUTPUT->footer();
//Check if there's any get actions that need to be serviced
$getVariable = filter_input(INPUT_GET, "action");
if($getVariable == "openFileManager") {core_files_renderer::render_form_filemanager();}
else if($getVariable == "createCourse")
{
/*Important note: there are two types of ids when it comes to courses
*
* Programmer's Notes:
*
* -$instance is the instance of a record of from the enrol table
* -the enrol table stores instances of courses...so does mdl_course
* -idnumber and id, the latter is the actual primary key, the other is
* I guess is for school admins or course creators to be able to number
* the courses according to their own system. idnumber can be null.
*
*/
$enrollmentPlugin = enrol_get_plugin("manual");
if($enrollmentPlugin)
{
//Create data for course_request
$data = new stdClass();
$data->requester = $USER->id;
$data->id = 1;
$course_request_object = new course_request($data);
unset($data);
//create data for new course
$data = new stdClass();
$data->fullname = 'Math';
$data->shortname = 'Math 7';
$data->summary = 'Awesome!';
$data->summaryformat = FORMAT_PLAIN;
$data->format = 'topics';
$data->newsitems = 0;
$data->numsections = 5;
//$data->category = $course_request_object->get_category();
$data->category = 1;
$course = create_course($data);
//Instance is the record from the enrol table
$instanceid = $enrollmentPlugin->add_instance($course);
$instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'), '*', MUST_EXIST);
$enrollmentPlugin->enrol_user($instance, $USER->id);
}
}
else if($getVariable == "appendDocument")
{
$courseID = filter_input(INPUT_GET, "courseID");
$fs = get_file_storage();
$data = array(
'contextid' => $courseID, // ID of context
'component' => 'course_myarea', // usually = table name
'filearea' => 'myarea', // usually = table name
'itemid' => 0, // usually = ID of row in table
'filepath' => '/', // any path beginning and ending in /
'filename' => 'myfile.txt'
);
$content = "hellp worldl";
$fs->create_file_from_string($data, $content);
}
else if($getvariable == null)
{
//if there are no get paramaters then it's a first time entry
//get all of user's courses, files, etc
$courses = enrol_get_all_users_courses($USER->id);
global $DB;
foreach($courses as $currentCourse)
{
$desiredID = $currentCourse->id;
$desiredFiles = $DB->get_record('files', array('contextid'=> $desiredID));
$contentHash = $desiredFiles->contenthash;
$dir1 = substr($contentHash, 0, 2); $dir2 = substr($contentHash, 2, 2);
$desiredPath = $CFG->dirrot."../../../../moodledata/filedir/"
.$dir1."/".$dir2."/".$contentHash;
$myFile = file_get_contents($desiredPath);
$type = mime_content_type($desiredPath);
$contentTypes = array("pdf" => "application/pdf",
"txt" => "text/plain");
//header("Content-Type: application/pdf");
//readfile($desiredPath, false, $foo);
$myFile = file_get_contents("goedel.pdf");
$foo = 3;
}
}
?>
Here's where GoogleDrive::getClient is defined in case it helps
class GoogleDrive
{
private static $AUTH_CODE;
public static function setAuthCode($desiredCode)
{
self::$AUTH_CODE = $desiredCode;
}
public static function getClient($credentialsPath, $callbackScript)
{
$client = new Google_Client();
$client->setApplicationName('MyApp');
$client->setScopes(Google_Service_Drive::DRIVE);
$client->setAuthConfig($credentialsPath);
$client->setAccessType('online');
$client->setPrompt('select_account consent');
$desiredVariable = self::$AUTH_CODE;
if($desiredVariable != null)
{
$accessToken = $client->fetchAccessTokenWithAuthCode($desiredVariable);
$client->setAccessToken($accessToken);
return $client;
}
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
$client->setRedirectUri($callbackScript);
redirect($authUrl);
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
}
However, when I run the previous code I get this error.
"{
"error": {
"code": 400,
"message": "This operation is not supported for this document",
"errors": [
{
"message": "This operation is not supported for this document",
"domain": "global",
"reason": "failedPrecondition"
}
],
"status": "FAILED_PRECONDITION"
}
}
"
Any help or direction will be greatly appreciated.
Edit 1: I've changed the script to reflect Tanaike's solution
I believe your situation and goal as follows.
You have already been able to use Google Docs API.
The script of a copy of a document worked.
You want to remove the error in your question.
For this, how about this modification?
From:
$desiredRequests = new Google_Service_Docs_Request(array(
'insertText' => array(
'text' => 'Hello world!',
'location' => array(
'index' => 25))));
In your script, when $batchUpdateRequests is retrieved, it becomes as follows.
{"requests":{"createNamedRangeType":{},"createNamedRangeDataType":{},"createParagraphBulletsType":{},"createParagraphBulletsDataType":{},"deleteContentRangeType":{},"deleteContentRangeDataType":{},"deleteNamedRangeType":{},"deleteNamedRangeDataType":{},"deleteParagraphBulletsType":{},"deleteParagraphBulletsDataType":{},"deletePositionedObjectType":{},"deletePositionedObjectDataType":{},"deleteTableColumnType":{},"deleteTableColumnDataType":{},"deleteTableRowType":{},"deleteTableRowDataType":{},"insertInlineImageType":{},"insertInlineImageDataType":{},"insertTableRowType":{},"insertTableRowDataType":{},"insertTextType":{},"insertTextDataType":{},"replaceAllTextType":{},"replaceAllTextDataType":{},"updateParagraphStyleType":{},"updateParagraphStyleDataType":{},"updateTextStyleType":{},"updateTextStyleDataType":{},"internal_gapi_mappings":{},"modelData":{},"processed":{},"insertText":{}}}
I think that this is the reason of your issue.
To:
$desiredRequests = array(new Google_Service_Docs_Request(array(
'insertText' => array(
'text' => 'Hello world!',
'location' => array(
'index' => 25)))));
In this modified script, when $batchUpdateRequests is retrieved, it becomes as follows.
{"requests":[{"insertText":{"text":"Hello world!","location":{"index":25,"segmentId":null}}}]}
In this request body, I could confirm that it worked.
Note:
If an error like Invalid requests[0].insertText: Index 25 must be less than the end index of the referenced segment occurs, please modify 'index' => 25 to 'index' => 1.
Reference:
Method: documents.batchUpdate
I am trying to create a Facebook-Login in my Laravel application. However, the array I get with all the user information does not contain the users email even though I already ask for permission to receive the email.
This is my code:
Route::get('login/fb', function() {
$facebook = new Facebook(Config::get('facebook'));
$params = array(
'redirect_uri' => url('/login/fb/callback'),
'scope' => 'email',
);
return Redirect::to($facebook->getLoginUrl($params));
});
Route::get('login/fb/callback', function() {
$code = Input::get('code');
if (strlen($code) == 0) return Redirect::to('/')->with('message', 'There was an error communicating with Facebook');
$facebook = new Facebook(Config::get('facebook'));
$me = $facebook->api('/me');
return $me;
Returning $me gives me all the important user information besides the email address.
Is there any way to fix this?
Any help would be much appreciated.
Thanks.
There are instances that facebook will not return an email. This can be because the user has not set a primary email, or their email has not been validated. In this case, your logic should check to see if an email was returned, if not, use their facebook email. FacebookUsername#facebook.com
//I used with sentry
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from facebook, get the token
$token = $fb->requestAccessToken( $code );
// Send a request with it
$result = json_decode($fb->request( '/me?fields=id,name,first_name,last_name,email,photos' ), true);
$message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name']. $result['email'];
//echo $message. "<br/>";
//Var_dump
//display whole array().
//echo('http://graph.facebook.com/'.$result['id'].'/picture?type=large<br>');
//dd($result);
$user = \User::where("email",$result['email'])->first();
if($user!=NULL){
$userxx = Sentry::findUserByLogin($result['email']);
Sentry::login($userxx, false);
return Redirect::to('Beşiktaş');
}
else
{
$k=str_random(8);
$user = Sentry::register(array(
'activated' => 1,
'facebook' => 1,
'password' => $k,
'email' => $result['email'],
'first_name' =>$result['first_name'],
'last_name' => $result['last_name'] ,
'avatar' => 'http://graph.facebook.com/'.$result['id'].'/picture?type=large',
));
Sentry::login($user, false);
return Redirect::to('Beşiktaş');
}
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
return Redirect::to( (string)$url );
}
I have a job site where 100 jobs posting daily. i also have a Facebook page. i want to post 10 jobs each hour to My Facebook page with cron jobs.
I am using the following code to post to Facebook face by accessing the URL Manually.
<?php
require_once 'facebook_sdk/src/facebook.php';
// configuration
$appid = 'xxxxxxx';
$appsecret = 'xxxxxxx';
$pageId = 'xxxxx';
$msg = 'test';
$title = 'pagetitle';
$uri = 'http://google.com/';
$desc = 'description here';
$pic = 'http://google.com/test/2.png';
$action_name = 'Go to my site';
$action_link = 'http://www.google.com';
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsecret,
'cookie' => false,
));
$user = $facebook->getUser();
// Contact Facebook and get token
if ($user) {
// you're logged in, and we'll get user acces token for posting on the wall
try {
$page_info = $facebook->api("/$pageId?fields=access_token");
if (!empty($page_info['access_token'])) {
$attachment = array(
'access_token' => $page_info['access_token'],
'message' => $msg,
'name' => $title,
'link' => $uri,
'description' => $desc,
'picture'=>$pic,
'actions' => json_encode(array('name' => $action_name,'link' => $action_link))
);
$status = $facebook->api("/$pageId/feed", "post", $attachment);
} else {
$status = 'No access token recieved';
}
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
} else {
// you're not logged in, the application will try to log in to get a access token
header("Location:{$facebook->getLoginUrl(array('scope' => 'photo_upload,user_status,publish_stream,user_photos,manage_pages'))}");
}
echo $status;
?>
It working fine. but i want to post the jobs automatically with corn jobs. how can i do it.
does anyone have any advice?
Please see the codes below and edit/complete it according to yours
class Facebook
{
/**
* #var The page id to edit
*/
private $page_id = '_PAGE_ID_';
/**
* #var the page access token given to the application above
*/
private $page_access_token = '_ACCESS_TOKEN_';
/**
* #var The back-end service for page's wall
*/
private $post_url = '';
/**
* Constructor, sets the url's
*/
public function Facebook()
{
$this->post_url = 'https://graph.facebook.com/'.$this->page_id.'/feed';
}
public function renew_access()
{
$url = 'https://graph.facebook.com/oauth/access_token?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&display=popup&code=_CODE_&redirect_uri=THIS_FILE_FULL_URL'; // THIS_FILE_FULL_URL = like http://site.com/fb.post.php
// request this url to renew access token to send posts when offline. get the access_token and set self::$page_access_token = _ACCESS_TOKEN_
}
private function getcode()
{
$url = 'https://www.facebook.com/dialog/oauth?client_id=CLIENT_ID&redirect_uri=THIS_FILE_FULL_URL'; // THIS_FILE_FULL_URL = like http://site.com/fb.post.php
// request this url to get _CODE_ to send posts when offline. then get the access_token and set self::$page_access_token = _ACCESS_TOKEN_
}
private function want_to_send()
{
// check for somethings if you want to send or you don't
// for eg. check for time or any other check if sent before, or just return true to pass
return true;
}
public function message($data)
{
// need token
$data['access_token'] = $this->page_access_token;
if(!$data['properties'])
$data['properties'] = '{"TITLE":"DESC"}';
try{
if(self::want_to_send())
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$this->post_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_USERAGENT , 'facebook-php-3.1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //to suppress the curl output
$return = curl_exec($ch);
curl_close ($ch);
}
}
catch ( exception $e){
//throw new Exception($e);
// or
error_log(json_encode($data));
}
//return $return; // if you want return
}
}
$facebook = new Facebook();
// make a simple post test
$facebook->message(array( 'message' => 'The status header',
'link' => 'http://cekirdek.com.tr',
'picture' => 'http://domain.com/picture_url.png',
'name' => 'Name of the picture, shown just above it',
'description' => 'Full description explaining whether the header or the picture' ) );
I need to post on facebook fan page with app.
My post type is text+image.
When i post only text, i have no problem, but when i try to add a jpg it doesn't works.
Here's my code:
<pre>
<?php
require_once 'facebook.php';
// configuration
$appid = 'XXX';
$appsecret = 'YYY';
$pageId = 'ZZZ';
$msg = 'MSG MSG MSG';
$title = 'TITOLO TITOLO TITOLO';
$uri = 'http://www.google.it/';
$desc = 'Description';
$pic = 'http://sharefavoritebibleverses.com/images/bible_verses.png';
$action_name = 'AZIONE NOME';
$action_link = 'http://www.yahoo.it';
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsecret,
'cookie' => false,
));
$user = $facebook->getUser();
// Contact Facebook and get token
if ($user)
{
// you're logged in, and we'll get user acces token for posting on the wall
try
{
$facebook->setFileUploadSupport(true);
$page_info = $facebook->api("/$pageId?fields=access_token");
if (!empty($page_info['access_token'])) {
/*$attachment = array(
'access_token' => $page_info['access_token'],
'message' => $msg,
'name' => $title,
'picture'=>$pic
);*/
$photo_details = array(
'message' => 'message',
'access_token' => 'XYZ'
);
$photo_details['picture'] = '#'.realpath('aaa.jpg');
echo realpath('aaa.jpg');
$status = $facebook->api("/$pageId/feed", "post", $photo_details);
}
else
{
$status = 'No access token recieved';
}
}
catch (FacebookApiException $e)
{
error_log($e);
$user = null;
}
}
else
{
// you're not logged in, the application will try to log in to get a access token
header("Location:{$facebook->getLoginUrl(array('scope' => 'photo_upload,user_status,publish_stream,user_photos,manage_pages'))}");
}
echo $status;
echo "<br>CONT=".count($status);
?>
Also i need a format like second one, and not like first:
What's wrong in my code?
Thanks!
Try this:
//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);
//Create an album
$album_details = array(
'message'=> 'Album desc',
'name'=> 'Album name'
);
$create_album = $facebook->api('/me/albums', 'post', $album_details);
//Get album ID of the album you've just created
$album_uid = $create_album['id'];
//Upload a photo to album of ID...
$photo_details = array(
'message'=> 'Photo message'
);
$file='app.jpg'; //Example image file
$photo_details['image'] = '#' . realpath($file);
$upload_photo = $facebook->api('/'.$album_uid.'/photos', 'post', $photo_details);
Please try to make sure that $pic is the relative image location on your server and not a generic web url of the image.
Here is the code i used to post stories to facebook page wall from my website. i have installed facebook sdk like facebook.php and base_facebook.php etc files.My requirement is to post stories without logging into facebook.i have gone through many tutorials yet i couldnt find any solution for this .can you please help me in this.here is the code which i am using.
$appid = 'xxxxx'; //Application ID
$appsec = 'xxxxx'; // Application secret
$redirectUrl = 'http://test.com/admin/'; //Facebook redirects back to this page
$permissions = 'publish_stream'; // Permissions we will need
if(isset($_POST['FacebookPageID']) && strlen($_POST['FacebookPageID'])>10)
{
$_SESSION['FacebookPageID']=$_POST['FacebookPageID'];
$_SESSION['FacebookMessage']=$_POST['FacebookMessage'];
$_SESSION['FacebookTitle']=$_POST['FacebookTitle'];
}
if(!is_numeric($_SESSION['FacebookPageID']) || strlen($_SESSION['FacebookPageID'])<5)
{
die("<meta http-equiv=\"refresh\" content=\"2;URL=".$redirectUrl."\" />");
}
else
{
if(!isset($_GET["code"]))
{
$_SESSION['state'] = md5(uniqid(rand(), TRUE));
$RedirectToFacebook = "https://www.facebook.com/dialog/oauth?client_id=".$appid;
$RedirectToFacebook .="&redirect_uri=".urlencode($redirectUrl.'test.php');
die("<script type=\"text/javascript\">top.location.href='" . $RedirectToFacebook . </script>
<noscript><a href='".$RedirectToFacebook."'>Needs Permissioins</a></noscript>");
}
else
{
############## Facebook Page ID ############
$facebookPageID = $_SESSION['FacebookPageID'];
############## Wall Message ############
$facebookMessage = (empty($_SESSION['FacebookMessage']) || s trlen($_SESSION['FacebookMessage'])<5)?"Nice Facebook Wall Posting Script!":$_SESSION['FacebookMessage'];
$facebookTitle = (empty($_SESSION['FacebookTitle']) || strlen($_SESSION['FacebookTitle'])<5)?"Nice Facebook Wall Posting Script!":$_SESSION['FacebookTitle'];
if($_SESSION['state'] !="")
{
echo $_SESSION['state'];
// $siteurl=$_GET['realurl'];
$AccessTokenUrl = "https://graph.facebook.com/oauth/access_token?client_id=".$appid;
$AccessTokenUrl .="&redirect_uri=".urlencode($redirectUrl.'test.php');
$AccessTokenUrl .="&client_secret=".$appsec;
$AccessTokenUrl .="&code=".$_GET["code"];
$ReturnedString = file_get_contents($AccessTokenUrl);
$params=null;
parse_str($ReturnedString, $params);
$OurAccessToken = $params['access_token']; //access token
//---------------
require_once('src/facebook.php' ); //Include our facebook Php Sdk
$post_url = '/'.$facebookPageID.'/feed';
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsec,
));
//the Posting Parameters
$PostData = array(
'message' =>$facebookMessage,
'name' => $_SESSION['title'],
'caption' => "testcom",
'link' => 'from tranz',
'description' => $facebookMessage,
' picture' => "http://test/uploads/".$_SESSION['imageshare']."",
'access_token' =>$OurAccessToken,
'actions' => array(
array(
'name' => 'Saaraan',
'link' => 'http://www.saaraan.com'
)
)
);
//print_r($PostData); exit;
try {
$result = $facebook->api($post_url, 'post', $PostData);
//$result = $facebook->api('me/feed','post', $PostData);
if($result)
{
// session_destroy();
echo 'Done..';
die("<meta http-equiv=\"refresh\" content=\"2;URL=".$redirectUrl."? success=1&fbp=".$facebookPageID."\" />");
}
}
catch (Exception $e)
{
echo 'Facebook could be experiencing some problem! Try again later <br />Facebook Says: '. $e->getMessage();
}
//--------------
}
}
Facebook requires users to be authenticated to post something. No, it is not possible to post without authentication, if authentication is what you mean by "logging in."