Upload Files to Sharepoint Library through WS with PHP (NTLM & ThyBag) - php

I use the Lists-WS from Sharepoint to retrieve information about DocumentLibraries and the files in these Libraries. Now I want to upload new files. How do I implement uploads with PHP? Till now I use Thybag SharePointAPI to get information (Link).
(the SharepointServer uses NTLM-Authentication)
THX in advance!!
UPDATE:
I want to call the Copy.asmx WS from sharepoint. To do so, I use the following lines:
$sourceurl = 'http://null';
$params = '
<CopyIntoItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<SourceUrl>'.$sourceurl.'</SourceUrl>
<DestinationUrls>' . $destinationURLs . '</DestinationUrls>
<Stream>' . $stream . '</Stream>
</CopyIntoItems>
';
$xmlvar = new \SoapVar($params, XSD_ANYXML);
// Attempt to run operation
try {
$result = $this->soapClient->CopyIntoItems($xmlvar)->CopyIntoItemsResponse->CopyIntoItemsResult;
} catch (\SoapFault $fault) {
$this->onError($fault);
}
But I dont even get any response ($result == NULL).....

You can use SPServices' CopyIntoItems method. You can find a detailed conversation here containing the details on using the CopyIntoItems service to upload a document.

Related

Run a files list on a list of google drive accounts programmatically

I'm currently doing a PHP script on a web app to scrap my drive :
By opening a PHP in my browser, I have a script based on examples provided by Google (https://github.com/google/google-api-php-client).
This script simply proceeds to a Files List and copy the files on the server.
It's working fine, but I want my Drive files to be synchronized with my server files. I have to run my PHP in my browser every time I want to copy again my files. Here are my questions about that :
Could I make a PHP script which would be executed programmatically by CRON everyday ?
At the moment the PHP opened in my browser needs an authentication (If no cookie of Google account already signed in is detected, I first need to login). I'd like to authorize my Google App once on my account to be able to scrap the drive every day.
Can I apply this script on multiple Google Accounts (Like having a list of G adresses or tokens, and the script runs for each one). The web app I'm doing is for a dizain of persons, and I'd like to synchronize their drives files with my server.
Thank you in advance for any answer. I don't know if this is very useful, but here is my code :
function retrieveAllFiles($service, $parameters) {
$results = array();
$pageToken = NULL;
do{
try {
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$results = array_merge($results, $files->getFiles());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "Une erreur s'est produite : " . $e->getMessage();
$pageToken = NULL;
}
}while($pageToken);
return $results;
}
// Function to get a list of files id
function scrapDrive($service, $excluded) {
$final_files = array();
$query = "";
if(sizeof($excluded) == 0){
$query = "name = '--------'";
}else{
$query = "name = '".$excluded[0]."'";
}
// I just do a custom query if the user has chosen to exclude personal folders from his drive
foreach ($excluded as $folder_name) {
$query .= " or name ='".$folder_name."'";
}
// Get folders ID
$excluded_folders = retrieveAllFiles($service, array('q' => $query));
$excluded_folders_id = array();
foreach ($excluded_folders as $folder) {
array_push($excluded_folders_id, $folder['id']);
}
$usermail = getUserMail($service);
// Getting only files from last month
$artworks_query = "modifiedTime > '".date("Y-m-d\TH:i:sP",strtotime("-1 month"))."'";
// Only getting images
$artworks_query .= " and mimeType contains 'image/' and '".$usermail."' in owners";
foreach ($excluded_folders_id as $id) {
$artworks_query .= " and not '".$id."' in parents";
}
$artworks = retrieveAllFiles($service, array('q' => $artworks_query));
foreach ($artworks as $artwork) {
$final_artworks[$artwork['id']] = $artwork['name'];
}
return $final_artworks;
}
$excluded = getExcludedFolders($_SESSION['id']);
$artworks = scrapDrive($service, $excluded);
$nb_of_artworks = sizeof($artworks);
$i = 1;
// Copy each file
foreach ($artworks as $artwork_id => $artwork_name) {
$response = $service->files->get($artwork_id, array(
'alt' => 'media' ));
$content = $response->getBody()->getContents();
file_put_contents("folder/".$artwork_id.'_'.$artwork_name, $content);
}
$i++;
}
Thank you in advance for any help ! :-)
Could I make a PHP script which would be executed programmatically by CRON everyday?
Yes you can run a php script in cron. how to run a php script daily with the cron job on Ubuntu os
At the moment the PHP opened in my browser needs an authentication (If no cookie of Google account already signed in is detected, I first need to login).
That is because you are using Oauth2. You could just as easily save your refresh token in a file and then have your script read the refresh token from the file rather than reading it from the cookie. check this
I'd like to authorize my Google App once on my account to be able to scrap the drive every day.
If this is an account that you personally have control of then you should consider using service account authentication rather than Oauth2. check this
Can I apply this script on multiple Google Accounts (Like having a list of G adresses or tokens, and the script runs for each one). The web app I'm doing is for a dizain of persons, and I'd like to synchronize their drives files with my server.
Using Oauth2 you can have a refresh token for as many accounts as you wish. The owner of the account must simply authenticate your application and you will have a refresh token to access it.

Google Drive PHP API V2 No results when listing

I'm creating a module for joomla that lists the the contents of a given folder. This module works as a service, so no OAuth should be required.
I'm stuck since every request I make has the same answer, no items. So I would like to know if I'm creating the client/service in a wrong way or I may have registered the application in a wrong way.
Here is the code:
// this class is where I have all the IDs from the google console
require_once(dirname(__FILE__) . '/gdrive/config.php');
require_once(dirname(__FILE__) . '/gdrive/gd-v2-php/apiClient.php');
require_once(dirname(__FILE__) . '/gdrive/gd-v2-php/contrib/apiDriveService.php');
$client = new apiClient();
$key = file_get_contents(Config::KEY_FILE);
$client->setClientId(Config::CLIENT_ID);
$client->setUseObjects(true);
$client->setAssertionCredentials(new apiAssertionCredentials(
Config::SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/drive'), $key)
);
$service = new apiDriveService($client);
try {
$parameters = array();
$parameters['maxResults'] = $maxResults;
$files = $service->files->listFiles($parameters);
$items = $files->getItems();
var_dump($items);
$pageToken = $files->getNextPageToken();
} catch (apiServiceException $e) {
print "Error code :" . $e->getCode() . "\n";
// Error message is formatted as "Error calling <REQUEST METHOD> <REQUEST URL>: (<CODE>) <MESSAGE OR REASON>".
print "Error message: " . $e->getMessage() . "\n";
} catch (apiException $e) {
// Other error.
print "An error occurred: (" . $e->getCode() . ") " . $e->getMessage() . "\n";
} catch (Exception $e) {
print "Cannot retrieve the files";
print($e->getMessage());
}
Sorry to ask such a noob question but this is driving me crazy
Thanks
P.S. just for the record, I followed this google-api-php-client/wiki/OAuth2#Service_Accounts
After having a second look to the documentation I found that Google Drive does not support service accounts. I don't know if this is going to change but, with the requirements I have (I need to show in the web is what an end user uploads to a folder (which is public) using the desktop app) I think I cannot use google drive as a valid solution.
I found a solution but I don't like to much since I should have to refresh the token forever Google Drive SDK Service Account Error

Writing to Google Docs Spreadsheet using PHP

Is there anyway I could write data to a Google Docs Spreadsheet using PHP, besides the Zend library? I have tried the Zend library, and while it is helpful, I want to be able to specify a specific row and column to write to, instead of writing to the last row of the specified column. From what I have seen, the Zend library is not capable of this.
Any links or code would be greatly appreciated!
I Hope this one useful for anyone..
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
// set credentials for ClientLogin authentication
$user = "someuser#gmail.com";
$pass = "somepass";
try {
// connect to API
$service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
$service = new Zend_Gdata_Spreadsheets($client);
// set target spreadsheet and worksheet
$ssKey = 'ssid';
$wsKey = 'wsid';
// update cell at row 6, column 5
$entry = $service->updateCell('6', '5', 'Hello, world', $ssKey, $wsKey);
echo 'Updated cell ' . $entry->getTitle()->getText() . '';
// clear cell at row 1, column 1
$entry = $service->updateCell('1', '1', '', $ssKey, $wsKey);
echo 'Cleared cell ' . $entry->getTitle()->getText();
} catch (Exception $e) {
die('ERROR: ' . $e->getMessage());
}
The Zend library should be able to edit the contents of a given cell within the spreadsheet. See documentation here: http://code.google.com/apis/spreadsheets/data/1.0/developers_guide_php.html#updateCell
The 'updateCell' method allows you to pass in a row and column as your target, and set the contents to the new value. Have you had a chance to try this method?

Google Adword PHP client library couldn't connect to host

Im working on connecting my website to connect to Google Adwords to create ads and campains depending up on the products in my site. I tried connecting by sending direct curl request and parse the received SOAP response. But that is too becoming complex for each request. So i tried using the PHP client library provided in Google Code. But none of the example is working correctly. I changed the user account details in auth.ini file but still on excecuting the example files it says
Failed to get authToken. Reason:
couldn't connect to host'.
I tried running the scripts in different servers but still getting the same error.
Following is the code to fetch all ads from Google adwords and this is a example file from Client library
$path = dirname(__FILE__) . '/../../src';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once 'Google/Api/Ads/AdWords/Lib/AdWordsUser.php';
try {
// Get AdWordsUser from credentials in "../auth.ini"
// relative to the AdWordsUser.php file's directory.
$user = new AdWordsUser();
// Log SOAP XML request and response.
$user->LogDefaults();
// Get the AdGroupAdService.
$adGroupAdService = $user->GetAdGroupAdService();
$adGroupId = (float) '01';
// Create selector.
$selector = new Selector();
$selector->fields = array('Id', 'AdGroupId', 'Status');
$selector->ordering = array(new OrderBy('Id', 'ASCENDING'));
// Create predicates.
$adGroupIdPredicate = new Predicate('AdGroupId', 'IN', array($adGroupId));
// By default disabled ads aren't returned by the selector. To return them
// include the DISABLED status in a predicate.
$statusPredicate =
new Predicate('Status', 'IN', array('ENABLED', 'PAUSED', 'DISABLED'));
$selector->predicates = array($adGroupIdPredicate, $statusPredicate);
// Get all ads.
$page = $adGroupAdService->get($selector);
// Display ads.
if (isset($page->entries)) {
foreach ($page->entries as $adGroupAd) {
printf("Ad with id '%s', type '%s', and status '%s' was found.\n",
$adGroupAd->ad->id, $adGroupAd->ad->AdType, $adGroupAd->status);
}
} else {
print "No ads were found.\n";
}
} catch (Exception $e) {
echo 'Inside catch exception';
print $e->getMessage();
}
and in the settings.ini file
DEFAULT_SERVER =
"https://adwords-sandbox.google.com"
; AUTH_SERVER = "<SERVER>"
In auth.ini file
My Google account's username and password are set correctly.
Can someone help me in getting this issue fixed.
Thanks
It's the AUTH_SERVER setting, not DEFAULT_SERVER, that indicates where authentication requests are being sent. This should be at the bottom of settings.ini but is normally commented out so that the default setting of https://www.google.com is used. You should check that AUTH_SERVER is commented out and that you can connect to https://www.google.com.

Problem using publishUserAction method to post to profile

I am using gigya php sdk, It works well I am able to post to user's wall or profile using socialise.setStatus method but I am have problems when I try to use the publishuseraction method. I get an error Invalid request signature.
$method = "socialize.publishUserAction";
$request = new GSRequest($apiKey,$secretKey,$method);
$userAction = new GSDictionary("{\"title\":\"This is my title\", \"userMessage\":\"This is a user message\", \"description\":\"This is a description\", \"linkBack\":\"http://google.com\", \"mediaItems\":[{\"src\":\"http://www.f2h.co.il/logo.jpg\", \"href\":\"http://www.f2h.co.il\",\"type\":\"image\"}]}");
$request->setParam("userAction", $userAction);
$request->setParam("uid", $userUID);
$response = $request->send();
if($response->getErrorCode()==0){
echo "Success";
} else {
echo ("Error: " . $response->getErrorMessage());
}
UPDATED AFTER USING $response->getLog()
apiMethod=socialize.publishUserAction
apiKey=correct_api_key
params={"userAction":{},uid":"MY_UID","format":"json","httpStatusCodes":"false"}
URL=http://socialize.gigya.com/socialize.publishUserAction postData=uid=urlencoded(MY_UID)&format=json&httpStatusCodes=false&apiKey=correct_api_keyƗtamp=1296229876&nonce=1.29622987636E%2B12&sig=HEdzy%2BzxetV8QvTDjdsdMWh0%2Fz8%3D
server= web504
I used both put method
$userAction = new GSDictionary();
$userAction->put("title", "This is my title");
$userAction->put("userMessage", "This is my user message");
$userAction->put("description", "This is my description");
$userAction->put("linkBack", "http://google.com");
$mediaItems = array();
$mediaItems[0] = new GSDictionary("{\"src\":\"http://www.f2h.co.il/logo.jpg\", \"href\":\"http://www.f2h.co.il\",\"type\":\"image\"}");
& JSON method
$userAction = new GSDictionary("{\"title\":\"This is my title\", \"userMessage\":\"This is a user message\", \"description\":\"This is a description\",
\"linkBack\":\"http://google.com\", \"mediaItems\":[ {\"src\":\"http://www.f2h.co.il/logo.jpg\", \"href\":\"http://www.f2h.co.il\",\"type\":\"image\"}]}");
I get the same error. And User action is empty using both methods. I appreciate any help.
Thanks.
Try calling getLog() for a bit more information about the error:
if($response->getErrorCode()==0){
echo "Success";
} else {
echo ("Error: " . $response->getErrorMessage());
print "<pre>";
print_r($response->getLog());
print "</pre>";
}
Also, are you able to run getUserInfo w/ the SDK? This is a simple test that also requires a signature. Use the example on the PHP SDK page (about 1/2 way down).

Categories