Authenticating with OpenLDAP from PHP - centos7

Using CentOS 7.5, Apache 2.4.6. Running in a VM. No SSL.
I followed https://linuxhostsupport.com/blog/how-to-install-ldap-on-centos-7/ and configured OpenLDAP.
From PHP, when I do an anonymous bind, and issue ldap_search, I see the entry for the user.
When binding with the userid & password, the function fails.
P.S: In case I am typing the wrong password, how do I change a password for a user defined in LDAP using ldif file?
Here is the code:
$ds = ldap_connect("localhost"); // must be a valid LDAP server!
echo "LDAP Server connection result is " . $ds . "<br />";
if ($ds) {
echo "Binding ...";
$r=ldap_bind($ds); // this is an "anonymous" bind, typically
// read-only access
echo "Bind result is " . $r . "<br />";
echo "Searching for (sn=*) ...";
// Search surname entry
$sr=ldap_search($ds, "o=Sapphire, ou=karachi", "sn=*");
echo "Search result is " . $sr . "<br />";
echo "Number of entries returned is " . ldap_count_entries($ds, $sr) . "<br />";
echo "Getting entries ...<p>";
$info = ldap_get_entries($ds, $sr);
echo "Data for " . $info["count"] . " items returned:<p>";
for ($i=0; $i<$info["count"]; $i++) {
echo "dn is: " . $info[$i]["dn"] . "<br />";
echo "first cn entry is: " . $info[$i]["cn"][0] . "<br />";
echo "first email entry is: " . $info[$i]["mail"][0] . "<br /><hr />";
}
echo "Binding as $userid ... ";
if( $r = ldap_bind($ds, "uid=hussain,ou=People,dc=karachi,dc=sapphire", $password) ){
echo "Userid or Password is valid";
}else{
echo "Userid or Password is not valid";
}
echo "Closing connection";
ldap_close($ds);
} else {
echo "<h4>Unable to connect to LDAP server</h4>";
}

Found the answer. I needed to add
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
before issuing the bind.

Related

how to get the product details in amazon mws?

Hi here is my code please check it and let me know what im missing.
im using amazon orders API for this.
<?php
require_once('.config.inc.php');
//$serviceUrl = "https://mws.amazonservices.com/Orders/2013-09-01";
// Europe
$serviceUrl = "https://mws-eu.amazonservices.com/Orders/2013-09-01";
// Japan
//$serviceUrl = "https://mws.amazonservices.jp/Orders/2013-09-01";
// China
//$serviceUrl = "https://mws.amazonservices.com.cn/Orders/2013-09-01";
$config = array (
'ServiceURL' => $serviceUrl,
'ProxyHost' => null,
'ProxyPort' => -1,
'ProxyUsername' => null,
'ProxyPassword' => null,
'MaxErrorRetry' => 3,
);
$service = new MarketplaceWebServiceOrders_Client(
AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY,
APPLICATION_NAME,
APPLICATION_VERSION,
$config);
$request = new MarketplaceWebServiceOrders_Model_ListOrdersRequest();
$request->setSellerId(MERCHANT_ID);
// object or array of parameters
echo"<pre>";
print_r($service);
invokeListOrders($service, $request);
function invokeListOrders(MarketplaceWebServiceOrders_Interface $service, $request)
{
try {
$response = $service->ListOrders($request);
echo ("Service Response\n");
echo ("=============================================================================\n");
$dom = new DOMDocument();
$dom->loadXML($response->toXML());
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
echo $dom->saveXML();
echo("ResponseHeaderMetadata: " . $response->getResponseHeaderMetadata() . "\n");
} catch (MarketplaceWebServiceOrders_Exception $ex) {
echo("Caught Exception: " . $ex->getMessage() . "\n");
echo("Response Status Code: " . $ex->getStatusCode() . "\n");
echo("Error Code: " . $ex->getErrorCode() . "\n");
echo("Error Type: " . $ex->getErrorType() . "\n");
echo("Request ID: " . $ex->getRequestId() . "\n");
echo("XML: " . $ex->getXML() . "\n");
echo("ResponseHeaderMetadata: " . $ex->getResponseHeaderMetadata() . "\n");
}
}
This is the XMl im using for getting the details i request somebody to reply me as soon as possible.
Just add these two lines after the
$request->setSellerId(MERCHANT_ID);
after this line add these two lines.
$request->setMarketplaceId(MARKETPLACE_ID);
$request->setCreatedAfter('2016-04-01');
Hope this helps..

How to match a regex pattern for multiple files under a directory in perl?

I wrote a script to match a pattern and return a statement for a file
#!/usr/bin/perl
use strict;
use warnings;
my $file = '/home/Sidtest/sid.txt';
open my $info , $file or die " Couldn't open the $file:$!";
while( my $line = <$info>) {
if ($line =~ m/^#LoadModule ssl_module/) {
print "FileName =",$file," Status = Failed \n";
}
elsif ($line =~ m/^LoadModule ssl_module/) {
print "FileName =",$file," Status = Passed \n";
}
}
close $info;
So now I am trying to modify this script to work for multiple files under the same directory. I haven't been able to do that successfully. Can anyone please help in how I can make it work for any number of files in a directory.
This will read every file in ./directory and foreach file, print out each line.
The print statement can be altered to print if /match/, or whatever you want:
my #dir = <directory/*>;
foreach my $file (#dir){
open my $input, '<', $file;
while (<$input>){
print "PASS: $_\n" if m/^#LoadModule ssl_module/;
[...]
}
}
The variable #ARGV contains a list of arguments sent to the script when started. Loop through #ARGV and call the script with the files you want to process:
#!/usr/bin/perl
use strict;
use warnings;
foreach my $file (#ARGV) {
open my $info , $file or die " Couldn't open the $file:$!";
while( my $line = <$info>) {
if ($line =~ m/^#LoadModule ssl_module/) {
print "FileName =",$file," Status = Failed \n";
}
elsif ($line =~ m/^LoadModule ssl_module/) {
print "FileName =",$file," Status = Passed \n";
}
}
close $info;
}
# process all files *.txt in your dir: ./myscript.pl /home/Sidtest/*.txt
Check perldoc perlrun, and look at the -p and -n parameters. Essentially, they treat your script as if it were the contents of a loop over stdin, where stdin is generated by iterating through the files supplied on the command line. The name of the file currently-being-processed can be accessed using the $ARGV variable.
So, you might go for an approach where your whole script looks more like this, using the -n param, where $_ contains the current line.:
if ( m/^#LoadModule ssl_module/) {
print "FileName =",$ARGV" Status = Failed \n";
} elsif (m/^LoadModule ssl_module/) {
print "FileName =",$ARGV," Status = Passed \n";
}

PHP if statement with PHP mail()

I just added a phone number input to a contact form and I want to make it so if the user chooses to input their phone number in our form I want to append some text + the phone number to the body of the email being sent out with the php mail() function. If the user leaves the phone number input blank I don't want the extra text.
This script worked perfectly until I inserted the if statement with the text I want appended. Thanks for any help you can provide!
<?php
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$number = $_REQUEST['number'];
$message = $_REQUEST['message'];
$to = "test#test.com";
$email_subject = "Message from test.com";
$email_body = "$message";
$headers = "From: $name <$email>";
mail($to,$email_subject,$email_body if ($number != "") { echo "Patient Phone Number: $number";},$headers);
?>
You cannot use if-statements inside function arguments, therefore use:
<?php
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$number = $_REQUEST['number'];
$message = $_REQUEST['message'];
$to = "test#test.com";
$email_subject = "Message from test.com";
$email_body = "$message";
/**
* Append number to email body (.= adds text after the previously defined $email_body -string)
*/
if ($number != "") {
$email_body .= "Patient Phone Number: $number";
}
$headers = "From: $name <$email>";
mail($to,$email_subject,$email_body,$headers);
?>
Try something more along the lines of this:
if($number != ""){
$email_body .= "Patient Phone Number: $number";
}
mail($to,$email_subject,$email_body,$headers);
Try to remove if statement out of mail function to assign it as a variable then send it to the mail function.

Perl read Gmail and parse the attachments- successful on my PC but failed on another one

I cooked up a script to check the arrival of an email (read Gmail) coming from a specified user with specified subject title using regular expression and . If it matches, it will download the attachment to an output location.
The Perl module I used is Mail::POP3Client (to get connection) and MIME::Parser (to parse attachments). The email server I am working on is Gmail.
However, strange thing happens. It work on my PC, but fails on another PC! You could download the code and replace those ARGV[i] with your personal info and try running that cod;
If the returned number of emails are not '-1', it means connection successful.
It's very strange that this code works on my pc but failed on another PC (always display -1 emails)! I'm thinking, is it because the Perl module installation is wrong or because the mail was blocked by firewall?
The error message is:
There are [-1] emails!
The codes are:
#!/usr/bin/perl -w
use strict;
use warnings;
use Mail::POP3Client;
use MIME::Parser;
use MIME::Entity;
use File::Copy;
use File::Glob ':glob';
my ($DAY,$MONTH,$YEAR);
my $host = 'pop.gmail.com';
my $user = $ARGV[0];
my $passwd = $ARGV[1];
my $sender =$ARGV[2];
my $outputloc=$ARGV[3];
my $subject=$ARGV[4];
my $attachedfile=$ARGV[5];
my $outfile=$ARGV[6];
my $today=return_time();
my $flag=0;
$attachedfile =~s/date/$today/g;
$outfile =~s/date/$today/g;
my $client = new Mail::POP3Client(
USER => $user,
PASSWORD => $passwd,
HOST => "pop.gmail.com",
PORT => 995,
USESSL => 'true',
);
my $parser = MIME::Parser->new;
$parser->output_dir("T:/dailyfiles/TEMP");
my $mgrnum = $client->Count;
print "There are [$mgrnum] emails!\n";
for ( my $i = 1 ; $i <= $mgrnum ; $i++ ) {
my $headandbody = $client->HeadAndBody($i);
my $entity = $parser->parse_data($headandbody);
$parser->decode_headers(1);
my $Subject=$entity->head->get('Subject');
my $From=$entity->head->get('From');
my $To=$entity->head->get('To');
my $Date=$entity->head->get('Date');
my $MIME_type=$entity->mime_type;
print "From = ",$From;
print "To = ",$To;
print "Cc = ",$entity->head->get('Cc'),"\n";
print "Subject = ",$Subject;
print "Date = ",$Date;
print "MIME type = ",$entity->mime_type,"\n";
print "Parts = ",scalar $entity->parts,"\n";
print "=========================================================\n";
exit if ( (scalar $entity->parts) == 1 );
chomp($Subject);
chomp($From);
if($Subject eq $subject && $From eq $sender) {
chdir "T:/dailyfiles/TEMP";
my #list = bsd_glob('*.txt');
my #list2 = bsd_glob('*.html');
unlink(#list,#list2);
my $dir="T:/dailyfiles/TEMP/";
opendir(DIR,$dir) or die$!;
while(defined(my $file=readdir DIR)){
my $oldfile=$file;
if($file =~/$attachedfile/){
$flag=1;
print "Original Attachment: $oldfile\n";
print "Renamed Attachment: ",$outfile,"\n";
if (-e $outfile) {
warn "can't rename $oldfile to $outfile: $file exists ";
} elsif (rename $oldfile, $outfile) {
} else {
warn "rename $oldfile to $outfile failed:$! ";
}
## copy and move files
move("T:/dailyfiles/TEMP/$outfile",$outputloc.$outfile);
print "STATUS: Required email arrival. Expected attachment forwarded to $outputloc.\n";
print "=========================================================\n";
}
}
if($flag==0){
print "STATUS: Required email arrival. However, attachment is disqualified.\n";
}
}
else{
print "STATUS: Required email not yet come. Try later.\n";
}
}
delete_dir();
##subroutines go here
sub return_time{
($DAY,$MONTH,$YEAR)=(gmtime)[3,4,5];
$today=sprintf("%04d%02d%02d",$YEAR+1900,$MONTH+1,$DAY);
return $today;
}
sub delete_dir{
my $dir="T:/dailyfiles/TEMP/";
opendir(DIR,$dir) or die$!;
while(defined(my $file=readdir DIR)){
unlink($dir.$file);
}
}
Reading Mail::POP3Client documentation, I see that you should check youк POP3 connection after creating an object. The error you receive indicates that connection error occured:
new returns a valid Mail::POP3Client object in all cases. To test for
a connection failure, you will need to check the number of messages:
-1 indicates a connection error. This will likely change sometime in the future to return undef on an error, setting $! as a side effect.
This change will not happen in any 2.x version.
You can do it like that:
my $client = new Mail::POP3Client(
USER => $user,
PASSWORD => $passwd,
HOST => "pop.gmail.com",
PORT => 995,
USESSL => 'true',
);
die "Can't connect to the server" if $client->Count == -1;
It's a good idea to track errors:
my $client = new Mail::POP3Client(
USER => $user,
PASSWORD => $passwd,
HOST => "pop.gmail.com",
PORT => 995,
USESSL => 'true',
) || die $!;
# ^^^^^^^^^ insert this and you will show connection error
Check the version of the modules that you are using.

Trying to compare web service response and expected xml from file

We're developing in Java for the most, but we want to integration test (using https://github.com/scottmuc/Pester) our web-services with ms as well. To do this I'm writing powershell scripts that connects to a web-service and compares the response to xml that I've loaded from a file.
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
$instance = New-WebServiceProxy -Uri "https://localhost:7002/service?WSDL" -Namespace "myspace"
$instance.Credentials = new-object System.Net.NetworkCredential("user", "pass")
...
$reply = $instance.fetchInformation($inputA, $inputB)
[xml]$expected = Get-Content ("expected.xml")
...
However, now I have a $reply that contains objects from the myspace namespace and an $expected that contains an XMLNode. I see two ways I can do this (there are probably many more):
Get the original XML response and compare that. However, I can't seem to find out how to get that.
Serialise the $expected XML into the myspace namespace objects. Is that possible?
You could serialize the response returned by the web service to XML and compare it with the contents of the expected.xml file as strings.
Here's an example:
$writer = New-Object System.IO.StringWriter
$serializer = New-Object System.Xml.Serialization.XmlSerializer($reply.GetType())
$serializer.Serialize($writer, $reply)
$replyAsXml = $writer.ToString()
$expectedReplyAsXml = Get-Content expected.xml
$replyAsXml -eq $expectedReplyAsXml
Note that in this example you need to make sure that XML contained in the expected.xml file matches the one returned by the XmlSerializer also in regard to spacing and indenting. In order to avoid that, you could strip all extra characters (such as spaces and newlines) from the two strings before comparing them.
I ended up with a completely different approach. The two XML's was quite different from each other so instead I created a custom comparator. This made it possible for me to simply write custom code to ignore uninteresting differences.
This lead to some pile of crude code that does the job:
# Assume two arrays of equal length
Function Zip {
Param($a1, $a2)
$sum = New-Object object[] $a1.Count
For ($i = 0; $i -lt $a1.Count; ++$i) {
$sum[$i] = New-Object object[] 2
$sum[$i][0] = $a1[$i]
$sum[$i][1] = $a2[$i]
}
Return ,$sum
}
Function XmlChildNodes2List{
param($nodes)
$myArray = New-Object object[] 0
For ($i = 0; $i -lt $nodes.Count; ++$i) {
$node = $nodes.Item($i)
If ($node -ne $null) {
$myArray += $node
}
}
Return ,$myArray
}
Function ShowContext{
Param($ctx)
" at " + $ctx
}
Function CompareNode{
Param($o1, $o2, $ctx)
Try {
Switch ($o1.GetType().Name) {
"XmlDocument" {
CompareXml $o1.ChildNodes $o2.ChildNodes
}
"XmlChildNodes" {
$olist1 = XmlChildNodes2List $o1 | Sort
$olist2 = XmlChildNodes2List $o2 | Sort
If ($olist1.Count -ne $olist2.Count) {
$msg = "Unequal child node count " + ($olist1 -join ",") + " and " + ($olist2 -join ",") + (ShowContext $ctx)
throw $msg
} Else {
$list = Zip $olist1 $olist2
$value = $true
foreach ($item in $list) {
if ($value -eq $true) {
$value = CompareXml $item[0] $item[1] $ctx
}
}
$value
}
}
"XmlElement" {
If ($o1.LocalName -eq $o2.LocalName) {
If ($o1.LocalName -eq "uninterestingElement" -or $o1.LocalName -eq "uninterestingElement2") {
$true
} Else {
CompareXML $o1.ChildNodes $o2.ChildNodes ($ctx + "/" + $o1.LocalName)
}
} Else {
throw ("Element " + $o1.LocalName + " != " + $o2.LocalName + (ShowContext $ctx))
}
}
"XmlDeclaration" {
$true
}
"XmlText" {
$result = $o1.InnerText.Replace("`r`n","`n")
$expect = $o2.InnerText.Replace("`r`n","`n")
# TODO: Hack to remove timezone from expected dates in format 2005-09-01+02:00, the webservice side of the
# reply to xml-conversion looses them
If ($expect -match "^(\d{4}-\d\d-\d\d)\+\d\d:\d\d$") {
$expect = $Matches[1]
}
If ($result -eq $expect) {
$true
} Else {
throw ($o1.InnerText + " is not equal to " + $o2.InnerText + (ShowContext $ctx))
}
}
Default {
throw ("What to do with node " + $o1.GetType().Name + (ShowContext $ctx))
}
}
} Catch [Exception] {
throw $_
}
}
Function CompareXML{
Param($o1, $o2, $ctx)
If ($o1 -eq $null -and $o2 -eq $null) {
$true
} ElseIf ($o1 -eq $null -or $o2 -eq $null) {
throw ("Response or expected is null")
} ElseIf ($o1.GetType() -eq $o2.GetType()) {
CompareNode $o1 $o2 $ctx
} Else {
throw ($o1.GetType().Name + " is not " + $o2.GetType().Name + (ShowContext $ctx))
}
}
This can then be run on two XML's like this:
CompareXML $result $expected ""