How do I verify that Zend\Mail has an open IMAP Stream? - php

My host company will not enable the IMAP extension on our web server so I cannot utilize IMAP functions. I am trying to use Zend\Mail as a replacement, but I have been unable to map out a one to one ratio of native IMAP functions with Zend\Mail functions.
Part of my scripts checks to see if an open IMAP stream exists and if it does, to close it and then reopen it. Here's how my php script does it using IMAP functions:
function open($box='INBOX') {
if ($this->mbox)
$this->close();
$args = array($this->srvstr.$this->mailbox_encode($box),
$this->getUsername(), $this->getPassword());
// Disable Kerberos and NTLM authentication if it happens to be
// supported locally or remotely
if (version_compare(PHP_VERSION, '5.3.2', '>='))
$args += array(NULL, 0, array(
'DISABLE_AUTHENTICATOR' => array('GSSAPI', 'NTLM')));
$this->mbox = call_user_func_array('imap_open', $args);
return $this->mbox;
}
function close($flag=CL_EXPUNGE) {
imap_close($this->mbox, $flag);
}
How do I do the same thing with Zend\Mail v2.2?
I have tried using this code, but it errors out with Status 500 and just returns a blank screen:
function open($box='INBOX') {
if ($mail)
$this->close();
$args = array($this->srvstr.$this->mailbox_encode($box),
$this->getUsername(), $this->getPassword());
// Disable Kerberos and NTLM authentication if it happens to be
// supported locally or remotely
if (version_compare(PHP_VERSION, '5.3.2', '>='))
$args += array(NULL, 0, array(
'DISABLE_AUTHENTICATOR' => array('GSSAPI', 'NTLM')));
$this->getProtocol();
$protocol = $this->ht['protocol'];
if ($protocol=="Imap")
$mail = new Zend\Mail\Storage\Imap($args);
else
$mail = new Zend\Mail\Storage\Pop3($args);
return $mail;
}
function close() {
$mail->close();
$mail='';
}

Your $args are wrong. That's how the params are written:
$mail = new Zend_Mail_Storage_Pop3(array('host' => 'localhost',
'user' => 'test',
'password' => 'test'));

Related

FTPS in Laravel not working (SSL write failed)

So I am trying to transfer a file via FTPS in Laravel. I am using this code to create a disk
public function disk(){
$protocol = $this->protocol;
if($this->protocol == "ftps"){
$protocol = "ftp";
}
$disk = Storage::build([
'driver' => $this->protocol,
'host' => $this->ip,
'username' => $this->username,
'password' => $this->password,
'ssl' => true,
'passive' => true
]);
return $disk;
}
And I am calling the function within this code-block and try to upload a file:
public function upload(ImportedImage $image){
$filepath = "path/to/file";
if($this->protocol == "ftp" || $this->protocol == "ftps"){
$this->disk()->putFileAs($this->folder, $filepath, $image->original_name);
return "ok";
}
}
But I get this error
ErrorException: ftp_fput(): SSL write failed in /var/www/html/zendee/vendor/league/flysystem/src/Adapter/Ftp.php:275
The object I am accessing has correct a username/password combination, I can access the server via cyberduck/filezilla, so that's not the issue. The protocol is "ftps", (so it gets changed to "ftp" in the "disk" function).
I have already looked into similar problems which where solved by the "passive" parameter. I tried every possible combination of the "ssl" and "passive" option - didn't help unfortunately.
It also said somewhere that I should configure my FTP-Server to allow ssl-only, so I also did that.
Thanks for every kind of help.

soap class run correctly on localhost but don't run on server

i have a problem with soap class in php. i have write a code to send sms via a sms panel. these codes run correctly on localhost (when run codes by xampp on my pc) but this code don't work when i run them on server. the php versions are same on both of them (localhost and xampp)
<?php
$FORM="30005966371";
$USERNAME="xxxx";
$PASSWORD="12345";
$DOMAIN="0098";
//---- variables ----
$TO="0935xxxxxxx";
$TEXT="test msg";
//-------------------
ini_set("soap.wsdl_cache_enabled", "0");
$sms_client = new SoapClient('http://webservice.0098sms.com/service.asmx?wsdl',array('encoding'=>'UTF-8'));
$parameters['username'] = $USERNAME;
$parameters['password'] = $PASSWORD;
$parameters['mobileno'] = $TO;
$parameters['pnlno'] = $FORM;
$parameters['text']=$TEXT;
$parameters['isflash'] =false;
echo $sms_client->SendSMS($parameters)->SendSMSResult;
?>
when i run above codes on localhost the message sends correctly but when run this code on server the following error returns:
bimehco.ir is currently unable to handle this request.
HTTP ERROR 500
i enabled soap extension in php.ini file on server but it still dont work correctly.
The initialization of the SoapClient class should look as follows when searching for errors.
$wsdl = 'http://webservice.0098sms.com/service.asmx?wsdl';
$options = [
'cache_wsdl' => WSDL_CACHE_NONE,
'exceptions' => true,
'trace' => true,
];
try {
$client = new SoapClient($wsdl, $options);
// do your request stuff here
} catch (SoapFault $fault) {
echo $fault->getMessage();
if ($client instanceof SoapClient) {
echo $client->__getLastRequest();
echo $client->__getLastResponse();
}
}
my soap codes were true and don't have any problem. it was a problem on host.
you can use above codes for soap.
or you can use curve function instead.

JAXL based chat client. Need help connecting to Gtalk or other server to test

I wish to send a message to XMPP based chat servers using php.
I am using JAXL, which seems the best (of limited) options for pure PHP server based chat.
However, I have yet to establish any connect, let alone send a message.
I am having a hard time working out if the problem is my code, my server (which is shared server, but has Cpanel, and a very helpfull host), or my settings.
The code I am using to try to connect to GTalk is;
$client = new JAXL(array(
'jid' => 'name#gmail.com',
'pass' => 'password',
'host'=> 'talk.google.com',
'port'=> 5222,
'domain'=> 'gmail.com', //unsure if this is the right setting.
'force_tls' => true,
'auth_type' => #$argv[3] ? $argv[3] : 'PLAIN',
));
//
// required XEP's
//
$client->require_xep(array(
'0199' // XMPP Ping
));
//
// add necessary event callbacks here
//
$client->add_cb('on_auth_success', function() {
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
// fetch roster list
$client->get_roster();
// fetch vcard
$client->get_vcard();
// set status
$client->set_status("available!", "dnd", 10);
});
$client->add_cb('on_connect_error', function() {
echo 'Connect Error';
});
$client->add_cb('on_auth_failure', function() {
echo 'Auth Error';
});
$client->add_cb('on_auth_success', function() {
global $client;
echo 'connected';
$client->send_chat_msg('test2#domain.com', 'webtest');
$client->shutdown();
});
//
// finally start configured xmpp stream
//
$client->start(array(
'--with-debug-shell' => true,
'--with-unix-sock' => true
));
echo "done\n";
Triggering the php (from a browser) then results in the server getting stuck. (no "done" message, just constant loading till a timeout from the browser)
The server logs show;
strict mode enabled, adding exception handlers. Set 'strict'=>TRUE inside JAXL config to disable this[0m
error handler called with 8, Undefined index: priv_dir,
And then lots of;
unable to connect tcp://talk.google.com:5222 with error no: 110, error str: Connection timed out
So I would appreciate help with any of the following;
Any specific problems with my code
Any issues with the gtalk connection settings at the start
Alternative recommendations to investigate this issue.
Or any general advice from people that have successfully used JAXL.
Thanks,
Thomas Wrobel
Ok problem might be TCP port is closed for your hosting , try to open it with your hosting first, also try to run your code locally to see if it's work fine .
Some people reported the issue was fixed by override method connect from file XMLStream.php by this one
/**
* Connect to XMPP Host
*
* #param integer $timeout
* #param boolean $persistent
* #param boolean $sendinit
*/
public function connect($timeout = 30, $persistent = false, $sendinit = true) {
$this->sent_disconnect = false;
$starttime = time();
do {
$this->disconnected = false;
$this->sent_disconnect = false;
if($persistent) {
$conflag = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT;
} else {
$conflag = STREAM_CLIENT_CONNECT;
}
$conntype = 'tcp';
if($this->use_ssl) $conntype = 'ssl';
$this->log->log("Connecting to $conntype://{$this->host}:{$this->port}");
try {
$this->socket = #stream_socket_client("$conntype://{$this->host}:{$this->port}", $errno, $errstr, $timeout, $conflag);
} catch (Exception $e) {
throw new XMPPHP_Exception($e->getMessage());
}
if(!$this->socket) {
$this->log->log("Could not connect.", XMPPHP_Log::LEVEL_ERROR);
$this->disconnected = true;
# Take it easy for a few seconds
sleep(min($timeout, 5));
}
} while (!$this->socket/* && (time() - $starttime) < $timeout*/);
if ($this->socket) {
stream_set_blocking($this->socket, 0);
if($sendinit) $this->send($this->stream_start);
} else {
throw new XMPPHP_Exception("Could not connect before timeout.");
}
}

SoapClient set custom HTTP Header

I am doing some work writing a PHP-based SOAP client application that uses the SOAP libraries native to PHP5. I need to send a an HTTP cookie and an additional HTTP header as part of the request. The cookie part is no problem:
Code:
$client = new SoapClient($webServiceURI, array("exceptions" => 0, "trace" => 1, "encoding" => $phpInternalEncoding));
$client->__setCookie($kkey, $vvalue);
My problem is the HTTP header. I was hoping there would have been a function named
__setHeader
or
__setHttpHeader
in the SOAP libraries. But no such luck.
Anyone else dealt with this? Is there a workaround? Would a different SOAP library be easier to work with? Thanks.
(I found this unanswerd question here http://www.phpfreaks.com/forums/index.php?topic=125387.0, I copied it b/c i've the same issue)
Try setting a stream context for the soap client:
$client = new SoapClient($webServiceURI, array(
"exceptions" => 0,
"trace" => 1,
"encoding" => $phpInternalEncoding,
'stream_context' => stream_context_create(array(
'http' => array(
'header' => 'SomeCustomHeader: value'
),
)),
));
This answer is the proper way to do it in PHP 5.3+ SoapClient set custom HTTP Header
However, PHP 5.2 does not take all of the values from the stream context into consideration. To get around this, you can make a subclass that handles it for you (in a hacky way, but it works).
class SoapClientBackport extends SoapClient {
public function __construct($wsdl, $options = array()){
if($options['stream_context'] && is_resource($options['stream_context'])){
$stream_context_options = stream_context_get_options($options['stream_context']);
$user_agent = (isset($stream_context_options['http']['user_agent']) ? $stream_context_options['http']['user_agent'] : "PHP-SOAP/" . PHP_VERSION) . "\r\n";
if(isset($stream_context_options['http']['header'])){
if(is_string($stream_context_options['http']['header'])){
$user_agent .= $stream_context_options['http']['header'] . "\r\n";
}
else if(is_array($stream_context_options['http']['header'])){
$user_agent .= implode("\r\n", $stream_context_options['http']['header']);
}
}
$options['user_agent'] = $user_agent;
}
parent::__construct($wsdl, $options);
}
}
I ran into a situation where I had to provide a hash of all the text of the soap request in the HTTP header of the request for authentication purposes. I accomplished this by subclassing SoapClient and using the stream_context option to set the header:
class AuthenticatingSoapClient extends SoapClient {
private $secretKey = "secretKeyString";
private $context;
function __construct($wsdl, $options) {
// Create the stream_context and add it to the options
$this->context = stream_context_create();
$options = array_merge($options, array('stream_context' => $this->context));
parent::SoapClient($wsdl, $options);
}
// Override doRequest to calculate the authentication hash from the $request.
function __doRequest($request, $location, $action, $version, $one_way = 0) {
// Grab all the text from the request.
$xml = simplexml_load_string($request);
$innerText = dom_import_simplexml($xml)->textContent;
// Calculate the authentication hash.
$encodedText = utf8_encode($innerText);
$authHash = base64_encode(hash_hmac("sha256", $encodedText, $this->secretKey, true));
// Set the HTTP headers.
stream_context_set_option($this->context, array('http' => array('header' => 'AuthHash: '. $authHash)));
return (parent::__doRequest($request, $location, $action, $version, $one_way));
}
}
Maybe someone searching will find this useful.
its easy to implement in nuSoap:
NUSOAP.PHP
add to class nusoap_base:
var additionalHeaders = array();
then goto function send of the same class
and add
foreach ($this->additionalHeaders as $key => $value) {
$http->setHeader($key, $value);
}
somewhere around (just before)
$http->setSOAPAction($soapaction); (line 7596)
now you can easy set headers:
$soapClient = new nusoap_client('wsdl adress','wsdl');
$soapClient->additionalHeaders = array('key'=>'val','key2'=>'val');
The SoapClient::__soapCall method has an $input_headers argument, which takes an array of SoapHeaders.
You could also use Zend Framework's SOAP client, which provides an addSoapInputHeader convenience method.

PHP Stream Notification Callback Not Invoked

I've been playing around with PHP Streams and have been experimenting by beginning to write the class shown here. The PHP docs are bit lean in this area to say the least.
I'm having a difficult time with getting my stream context to invoke the callback method specified. If I use a function like file_get_contents or fopen to connect to a socket the callback is invoked, but if I use stream_socket_client it does not.
I assume it should because I'm passing the context to stream_socket_client and if I use stream_socket_recvfrom I get the same string back from the socket as fgets would return.
Relevant PHP docs are linked at the end of the post.
class IMAP {
// Connection Parameters
private $host;
private $port;
private $timeout;
// Credentials
private $email;
private $password;
private $client;
private $transcript;
function __construct($connection, $credentials) {
// Set Connection Settings
$this->host = $connection['host'];
$this->port = $connection['port'];
$this->timeout = $connection['timeout'];
// Set Credentials
$this->email = $credentials['email'];
$this->password = $credentials['password'];
// Connect to the IMAP server
$params = array('notification'=>array($this, 'getLine'));
$ctx = stream_context_create();
stream_context_set_params($ctx, $params);
$this->client = stream_socket_client("tcp://$this->host:$this->port",$errno, $errstr, $this->timeout, STREAM_CLIENT_CONNECT, $ctx);
stream_socket_sendto($this->client, "a001 NOOP\r\n");
}
function getLine($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
$args = func_get_args();
var_dump($args);
}
}
$connection = array(
'host' => 'somehost',
'port' => 143,
'timeout' => 10
);
$credentails = array(
'email' => 'someemail',
'password' => 'somepassword'
);
$imap = new IMAP($connection, $credentails);
?>
http://us3.php.net/manual/en/function.stream-context-set-params.php
http://us3.php.net/manual/en/context.params.php
I found this somewhat related PHP bug report too, but it looks like the report was pointless:
http://bugs.php.net/bug.php?id=42387&edit=1
Looks like this isn't supported by the socket streams as of php 5.3.0.
The only function I could find that calls the notifier function (in the C code) is php_stream_notification_notify in main/streams/streams.c. There are also some #defines
#define php_stream_notify_info
#define php_stream_notify_progress
#define php_stream_notify_progress_init
#define php_stream_notify_progress_increment
#define php_stream_notify_file_size
#define php_stream_notify_error
which boil down to a call to php_stream_notification_notify. The ftp wrapper e.g. calls
php_stream_notify_info(context, PHP_STREAM_NOTIFY_CONNECT, NULL, 0);
in php_ftp_fopen_connect. Same with curl and the http wrapper. But there's no such call for stream_socket_client() or related functions. And the examples at http://php.net/function.stream-notification-callback don't work if you replace the protocol wrapper by a transport like tcp: (or even file:).

Categories