SoapClient + PHP + Sharepoint + Getting images from a list OR GetItemsByIds - php

I am using SoapClient to pull data out of a sharepoint list. If its a normal text field it works fine and gives me the image. I can even attach the image to the individual list elements and link it into another field and get the image that way. The problem with that is it asks me to log in to my sharepoint account whenever I access the page, which obviously a normal user of my site will not be able to do.
First, if there is a way around this, that will be a sufficient answer because that is my ideal way of doing it.
However, if the better way is to make a picture gallery and then pull the pictures from there then that isn't a problem.
Basically what I need to know is how to use the Imaging library and maybe the GetItemsByIds method? I am very new to soap and sharepoint in general so I appologize for what may be trivial questions but I really need to know how to do this and I can find no resource on the internet that explains what I need to know (if there is one, link it!). Keep in mind, I have to do this in PHP.
Here is some code that I use to pull the list data:
<?php
$authParams = array(
'login' => 'username',
'password' => 'pass'
);
$listName = "{GUID}";
$rowLimit = '500';
$wsdl = "list.wsdl";
$soapClient = new SoapClient($wsdl, $authParams);
$params = array(
'listName' => $listName,
'rowLimit' => $rowLimit;
);
echo file_get_contents($wsdl, FILE_TEXT, stream_context_create(array('http' => array('timeout' => 1))), 0, 1);
$rawXMLresponse = null;
try{
$rawXMLresponse = $soapClient->GetListItems($params)->GetListItemsResult->any;
}
catch(SoapFault $fault){
echo 'Fault code: '.$fault->faultcode;
echo 'Fault string: '.$fault->faultstring;
}
echo '<pre>' . $rawXMLresponse . '</pre>';
$dom = new DOMDocument();
$dom->loadXML($rawXMLresponse);
$results = $dom->getElementsByTagNameNS("#RowsetSchema", "*");
?>
//do the useful thing
<?php
unset($soapClient);
?>

It was an issue with the user permissions. Once we had an account with the correct permissions, it worked fine.

Related

Get data to/from secondary PHP file - works with some data, not with other

I have a SPA (react) that is uses PHP calls to connect to a MongoDB.
Works great.
However, due to 'rules' I need to serve the javascript files from a different server -- a server that supports neither MongoDB nor MongoDB php client. Let's call this server, SERVER_A.
Let's call the server hosting the MongoDB PHP client and the MongoDB, SERVER_B. ('B' for 'backend'... :) )
The solution, I believe, was to build a php 'middleman' on SERVER_A that simply passes data on to SERVER_B. Research shows me that file_get_contents is the tool for this.
So I take my original known-working PHP file, I put it on SERVER_B and rename it to "mongoPatch_backend.php".
<?php
$user = "xxxx";
$pwd = 'xxx';
$filter = [];
if (isset($_REQUEST['needleKey'])) {
$needleKey = $_REQUEST['needleKey'];
$needle = $_REQUEST['needle'];
$filter = [$needleKey => $needle];
}
$newData = $_REQUEST['newData'];
$filter = ['x' => ['$gt' => 1]];
$options = [
'projection' => ['_id' => 0],
'sort' => ['x' => -1],
];
$bson = MongoDB\BSON\fromJSON($newData);
$value = MongoDB\BSON\toPHP($bson);
$manager = new MongoDB\Driver\Manager("mongodb://${user}:${pwd}#SERVER_B:27017");
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
[$needleKey => $needle],
['$set' => $value],
['multi' => false, 'upsert' => true]
);
$results = $manager->executeBulkWrite('sedwe.users', $bulk);
var_dump($results);
?>
On SERVER_A I then make a new file, dbPatch.php, like so:
<?php
$API = "https://SERVER_B/php/mongoPatch_backend.php?";
if (isset($_REQUEST['needleKey'])) {
$needleKey = $_REQUEST['needleKey'];
$needle = $_REQUEST['needle'];
$filter = [$needleKey => $needle];
}
$newData = $_REQUEST['newData'];
$postData = "needleKey=".urlencode($needleKey);
$postData .= "&needle=".urlencode($needle);
$postData .= "&newData=".urlencode($newData);
// echo $API.$postData;
$data = file_get_contents($API.$postData);
echo $data;
?>
But when I call it, I get nothing echo'd back out of $data.
Any idea why? Remember, the exact same call directly to mongoPatch_backend.php works just fine (but it's a CORS call, so it's not a valid option).
So here is what I've tried:
First, to ensure my AJAX call was still working, I spit out the response to the console. I get nothing.
So I changed the last line of the middleman (dbPatch.php) to echo "Hello World" instead of echo $data and received "Hello World" on the console as expected.
Next, I then changed the last line of my middleman (dbPatch.php) back to echo $data and tried reducing the 'backend' to a simple <?php echo "Hello Back World"; ?> and got nothing on the console.
Next, I go to https://SERVER_B/php/mongoPatch_backend.php in a browser ... and I'm greeted with "Hello Back World" as expected in the browser.
... which leads me to believe something is up with the transferring of info from server to server. Logical call, eh?
Unfortunately, when I try the same thing with just a 'fetch' command, it works perfectly fine:
Here is my 'middleman' (dbFetch.php) script on SERVER_A:
<?php
$API = "https://SERVER_B/php/mongoFetch_backend.php?";
$collection = $_REQUEST['collection'];
$postData = "collection=".urlencode($collection);
$needleID = $_REQUEST['needleID'];
$postData .= "&needleID=".urlencode($needleID);
$data = file_get_contents($API.$postData);
echo $data;
?>
And this is the file on the backend, SERVER_B:
<?php
$user = "xxxx";
$pwd = 'xxxx';
$filter = [];
if (isset($_REQUEST['needleID'])) {
$needleID = $_REQUEST['needleID'];
$filter = ['id'=> $needleID];
}
if (isset($_REQUEST['collection'])) {
$collection = $_REQUEST['collection'];
}
//Manager Class
$connection = new MongoDB\Driver\Manager("mongodb://${user}:${pwd}#SERVER_B:27017");
// Query Class
$query = new MongoDB\Driver\Query($filter);
$rows = $connection->executeQuery("db_name.$collection", $query);
// Convert rows to Array and send result back to client
$rowsArr = $rows->toArray();
echo json_encode($rowsArr);
?>
Huzzah, this works! ... and it's also proof there doesn't appear to be a problem with the server-to-server communication.
So back to ground zero.
I then go with a very simple newData value -- shorter, but same general layout - stringified json. It works! The data ends up in the database.
So I'm forced to think something is wrong with the data in newData (which is only a few hundred lines of stringified JSON made like this: encodeURIComponent(JSON.stringify(newData)). But, this bears repeating: this works if I skip the middleman.
... and that puts me at a loss. PHP isn't something I understand well... can you help?
EDIT to answer comment:
When I call mongoPatch_backend.php directly on SERVER_B it works (as stated above). I had it echo the $newData and it spits out a stringified JSON version of the variable (not URLencoded).
When I call dbPatch.php, it does not give me anything that was passed back from mongoPatch_backend.
As I said in the OP, if I modify mongoPatch_backend.php to do nothing other than echo "hellow world" I am still unable to log it to console when calling it via the above dbPatch.php file.
EDIT: I also tried putting the two PHP files on the same server and am getting the same results. (ie: both the dbPatch.php and mongoPatch.php files are in the same directory on the same server)
EDIT2: I have done a var_dump from the middleman and I get standard-looking human-readable stringified text back.
I do the same var_dump($_REQUEST['newData']); in the backend file and I get nothing back.

Add samlp:extensions to authsources.php SimpleSamlPHP

What I wish to accomplish is adding the following example to Authnrequest
<samlp:Extensions>
<somens:TheExtensionName xmlns:somens="http://uriofextension/">
<somens:TheExtensionName Name="AttributeName" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
isRequired="true"/>
</somens:TheExtensionName >
</samlp:Extensions>
By using authsource.php, how am I able to accomplish that?
I've read the documentation and at the point
https://simplesamlphp.org/docs/stable/saml:sp
5.8 Using samlp:Extensions
They have:
$dom = \SAML2\DOMDocumentFactory::create();
$ce = $dom->createElementNS('http://www.example.com/XFoo', 'xfoo:test', 'Test data!');
$ext[] = new \SAML2\XML\Chunk($ce);
$auth = new \SimpleSAML\Auth\Simple('default-sp');
$auth->login(array(
'saml:Extensions' => $ext,
));
But where is this code included? As I've added it to the authsources.php without luck, and can't figure out how to use this, consider also my lack of knowledge regarding php, so maybe im just messing things.
This is what I've tried in authsources.php
Disregard some parts of the code that belong to the examples provided
<?php
$dom = \SAML2\DOMDocumentFactory::create();
$ce = $dom->createElementNS('http://www.example.com/XFoo', 'xfoo:test', 'Test data!');
$ext[] = new \SAML2\XML\Chunk($ce);
$config = array(
'sp.name' => array(
'saml:SP',
'privatekey' => '/certs/privkey.pem',
'certificate' => '/certs/fullchain.pem',
'entityID' => 'entityID',
'idp' => 'idpID',
'saml:Extensions' => $ext,
),
);
Well I've not been able to use authsources.php yet, but managed to recreate it with the samlp:extensions authnrequest I needed.
I've created an php app and connected that to Simplesaml Service Provider in order to send the request with samlp:Extensions and here is a code for those having the same issue:
app/app.php
<?php
//Load SimpleSAMLphp.
require_once('/var/www/simplesamlphp/lib/_autoload.php');
//Initiate a SimpleSAML_Auth_Simple object.
$as = new SimpleSAML_Auth_Simple('name-of-sp');
//Standard PHP lib more info at -> http://php.net/manual/en/domdocument.createelementns.phphttp://php.net/manual/en/domdocument.createelementns.php
$dom = SAML2_DOMDocumentFactory::create();
$attributes_ext = $dom->createElementNS('namespace-uri', 'fa:RequestedAttributes');
$item = $dom->createElementNS('namespace-uri', 'fa:RequestedAttribute');
$attrName = $dom->createAttribute('Name');
$attrName->value = 'attributeName';
$attrNameFormat = $dom->createAttribute('NameFormat');
$attrNameFormat->value = "urn:oasis:names:tc:SAML:2.0:attrname-format:uri";
$attrRequirement = $dom->createAttribute('isRequired');
$attrRequirement->value = "true";
$item->appendChild($attrName);
$item->appendChild($attrNameFormat);
$item->appendChild($attrRequirement);
$attributes_ext->appendChild($item);
$ext[] = new SAML2_XML_Chunk($attributes_ext);
$as->login(array(
'saml:Extensions' => $ext,
));
//If the user is not authenticated, authenticate the user
$as->requireAuth();
//Get the users attributes and print them.
$attributes = $as->getAttributes();
print_r($attributes);
//Output the attributes to a file
$myFile = "/tmp/attributes.log";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = print_r($attributes, true);
fwrite($fh, $stringData);
fclose($fh);
//Displays a Login and Logout link
$url_in = $as->getLoginURL();
$url_out = $as->getLogoutURL();
print('<br>Login');
print('<br>Logout<br>');
//If using PHP sessions in SimpleSAMLphp cleanup the SimpleSAMLphp session to be able to use $_SESSION
$session = SimpleSAML_Session::getSessionFromRequest();
$session->cleanup();
//Display PHP information
phpinfo()
?>
</body>
</html>
To set it to run for experiment
php -S 0.0.0.0:5000 -t app/
Navigate to localhost:5000/app.php, this will automatically send you to the login of the IDP, using the SP configurations. You can try with authsources.php examples provided by simplesamlphp

Always getting response as Invalid Session Token in soap client php

I have php version 7.1 in my localhost. I have made changes in my php.ini file to run SOAP from my localhost.
I need to generate primary and secondary session token by passing login id and password to SOAP client API.
Once session token is authenticated it will return some rate chart. My code is generating session tokens. But when I am passing that token key to the next method in SOAP Client api its always giving me an error like "Invalid Session Token" or "Invalid Authentication". However the same tokens are working well in SOAP UI exe. I mean I have installed SOAP UI exe and by using wsdl "http://cnx.test.dat.com:9280/wsdl/TfmiFreightMatching.wsdl" and using method "Login" and "LookupRate" its working everything fine. The way i need that.
But whenever i am using that tokens in php localhost its always giving me an authentication error by SOAP Client.
I am sharing my code below.
$wsdl = "http://cnx.test.dat.com:9280/wsdl/TfmiFreightMatching.wsdl";
$client = new SoapClient($wsdl, array('trace' => true));
$params = array('loginOperation'=>array('loginId'=>'ryder_cnx1','password'=>'ryder1','thirdPartyId'=>'dl'));
$client->Login($params);
$data = $client->__getLastResponse();
$p = xml_parser_create();
xml_parse_into_struct($p, $data, $vals, $index);
xml_parser_free($p);
$token = [];
foreach ($vals as $key => $value) {
foreach ($value as $key1 => $value1) {
if($key1 == "value")
$token[] = $value1;
}
}
echo "Primary Token = ".$token[0];
echo "<br> Secondary Token = ".$token[1];
//echo "<br> Expiry Date = ".$token[2];
$params_session = array("sessionToken"=> array("primary"=>$token[0], "secondary"=>$token[1]));
$namespace = 'http://www.tcore.com/TcoreTypes.xsd'; // I am not sure about this namespace. Whether its correct or not.
$header = new SoapHeader($namespace,'sessionHeader',$params_session,true);
$client->__setSoapHeaders($header);
$params_data = array('lookupRateOperations'=> array(
'equipment'=>'Vans',
'origin'=>array('postalCode'=>array('country'=>'US','code'=>'30004')),
'destination'=>array('postalCode'=>array('country'=>'US','code'=>'10001'))
));
try{
$result = $client->LookupRate($params_data);
print_r($result);
}catch (SoapFault $exception){
//or any other handling you like
print_r(get_class($exception));
enter code hereprint_r($exception);
}
if anybody have any idea, please share it with me.
Awaiting any response.
Thanks a lot in advance :)
I know this is very old, and most likely the OP figured it out. But in case anyone else comes along, I was able to get it working with two slight changes.
First,
$namespace = 'http://www.tcore.com/TcoreTypes.xsd';
Should be
$namespace = 'http://www.tcore.com/TcoreHeaders.xsd';
Second,
$params_session = array("sessionToken"=> array("primary"=>$token[0], "secondary"=>$token[1]));
should be
$params_session = array(
"sessionToken"=> array(
"primary"=>base64_decode($token[0]),
"secondary"=>base64_decode($token[1])
)
);
The rest of my code is similar enough that if the above changes are made, it should work. I would also refrain from posting real usernames and passwords, btw.

To download asmx list files and use them as wsdl files + sharepoint

I am trying to retrieve the data from a list in share-point 2007 through a web-service written in php as:
<?php
//Authentication details
$authParams = array('login' => 'username', 'password' => 'password' , "authentication" => SOAP_AUTHENTICATION_DIGEST);
/* A string that contains either the display name or the GUID for the list.
* It is recommended that you use the GUID, which must be surrounded by curly
* braces ({}).
*/
$listName = "Testlist";
$rowLimit = '150';
/* Local path to the Lists.asmx WSDL file (localhost). You must first download
* it manually from your SharePoint site (which should be available at
* yoursharepointsite.com/subsite/_vti_bin/Lists.asmx?WSDL)
*/
$wsdl = "http://localhost/phpsp/Lists.wsdl";
//Creating the SOAP client and initializing the GetListItems method parameters
$soapClient = new SoapClient($wsdl, $authParams);
$params = array('listName' => $listName, 'rowLimit' => $rowLimit);
//Calling the GetListItems Web Service
$rawXMLresponse = null;
try{
$rawXMLresponse = $soapClient->GetListItems($params)->GetListItemsResult->any;
}
catch(SoapFault $fault){
echo 'Fault code: '.$fault->faultcode;
echo 'Fault string: '.$fault->faultstring;
}
echo '<pre>' . $rawXMLresponse . '</pre>';
..
..
?>
I have lists created in share-point and in the url, the lists display show '.asmx' extension. How can i manually download the lists and use them as '.wsdl' as done in this sample code.
I searched for the same over the net and people tell it can be obtained at:
sharepoint.url/subsite/_vti_bin/Lists.asmx?WSDL
But, i was not able to get the .wsdl files.
Please take this wsdl file from http://sharepointserver:port/_vti_bin/Lists.asmx?wsdl
and save the file as listswsdl.wsdl to your php server in phpsp/listswsdl.wsdl
Lastly, modify this line:
$wsdl = "http://localhost/phpsp/listswsdl.wsdl";

login with curl and get session

hello i need somehow to get top Regional interest and interest over time from
http://www.google.com/trends?q=lingerie+&ctab=0&geo=id&date=all&sort=0
or better
http://www.google.com/insights/search/#q=lingerie&geo=ID&cmpt=q
so i found out that we have to login to export data can anybody give me an example doing this with our google username and password? maybe using curl to export the data? or something else
Thanks for looking in
Adam Ramadhan
Just to be quick about it, I used my xhttp class which is a curl wrapper, and I think the code is easy enough to follow.
<?php
header('content-type: text/plain');
// Set account login info
$data['post'] = array(
'accountType' => 'HOSTED_OR_GOOGLE', // indicates a Google account
'Email' => '', // full email address
'Passwd' => '',
'service' => 'trendspro', // Name of the Google service
'source' => 'codecri.me-example-1.0' // Application's name, e.g. companyName-applicationName-versionID
);
$response = xhttp::fetch('https://www.google.com/accounts/ClientLogin', $data);
// Test if unsuccessful
if(!$response['successful']) {
echo 'response: '; print_r($response);
die();
}
// Extract SID
preg_match('/SID=(.+)/', $response['body'], $matches);
$sid = $matches[1];
// Erase POST variables used on the previous xhttp call
$data = array();
// Set the SID in cookies
$data['cookies'] = array(
'SID' => $sid
);
$response = xhttp::fetch('http://www.google.com/insights/search/overviewReport?q=lingerie&geo=ID&cmpt=q&content=1&export=1', $data);
// CSV data in the response body
echo $response['body'];
?>
The result is at: http://codecri.me/apps/test/test.google.trends.php
But I'm not sure if the result is what you are looking for.
Since April 2012 Google changed it's auth policy, edit the Arvin's code as follows:
// Extract Auth
preg_match('/Auth=(.+)/', $response['body'], $matches);
$auth = $matches[1];
// Erase POST variables used on the previous xhttp call
$data = array();
// Set the Authorization header
$data['headers'] = array(
'Authorization' => 'GoogleLogin auth='.$auth
);
The curl man page describes how to provide username and password. Have you tried the -u flag?
-u/--user
Specify the user name and password to use for server authentication. Overrides -n/--netrc and --netrc-optional.
If you just give the user name (without entering a colon) curl will prompt for a password.
If you use an SSPI-enabled curl binary and do NTLM authentication, you can force curl to pick up the user name and password from your environment by simply specifying a single colon with this option: "-u :".
If this option is used several times, the last one will be used.

Categories