i have a problem with socket connections
i need multiple socket read with several clients but i can connect several clients but only can one socket_read for client, if i add second socket_read, the program doesnt work
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
$socket_bind($sock, $address , $port);
$socket_listen ($sock , 10)
while (true){
$read = array();
//first socket is the master socket
$read[0] = $sock;
//now add the existing client sockets
for ($i = 0; $i < $max_clients; $i++)
{
if($client_socks[$i] != null)
{
$read[$i+1] = $client_socks[$i];
}
}
//now call select - blocking call
if(socket_select($read , $write , $except , null) === false)
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not listen on socket : [$errorcode] $errormsg \n");
}
//if ready contains the master socket, then a new connection has come in
if (in_array($sock, $read))
{
for ($i = 0; $i < $max_clients; $i++)
{
if ($client_socks[$i] == null)
{
$client_socks[$i] = socket_accept($sock);
//display information about the client who is connected
if(socket_getsockname($client_socks[$i], $address, $port))
{
echo "Client $i : $port . \n";
}
//Send Welcome message to client
$msg = "Bienvenido cliente {$key[0]} \n\r";
$msg .= "1.-Crear Paleta\n\r";
$msg .= "2.-Ubicar Paleta\n\r";
$msg .= "exz.-Salir\n\r";
socket_write($client_socks[$i] , $msg);
break;
}
}
}
//check each client if they send any data
for ($i = 0; $i < $max_clients; $i++)
{
if (in_array($client_socks[$i] , $read))
{
if (false === ($input = socket_read($client_socks[$i],PHP_NORMA))) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
break 2;
}
echo "client $i : ";
echo "$input";
//send response to client
socket_write ($client_socks[$i], "client $i : ");
socket_write ($client_socks[$i], $input);
socket_write ($client_socks[$i], "\r");
$y++;
}
}
}
Related
I am using php mail() (Via piped to program) and my goal is to simply get the email and scan the "from" header to filter it and then if it passes my "rules" or "checks" pass it along to the intended receiver. I have been able to use a sample code to get the mail and I can actually get my "test check" done. The problem I am having is that I cannot get the php mail() function to resend the mail as it was (plain or html). Every time i get my test mail, it comes with all the headers exposed and code. Not a nice and neat email. I also found out that I could encounter problems with this if there are attachments to the mail. I have seen alot of suggestions about going thru PHPMailer and I am willing to entertain that option. I just don't need this to get to complicated. here is the code I am using -
#!/usr/bin/php -q
<?php
$notify= 'myemail#mydomain.com'; // an email address required in case of errors
function mailRead($iKlimit = "")
{
if ($iKlimit == "") {
$iKlimit = 1024;
}
$sErrorSTDINFail = "Error - failed to read mail from STDIN!";
$fp = fopen("php://stdin", "r");
if (!$fp) {
echo $sErrorSTDINFail;
exit();
}
$sEmail = "";
if ($iKlimit == -1) {
while (!feof($fp)) {
$sEmail .= fread($fp, 1024);
}
} else {
while (!feof($fp) && $i_limit < $iKlimit) {
$sEmail .= fread($fp, 1024);
$i_limit++;
}
}
fclose($fp);
return $sEmail;
}
$email = mailRead();
$lines = explode("\n", $email);
$to = "";
$from = "";
$subject = "";
$headers = "";
$message = "";
$splittingheaders = true;
for ($i=0; $i < count($lines); $i++) {
if ($splittingheaders) {
$headers .= $lines[$i]."\n";
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
$tst = substr($subject, -3);
if ($tst == "win" | $tst == "biz" | $tst == "net"){
$subject = $subject . "BAD ADDRESS";
}
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
if (preg_match("/^To: (.*)/", $lines[$i], $matches)) {
$to = $matches[1];
}
} else {
// not a header, but message
$message .= $lines[$i]."\n";
}
if (trim($lines[$i])=="") {
// empty line, header section has ended
$splittingheaders = false;
}
}
mail('noreply#mydomain.com', $subject, $message);
?>
I am interested in learning, I am code savvy. Somewhat new to email formatting, but very understanding of PHP. Any help is appreciated. Thanx.
could any one help me to understand the following example about handling multiple connection in PHP socket programming.
I need just to explain for me these steps
if(socket_select($read , $write , $except , null) === false)
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not listen on socket : [$errorcode] $errormsg \n");
}
//if ready contains the master socket, then a new connection has come in
if (in_array($sock, $read))
{
}
really I cant understand what happen in those steps.
this is the full example :
error_reporting(~E_NOTICE);
set_time_limit (0);
$address = "0.0.0.0";
$port = 6000;
$max_clients = 10;
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
// Bind the source address
if( !socket_bind($sock, $address , 5000) )
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not bind socket : [$errorcode] $errormsg \n");
}
echo "Socket bind OK \n";
if(!socket_listen ($sock , 10))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not listen on socket : [$errorcode] $errormsg \n");
}
echo "Socket listen OK \n";
echo "Waiting for incoming connections... \n";
//array of client sockets
$client_socks = array();
//array of sockets to read
$read = array();
//start loop to listen for incoming connections and process existing connections
while (true)
{
//prepare array of readable client sockets
$read = array();
//first socket is the master socket
$read[0] = $sock;
//now add the existing client sockets
for ($i = 0; $i < $max_clients; $i++)
{
if($client_socks[$i] != null)
{
$read[$i+1] = $client_socks[$i];
}
}
//now call select - blocking call
if(socket_select($read , $write , $except , null) === false)
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not listen on socket : [$errorcode] $errormsg \n");
}
//if ready contains the master socket, then a new connection has come in
if (in_array($sock, $read))
{
for ($i = 0; $i < $max_clients; $i++)
{
if ($client_socks[$i] == null)
{
$client_socks[$i] = socket_accept($sock);
//display information about the client who is connected
if(socket_getpeername($client_socks[$i], $address, $port))
{
echo "Client $address : $port is now connected to us. \n";
}
//Send Welcome message to client
$message = "Welcome to php socket server version 1.0 \n";
$message .= "Enter a message and press enter, and i shall reply back \n";
socket_write($client_socks[$i] , $message);
break;
}
}
}
//check each client if they send any data
for ($i = 0; $i < $max_clients; $i++)
{
if (in_array($client_socks[$i] , $read))
{
$input = socket_read($client_socks[$i] , 1024);
if ($input == null)
{
//zero length string meaning disconnected, remove and close the socket
unset($client_socks[$i]);
socket_close($client_socks[$i]);
}
$n = trim($input);
$output = "OK ... $input";
echo "Sending output to client \n";
//send response to client
socket_write($client_socks[$i] , $output." welcome any time");
}
}
}
I've set up Freeswitch and simple hotline using mod_callcenter and it works fine. I'm curious whether it would be possible to set text-chat hotline by combine mod_sms with mod_callcenter. Maybe different modules should be used for that?
I'm not sure, but this might offer some insights you need to get you going: http://www.thenoccave.com/2012/03/05/freeswitch-callcenter-sms-alerts/
The PHP code that was written is as follows:
#!/usr/bin/php
<?php
$GLOBALS['server'] = 'localhost';
$GLOBALS['port'] = '8021';
$GLOBALS['password'] = 'ClueCon';
$GLOBALS['clickatellapi_id'] = '1234456';
$GLOBALS['clickatelluser'] = 'username';
$GLOBALS['clickatellpassword'] = 'password';
$GLOBALS['contactnumbers'][] = '61123456789';
$GLOBALS['contactnumbers'][] = '61987654321';
$queuealerter = array();
require_once('/usr/local/freeswitch/scripts/ESL.php');
function sendnotification($queuename){
$message = 'There is a call in the queue ' . $queuename . ' and no agents are logged in to take it';
for($i=0; $i < count($GLOBALS['contactnumbers']); $i++){
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL,'http://api.clickatell.com/http/sendmsg?api_id=' . $GLOBALS['clickatellapi_id'] . '&user=' . $GLOBALS['clickatelluser'] . '&password=' . $GLOBALS['clickatellpassword'] . '&to=' . $GLOBALS['contactnumbers'][$i] . '&text=' . urlencode($message));
curl_exec($curl_handle);
curl_close($curl_handle);
}
}
$sock = new ESLconnection($GLOBALS['server'], $GLOBALS['port'], $GLOBALS['password']);
$res = $sock->api('callcenter_config queue list');
$queuelist = preg_split('/\r\n|\r|\n/', $res->getBody());
//get a list of all the queues
for($i=1; $i < count($queuelist); $i++){
$queuedetails = explode('|', $queuelist[$i]);
if($queuedetails[0] != '+OK' && $queuedetails[0] != ''){
$newQueue = array();
$newQueue['Name'] = $queuedetails[0];
$newQueue['AgentCount'] = 0;
$newQueue['CallCount'] = 0;
$queuealerter['Queues'][] = $newQueue;
}
}
//for each queue check if there is a logged in agent
for($i=0; $i < count($queuealerter['Queues']); $i++){
$res = $sock->api('callcenter_config queue list agents ' . $queuealerter['Queues'][$i]['Name']);
$agentdetails = preg_split('/\r\n|\r|\n/', $res->getBody());
for($i2=1; $i2 < count($agentdetails); $i2++){
$agentdetail = explode('|', $agentdetails[$i2]);
if($agentdetail[0] != '+OK' && $agentdetail[0] != '' && $agentdetail[5] == 'Available'){
$queuealerter['Queues'][$i]['AgentCount'] += 1;
}
}
//get all the calls in the queue
$res = $sock->api('callcenter_config queue list members ' . $queuealerter['Queues'][$i]['Name']);
$calldetails = preg_split('/\r\n|\r|\n/', $res->getBody());
for($i2=1; $i2 < count($calldetails); $i2++){
$calldetail = explode('|', $calldetails[$i2]);
if($calldetail[0] != '+OK' && $calldetail[0] != ''){
$queuealerter['Queues'][$i]['CallCount'] += 1;
}
}
}
//for each queue check
for($i=0; $i < count ($queuealerter['Queues']); $i++){
if($queuealerter['Queues'][$i]['CallCount'] > 0 && $queuealerter['Queues'][$i]['AgentCount'] == 0){
sendnotification($queuealerter['Queues'][$i]['Name']);
}
}
?>
I've been trying for hours to modify this plugin to work with custom taxonomies instead of post titles and/or post content
http://wordpress.org/extend/plugins/kau-boys-autocompleter/
Added the code / part of the plugin where I think the modification should be done. I could post some stuff I tried but I think it would just confuse people, I don't think I ever came close. Normally I can modify code perfectly but just can't seem to find it. I've tried this method posted here.
http://wordpress.org/support/topic/autocomplete-taxonomy-in-stead-of-title-or-content
But it doesn't work. I've tried searching for possible solutions around his suggestion but I'm starting to think his suggestion isn't even close to fixing it.
if(WP_DEBUG){
error_reporting(E_ALL);
} else {
error_reporting(0);
}
header('Content-Type: text/html; charset=utf-8');
// remove the filter functions from relevanssi
if(function_exists('relevanssi_kill')) remove_filter('posts_where', 'relevanssi_kill');
if(function_exists('relevanssi_query')) remove_filter('the_posts', 'relevanssi_query');
if(function_exists('relevanssi_kill')) remove_filter('post_limits', 'relevanssi_getLimit');
$choices = get_option('kau-boys_autocompleter_choices');
$framework = get_option('kau-boys_autocompleter_framework');
$encoding = get_option('kau-boys_autocompleter_encoding');
$searchfields = get_option('kau-boys_autocompleter_searchfields');
$resultfields = get_option('kau-boys_autocompleter_resultfields');
$titlelength = get_option('kau-boys_autocompleter_titlelength');
$contentlength = get_option('kau-boys_autocompleter_contentlength');
if(empty($choices)) $choices = 10;
if(empty($framework)) $framework = 'jQuery';
if(empty($encoding)) $encoding = 'UTF-8';
if(empty($searchfields)) $searchfields = 'both';
if(empty($resultfields)) $resultfields = 'both';
if(empty($titlelength)) $titlelength = 50;
if(empty($contentlength)) $contentlength = 120;
mb_internal_encoding($encoding);
mb_regex_encoding($encoding);
$words = '%'.$_REQUEST['q'].'%';
switch($searchfields){
case 'post_title' :
$where = 'post_title LIKE "'.$words.'"';
break;
case 'post_content' :
$where = 'post_content LIKE "'.$words.'"';
default :
$where = 'post_title LIKE "'.$words.'" OR post_content LIKE "'.$words.'"';
}
$wp_query = new WP_Query();
$wp_query->query(array(
's' => $_REQUEST['q'],
'showposts' => $choices,
'post_status' => 'publish'
));
$posts = $wp_query->posts;
$results = array();
foreach ($posts as $key => $post){
setup_postdata($post);
$title = strip_tags(html_entity_decode(get_the_title($post->ID), ENT_NOQUOTES, 'UTF-8'));
$content = strip_tags(strip_shortcodes(html_entity_decode(get_the_content($post->ID), ENT_NOQUOTES, 'UTF-8')));
if(mb_strpos(mb_strtolower(($searchfields == 'post_title')? $title : (($searchfields == 'post_content')? $content : $title.$content)), mb_strtolower($_REQUEST['q'])) !== false){
$results[] = array(
'url' => get_permalink($post->ID),
'title' => highlightSearchString(strtruncate($title, $titlelength, true), $_REQUEST['q']),
'content' => (($resultfields == 'both')? highlightSearchString(strtruncate($content, $contentlength, false, '[...]', $_REQUEST['q']), $_REQUEST['q']) : '')
);
}
}
printResults($results, $framework);
function highlightSearchString($value, $searchString){
if((version_compare(phpversion(), '5.0') < 0) && (strtolower(mb_internal_encoding()) == 'utf-8')){
$value = utf8_encode(html_entity_decode(utf8_decode($value)));
}
$regex_chars = '\.+?(){}[]^$';
for ($i=0; $i<mb_strlen($regex_chars); $i++) {
$char = mb_substr($regex_chars, $i, 1);
$searchString = str_replace($char, '\\'.$char, $searchString);
}
$searchString = '(.*)('.$searchString.')(.*)';
return mb_eregi_replace($searchString, '\1<span class="ac_match">\2</span>\3', $value);
}
function strtruncate($str, $length = 50, $cutWord = false, $suffix = '...', $needle = ''){
$str = trim($str);
if((version_compare(phpversion(), '5.0') < 0) && (strtolower(mb_internal_encoding()) == 'utf-8')){
$str = utf8_encode(html_entity_decode(utf8_decode($str)));
}else{
$str = html_entity_decode($str, ENT_NOQUOTES, mb_internal_encoding());
}
if(mb_strlen($str)>$length){
if(!empty($needle) && mb_strpos(mb_strtolower($str), mb_strtolower($needle)) > 0){
$pos = mb_strpos(mb_strtolower($str), mb_strtolower($needle)) + (mb_strlen($needle) / 2);
$startToShort = ($pos - ($length / 2)) < 0;
$endToShort = ($pos + ($length / 2)) > mb_strlen($str);
// build the prefix and suffix
$prefix = $suffix;
if($startToShort){
$prefix = '';
}
if($endToShort){
$suffix = '';
}
// set maximum length
$length = $length - mb_strlen($prefix) - mb_strlen($suffix);
// get the start
if($startToShort){
$start = 0;
} elseif($endToShort){
$start = mb_strlen($str) - $length;
} else {
$start = $pos - ($length / 2);
}
// shorten the string
$string = mb_substr($str, $start, $length);
if($cutWord){
return $prefix.$string.$suffix;
} else {
$firstWhitespace = ($startToShort)? 0 : mb_strpos($string, ' ');
$lastWhitespace =($endToShort)? mb_strlen($string) : mb_strrpos($string, ' ');
return $prefix.' '.(!empty($lastWhitespace)? mb_substr($string, $firstWhitespace, ($lastWhitespace - $firstWhitespace)) : $string).' '.$suffix;
}
} else {
$string = mb_substr($str, 0, $length - mb_strlen($suffix));
return (($cutWord) ? $string : mb_substr($string, 0, mb_strrpos($string, ' ')).' ').$suffix;
}
} else {
return $str;
}
}
function printResults($results, $framework){
if($framework == 'scriptaculous'){
echo '<ul>';
foreach($results as $result){
echo ' <li>
<a href="'.$result['url'].'">
<span class="title">'.$result['title'].'</span>
<span style="display: block;">'.$result['content'].'</span>
</a>
</li>';
}
echo '</ul>';
} else {
foreach($results as $result){
echo str_replace(array("\n", "\r", '|'), array(' ',' ', '|'), '<span class="title">'.$result['title'].'</span><p>'.$result['content'].'</p>')
.'|'
.str_replace(array("\n", "\r", '|'), array(' ',' ', '|'), $result['url'])
."\n";
}
}
}
How can i find out that how many attachments a message has?
Is this method reliable?
$attachments = 0;
$msg = $mail->getMessage($msgno);
if($msg->isMultipart()){
$parts = $msg->countParts();
for($i=1; $i<=$parts; $i++){
$part = $msg->getPart($i);
try {
if(strpos($part->contentType,'text/html')===false && strpos($part->contentType,'text/plain')===false)
$attachments++;
} catch (Zend_Mail_Exception $e) {}
}
}
or this?
$matches = array();
$pattern = '`Content-Disposition: (?!inline)(.*)[\s]*filename=`';
$attachments = (string) preg_match_all($pattern, $storage->getRawContent($msgno), $matches);
It is possible to have attachments that are text/html or text/plain, so it may not be reliable in all cases. If there is an attachment that is an HTML file for example, you could have this situation.
You may be better off checking the content-disposition of each mime part instead:
$attachments = 0;
$msg = $mail->getMessage($msgno);
if($msg->isMultipart()){
foreach($msg->getParts() as $part) {
try {
if ($part->disposition == Zend_Mime::DISPOSITION_ATTACHMENT ||
$part->disposition == Zend_Mime::DISPOSITION_INLINE)
$attachments++;
} catch (Zend_Mail_Exception $e) {}
}
}