php imap - imap_setflag_full - php

I have this code it works perfectly.... the only problem i have is with imap_setflag_full($imap,$i, "\\Seen"); that the flag SEEN doesn't seem to be setting ..
$imap = imap_open("{mail.xyz.com:993/imap/ssl/novalidate-cert}INBOX", "username", "pass");
$message_count=2;
for ($i = 1; $i <= $message_count; ++$i) {
$header = imap_header($imap, $i);
$body = trim(substr(imap_body($imap, $i), 0, 1000));
$prettydate = date("jS F Y", $header->udate);
echo "<pre>".print_r($header)."</pre>";
if (isset($header->from[0]->personal)) {
$personal = $header->from[0]->personal;
} else {
$personal = $header->from[0]->mailbox;
}
$email = "$personal < ".$header->from[0]->mailbox."#".$header->from[0]->host." >";
echo "On $prettydate, $email said \"$body\".\n <BR>";
imap_setflag_full($imap,$i, "\\Seen"); // Set the flag "Seen"
}
imap_close($imap);
i printed the heads after i have tried to set the flag and it doesn't show up. however if i tired imap_setflag_full($imap,$i, "\\Flagged"); the flagged paraemeter would be F and if put imap_clearflag_full($imap,$i,'\\Flagged') the F would be removed... the only problem is the SEEN and UNSEEN... any help is appreciated.
thanks

Suggestions:
Start using an imap function that returns an array of messages
Start catching the imap returned values to see if there is an error.
Try switching to UID would be my last suggestion.
I had the same problem where I was mixing Message Number with Message UID and this is why the Unseen was not (always) set. This does not seem to be your case.
$mbox = imap_open ( $account, $user, $pwd);
if( $mbox !== false ) {
$numMsg = imap_num_msg ( $mbox );
$msgs = imap_search($mbox, 'UNSEEN', SE_UID);
// Go through ALL emails.
foreach ( $msgs as $msguid ) {
$msgno = imap_msgno ( $mbox, $msguid );
$header = imap_headerinfo( $mbox, $msgno);
if( $header === false ) {
... log error
}
$email = imap_body ( $mbox, $msgno );
// Mark as Read
$result = imap_setflag_full($mbox, $msguid, "\\Seen", ST_UID);
if( $result === false ) {
... log error
}
}
imap_close ( $mbox );
}

Related

phpscript stops after 4th sleep

I have a csv file containing about 3500 user's data. I want to import these users to my database and send them an email that they are registered.
I have the following code:
public function importUsers()
{
$this->load->model('perk/engagement_model');
$this->load->model('user/users_model');
$this->load->model('acl/aclUserRoles_model');
$allengagements = $this->engagement_model->getAll();
$filename = base_url() . 'assets/overdracht_users.csv';
$file = fopen($filename, "r");
$count = 0;
$totalImported = 0;
$importFails = array();
$mailFails = array();
while (($mappedData = fgetcsv($file, 10000, ";")) !== FALSE)
{
$count++;
//Skip first line because it is the header
if ($count > 1) {
if (!empty($mappedData[0])) {
$email = $mappedData[0];
$user = $this->users_model->getByEmail($email);
if (!$user) {
$user = new stdClass();
$user->email = $mappedData[0];
$user->first_name = $mappedData[1];
$user->family_name = $mappedData[2];
$user->address_line1 = $mappedData[3];
$user->address_postal_code = $mappedData[4];
$user->address_city = $mappedData[5];
$user->address_country = 'BE';
$user->volunteer_location = $mappedData[5];
$user->volunteer_location_max_distance = 50;
$user->phone = $mappedData[6];
if (!empty($mappedData[7])) {
$user->birthdate = $mappedData[7] . "-01-01 00:00:00";
} else {
$user->birthdate = null;
}
foreach ($allengagements as $eng) {
if ($eng->description == $mappedData[8]) {
$engagement = $eng->engagement_id;
}
}
$user->engagement = $engagement;
if (!empty($mappedData[9])) {
$date_created = str_replace('/', '-', $mappedData[9]);
$date_created = date('Y-m-d H:i:s', strtotime($date_created));
} else {
$date_created = date('Y-m-d H:i:s');
}
$user->created_at = $date_created;
if (!empty($mappedData[10])) {
$date_login = str_replace('/', '-', $mappedData[10]);
$date_login = date('Y-m-d H:i:s', strtotime($date_login));
} else {
$date_login = null;
}
$user->last_login = $date_login;
$user->auth_level = 1;
$user->is_profile_public = 1;
$user->is_account_active = 1;
$combinedname = $mappedData[1] . $mappedData[2];
$username = str_replace(' ', '', $combinedname);
if (!$this->users_model->isUsernameExists($username)) {
$uniqueUsername = $username;
} else {
$counter = 1;
while ($this->users_model->isUsernameExists($username . $counter)) {
$counter++;
}
$uniqueUsername = $username . $counter;
}
$user->username = $uniqueUsername;
$userid = $this->users_model->add($user);
if (!empty($userid)) {
$totalImported++;
//Add the user in the volunteer group in ACL
$aclData = [
'userID' => $userid,
'roleID' => 1,
'addDate' => date('Y-m-d H:i:s')
];
$this->aclUserRoles_model->add($aclData);
//Registration mail to volunteer
$mail_data['name'] = $user->first_name . ' ' . $user->family_name;
$mail_data['username'] = $user->username;
$this->email->from(GENERAL_MAIL, 'Test');
$this->email->to($user->email);
//$this->email->bcc(GENERAL_MAIL);
$this->email->subject('Test');
$message = $this->load->view('mail/register/registration',$mail_data,TRUE);
$this->email->message($message);
$mailsent = $this->email->send();
if (!$mailsent) {
array_push($mailFails, $mappedData);
}
} else {
array_push($importFails, $mappedData);
}
if ($count % 50 == 0) {
var_dump("count is " . $count);
var_dump("we are sleeping");
$min=20;
$max=40;
$randSleep = rand($min,$max);
sleep($randSleep);
var_dump("end of sleep (which is " . $randSleep . "seconds long)");
}
var_dump($user);
} else {
array_push($importFails, $mappedData);
}
}
}
}
var_dump("Totale aantal rijen in het bestand (met header) : " . $count);
var_dump("Totale aantal geimporteerd in de database : " . $totalImported);
var_dump("Totale aantal gefaalde imports in de database : " . count($importFails));
var_dump("Deze zijn gefailed : ");
var_dump($importFails);
}
If I do not add the users in the database, or send out a mail, and just var_dump() the $user, i can see all 3500+ users being correctly created in php objects (so they should be able to be inserted correctly).
The problem is that I want to add in a random sleep, between 20 and 40 seconds after every 50 mails that I sent.
So I started doing some testing and after commenting out the insert and mail code, I started running the script, noticing that after some amount (not 50 at all), it just stops for a bit, then continues and shows me the the var_dumps in my if case at the bottom, it can be shown here in the screenshots below.
The first screenshot shows the code stopping for a bit (note that I am only var_dumping stuff, i am not adding something in the database or sending out an email yet).
This screenshot shows what happens after the script reaches 200:
The script just completely stops from this point on. I have tried this 3 times, and every single time it stops exactly on 200.
What is happening here??
Most likely you're hitting default PHP limits. temporarily remove PHP default limits with:
ini_set('memory_limit',-1);
set_time_limit(0);
then, rerun the script and check your output.
There can be multiple reasons, but to know the exact one please enable error output with.
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
and if limits are not the problem, the errors will tell you more.
HINT: using logs are still better than outputting errors to the visitors, but my guess is you're testing this on your computer.

PHP & IMAP: EmailReplyParser not returning message

I'm using the EmailReplyParser by Will Durand and the getContent() method doesn't appear to be returning anything.
// Code adapted from "Retrieve Your Gmail Emails Using PHP and IMAP" by David Walsh ( https://davidwalsh.name/gmail-php-imap ).
// Reference: http://php.net/manual/en/function.imap-open.php
public function imap () {
$array_messages = array();
// Attempt a connection.
$this->inbox = imap_open($this->array_parameters['hostname'], $this->array_parameters['username'], $this->array_parameters['password']) or die("I cannot connect: " . imap_last_error());
// Grab the Messages.
$emails = imap_search($this->inbox, 'ALL');
if( is_array($emails) && ( count($emails) > 0 ) ):
$user = $this->flexi_auth->get_user_identity();
// Organise the Messages in chronological order.
rsort($emails);
foreach($emails as $email_number):
$note_id = 0;
if ( $user == $this->flexi_auth->get_user_identity() ):
// Get the information specific to each Message.
$overview = imap_fetch_overview($this->inbox, $email_number, 0);
$message = imap_fetchbody($this->inbox, $email_number, 2);
// Get the meta data.
$array_messages['seen'] = $overview[0]->seen;
$array_messages['subject'] = $overview[0]->subject;
$array_messages['from'] = $overview[0]->from;
// Format the time.
$date = DateTime::createFromFormat( 'D, d M Y H:i:s O', $overview[0]->date);
$array_messages['date'] = $date->format('Y-m-d H:i:s');
// Get the Message.
$objMessage = (new EmailParser())->parse($message);
$fragment = current($objMessage->getFragments());
$array_messages['message'] = $fragment->getContent();
endif;
$note_id = $this->messages_model->add(
$array_messages['from'],
$array_messages['date'],
$array_messages['seen'],
$array_messages['message'],
$array_messages['subject']
);
if ( $note_id > 0 ):
imap_delete($this->inbox, $email_number);
endif;
endforeach;
endif;
imap_close($this->inbox, CL_EXPUNGE);
return true;
}
If I swap $fragment->getContent() for quoted_printable_decode($message), everything works.
I'm not seeing any errors with EmailReplyParser in so far as referencing it (the installation via Composer went without a problem).

sqlite3 replacement for sqlite_has_more

First of thank you for your help.
The code piece "while (sqlite_has_more($dres))" is using sqlite2 and I need sqlite3. If there isn't a replacement for has_more is there another code I can use to still Find whether or not more rows are available?
F.Y.I. The server updated their stuff which included their sqlite and now I have to fix this last peice of code to get the schedule to populate and not give me this error.
Fatal error: Non-static method SQLite3::open() cannot be called statically in /home/server/public_html/current-list.php on line 57
$row_num = 0;
if ($dbh = SQLite3::open($sked_path))
{
$qsql = "SELECT rowid,* FROM sked ORDER BY sk_dow_num, sk_time_start, sk_time_end";
$dres = SQLite3::query($dbh, $qsql);
if (SQLite3::num_Rows($dres) > 0)
{
$last_dow = "";
$last_start = "0000";
$last_end = "0000";
while (sqlite_has_more($dres))
{
$ska = Sqlite3Result::fetchArray($dres, SQLITE3_ASSOC);
$rid = $ska['rowid'];
$dow = $ska['sk_dow_name'];
$start = $ska['sk_time_start'];
$end = $ska['sk_time_end'];
$title = preg_replace("/<br\s*\/*>/", " ", $ska['sk_show_title']);
$show_dow = strtoupper($dow);
$show_start = strtoupper(formatTimeAmPm($start));
$show_end = strtoupper(formatTimeAmPm($end));
$show_style = "";
if (stristr($title, "Encore Show"))
$show_style = " class=\"$text_style\"";
Something like ...
<?php
$dbh = new SQLite3;
if ( !$dbh->open($sked_path) ) {
trigger_error('...error handling...', E_USER_ERROR);
}
else {
$dres = $dbh->query('
SELECT
rowid,*
FROM
sked
ORDER BY
sk_dow_num, sk_time_start, sk_time_end
');
if ( !$dres ) {
trigger_error('...error handling...', E_USER_ERROR);
}
else {
$ska = $dres->fetchArray(SQLITE3_ASSOC);
if ( !$ska ) {
onNoRecords();
}
else {
do {
doSomethingWithRowData($ska);
}
while( false!=($ska=$dres->fetchArray(SQLITE3_ASSOC)) );
}
}
}
(completely untested)

Warning: strpos() expects parameter 1 to be string, resource

I recently migrated a PHP site to my server and after migration I receive this error message. As I'm not really familiar with PHP, I'd really appreciate any help. Thanks.
Warning: strpos() expects parameter 1 to be string, resource given in
.../public_html/store /product_list.php on line 121
Line 121 is as follows...
$exists = (strpos($handle, "Resource id") !== false) ? true : false;
Here is the rest of the code on the top of the page for relevance.
<?php session_start();
include_once("../includes/define.inc.php");
include("../includes/common.php");
include("../includes/mysql_functions.php");
if( isset( $_GET['category'] ) )
{
$exists = checkIfExists("aw_category", "aw_category_urlalias='". $_GET['category']."'", "aw_category_id");
if( !$exists )
{
header("Location: " . PRODUCT_LIST );
}
}
$get_category = ( isset( $_GET['category'] ) ) ? $_GET['category'] : "";
$category_id = ( $get_category == "" ) ? "" : getCategoryIDByAlias( $get_category );
$get_page = (isset($_GET['page']) ) ? $_GET['page'] : 0;
/*category menu*/
$qry_cat = "SELECT aw_category_urlalias, aw_category_id,aw_category_name,aw_category_order,aw_category_status FROM aw_category WHERE aw_category_status = 1 ORDER BY aw_category_order asc";
$result_cat = Query($qry_cat);
/*product*/
$qry_pro = "SELECT *
FROM aw_product
INNER JOIN aw_category
ON aw_product.aw_product_category = aw_category.aw_category_id
INNER JOIN aw_image
ON aw_product.aw_product_id = aw_image.aw_img_prodid
WHERE aw_product.aw_product_status = 1";
if( $category_id == "" )
{ //Feature Product
$qry_pro .= " AND aw_product.aw_product_category = 1";
} else {
$qry_pro .= " AND aw_product.aw_product_category = ".$category_id."";
}
$qry_pro .= " GROUP BY aw_product.aw_product_id
ORDER BY aw_product.aw_product_priority desc,aw_product.aw_product_date desc";
if( $get_category=="" )
{ //Feature Product
$qry_pro .= " LIMIT 6";
}
$result_pro = Query( $qry_pro );
//$row_pro = mysql_fetch_array($result_pro);
$result_pro2 = Query( $qry_pro );
if( !$get_category == "" )
{
/*Pagination*/
$num_per_page= 12;
$num_rows = mysql_num_rows($result_pro);
$num_pages = ceil($num_rows/$num_per_page);
$nav = "";
$begin = $get_page * $num_per_page;
$qry_pro .= " LIMIT " . $begin . ",12";
$result_pro = Query( $qry_pro );
$row_pro = mysql_fetch_array($result_pro);
if( $get_page > 0 )
{
$nav ="<a class=\"page_a\" href=\"".PRODUCT_LIST."?category=".$get_category."&page=".( $get_page-1 )."\">« Previous</a> | ";
}
for($p=0;$p<$num_pages;$p++)
{
if($get_page == $p)
$nav .="<a class=\"page_a\" style='text-decoration:underline' href=\"".PRODUCT_LIST."?category=".$get_category."&page=".$p."\">".($p+1)."</a> | ";
else
$nav .="<a class=\"page_a\" href=\"".PRODUCT_LIST."?category=".$get_category."&page=".$p."\">".($p+1)."</a> | ";
}
if($get_page<$num_pages-1)
{
$nav .="<a class=\"page_a\" href=\"".PRODUCT_LIST."?category=".$get_category."&page=".($get_page+1)."\"> Next »</a>";
}
}//-------
/*news*/
$qry_news = "SELECT aw_news_title FROM aw_news ORDER BY aw_news_date desc LIMIT 8";
$result_news = Query($qry_news);
function getCategoryIDByAlias( $alias )
{
$query = "SELECT aw_category_id FROM aw_category WHERE aw_category_urlalias='".$alias."'";
$rs = Query( $query );
$row = mysql_fetch_array( $rs );
return $row['aw_category_id'];
}
function checkIfThumbExists( $thumb )
{
//$exists = ( file_exists( $img_src_thumb ) ) ? true : false;
//echo $exists;
//$exists = ( is_file( $img_src_thumb ) ) ? true : false;
//echo $exists;
//$AgetHeaders = #get_headers( $img_src_thumb );
//$exists = ( preg_match( "|200|", $AgetHeaders[0] ) ) ? true : false;
//echo $exists;
//$header_response = get_headers($img_src_thumb, 1);
//$exists = ( strpos( $header_response[0], "404" ) !== false ) ? false : true;;
//echo $exists;
$handle = #fopen($thumb, 'r');
$exists = (strpos($handle, "Resource id") !== false) ? true : false;
if( $exists )
{
$size = getimagesize( $thumb );
if( $size[3] == 'width="214" height="214"')
{
$exists = true;
} else {
$exists = false;
}
}
return $exists;
}
?>
Try replacing line 121 with the following:
$handle = #file_get_contents($thumb);
$handle = #fopen($thumb, 'r');
$handle not is string
The error is clear. Read manual of stropos()
It need to take a string in parameter, but in you case you set there one source($handle = #fopen($thumb, 'r');) and one string("Resource id")
Use file_get_contents, as example.
fopen returns a resource and strpos expects the first parameter to be a string.
You may use file_get_contents instead, but are you sure you want to check the binary data of a image?
$data = file_get_contents($thumb);
I don't know what are you trying to do with this line, but if you want to weather the file exists or not, i recommend you to use the native PHP functión file_exists, that gives you the chance to check if the file exists or not:
$exists = file_exists($thumb)
Here is PHP reference.
http://es1.php.net/manual/es/function.file-exists.php
As mentioned in other answers you are giving strpos a file handle or 'resource', which is wrong.
However, it looks like you want to test is if the file exists so I would simply do:
$handle = #fopen($thumb, 'r');
if($handle)
{
// File exists
}
else
{
// File doesn't exist
}
As fopen() will return a pointer (resource) if the file can be opened, else false if not.
file_get_contents() looks like the wrong option as it appears you are trying to open and image, so why would you want to search the binary for a string.

MYSQLi SELECT Fetch Object

if ( isset($_POST['update']) ){
$db=mysqli_connect("localhost","****","****","****");
$lasttime = isset($_POST['timestamp']) ? $_POST['timestamp'] : 0;
while (1){
sleep(1);
clearstatcache();
$mresult = mysqli_query($db,"SELECT * FROM tblchat WHERE msg_datetime > $lasttime");
if (!empty($mresult)){ break; }
}
$msgs = array();
while ($row = mysqli_fetch_object( $mresult )) { $msgs[] = $row; }
mysqli_free_result($mresult);
$response = array();
$response['msgs'] = $msgs;
echo json_encode($response);
flush();
mysqli_close($db);
exit();
}
The code is the server for a long polling connection with client. If update is requested, the while loops check for any new messages received after the timestamp sent with the update request. If found, it puts the result in an array and echo it back to the client.
The resulting output is something like this [msgs:[{msg_from:"",msg_to:"",msg:"",msg_datetime:""},{msg_from:"",msg_to:"",msg:"",msg_datetime:""}]]
The code works fine for the first time and send all the recent messages well encapsulated but then it again sends an empty array of messages. Please guide me.
solved the issue with mysqli_num_rows
if (mysqli_num_rows($mresult)){ $msgs = array(); while ($row = mysqli_fetch_object( $mresult )) { $msgs[] = $row; } mysqli_free_result($mresult); break; }
if (mysqli_num_rows($wresult)){ $writers = array(); while ($row = mysqli_fetch_object( $wresult )) { $writers[] = $row; } mysqli_free_result($wresult); break; }
thanks everyone for their help!

Categories