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).
Related
Problem:
run_overview() displays account_page-overview.php well.
The problem is that it blocks footer(), so the footer part disappears on frontend.
When I remove 'require $template;' of the run_overview(), it shows a footer part well, but doesn't show run_overview() part.
Action I took:
I tried changing the following code (and removed require $template;), but it doesn't display run_overview() part.
include locate_template('public/views/account_page-overview.php', false, false);
Need Help:
Would you please let me know if there is another method to display both run_overview() and footer()?
PHP Code:
private function run_overview(){
/*
* #param none
* #return none (print html)
*/
global $indeed_db;
$post_overview = get_user_meta($this->uid, 'uap_overview_post', true);
if ($post_overview && $post_overview!=-1){
//print the post for user
$post = get_post($post_overview);
$data['message'] = $post->post_content;
} else {
//predifined message
$data['message'] = uap_replace_constants($this->account_page_settings['uap_tab_overview_content'], $this->uid);
$data['message'] = stripslashes($data['message']);
$data['message'] = uap_correct_text($data['message']);
}
$data['title'] = $this->account_page_settings['uap_tab_overview_title'];
$data['stats'] = $indeed_db->get_stats_for_payments($this->affiliate_id);
$data['stats']['currency'] = get_option('uap_currency');
$data['help_url'] = $url = add_query_arg('uap_aff_subtab', 'help', $this->account_page_base_url);
$data['statsForLast30'] = $indeed_db->getReferralsAmountForLastDays( $this->affiliate_id, 30 );
$data['referralsStats'] = $indeed_db->get_stats_for_reports( 'last_month', $this->affiliate_id );
$data['referralsExtraStats'] = $indeed_db->get_referral_report_by_date( $this->affiliate_id, date( 'Y-m-d h:i:s', time() - 30 * 24 * 60 * 60 ), date( 'Y-m-d h:i:s', time() ) );
$this->print_top_messages();
$fullPath = UAP_PATH . 'public/views/account_page-overview.php';
$searchFilename = 'account_page-overview.php';
$template = apply_filters('uap_filter_on_load_template', $fullPath, $searchFilename );
require $template;
}
private function footer(){
global $indeed_db;
$data['footer_content'] = uap_replace_constants($this->account_page_settings['uap_ap_footer_msg'], $this->uid);
$data['footer_content'] = stripslashes($data['footer_content']);
$fullPath = UAP_PATH . 'public/views/account_page-footer.php';
$searchFilename = 'account_page-footer.php';
$template = apply_filters('uap_filter_on_load_template', $fullPath, $searchFilename );
require $template;
}
Thank you.
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.
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 );
}
I have been trying to export all of our invoices in a specific format for importing into Sage accounting. I have been unable to export via Dataflow as I need to export the customer ID (which strangely is unavailable) and also a couple of static fields to denote tax codes etc…
This has left me with the option of using the API to export the data and write it to a CSV. I have taken an example script I found (sorry can’t remember where in order to credit it...) and made some amendments and have come up with the following:
<?php
$website = 'www.example.com';
$api_login = 'user';
$api_key ='password';
function magento_soap_array($website,$api_login,$api_key,$list_type,$extra_info){
$proxy = new SoapClient('http://'.$website.'/api/soap/?wsdl');
$sessionId = $proxy->login($api_login, $api_key);
$results = $proxy->call($sessionId,$list_type,1);
if($list_type == 'order_invoice.list'){
/*** INVOICES CSV EXPORT START ***/
$filename = "invoices.csv";
$data = "Type,Account Reference,Nominal A/C Ref,Date,Invoice No,Net Amount,Tax Code,Tax Amount\n";
foreach($results as $invoice){
foreach($invoice as $entry => $value){
if ($entry == "order_id"){
$orders = $proxy->call($sessionId,'sales_order.list',$value);
}
}
$type = "SI";
$nominal = "4600";
$format = 'Y-m-d H:i:s';
$date = DateTime::createFromFormat($format, $invoice['created_at']);
$invoicedOn = $date->format('d/m/Y');
$invoiceNo = $invoice['increment_id'];
$subtotal = $invoice['base_subtotal'];
$shipping = $invoice['base_shipping_amount'];
$net = $subtotal+$shipping;
$taxCode = "T1";
$taxAmount = $invoice['tax_amount'];
$orderNumber = $invoice['order_id'];
foreach($orders as $order){
if ($order['order_id'] == $orderNumber){
$accRef = $order['customer_id'];
}
}
$data .= "$type,$accRef,$nominal,$invoicedOn,$invoiceNo,$net,$taxCode,$taxAmount\n";
}
file_put_contents($_SERVER['DOCUMENT_ROOT']."/var/export/" . $filename, "$header\n$data");
/*** INVOICES CSV EXPORT END ***/
}else{
echo "nothing to see here";
}/*** GENERIC PAGES END ***/
}/*** END function magento_soap_array ***/
if($_GET['p']=="1")
{
magento_soap_array($website,$api_login,$api_key,'customer.list','Customer List');
}
else if($_GET['p']=="2")
{
magento_soap_array($website,$api_login,$api_key,'order_creditmemo.list','Credit Note List');
}
else if($_GET['p']=="3")
{
magento_soap_array($website,$api_login,$api_key,'sales_order.list','Orders List');
}
else if($_GET['p']=="4")
{
magento_soap_array($website,$api_login,$api_key,'order_invoice.list','Invoice List');
}
?>
This seems to be working fine, however it is VERY slow and I can’t help but think there must be a better, more efficient way of doing it…
Has anybody got any ideas?
Thanks
Marc
i think on put break; would be okey. because only one key with order_id, no need to looping after found order_id key.
if ($entry == "order_id"){
$orders = $proxy->call($sessionId,'sales_order.list',$value);
break;
}
and you can gather all call(s) and call it with multicall as example:
$client = new SoapClient('http://magentohost/soap/api/?wsdl');
// If somestuff requires api authentification,
// then get a session token
$session = $client->login('apiUser', 'apiKey');
$result = $client->call($session, 'somestuff.method');
$result = $client->call($session, 'somestuff.method', 'arg1');
$result = $client->call($session, 'somestuff.method', array('arg1', 'arg2', 'arg3'));
$result = $client->multiCall($session, array(
array('somestuff.method'),
array('somestuff.method', 'arg1'),
array('somestuff.method', array('arg1', 'arg2'))
));
// If you don't need the session anymore
$client->endSession($session);
source
My current code looks like this:
define ( 'CPU_NAME', 'remote_server' );
$obj = new COM ( 'winmgmts:{impersonationLevel=impersonate}//' . CPU_NAME . '/root/cimv2' );
if ( is_object ( $obj ) ){
$process = $obj->execquery ( "SELECT * FROM Win32_Process" );
}
Where would I put the login credentials for the remote_server?
I see that it would take a username and password, but I'm not sure how to implement that.
Any help would be appreciated.
Reference: http://us3.php.net/manual/en/class.com.php
<?php
$obj = new COM ( 'winmgmts://localhost/root/CIMV2' );
$fso = new COM ( "Scripting.FileSystemObject" );
$wmi_computersystem = $obj->ExecQuery("Select * from Win32_ComputerSystem");
$wmi_bios = $obj->ExecQuery("Select * from Win32_BIOS");
$processor = $obj->ExecQuery("Select * from Win32_Processor");
$PhysicalMemory = $obj->ExecQuery("Select * from Win32_PhysicalMemory");
$BaseBoard = $obj->ExecQuery("Select * from Win32_BaseBoard");
$LogicalDisk = $obj->ExecQuery("Select * from Win32_LogicalDisk");
foreach ( $wmi_computersystem as $wmi_call )
{
$model = $wmi_call->Model;
}
foreach ( $wmi_bios as $wmi_call )
{
$serial = $wmi_call->SerialNumber;
$bios_version = $wmi_call->SMBIOSBIOSVersion;
}
foreach ( $processor as $wmi_processor )
{
$idprocessor = $wmi_processor->ProcessorId;
$Architecture = $wmi_processor->Architecture;
$Name = $wmi_processor->Name;
$Version = $wmi_processor->Version;
}
foreach ( $PhysicalMemory as $wmi_PhysicalMemory )
{
$Capacity = $wmi_PhysicalMemory->Capacity;
$PartNumber = $wmi_PhysicalMemory->PartNumber;
$Name = $wmi_PhysicalMemory->Name;
}
foreach ( $BaseBoard as $wmi_BaseBoard )
{
$SerialNumber = $wmi_BaseBoard->SerialNumber;
}
foreach ( $LogicalDisk as $wmi_LogicalDisk )
{
$SerialNumberDisk = $wmi_LogicalDisk->VolumeSerialNumber;
$FileSystem = $wmi_LogicalDisk->FileSystem;
}
echo "Bios version : ".$bios_version."<br/>
Serial number of bios : ".$serial."<br/>
Hardware Model : ".$model."<br/>
ID-Processor : ".$idprocessor."<br/>
Architecture-Processor : ".$Architecture."<br/>
Name-Processor : ".$Name."<br/>
Version-Processor : ".$Version."<br/>
<hr>
<hr>
PhysicalMemory
<hr>
<hr>
Capacity : ".$Capacity."<br/>
Name : ".$Name."<br/>
<hr>
<hr>
carte mere
<hr>
<hr>
SerialNumber : ".$SerialNumber."<br/>
<hr>
<hr>
disk
<hr>
<hr>
SerialNumber : ".$SerialNumberDisk."<br/>
FileSystem : ".$FileSystem."<br>
";
?>
<?php
$strComputer = "YOURREMOTEHOST";
$objSWbemLocator = new COM ("WbemScripting.SWbemLocator");
$objSWbemServices = $objSWbemLocator->ConnectServer($strComputer, "root\cimv2", "DOMAIN\USER", "Password");
$objSWbemServices->Security_->ImpersonationLevel = 3;
$obj = $objSWbemServices;
$fso = new COM ( "Scripting.FileSystemObject" );
//... insert your code here
//... insert your code here
?>
CONNECTING
For global admins
define("NAMECOMP", 'COMP1'); // COMP1 - name or ip of local or remote computer
$WMI= new COM ( 'winmgmts:{impersonationLevel=impersonate}//'. NAMECOMP.'/root/cimv2' );
For with login and password
$objLocator = new COM("WbemScripting.SWbemLocator");
$objService = $objLocator->ConnectServer(
'ComputerName', //name/ip remote/local comp
"root\cimv2",
'login', //login remote/local comp
'password', //password remote/local comp
"MS_409",
"ntlmdomain: YourDomain" //domain remote/local comp
);
GET INFORMATION
$CountCore=0;
foreach ($WMI->instancesof ( 'Win32_Processor' ) as $proc ) {
++$CountCore;
}
echo 'Count Core = ' . $CountCore;
add information of speed and socket processor
$CountCore=0;
foreach ($WMI->instancesof ( 'Win32_Processor' ) as $Processor) {
++$CountCore;
$Speed=$Processor->CurrentClockSpeed;
$Socket=$Processor->SocketDesignation;
}
echo 'count core = '.$CountCore;
echo 'speed = ' . $Speed. 'Mhz';
echo 'socket = '.$Socket;
get other information simple - just replace class for instancesof ('Win32_Processor')
Information of classes WMI
SEND COMMAND
if ((($_GET['Reboot']==1) OR ($_GET['Shutdown']==1))) {
define("NAMECOMP", 'COMP1');
$WMI= new COM('winmgmts:{impersonationLevel=impersonate,(Shutdown)}//'. NAMECOMP.'/root/cimv2');
foreach($WMI->instancesof('Win32_OperatingSystem') as $mp) {
if ($_GET['Reboot']==1) {
$mp->Reboot;
}
if ($_GET['Shutdown']==1) {
$mp->Shutdown;
}
}
Links:
WMI Isn't Working!
Component_Object_Model
Win32 Classes
For Yii Framework
I know this thread is not the newest but maby this info helps someone.
If you try to read or write Registy keys or installed Software class on a Remote Computer you need to pass the Architecture under the query should run. You can use something like this.
function Connect($server = "RemotePC",$namespace = "root/CIMV2",$impersonate = 3,$Architecture = 64,$userid = null,$password = null){
try {
$wbemnvs = new COM("WbemScripting.SWbemNamedValueSet");
$wbemnvs->add("__ProviderArchitecture", $Architecture);
$wbemnvs->add("__RequiredArchitecture", true);
$wmiLocator = new COM("WbemScripting.SWbemLocator");
$this->wmiNameSpace = $wmiLocator->ConnectServer($server, $namespace, $userid, $password,null,null,128,$wbemnvs);
if($this->wmiNameSpace){
$this->ConnectedServer = $server;
}else{ return false; }
if($impersonate){
// mehr infos: http://msdn.microsoft.com/en-us/library/aa393618%28v=vs.85%29.aspx
$this->wmiNameSpace->Security_->ImpersonationLevel = $impersonate;
}
return true;
}
catch(Exception $e){
$this->wmiNameSpace = NULL;
return false;
}
}
check out my wmi.class.php at: http://scbbb.blogspot.de/2014/02/wmi-via-php.html