Esempio n. 1
0
function canSendPassword()
{
    require_once 'include/SugarPHPMailer.php';
    global $mod_strings;
    global $current_user;
    global $app_strings;
    $mail = new SugarPHPMailer();
    $emailTemp = new EmailTemplate();
    $mail->setMailerForSystem();
    $emailTemp->disable_row_level_security = true;
    if ($current_user->is_admin) {
        if ($emailTemp->retrieve($GLOBALS['sugar_config']['passwordsetting']['generatepasswordtmpl']) == '') {
            return $mod_strings['LBL_EMAIL_TEMPLATE_MISSING'];
        }
        if (empty($emailTemp->body) && empty($emailTemp->body_html)) {
            return $app_strings['LBL_EMAIL_TEMPLATE_EDIT_PLAIN_TEXT'];
        }
        if ($mail->Mailer == 'smtp' && $mail->Host == '') {
            return $mod_strings['ERR_SERVER_SMTP_EMPTY'];
        }
        $email_errors = $mod_strings['ERR_EMAIL_NOT_SENT_ADMIN'];
        if ($mail->Mailer == 'smtp') {
            $email_errors .= "<br>-" . $mod_strings['ERR_SMTP_URL_SMTP_PORT'];
        }
        if ($mail->SMTPAuth) {
            $email_errors .= "<br>-" . $mod_strings['ERR_SMTP_USERNAME_SMTP_PASSWORD'];
        }
        $email_errors .= "<br>-" . $mod_strings['ERR_RECIPIENT_EMAIL'];
        $email_errors .= "<br>-" . $mod_strings['ERR_SERVER_STATUS'];
        return $email_errors;
    } else {
        return $mod_strings['LBL_EMAIL_NOT_SENT'];
    }
}
Esempio n. 2
0
 /**
  * send reminders
  * @param SugarBean $bean
  * @param Administration $admin
  * @param array $recipients
  * @return boolean
  */
 protected function sendReminders(SugarBean $bean, Administration $admin, $recipients)
 {
     global $sugar_config;
     $user = new User();
     $user->retrieve($bean->created_by);
     $OBCharset = $GLOBALS['locale']->getPrecedentPreference('default_email_charset');
     ///////////////////EMAIL///////////////////////////
     require_once "include/SugarPHPMailer.php";
     $mail = new SugarPHPMailer();
     $mail->setMailerForSystem();
     if (empty($admin->settings['notify_send_from_assigning_user'])) {
         $from_address = $admin->settings['notify_fromaddress'];
         $from_name = $admin->settings['notify_fromname'] ? "" : $admin->settings['notify_fromname'];
     } else {
         $from_address = $user->emailAddress->getReplyToAddress($user);
         $from_name = $user->full_name;
     }
     $mail->From = $from_address;
     $mail->FromName = $from_name;
     $mail->Body = "Напоминание о сделке '{$bean->name}' - {$sugar_config['site_url']}/index.php?action=DetailView&module=Opportunities&record={$bean->id}";
     $mail->Subject = "SugarCRM::Напоминание о сделке";
     $oe = new OutboundEmail();
     $oe = $oe->getSystemMailerSettings();
     if (empty($oe->mail_smtpserver)) {
         $GLOBALS['log']->fatal("Email Reminder: error sending email, system smtp server is not set");
         return;
     }
     foreach ($recipients as $r) {
         $mail->ClearAddresses();
         $mail->AddAddress($r['email'], $GLOBALS['locale']->translateCharsetMIME(trim($r['name']), 'UTF-8', $OBCharset));
         $mail->prepForOutbound();
         if (!$mail->Send()) {
             $GLOBALS['log']->fatal("Email Reminder: error sending e-mail (method: {$mail->Mailer}), (error: {$mail->ErrorInfo})");
         }
     }
     ///////////////////SMS///////////////////////////
     require_once 'custom/sms/sms.php';
     $sms = new sms();
     $sms->parent_type = 'Users';
     foreach ($recipients as $r) {
         $sms->parent_id = $r['id'];
         $sms->pname = $r['name'];
         $type = "Напоминание о сделке ";
         $text = $type . $bean->name;
         /*if($sms->send_message($r['number'], $text) == "SENT")
         		return true;
                   else
         		return false;*/
     }
     ///////////////////ALERT/////////////////////////// !TODO
     /*$timeStart = strtotime($db->fromConvert($bean->date_start, 'datetime'));
     		$this->addAlert($app_strings['MSG_JS_ALERT_MTG_REMINDER_CALL'], $bean->name, $app_strings['MSG_JS_ALERT_MTG_REMINDER_TIME'].$timedate->to_display_date_time($db->fromConvert($bean->date_remind, 'datetime')) , $app_strings['MSG_JS_ALERT_MTG_REMINDER_DESC'].$bean->description. $app_strings['MSG_JS_ALERT_MTG_REMINDER_CALL_MSG'] , $timeStart - strtotime($this->now), 'index.php?action=DetailView&module=Opportunities&record=' . $bean->id);
     		*/
     return true;
 }
 public function notify_on_delete($bean, $event, $arguments)
 {
     //Send an email to the department manager
     require_once "include/SugarPHPMailer.php";
     $email_obj = new Email();
     $defaults = $email_obj->getSystemDefaultEmail();
     $mail = new SugarPHPMailer();
     $mail->setMailerForSystem();
     $mail->From = $defaults["email"];
     $mail->FromName = $defaults["name"];
     $mail->Subject = "Account record deleted";
     $mail->Body = "The account record with ID: " . $bean->id . ", Name: " . $bean->name . ", Address: " . $bean->billing_address_street . ", " . $bean->billing_address_city . ", " . $bean->billing_address_state . ", " . $bean->billing_address_postalcode . ", " . $bean->billing_address_country . " is being deleted.";
     $mail->prepForOutbound();
     $mail->AddAddress("*****@*****.**");
     @$mail->Send();
 }
Esempio n. 4
0
function sendSugarPHPMail($tos, $subject, $body)
{
    require_once 'include/SugarPHPMailer.php';
    require_once 'modules/Administration/Administration.php';
    global $current_user;
    $mail = new SugarPHPMailer();
    $admin = new Administration();
    $admin->retrieveSettings();
    if ($admin->settings['mail_sendtype'] == "SMTP") {
        $mail->Host = $admin->settings['mail_smtpserver'];
        $mail->Port = $admin->settings['mail_smtpport'];
        if ($admin->settings['mail_smtpauth_req']) {
            $mail->SMTPAuth = TRUE;
            $mail->Username = $admin->settings['mail_smtpuser'];
            $mail->Password = $admin->settings['mail_smtppass'];
        }
        $mail->Mailer = "smtp";
        $mail->SMTPKeepAlive = true;
    } else {
        $mail->mailer = 'sendmail';
    }
    $mail->IsSMTP();
    // send via SMTP
    if ($admin->settings['mail_smtpssl'] == '2') {
        $mail->SMTPSecure = "tls";
    } elseif ($admin->settings['mail_smtpssl'] == '1') {
        $mail->SMTPSecure = "ssl";
    }
    $mail->CharSet = 'UTF-8';
    $mail->From = $admin->settings['notify_fromaddress'];
    $mail->FromName = $admin->settings['notify_fromname'];
    $mail->ContentType = "text/html";
    //"text/plain"
    $mail->IsHTML(true);
    $mail->Subject = $subject;
    $mail->Body = $body;
    foreach ($tos as $name => $address) {
        $mail->AddAddress("{$address}", "{$name}");
    }
    if (!$mail->send()) {
        $GLOBALS['log']->info("sendSugarPHPMail - Mailer error: " . $mail->ErrorInfo);
        return false;
    } else {
        return true;
    }
}
 function SendEmail($emailsTo, $emailSubject, $emailBody)
 {
     $emailObj = new Email();
     $defaults = $emailObj->getSystemDefaultEmail();
     $mail = new SugarPHPMailer();
     $mail->setMailerForSystem();
     $mail->From = $defaults['email'];
     $mail->FromName = $defaults['name'];
     $mail->ClearAllRecipients();
     $mail->ClearReplyTos();
     $mail->Subject = from_html($emailSubject);
     $mail->Body = $emailBody;
     $mail->AltBody = from_html($emailBody);
     $mail->prepForOutbound();
     foreach ($emailsTo as &$value) {
         $mail->AddAddress($value);
     }
     if (@$mail->Send()) {
     }
 }
Esempio n. 6
0
 function sendEmail($emailTo, $emailSubject, $emailBody, $altemailBody, SugarBean $relatedBean = null)
 {
     require_once 'modules/Emails/Email.php';
     require_once 'include/SugarPHPMailer.php';
     $emailObj = new Email();
     $emailSettings = getPortalEmailSettings();
     $mail = new SugarPHPMailer();
     $mail->setMailerForSystem();
     $mail->From = $emailSettings['from_address'];
     $mail->FromName = $emailSettings['from_name'];
     $mail->ClearAllRecipients();
     $mail->ClearReplyTos();
     $mail->Subject = from_html($emailSubject);
     $mail->Body = $emailBody;
     $mail->AltBody = $altemailBody;
     $mail->prepForOutbound();
     $mail->AddAddress($emailTo);
     //now create email
     if (@$mail->Send()) {
         $emailObj->to_addrs = '';
         $emailObj->type = 'archived';
         $emailObj->deleted = '0';
         $emailObj->name = $mail->Subject;
         $emailObj->description = $mail->AltBody;
         $emailObj->description_html = $mail->Body;
         $emailObj->from_addr = $mail->From;
         if ($relatedBean instanceof SugarBean && !empty($relatedBean->id)) {
             $emailObj->parent_type = $relatedBean->module_dir;
             $emailObj->parent_id = $relatedBean->id;
         }
         $emailObj->date_sent = TimeDate::getInstance()->nowDb();
         $emailObj->modified_user_id = '1';
         $emailObj->created_by = '1';
         $emailObj->status = 'sent';
         $emailObj->save();
     }
 }
Esempio n. 7
0
    public function run($data)
    {
        global $sugar_config, $timedate;
        $bean = BeanFactory::getBean('AOR_Scheduled_Reports', $data);
        $report = $bean->get_linked_beans('aor_report', 'AOR_Reports');
        if ($report) {
            $report = $report[0];
        } else {
            return false;
        }
        $html = "<h1>{$report->name}</h1>" . $report->build_group_report();
        $html .= <<<EOF
        <style>
        h1{
            color: black;
        }
        .list
        {
            font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;font-size: 12px;
            background: #fff;margin: 45px;width: 480px;border-collapse: collapse;text-align: left;
        }
        .list th
        {
            font-size: 14px;
            font-weight: normal;
            color: black;
            padding: 10px 8px;
            border-bottom: 2px solid black};
        }
        .list td
        {
            padding: 9px 8px 0px 8px;
        }
        </style>
EOF;
        $emailObj = new Email();
        $defaults = $emailObj->getSystemDefaultEmail();
        $mail = new SugarPHPMailer();
        /*$result = $report->db->query($report->build_report_query());
          $reportData = array();
          while($row = $report->db->fetchByAssoc($result, false))
          {
              $reportData[] = $row;
          }
          $fields = $report->getReportFields();
          foreach($report->get_linked_beans('aor_charts','AOR_Charts') as $chart){
              $image = $chart->buildChartImage($reportData,$fields,false);
              $mail->AddStringEmbeddedImage($image,$chart->id,$chart->name.".png",'base64','image/png');
              $html .= "<img src='cid:{$chart->id}'>";
          }*/
        $mail->setMailerForSystem();
        $mail->IsHTML(true);
        $mail->From = $defaults['email'];
        $mail->FromName = $defaults['name'];
        $mail->Subject = from_html($bean->name);
        $mail->Body = $html;
        $mail->prepForOutbound();
        $success = true;
        $emails = $bean->get_email_recipients();
        foreach ($emails as $email_address) {
            $mail->ClearAddresses();
            $mail->AddAddress($email_address);
            $success = $mail->Send() && $success;
        }
        $bean->last_run = $timedate->getNow()->asDb(false);
        $bean->save();
        return true;
    }
 function _Send_Email($fromAddress, $fromName, $toAddresses, $subject, $module, $bean_id, $body, $attachedFiles = array(), $saveCopy = true)
 {
     global $current_user, $sugar_config;
     if ($sugar_config['dbconfig']['db_host_name'] != '10.2.1.20' && $sugar_config['dbconfig']['db_host_name'] != '127.0.0.1') {
         $send_ok = false;
     } else {
         $send_ok = true;
     }
     //Replace general variables for all email templates.
     $keys = array('$contact_name', '$contact_first_name', '$sales_full_name', '$sales_first_name');
     $vars_count = $this->substr_count_array($body, $keys);
     if (($module == 'Contacts' || $module == 'Leads') && $vars_count > 0) {
         $clientObj = BeanFactory::getBean($module, $bean_id);
         $sale_person = $this->_getSalesPerson($clientObj);
         $data = array($clientObj->first_name . ' ' . $clientObj->last_name, $clientObj->first_name, $sale_person['sales_full_name'], $sale_person['sales_first_name']);
         $body = str_replace($keys, $data, $body);
     }
     //if(!$send_ok) $GLOBALS['log']->error('Mail Service: not a Live Server, trashmail accounts service only. ');
     $emailObj = new Email();
     $defaults = $emailObj->getSystemDefaultEmail();
     $mail = new SugarPHPMailer();
     $mail->setMailerForSystem();
     $mail->From = $fromAddress;
     $mail->FromName = $fromName;
     $mail->Subject = $subject;
     $mail->Body = $body;
     $mail->ContentType = "text/html";
     $mail->prepForOutbound();
     $test_addr = false;
     foreach ($toAddresses as $name => $email) {
         $mail->AddAddress($email, $name);
         if (substr_count($email, '@trashmail') > 0 || $email == '*****@*****.**') {
             $test_addr = true;
         }
     }
     if ($send_ok || $test_addr) {
         if (!empty($attachedFiles)) {
             foreach ($attachedFiles as $files) {
                 $mail->AddAttachment($files['file_location'] . $files['filename'], $files['filename'], 'base64');
             }
         }
         if (@$mail->Send()) {
             if ($saveCopy) {
                 $emailObj->from_addr = $fromAddress;
                 $emailObj->reply_to_addr = implode(',', $toAddresses);
                 $emailObj->to_addrs = implode(',', $toAddresses);
                 $emailObj->name = $subject;
                 $emailObj->type = 'out';
                 $emailObj->status = 'sent';
                 $emailObj->intent = 'pick';
                 $emailObj->parent_type = $module;
                 $emailObj->parent_id = $bean_id;
                 $emailObj->description_html = $body;
                 $emailObj->description = $body;
                 $emailObj->assigned_user_id = $current_user->id;
                 $emailObj->save();
                 if (!empty($attachedFiles)) {
                     foreach ($attachedFiles as $files) {
                         $Notes = BeanFactory::getBean('Notes');
                         $Notes->name = $files['filename'];
                         $Notes->file_mime_type = 'pdf';
                         $Notes->filename = $files['filename'];
                         $Notes->parent_type = 'Emails';
                         $Notes->parent_id = $emailObj->id;
                         $Notes->save();
                         $pdf = file_get_contents($files['file_location'] . $files['filename']);
                         file_put_contents('upload/' . $Notes->id, $pdf);
                     }
                 }
             }
             return true;
         } else {
             $GLOBALS['log']->info("Mailer error: " . $mail->ErrorInfo);
             return false;
         }
     } else {
         $GLOBALS['log']->error('Mail Service: not a Live Server(' . $sugar_config['dbconfig']['db_host_name'] . '), trashmail accounts service only. Cannot send mail to ' . print_r($toAddresses, true));
         $emailObj->from_addr = $fromAddress;
         $emailObj->reply_to_addr = implode(',', $toAddresses);
         $emailObj->to_addrs = implode(',', $toAddresses);
         $emailObj->name = 'TEST MODE, NOT SENT: ' . $subject;
         $emailObj->type = 'out';
         $emailObj->status = 'NOT sent';
         $emailObj->intent = 'pick';
         $emailObj->parent_type = $module;
         $emailObj->parent_id = $bean_id;
         $emailObj->description_html = $body;
         $emailObj->description = $body;
         $emailObj->assigned_user_id = $current_user->id;
         $emailObj->save();
         return false;
     }
 }
Esempio n. 9
0
    if ($prevemail != "*****@*****.**") {
        $idx++;
        $emailbody[$idx]['email'] = "*****@*****.**";
        $emailbody[$idx]['subject'] = "CS All Unassigned Case Report";
        $emailbody[$idx]['body'] .= "The following cases are unassigned :<br /><br />";
        $emailbody[$idx]['body'] .= "<a href='" . $row['link'] . "'>" . $row['case_number'] . " - " . $row['name'] . "</a><br />";
        $prevemail = "*****@*****.**";
    } else {
        $emailbody[$idx]['body'] .= "<a href='" . $row['link'] . "'>" . $row['case_number'] . " - " . $row['name'] . "</a><br />";
        $prevemail = "*****@*****.**";
    }
}
/* Send out emails */
$emailObj = new Email();
$defaults = $emailObj->getSystemDefaultEmail();
$mail = new SugarPHPMailer();
$mail->setMailerForSystem();
$mail->From = $defaults['email'];
$mail->FromName = $defaults['name'];
foreach ($emailbody as $data) {
    $mail->ClearAllRecipients();
    $mail->ClearReplyTos();
    $mail->Subject = $data['subject'];
    $mail->IsHTML(true);
    $mail->Body = $data['body'];
    $mail->AltBody = $data['body'];
    $mail->prepForOutbound();
    $mail->AddAddress($data['email']);
    $mail->Send();
}
/* Clean up shop */
Esempio n. 10
0
/* Query database to get case aging */
$query = 'select c.case_number,c.name,concat("http://dcmaster.mydatacom.com/index.php?module=Cases&action=DetailView&record=",c.id) as link from cases as c where c.id not in (select distinct case_id from projects_cases) and c.account_id is null and c.status="New" and c.deleted=0;';
$db = DBManagerFactory::getInstance();
$result = $db->query($query, true, 'Case Unassigned Query Failed');
/* Create email bodies to send */
$linecount = 0;
$emailbody = "The following cases are currently unassigned:<br /><br />";
while (($row = $db->fetchByAssoc($result)) != null) {
    $emailbody .= "<a href='" . $row['link'] . "'>" . $row['case_number'] . " - " . $row['name'] . " </a><br />";
    $linecount++;
}
if ($linecount > 0) {
    /* Send out emails */
    $emailObj = new Email();
    $defaults = $emailObj->getSystemDefaultEmail();
    $mail = new SugarPHPMailer();
    $mail->setMailerForSystem();
    $mail->From = $defaults['email'];
    $mail->FromName = $defaults['name'];
    $mail->ClearAllRecipients();
    $mail->ClearReplyTos();
    $mail->Subject = "Unassigned Case Report";
    $mail->IsHTML(true);
    $mail->Body = $emailbody;
    $mail->AltBody = $emailbody;
    $mail->prepForOutbound();
    $mail->AddAddress('*****@*****.**');
    $mail->Send();
    /* Clean up shop */
    $mail->SMTPClose();
}
Esempio n. 11
0
 /**
  * Sends Email
  * @return bool True on success
  */
 function send()
 {
     global $mod_strings, $app_strings;
     global $current_user;
     global $sugar_config;
     global $locale;
     $OBCharset = $locale->getPrecedentPreference('default_email_charset');
     $mail = new SugarPHPMailer();
     foreach ($this->to_addrs_arr as $addr_arr) {
         if (empty($addr_arr['display'])) {
             $mail->AddAddress($addr_arr['email'], "");
         } else {
             $mail->AddAddress($addr_arr['email'], $locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
         }
     }
     foreach ($this->cc_addrs_arr as $addr_arr) {
         if (empty($addr_arr['display'])) {
             $mail->AddCC($addr_arr['email'], "");
         } else {
             $mail->AddCC($addr_arr['email'], $locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
         }
     }
     foreach ($this->bcc_addrs_arr as $addr_arr) {
         if (empty($addr_arr['display'])) {
             $mail->AddBCC($addr_arr['email'], "");
         } else {
             $mail->AddBCC($addr_arr['email'], $locale->translateCharsetMIME(trim($addr_arr['display']), 'UTF-8', $OBCharset));
         }
     }
     $mail = $this->setMailer($mail);
     // FROM ADDRESS
     if (!empty($this->from_addr)) {
         $mail->From = $this->from_addr;
     } else {
         $mail->From = $current_user->getPreference('mail_fromaddress');
         $this->from_addr = $mail->From;
     }
     // FROM NAME
     if (!empty($this->from_name)) {
         $mail->FromName = $this->from_name;
     } else {
         $mail->FromName = $current_user->getPreference('mail_fromname');
         $this->from_name = $mail->FromName;
     }
     //Reply to information for case create and autoreply.
     if (!empty($this->reply_to_name)) {
         $ReplyToName = $this->reply_to_name;
     } else {
         $ReplyToName = $mail->FromName;
     }
     if (!empty($this->reply_to_addr)) {
         $ReplyToAddr = $this->reply_to_addr;
     } else {
         $ReplyToAddr = $mail->From;
     }
     $mail->Sender = $mail->From;
     /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */
     $mail->AddReplyTo($ReplyToAddr, $locale->translateCharsetMIME(trim($ReplyToName), 'UTF-8', $OBCharset));
     //$mail->Subject = html_entity_decode($this->name, ENT_QUOTES, 'UTF-8');
     $mail->Subject = $this->name;
     ///////////////////////////////////////////////////////////////////////
     ////	ATTACHMENTS
     foreach ($this->saved_attachments as $note) {
         $mime_type = 'text/plain';
         if ($note->object_name == 'Note') {
             if (!empty($note->file->temp_file_location) && is_file($note->file->temp_file_location)) {
                 // brandy-new file upload/attachment
                 $file_location = $sugar_config['upload_dir'] . $note->id;
                 $filename = $note->file->original_file_name;
                 $mime_type = $note->file->mime_type;
             } else {
                 // attachment coming from template/forward
                 $file_location = rawurldecode(UploadFile::get_file_path($note->filename, $note->id));
                 // cn: bug 9723 - documents from EmailTemplates sent with Doc Name, not file name.
                 $filename = !empty($note->filename) ? $note->filename : $note->name;
                 $mime_type = $note->file_mime_type;
             }
         } elseif ($note->object_name == 'DocumentRevision') {
             // from Documents
             $filePathName = $note->id;
             // cn: bug 9723 - Emails with documents send GUID instead of Doc name
             $filename = $note->getDocumentRevisionNameForDisplay();
             $file_location = getcwd() . '/' . $GLOBALS['sugar_config']['upload_dir'] . $filePathName;
             $mime_type = $note->file_mime_type;
         }
         // strip out the "Email attachment label if exists
         $filename = str_replace($mod_strings['LBL_EMAIL_ATTACHMENT'] . ': ', '', $filename);
         //is attachment in our list of bad files extensions?  If so, append .txt to file location
         //get position of last "." in file name
         $file_ext_beg = strrpos($file_location, ".");
         $file_ext = "";
         //get file extension
         if ($file_ext_beg > 0) {
             $file_ext = substr($file_location, $file_ext_beg + 1);
         }
         //check to see if this is a file with extension located in "badext"
         foreach ($sugar_config['upload_badext'] as $badExt) {
             if (strtolower($file_ext) == strtolower($badExt)) {
                 //if found, then append with .txt to filename and break out of lookup
                 //this will make sure that the file goes out with right extension, but is stored
                 //as a text in db.
                 $file_location = $file_location . ".txt";
                 break;
                 // no need to look for more
             }
         }
         $mail->AddAttachment($file_location, $locale->translateCharsetMIME(trim($filename), 'UTF-8', $OBCharset), 'base64', $mime_type);
         // embedded Images
         if ($note->embed_flag == true) {
             $cid = $filename;
             $mail->AddEmbeddedImage($file_location, $cid, $filename, 'base64', $mime_type);
         }
     }
     ////	END ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////
     $mail = $this->handleBody($mail);
     $GLOBALS['log']->debug('Email sending --------------------- ');
     ///////////////////////////////////////////////////////////////////////
     ////	I18N TRANSLATION
     $mail->prepForOutbound();
     ////	END I18N TRANSLATION
     ///////////////////////////////////////////////////////////////////////
     if ($mail->Send()) {
         ///////////////////////////////////////////////////////////////////
         ////	INBOUND EMAIL HANDLING
         // mark replied
         if (!empty($_REQUEST['inbound_email_id'])) {
             $ieMail = new Email();
             $ieMail->retrieve($_REQUEST['inbound_email_id']);
             $ieMail->status = 'replied';
             $ieMail->save();
         }
         $GLOBALS['log']->debug(' --------------------- buh bye -- sent successful');
         ////	END INBOUND EMAIL HANDLING
         ///////////////////////////////////////////////////////////////////
         return true;
     }
     $GLOBALS['log']->debug($app_strings['LBL_EMAIL_ERROR_PREPEND'] . $mail->ErrorInfo);
     return false;
 }
Esempio n. 12
0
 /**
  * send reminders
  * @param SugarBean $bean
  * @param Administration $admin
  * @param array $recipients
  * @return boolean
  */
 protected function sendReminders(SugarBean $bean, Administration $admin, $recipients)
 {
     if (empty($_SESSION['authenticated_user_language'])) {
         $current_language = $GLOBALS['sugar_config']['default_language'];
     } else {
         $current_language = $_SESSION['authenticated_user_language'];
     }
     if (!empty($bean->created_by)) {
         $user_id = $bean->created_by;
     } else {
         if (!empty($bean->assigned_user_id)) {
             $user_id = $bean->assigned_user_id;
         } else {
             $user_id = $GLOBALS['current_user']->id;
         }
     }
     $user = new User();
     $user->retrieve($bean->created_by);
     $OBCharset = $GLOBALS['locale']->getPrecedentPreference('default_email_charset');
     $mail = new SugarPHPMailer();
     $mail->setMailerForSystem();
     if (empty($admin->settings['notify_send_from_assigning_user'])) {
         $from_address = $admin->settings['notify_fromaddress'];
         $from_name = $admin->settings['notify_fromname'] ? "" : $admin->settings['notify_fromname'];
     } else {
         $from_address = $user->emailAddress->getReplyToAddress($user);
         $from_name = $user->full_name;
     }
     $mail->From = $from_address;
     $mail->FromName = $from_name;
     $xtpl = new XTemplate(get_notify_template_file($current_language));
     $xtpl = $this->setReminderBody($xtpl, $bean, $user);
     $template_name = $GLOBALS['beanList'][$bean->module_dir] . 'Reminder';
     $xtpl->parse($template_name);
     $xtpl->parse($template_name . "_Subject");
     $mail->Body = from_html(trim($xtpl->text($template_name)));
     $mail->Subject = from_html($xtpl->text($template_name . "_Subject"));
     $oe = new OutboundEmail();
     $oe = $oe->getSystemMailerSettings();
     if (empty($oe->mail_smtpserver)) {
         Log::fatal("Email Reminder: error sending email, system smtp server is not set");
         return;
     }
     foreach ($recipients as $r) {
         $mail->ClearAddresses();
         $mail->AddAddress($r['email'], $GLOBALS['locale']->translateCharsetMIME(trim($r['name']), 'UTF-8', $OBCharset));
         $mail->prepForOutbound();
         if (!$mail->Send()) {
             Log::fatal("Email Reminder: error sending e-mail (method: {$mail->Mailer}), (error: {$mail->ErrorInfo})");
         }
     }
     return true;
 }
 /**
  * Sends the users password to the email address or sends 
  *
  * @param unknown_type $user_id
  * @param unknown_type $password
  */
 function sendEmailPassword($user_id, $password)
 {
     $result = $GLOBALS['db']->query("SELECT email1, email2, first_name, last_name FROM users WHERE id='{$user_id}'");
     $row = $GLOBALS['db']->fetchByAssoc($result);
     global $sugar_config;
     if (empty($row['email1']) && empty($row['email2'])) {
         $_SESSION['login_error'] = 'Please contact an administrator to setup up your email address associated to this account';
         return;
     }
     require_once "include/SugarPHPMailer.php";
     $notify_mail = new SugarPHPMailer();
     $notify_mail->CharSet = $sugar_config['default_charset'];
     $notify_mail->AddAddress(!empty($row['email1']) ? $row['email1'] : $row['email2'], $row['first_name'] . ' ' . $row['last_name']);
     if (empty($_SESSION['authenticated_user_language'])) {
         $current_language = $sugar_config['default_language'];
     } else {
         $current_language = $_SESSION['authenticated_user_language'];
     }
     $mail_settings = new Administration();
     $mail_settings->retrieveSettings('mail');
     $notify_mail->Subject = 'Sugar Token';
     $notify_mail->Body = 'Your sugar session authentication token  is: ' . $password;
     if ($mail_settings->settings['mail_sendtype'] == "SMTP") {
         $notify_mail->Mailer = "smtp";
         $notify_mail->Host = $mail_settings->settings['mail_smtpserver'];
         $notify_mail->Port = $mail_settings->settings['mail_smtpport'];
         if ($mail_settings->settings['mail_smtpauth_req']) {
             $notify_mail->SMTPAuth = TRUE;
             $notify_mail->Username = $mail_settings->settings['mail_smtpuser'];
             $notify_mail->Password = $mail_settings->settings['mail_smtppass'];
         }
     }
     $notify_mail->From = '*****@*****.**';
     $notify_mail->FromName = 'Sugar Authentication';
     if (!$notify_mail->Send()) {
         $GLOBALS['log']->warn("Notifications: error sending e-mail (method: {$notify_mail->Mailer}), (error: {$notify_mail->ErrorInfo})");
     } else {
         $GLOBALS['log']->info("Notifications: e-mail successfully sent");
     }
 }
Esempio n. 14
0
 function send()
 {
     global $mod_strings;
     global $current_user;
     global $sugar_config;
     global $locale;
     $mail = new SugarPHPMailer();
     foreach ($this->to_addrs_arr as $addr_arr) {
         if (empty($addr_arr['display'])) {
             $mail->AddAddress($addr_arr['email'], "");
         } else {
             $mail->AddAddress($addr_arr['email'], $addr_arr['display']);
         }
     }
     foreach ($this->cc_addrs_arr as $addr_arr) {
         if (empty($addr_arr['display'])) {
             $mail->AddCC($addr_arr['email'], "");
         } else {
             $mail->AddCC($addr_arr['email'], $addr_arr['display']);
         }
     }
     foreach ($this->bcc_addrs_arr as $addr_arr) {
         if (empty($addr_arr['display'])) {
             $mail->AddBCC($addr_arr['email'], "");
         } else {
             $mail->AddBCC($addr_arr['email'], $addr_arr['display']);
         }
     }
     if ($current_user->getPreference('mail_sendtype') == "SMTP") {
         $mail->Mailer = "smtp";
         $mail->Host = $current_user->getPreference('mail_smtpserver');
         $mail->Port = $current_user->getPreference('mail_smtpport');
         if ($current_user->getPreference('mail_smtpauth_req')) {
             $mail->SMTPAuth = TRUE;
             $mail->Username = $current_user->getPreference('mail_smtpuser');
             $mail->Password = $current_user->getPreference('mail_smtppass');
         }
     } else {
         // cn:no need to check since we default to it in any case!
         $mail->Mailer = "sendmail";
     }
     // FROM ADDRESS
     if (!empty($this->from_addr)) {
         $mail->From = $this->from_addr;
     } else {
         $mail->From = $current_user->getPreference('mail_fromaddress');
         $this->from_addr = $mail->From;
     }
     // FROM NAME
     if (!empty($this->from_name)) {
         $mail->FromName = $this->from_name;
     } else {
         $mail->FromName = $current_user->getPreference('mail_fromname');
         $this->from_name = $mail->FromName;
     }
     $mail->Sender = $mail->From;
     /* set Return-Path field in header to reduce spam score in emails sent via Sugar's Email module */
     $mail->AddReplyTo($mail->From, $mail->FromName);
     $encoding = version_compare(phpversion(), '5.0', '>=') ? 'UTF-8' : 'ISO-8859-1';
     $mail->Subject = html_entity_decode($this->name, ENT_QUOTES, $encoding);
     ///////////////////////////////////////////////////////////////////////
     ////	ATTACHMENTS
     foreach ($this->saved_attachments as $note) {
         $mime_type = 'text/plain';
         if ($note->object_name == 'Note') {
             if (!empty($note->file->temp_file_location) && is_file($note->file->temp_file_location)) {
                 // brandy-new file upload/attachment
                 $file_location = $sugar_config['upload_dir'] . $note->id;
                 $filename = $note->file->original_file_name;
                 $mime_type = $note->file->mime_type;
             } else {
                 // attachment coming from template/forward
                 $file_location = rawurldecode(UploadFile::get_file_path($note->filename, $note->id));
                 $filename = $note->name;
                 $mime_type = $note->file_mime_type;
             }
         } elseif ($note->object_name == 'DocumentRevision') {
             // from Documents
             $filename = $note->id;
             $file_location = getcwd() . '/cache/upload/' . $filename;
             $mime_type = $note->file_mime_type;
         }
         // strip out the "Email attachment label if exists
         $filename = str_replace($mod_strings['LBL_EMAIL_ATTACHMENT'] . ': ', '', $filename);
         // cn: bug 9233 attachment filenames need to be translated into the destination charset.
         $filename = $locale->translateCharset($filename, 'UTF-8', $locale->getPrecedentPreference('default_email_charset'));
         //is attachment in our list of bad files extensions?  If so, append .txt to file location
         //get position of last "." in file name
         $file_ext_beg = strrpos($file_location, ".");
         $file_ext = "";
         //get file extension
         if ($file_ext_beg > 0) {
             $file_ext = substr($file_location, $file_ext_beg + 1);
         }
         //check to see if this is a file with extension located in "badext"
         foreach ($sugar_config['upload_badext'] as $badExt) {
             if (strtolower($file_ext) == strtolower($badExt)) {
                 //if found, then append with .txt to filename and break out of lookup
                 //this will make sure that the file goes out with right extension, but is stored
                 //as a text in db.
                 $file_location = $file_location . ".txt";
                 break;
                 // no need to look for more
             }
         }
         $mail->AddAttachment($file_location, $filename, 'base64', $mime_type);
     }
     ////	END ATTACHMENTS
     ///////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////
     ////	HANDLE EMAIL FORMAT PREFERENCE
     // the if() below is HIGHLY dependent on the Javascript unchecking the Send HTML Email box
     // HTML email
     if (isset($_REQUEST['setEditor']) && $_REQUEST['setEditor'] == 1 && trim($_REQUEST['description_html']) != '' || trim($this->description_html) != '') {
         // wp: if body is html, then insert new lines at 996 characters. no effect on client side
         // due to RFC 2822 which limits email lines to 998
         $mail->IsHTML(true);
         $body = from_html(wordwrap($this->description_html, 996));
         $mail->Body = $body;
         // if alternative body is defined, use that, else, striptags the HTML part
         if (trim($this->description) == '') {
             $plainText = from_html($this->description_html);
             $plainText = strip_tags(br2nl($plainText));
             //$plainText = $locale->translateCharset($plainText, 'UTF-8', $locale->getPrecedentPreference('default_email_charset'));
             $mail->AltBody = $plainText;
             $this->description = $plainText;
         } else {
             $mail->AltBody = wordwrap(from_html($this->description), 996);
         }
         // cn: bug 9709 - html email sent accidentally
         // handle signatures fubar'ing the type
         $sigs = $current_user->getDefaultSignature();
         $htmlSig = trim(str_replace(" ", "", strip_tags(from_html($sigs['signature_html']))));
         $htmlBody = trim(str_replace(" ", "", strip_tags(from_html($this->description_html))));
         if ($htmlSig == $htmlBody) {
             // found just a sig. ignore it.
             $this->description_html = '';
             $mail->IsHTML(false);
             $mail->Body = wordwrap(from_html($this->description, 996));
         }
     } else {
         // plain text only
         $this->description_html = '';
         $mail->IsHTML(false);
         $mail->Body = wordwrap(from_html($this->description, 996));
     }
     // wp: if plain text version has lines greater than 998, use base64 encoding
     foreach (explode("\n", $mail->ContentType == "text/html" ? $mail->AltBody : $mail->Body) as $line) {
         if (strlen($line) > 998) {
             $mail->Encoding = 'base64';
             break;
         }
     }
     ////	HANDLE EMAIL FORMAT PREFERENCE
     ///////////////////////////////////////////////////////////////////////
     ///////////////////////////////////////////////////////////////////////
     ////    SAVE RAW MESSAGE
     $mail->SetMessageType();
     $raw = $mail->CreateHeader();
     $raw .= $mail->CreateBody();
     $this->raw_source = urlencode($raw);
     ////    END SAVE RAW MESSAGE
     ///////////////////////////////////////////////////////////////////////
     $GLOBALS['log']->debug('Email sending --------------------- ');
     ///////////////////////////////////////////////////////////////////////
     ////	I18N TRANSLATION
     $mail->prepForOutbound();
     ////	END I18N TRANSLATION
     ///////////////////////////////////////////////////////////////////////
     if ($mail->Send()) {
         ///////////////////////////////////////////////////////////////////
         ////	INBOUND EMAIL HANDLING
         // mark replied
         if (!empty($_REQUEST['inbound_email_id'])) {
             $ieMail = new Email();
             $ieMail->retrieve($_REQUEST['inbound_email_id']);
             $ieMail->status = 'replied';
             $ieMail->save();
         }
         $GLOBALS['log']->debug(' --------------------- buh bye -- sent successful');
         ////	END INBOUND EMAIL HANDLING
         ///////////////////////////////////////////////////////////////////
         return true;
     }
     $GLOBALS['log']->fatal("Error emailing:" . $mail->ErrorInfo);
     return false;
 }
Esempio n. 15
0
    $sugar_smarty->assign("LDAP_ENC_KEY_DESC", $config_strings['LBL_LDAP_ENC_KEY_DESC']);
}
$sugar_smarty->assign("settings", $focus->settings);
if ($valid_public_key) {
    if (!empty($focus->settings['captcha_on'])) {
        $sugar_smarty->assign("CAPTCHA_CONFIG_DISPLAY", 'inline');
    } else {
        $sugar_smarty->assign("CAPTCHA_CONFIG_DISPLAY", 'none');
    }
} else {
    $sugar_smarty->assign("CAPTCHA_CONFIG_DISPLAY", 'inline');
}
$sugar_smarty->assign("VALID_PUBLIC_KEY", $valid_public_key);
$res = $GLOBALS['sugar_config']['passwordsetting'];
require_once 'include/SugarPHPMailer.php';
$mail = new SugarPHPMailer();
$mail->setMailerForSystem();
if ($mail->Mailer == 'smtp' && $mail->Host == '') {
    $sugar_smarty->assign("SMTP_SERVER_NOT_SET", '1');
} else {
    $sugar_smarty->assign("SMTP_SERVER_NOT_SET", '0');
}
$focus = new InboundEmail();
$focus->checkImap();
$storedOptions = unserialize(base64_decode($focus->stored_options));
$email_templates_arr = get_bean_select_array(true, 'EmailTemplate', 'name', '', 'name', true);
$create_case_email_template = isset($storedOptions['create_case_email_template']) ? $storedOptions['create_case_email_template'] : "";
$TMPL_DRPDWN_LOST = get_select_options_with_id($email_templates_arr, $res['lostpasswordtmpl']);
$TMPL_DRPDWN_GENERATE = get_select_options_with_id($email_templates_arr, $res['generatepasswordtmpl']);
$sugar_smarty->assign("TMPL_DRPDWN_LOST", $TMPL_DRPDWN_LOST);
$sugar_smarty->assign("TMPL_DRPDWN_GENERATE", $TMPL_DRPDWN_GENERATE);
Esempio n. 16
0
require_once 'include/entryPoint.php';
require_once 'include/database/DBManagerFactory.php';
require_once 'include/SugarPHPMailer.php';
require_once 'modules/Emails/Email.php';
/* Query database to get case aging */
$query = 'select ca.date_created,c.case_number,c.name,concat("http://dcmaster.mydatacom.com/index.php?module=Cases&action=DetailView&record=",c.id) as link from cases_audit as ca, cases as c where ca.field_name="status" and ca.after_value_string="closed" and c.deleted=0 and timestampdiff(hour,date_created,now())<=24 and c.id=ca.parent_id;';
$db = DBManagerFactory::getInstance();
$result = $db->query($query, true, 'Case Closed Query Failed');
/* Create email bodies to send */
$emailbody = "The following cases were closed in the last 24 hours:<br /><br />";
while (($row = $db->fetchByAssoc($result)) != null) {
    $emailbody .= "<a href='" . $row['link'] . "'>" . $row['case_number'] . " - " . $row['name'] . " - " . $row['date_created'] . " </a><br />";
}
/* Send out emails */
$emailObj = new Email();
$defaults = $emailObj->getSystemDefaultEmail();
$mail = new SugarPHPMailer();
$mail->setMailerForSystem();
$mail->From = $defaults['email'];
$mail->FromName = $defaults['name'];
$mail->ClearAllRecipients();
$mail->ClearReplyTos();
$mail->Subject = "Case Closed Report";
$mail->IsHTML(true);
$mail->Body = $emailbody;
$mail->AltBody = $emailbody;
$mail->prepForOutbound();
$mail->AddAddress('*****@*****.**');
$mail->Send();
/* Clean up shop */
$mail->SMTPClose();
Esempio n. 17
0
function displayReport($reportId, $vardefFilters, $sort_field, $sort_direction, $sort_index, $page_number = '', $isDashlet = false, $dashletId = '', $getLibraries = true, $returnHtml = false, $override_entries = null, $avoidAjaxRequest = false, $contextDomainId = null)
{
    global $current_user, $timedate, $mod_strings, $app_strings, $theme, $db, $app_list_strings, $beanList, $beanFiles, $current_language, $sugar_config;
    require_once 'modules/asol_Reports/include_basic/reportsUtils.php';
    require_once 'modules/asol_Reports/include_basic/ReportChart.php';
    require_once 'modules/asol_Reports/ReportsDashletChart.php';
    require_once 'modules/asol_Reports/include_basic/generateReportsFunctions.php';
    //****************************//
    //****Instance Report Bean****//
    //****************************//
    $focus = BeanFactory::getBean('asol_Reports', $reportId);
    //****************************//
    //****Variables Definition****//
    //****************************//
    $hasVardefFilter = !empty($vardefFilters);
    $hasCurlRequestEnabled = isset($sugar_config["asolReportsCurlRequestUrl"]) ? true : false;
    $hasNoPagination = isset($sugar_config["asolReportsAvoidReportsPagination"]) && $sugar_config["asolReportsAvoidReportsPagination"] == true;
    $dispatcherMaxRequests = isset($sugar_config['asolReportsDispatcherMaxRequests']) ? $sugar_config['asolReportsDispatcherMaxRequests'] : 0;
    $dashletExportButtons = isset($sugar_config['asolReportsDashletExportButtons']) ? $sugar_config['asolReportsDashletExportButtons'] : true;
    $isHttpReportRequest = isset($_REQUEST['sourceCall']) && $_REQUEST['sourceCall'] == "httpReportRequest";
    $isReloadReport = isset($_REQUEST['entryPoint']) && $_REQUEST['entryPoint'] == 'reloadReport';
    $isWsExecution = isset($_REQUEST['asolReportsWebServiceExecution']) && $_REQUEST['asolReportsWebServiceExecution'];
    $entryPointExecuted = isset($_REQUEST['entryPoint']) && in_array($_REQUEST['entryPoint'], array('reloadReport', 'viewReport'));
    $executeReportDirectly = !$hasCurlRequestEnabled || $avoidAjaxRequest;
    $reorderDetailGroups = true;
    //*********************************//
    //***Unserialize Report Elements***//
    //*********************************//
    $storedSelectedFields = unserialize(base64_decode($focus->report_fields));
    $storedSelectedFilters = unserialize(base64_decode($focus->report_filters));
    $storedSelectedCharts = unserialize(base64_decode($focus->report_charts_detail));
    $storedSelectedDescription = unserialize(base64_decode($focus->description));
    //***********************//
    //***AlineaSol Premium***//
    //***********************//
    $predefinedTemplatesResult = asol_ReportsUtils::managePremiumFeature("templatesReports", "reportFunctions.php", "getPredefinedTemplates", array('json_encode' => false, 'currentModule' => null));
    $predefinedTemplates = $predefinedTemplatesResult !== false ? $predefinedTemplatesResult : null;
    //***********************//
    //***AlineaSol Premium***//
    //***********************//
    //***********************//
    //***AlineaSol Premium***//
    //***********************//
    $currentReportCss = asol_ReportsUtils::managePremiumFeature("cssPerReport", "reportFunctions.php", "getCurrentReportCss", array('reportTemplates' => $storedSelectedFields['tables'][0]['templates'], 'selectedValue' => $storedSelectedFields['tables'][0]['css'], 'jsonCssTemplates' => $predefinedTemplates['css'], 'dashletId' => $dashletId));
    //***********************//
    //***AlineaSol Premium***//
    //***********************//
    //****************************//
    //*****module Strings FIX*****//
    //****************************//
    $mod_strings['MSG_REPORT_SEND_EMAIL_ALERT'] = str_replace("&#039", "\\&#039", str_replace("'", "\\&#039", translate('MSG_REPORT_SEND_EMAIL_ALERT', 'asol_Reports')));
    //****************************************//
    //****Check if External App is defined****//
    //****************************************//
    $reportScheduledTypeArray = explode('${dollar}', $focus->report_scheduled_type);
    $reportScheduledAppArray = explode('${pipe}', $reportScheduledTypeArray[1]);
    $hasExternalApp = !empty($reportScheduledAppArray[1]);
    //****************************************//
    //********Get External Parameters*********//
    //****************************************//
    $externalParams = asol_ReportsGenerationFunctions::getExternalRequestParams();
    $current_language = $externalParams["current_language"];
    $mod_strings = $externalParams["mod_strings"];
    $current_user = $externalParams["current_user"];
    //****************************************//
    //****Clean DataBase Report Dispatcher****//
    //****************************************//
    if (empty($vardefFilters)) {
        asol_ReportsGenerationFunctions::cleanDataBaseReportDispatcher();
    }
    $reportTypeSplitted = explode(':', $focus->report_type);
    $reportType = $reportTypeSplitted[0];
    //report_type
    if ($reportType === 'webservice_remote' && $entryPointExecuted) {
        //***********************//
        //***AlineaSol Premium***//
        //***********************//
        $extraParams = array('reportId' => $reportId, 'vardefFilters' => $vardefFilters, 'sort_field' => $sort_field, 'sort_direction' => $sort_direction, 'sort_index' => $sort_index, 'page_number' => $page_number, 'isDashlet' => $isDashlet, 'dashletId' => $dashletId, 'getLibraries' => $getLibraries);
        $executedWebServiceReport = asol_ReportsUtils::managePremiumFeature("webServiceReport", "reportFunctions.php", "executeWebServiceReport", $extraParams);
        $executedWebServiceReportHtml = $executedWebServiceReport !== false ? $executedWebServiceReport : null;
        //***********************//
        //***AlineaSol Premium***//
        //***********************//
        $tmpFilesDir = "modules/asol_Reports/tmpReportFiles/";
        $httpHtmlFile = $_REQUEST['httpHtmlFile'];
        $justDisplay = !$isHttpReportRequest;
        if (isset($justDisplay) && $justDisplay) {
            if ($returnHtml) {
                return $executedWebServiceReportHtml;
            } else {
                echo $executedWebServiceReportHtml;
            }
        } else {
            $exportHttpFile = fopen($tmpFilesDir . $httpHtmlFile, "w");
            fwrite($exportHttpFile, $executedWebServiceReportHtml);
            fclose($exportHttpFile);
            if ($returnHtml) {
                return false;
            }
        }
    } else {
        if ($reportType === 'stored' && $_REQUEST['entryPoint'] != 'viewReport') {
            // Stored Report!
            //****************************************//
            //*********Get Stored Report Data*********//
            //****************************************//
            $reportType = explode(':', $focus->report_type);
            echo asol_ReportsGenerationFunctions::getStoredReportData($reportType[1], $reportId, $isDashlet, $dashletId, $focus->report_charts);
        } else {
            // Anything else Report!
            if ($entryPointExecuted || $executeReportDirectly) {
                //*********************************//
                //****Check Access To Reports******//
                //*********************************//
                if (!ACLController::checkAccess('asol_Reports', 'view', true) && !$hasVardefFilter) {
                    die("<font color='red'>" . $app_strings["LBL_EMAIL_DELETE_ERROR_DESC"] . "</font>");
                }
                //*************************************************//
                //******Requiring FilesGet External Parameters*****//
                //*************************************************//
                require_once "include/SugarPHPMailer.php";
                require_once 'modules/asol_Reports/include_basic/ReportExcel.php';
                require_once 'modules/asol_Reports/include_basic/ReportFile.php';
                require_once 'modules/asol_Reports/include_basic/ReportChart.php';
                require_once 'modules/asol_Reports/include_basic/manageReportsFunctions.php';
                require_once 'modules/asol_Reports/include_basic/generateQuery.php';
                //*****************************//
                //****Variable Definition******//
                //*****************************//
                $fixedReportId = str_replace("-", "", $focus->id);
                $return_action = isset($_REQUEST['return_action']) ? $_REQUEST['return_action'] : "";
                //***********************//
                //***AlineaSol Premium***//
                //***********************//
                $extraParams = array('isDynamic' => $focus->dynamic_tables == '1', 'dynamicTableValue' => $focus->dynamic_sql, 'usedDb' => $focus->alternative_database >= 0 ? $focus->alternative_database : false);
                $matchTablesResult = asol_ReportsUtils::managePremiumFeature("dynamicTablesReport", "reportFunctions.php", "getMatchTablesResult", $extraParams);
                $reportUsedModules = $matchTablesResult !== false ? $matchTablesResult : array($focus->report_module);
                $multiModuleReport = $matchTablesResult !== false && count($matchTablesResult) > 1;
                $hasNoPagination = $multiModuleReport ? true : $hasNoPagination;
                $externalDbSimpleName = $matchTablesResult !== false ? true : false;
                //***********************//
                //***AlineaSol Premium***//
                //***********************//
                $report_data['record'] = $focus->id;
                $report_data['report_name'] = $focus->name;
                $report_data['audited_report'] = $focus->audited_report;
                $report_data['description'] = $focus->description;
                $report_data['assigned_user_id'] = $focus->assigned_user_id;
                $report_data['created_by'] = $focus->created_by;
                $report_data['report_attachment_format'] = $focus->report_attachment_format;
                $report_data['report_charts'] = $focus->report_charts;
                $report_data['report_charts_engine'] = $focus->report_charts_engine;
                $report_data['scheduled_images'] = $focus->scheduled_images;
                $report_data['row_index_display'] = $focus->row_index_display;
                $report_data['results_limit'] = $focus->results_limit;
                $report_data['table_config'] = asol_ReportsGenerationFunctions::getTableConfiguration($focus->report_fields, 0);
                $audited_report = $report_data['audited_report'] == '1' ? true : false;
                $availableReport = true;
                $oversizedReport = false;
                $detailMultiQuery = isset($report_data['table_config']['multiQuery']) && $report_data['table_config']['multiQuery'];
                $displayTotals = !isset($report_data['table_config']['totals']['visible']) || $report_data['table_config']['totals']['visible'];
                $displaySubtotals = !isset($report_data['table_config']['subtotals']['visible']) || $report_data['table_config']['subtotals']['visible'];
                $displayPagination = isset($report_data['table_config']['pagination']['visible']) ? $report_data['table_config']['pagination']['visible'] : 'all';
                $displayTotals = false;
                $displaySubtotals = false;
                $allowExportGeneratedFile = !isset($vardefFilters) || $isWsExecution;
                $externalCall = false;
                $schedulerCall = false;
                $userTZ = null;
                $searchCriteria = isset($_REQUEST['search_criteria']);
                $currentUserId = $_REQUEST['currentUserId'];
                //****************************************//
                //****External Dispatcher Management******//
                //****************************************//
                if (!$hasVardefFilter && isset($_REQUEST['sourceCall']) && $_REQUEST['sourceCall'] == "external") {
                    asol_ReportsGenerationFunctions::manageReportExternalDispatcher($dispatcherMaxRequests);
                    asol_ReportsUtils::reports_log('asol', 'Executing Report with Id [' . $reportId . ']' . (asol_ReportsUtils::isDomainsInstalled() ? ' Domain [' . $contextDomainId . ']' : ''), __FILE__, __METHOD__, __LINE__);
                }
                if (isset($_REQUEST['sourceCall']) && $_REQUEST['sourceCall'] == "external" || isset($_REQUEST['schedulerCall']) && $_REQUEST['schedulerCall'] == "true") {
                    //**********************************************************//
                    //********Manage External Execution Report Variables********//
                    //**********************************************************//
                    $externalCall = true;
                    $overridedExternalVariables = asol_ReportsGenerationFunctions::overrideExternalReportVariables($report_data['created_by']);
                    $theUser = $overridedExternalVariables["theUser"];
                    $current_user = $overridedExternalVariables["current_user"];
                    $allowExportGeneratedFile = $overridedExternalVariables["allowExportGeneratedFile"];
                    $schedulerCall = $overridedExternalVariables["schedulerCall"];
                    $externalUserDateFormat = $overridedExternalVariables["externalUserDateFormat"];
                    $externalUserDateTimeFormat = $overridedExternalVariables["externalUserDateTimeFormat"];
                }
                //*************************************//
                //********Manage Report Domain*********//
                //*************************************//
                if (asol_ReportsUtils::isDomainsInstalled()) {
                    $reportDomain = $contextDomainId !== null ? $contextDomainId : $current_user->asol_default_domain;
                    if ($focus->report_type !== 'external') {
                        $manageReportDomain = asol_ReportsGenerationFunctions::manageReportDomain($reportId, $reportDomain, $focus->asol_domain_id);
                        if (!$manageReportDomain) {
                            $availableReport = false;
                            if ($returnHtml) {
                                return include "modules/asol_Reports/include_basic/DetailViewHttpSave.php";
                            } else {
                                include "modules/asol_Reports/include_basic/DetailViewHttpSave.php";
                                exit;
                            }
                        }
                    }
                }
                //*********************************************************//
                //********Reset Global Format & UserPrefs Variables********//
                //*********************************************************//
                $userDateFormat = $externalCall ? $externalUserDateFormat : $current_user->getPreference('datef');
                $userDateTimeFormat = $externalCall ? $externalUserDateTimeFormat : $current_user->getPreference('datef') . ' ' . $current_user->getPreference('timef');
                $gmtZone = $externalCall ? $theUser->getUserDateTimePreferences() : $current_user->getUserDateTimePreferences();
                $userTZlabel = $externalCall ? $theUser->getPreference("timezone") . " " . $gmtZone["userGmt"] : $current_user->getPreference("timezone") . " " . $gmtZone["userGmt"];
                $userTZ = $externalCall ? $theUser->getPreference("timezone") : $current_user->getPreference("timezone");
                date_default_timezone_set($userTZ);
                $phpDateTime = new DateTime(null, new DateTimeZone($userTZ));
                $hourOffset = $phpDateTime->getOffset() * -1;
                //****************************************//
                //*****Get Current User Configuration*****//
                //****************************************//
                $currentUserAsolConfig = asol_ReportsGenerationFunctions::getCurrentUserAsolConfig($current_user->id);
                $quarter_month = $currentUserAsolConfig["quarter_month"];
                $entriesPerPage = $currentUserAsolConfig["entriesPerPage"];
                $pdf_orientation = $currentUserAsolConfig["pdf_orientation"];
                $week_start = $currentUserAsolConfig["week_start"];
                $pdf_img_scaling_factor = $currentUserAsolConfig["pdf_img_scaling_factor"];
                $scheduled_files_ttl = $currentUserAsolConfig["scheduled_files_ttl"];
                $host_name = $currentUserAsolConfig["host_name"];
                //**************************************//
                //****Override Pagination Parameters****//
                //**************************************//
                if ($externalCall || $hasNoPagination) {
                    $entriesPerPage = 1000000;
                }
                //***********************//
                //***AlineaSol Premium***//
                //***********************//
                if ($hasVardefFilter) {
                    $extraParams = array('overrideEntries' => $override_entries);
                    $paginationEntries = asol_ReportsUtils::managePremiumFeature("reportFieldsManagement", "reportFunctions.php", "getReportFieldsManagementPaginationEntries", $extraParams);
                    if ($paginationEntries !== false) {
                        $hasNoPagination = false;
                        $entriesPerPage = $paginationEntries;
                    }
                }
                //***********************//
                //***AlineaSol Premium***//
                //***********************//
                //*****************************//
                //*****Variable Definition*****//
                //*****************************//
                $rs_user_name = asol_Report::getSelectionResults("SELECT user_name FROM users WHERE id = '" . $focus->assigned_user_id . "'", null, false);
                $report_data['assigned_user_name'] = $rs_user_name[0]['user_name'];
                $reportType = explode(':', $focus->report_type);
                $report_data['report_type'] = $reportType[0];
                $report_data['report_type_stored_data'] = $reportType[1];
                $isStoredReport = $report_data['report_type'] == 'stored' ? true : false;
                $report_data['email_list'] = $focus->email_list;
                $report_name = $focus->name;
                $report_filters = $focus->report_filters;
                $report_charts = $report_data['report_charts'];
                $report_charts_engine = $report_data['report_charts_engine'];
                //********************************************//
                //*****Resultation Arrays Initialization******//
                //********************************************//
                $rs = array();
                $rsTotals = array();
                $subGroups = array();
                $subTotals = array();
                $subTotalsC = array();
                foreach ($reportUsedModules as $moduleIteration => $currentUsedModule) {
                    $lastModuleIteration = $moduleIteration === count($reportUsedModules) - 1;
                    //******************************//
                    //***Get Back Report Elements***//
                    //******************************//
                    $selectedFields = $storedSelectedFields;
                    $selectedFilters = $storedSelectedFilters;
                    $selectedCharts = $storedSelectedCharts;
                    $selectedDescription = $storedSelectedDescription;
                    //*********************************************//
                    //**Execute report with default filter values**//
                    //*********************************************//
                    $initialExecution = $selectedFilters['config']['initialExecution'];
                    if (isset($initialExecution) && $initialExecution) {
                        $searchCriteria = true;
                    }
                    //*****************************//
                    //*****Variable Definition*****//
                    //*****************************//
                    $publicDescription = $selectedDescription['public'];
                    $report_module = $report_data['report_module'] = $focus->report_module = $currentUsedModule;
                    //********************************************//
                    //*****Managing External Database Queries*****//
                    //********************************************//
                    $alternativeDb = $focus->alternative_database >= 0 ? $focus->alternative_database : false;
                    $externalDataBaseQueryParams = asol_ReportsGenerationFunctions::manageExternalDatabaseQueries($alternativeDb, $report_module, $externalDbSimpleName);
                    $useExternalDbConnection = true;
                    $useAlternativeDbConnection = $externalDataBaseQueryParams["useAlternativeDbConnection"];
                    $domainField = $externalDataBaseQueryParams["domainField"];
                    $gmtDates = $externalDataBaseQueryParams["gmtDates"];
                    $report_module = $externalDataBaseQueryParams["report_module"];
                    $report_table = $externalDataBaseQueryParams["report_table"];
                    $report_table_primary_key = $externalDataBaseQueryParams["report_table_primary_key"];
                    //*****************************//
                    //*******Temporal Fixes********//
                    //*****************************//
                    asol_ReportsGenerationFunctions::doTemporalFixes($report_table, $selectedFields, $selectedFilters);
                    //*************************************//
                    //******Generate Chart Info Array******//
                    //*************************************//
                    $urlChart = array();
                    $chartSubGroupsValues = array();
                    $chartInfoParams = asol_ReportsGenerationFunctions::getChartInfoParams($selectedCharts, $audited_report, $report_table);
                    $hasStackChart = $chartInfoParams["hasStackChart"];
                    $chartInfo = $chartInfoParams["chartInfo"];
                    $chartConfig = $chartInfoParams["chartConfig"];
                    //***********************************************//
                    //*******Manage Filters & External Filters*******//
                    //***********************************************//
                    $extFilters = asol_ReportsGenerationFunctions::buildExternalFilters($_REQUEST["external_filters"], $vardefFilters, $userDateFormat);
                    $filteringParams = asol_ReportsGenerationFunctions::getFilteringParams($selectedFilters, $extFilters, $report_module, $predefinedTemplates, $dashletId, $userDateFormat, $audited_report);
                    $filterValuesData = $filteringParams["filterValues"]["data"];
                    $filtersPanel = $filteringParams["filtersPanel"];
                    $filtersHiddenInputs = $filteringParams["filtersHiddenInputs"];
                    if ($filtersHiddenInputs == false || $searchCriteria == true) {
                        //************************************//
                        //*******Prepare SQL SubClauses*******//
                        //************************************//
                        foreach ($selectedFields['tables'][0]['data'] as $index => &$currentValues) {
                            //***********************//
                            //***AlineaSol Premium***//
                            //***********************//
                            $currentSql = asol_ReportsUtils::managePremiumFeature("predefinedTemplates", "reportFunctions.php", "getSqlTemplateValue", array('currentSQL' => $currentValues['sql'], 'template' => $currentValues['templates']['sql'], 'sqlTemplates' => $predefinedTemplates['sql']));
                            $currentValues['sql'] = $currentSql !== false ? $currentSql : $currentValues['sql'];
                            asol_ReportsGenerateQuery::validateSqlRemovedFields($currentValues['sql'], $alternativeDb, $report_table);
                            if (empty($currentValues['sql']) && !empty($currentValues["subQuery"]["module"])) {
                                $externalDataBaseQueryParams = asol_ReportsGenerationFunctions::manageExternalDatabaseQueries($alternativeDb, $currentValues["subQuery"]['module'], true);
                                $domainSubField = $externalDataBaseQueryParams["domainField"];
                                $currentSql = asol_ReportsUtils::managePremiumFeature("subReports", "reportFunctions.php", "getSqlFromSubReport", array('alternativeDb' => $alternativeDb, 'subQuery' => $currentValues["subQuery"], 'index' => $index, 'hourOffset' => $hourOffset, 'quarterMonth' => $quarter_month, 'weekStart' => $week_start, 'currentUser' => $current_user, 'schedulerCall' => $schedulerCall, 'reportDomain' => $reportDomain, 'domainField' => $domainSubField, 'sqlTemplates' => $predefinedTemplates['sql']));
                                $currentValues['sql'] = $currentSql !== false ? $currentSql : $currentValues['sql'];
                            }
                            //***********************//
                            //***AlineaSol Premium***//
                            //***********************//
                        }
                        //*********************************//
                        //*******Get Queries [Joins]*******//
                        //*********************************//
                        $fieldsByRef = array();
                        $joinQueryArray = asol_ReportsGenerateQuery::getSqlJoinQuery($selectedFields, $filterValuesData, $report_data['results_limit'], $report_module, $report_table, $audited_report, $alternativeDb, $fieldsByRef, '', $domainField);
                        $moduleCustomJoined = $joinQueryArray["moduleCustomJoined"];
                        $moduleCountCustomJoined = $joinQueryArray["moduleCountCustomJoined"];
                        $aliasIndexTable = $joinQueryArray["aliasIndexTable"];
                        $sqlJoin = $joinQueryArray["querys"]["Join"];
                        $sqlCountJoin = $joinQueryArray["querys"]["CountJoin"];
                        foreach ($selectedFields['tables'][0]['data'] as $index => &$currentValues) {
                            //***********************//
                            //***AlineaSol Premium***//
                            //***********************//
                            $extraParams = array('currentSql' => $currentValues['sql'], 'fieldsByRef' => $fieldsByRef, 'suppressChars' => true);
                            $currentSql = asol_ReportsUtils::managePremiumFeature("sqlWithReferences", "reportFunctions.php", "replaceSqlReferenceByValue", $extraParams);
                            $currentValues['sql'] = $currentSql !== false ? $currentSql : $currentValues['sql'];
                            //***********************//
                            //***AlineaSol Premium***//
                            //***********************//
                        }
                        //**********************************//
                        //*******Get Queries [Select]*******//
                        //**********************************//
                        $filtersByRef = array();
                        asol_ReportsGenerateQuery::generateSqlWhere($selectedFields, $filterValuesData, $report_table, $hourOffset, $quarter_month, $week_start, $fieldsByRef, $filtersByRef);
                        $selectQueryArray = asol_ReportsGenerateQuery::getSqlSelectQuery($selectedFields, $chartInfo, $predefinedTemplates, $alternativeDb, $report_table, $hourOffset, $quarter_month, $week_start, $audited_report, $displayTotals, $displaySubtotals, $fieldsByRef, $filtersByRef, $aliasIndexTable, '');
                        $referenceAlias = $selectQueryArray["referenceAlias"];
                        $columns = $selectQueryArray["columns"];
                        $types = $selectQueryArray["types"];
                        $columnsU = $selectQueryArray["columnsU"];
                        //Untranslated Alias
                        $columnsO = $selectQueryArray["columnsO"];
                        //Original Field with Join Alias
                        $columnsN = $selectQueryArray["columnsN"];
                        //Not Modified Field
                        $columnsI = $selectQueryArray["columnsI"];
                        //Field Index
                        $isGroupedReport = $selectQueryArray["hasGrouped"];
                        $hasGroupedFunctionWithSQL = $isGroupedReport && $selectQueryArray["hasFunctionWithSQL"];
                        $groupSubTotalField = $selectQueryArray["groupSubTotalField"];
                        $groupSubTotalFieldAscSort = $selectQueryArray["groupSubTotalFieldAscSort"];
                        $totals = $selectQueryArray["totals"];
                        $resulset_fields = $selectQueryArray["resultsetFields"];
                        $sqlTotalsC = $selectQueryArray["querys"]["Charts"];
                        //***AlineaSol Premium***//
                        $fieldSqlFilterReference = asol_ReportsUtils::managePremiumFeature("sqlFilterReference", "reportFunctions.php", "replaceReportsFilterVars", array('filtersByRef' => $filtersByRef, 'currentField' => null, 'sqlContent' => $sqlTotalsC));
                        if ($fieldSqlFilterReference !== false) {
                            $sqlTotalsC = isset($fieldSqlFilterReference['sql']) ? $fieldSqlFilterReference['sql'] : $sqlTotalsC;
                        }
                        //***AlineaSol Premium***//
                        $sqlSelect = $selectQueryArray["querys"]["Select"];
                        //***AlineaSol Premium***//
                        $fieldSqlFilterReference = asol_ReportsUtils::managePremiumFeature("sqlFilterReference", "reportFunctions.php", "replaceReportsFilterVars", array('filtersByRef' => $filtersByRef, 'currentField' => null, 'sqlContent' => $sqlSelect));
                        if ($fieldSqlFilterReference !== false) {
                            $sqlSelect = isset($fieldSqlFilterReference['sql']) ? $fieldSqlFilterReference['sql'] : $sqlSelect;
                        }
                        //***AlineaSol Premium***//
                        $sqlTotals = $selectQueryArray["querys"]["Totals"];
                        //***AlineaSol Premium***//
                        $fieldSqlFilterReference = asol_ReportsUtils::managePremiumFeature("sqlFilterReference", "reportFunctions.php", "replaceReportsFilterVars", array('filtersByRef' => $filtersByRef, 'currentField' => null, 'sqlContent' => $sqlTotals));
                        if ($fieldSqlFilterReference !== false) {
                            $sqlTotals = isset($fieldSqlFilterReference['sql']) ? $fieldSqlFilterReference['sql'] : $sqlTotals;
                        }
                        //***AlineaSol Premium***//
                        //********************************//
                        //*******Get Queries [From]*******//
                        //********************************//
                        $sqlFrom = asol_ReportsGenerateQuery::getSqlFromQuery($report_table, $audited_report, '');
                        //*********************************//
                        //*******Get Queries [Where]*******//
                        //*********************************//
                        asol_ReportsGenerateQuery::replaceFiltersWithNamedFieldAlias($selectedFields, $filtersByRef);
                        $sqlWhere = asol_ReportsGenerateQuery::getSqlWhereQuery($filtersByRef, $report_table, $useAlternativeDbConnection, '');
                        //***AlineaSol Premium***//
                        $extraParams = array('currentSql' => $sqlWhere, 'fieldsByRef' => $fieldsByRef, 'suppressChars' => true);
                        $currentSql = asol_ReportsUtils::managePremiumFeature("sqlWithReferences", "reportFunctions.php", "replaceSqlReferenceByValue", $extraParams);
                        $sqlWhere = $currentSql !== false ? $currentSql : $sqlWhere;
                        //***AlineaSol Premium***//
                        if (asol_ReportsUtils::isDomainsInstalled()) {
                            asol_ReportsGenerateQuery::modifySqlWhereForAsolDomainsQuery($sqlWhere, $report_table, $current_user, $schedulerCall, $reportDomain, $domainField, '');
                        }
                        //***********************//
                        //****Get Email Alert****//
                        //***********************//
                        $sendEmailquestion = asol_ReportsGenerationFunctions::getSendEmailAlert($focus->email_list, $reportDomain);
                        //***********************************//
                        //*******Get Queries [GroupBy]*******//
                        //***********************************//
                        $groupQueryArray = asol_ReportsGenerateQuery::getSqlGroupByQuery($selectedFields, $report_table, $filtersByRef);
                        $sqlGroup = $groupQueryArray["querys"]["Group"];
                        $sqlChartGroup = $groupQueryArray["querys"]["ChartGroup"];
                        $details = $groupQueryArray["details"];
                        $groups = $groupQueryArray["groups"];
                        $isDetailedReport = $groupQueryArray["hasDetail"];
                        $isGroupedReport = $groupQueryArray["hasGrouped"];
                        $hasFunctionField = $groupQueryArray["hasFunctionField"];
                        $massiveData = $groupQueryArray["massiveData"];
                        //***********************************//
                        //****Manage Query Autoprotection****//
                        //***********************************//
                        $totalEntries = asol_ReportsGenerationFunctions::getReportTotalEntries($sqlFrom, $sqlCountJoin, $sqlWhere, $sqlGroup, $details, $groups, $useExternalDbConnection, $alternativeDb);
                        $checkMaxAllowedResults = isset($sugar_config['asolReportsMaxAllowedResults']) ? true : false;
                        $checkMaxAllowedNotIndexedOrderBy = isset($sugar_config['asolReportsMaxAllowedNotIndexedOrderBy']) ? true : false;
                        $checkMaxAllowedDisplayed = isset($sugar_config['asolReportsMaxAllowedDisplayed']) ? true : false;
                        $checkMaxAllowedParseMultiTable = isset($sugar_config['asolReportsMaxAllowedParseMultiTable']) ? true : false;
                        $maxAllowedResults = false;
                        $maxAllowedNotIndexedOrderBy = false;
                        if ($checkMaxAllowedResults || $checkMaxAllowedNotIndexedOrderBy || $checkMaxAllowedDisplayed || $checkMaxAllowedParseMultiTable) {
                            $maxAllowedResultsQuery = "EXPLAIN " . $sqlSelect . $sqlFrom . $sqlJoin . $sqlWhere . $sqlGroup . $sqlLimit;
                            $maxAllowedResultsRow = asol_Report::getSelectionResults($maxAllowedResultsQuery, null, $useExternalDbConnection, $alternativeDb, null, null, true);
                            $productResults = 1;
                            foreach ($maxAllowedResultsRow as $maxAllowedResult) {
                                if ($maxAllowedResult['select_type'] == 'PRIMARY') {
                                    $productResults *= $maxAllowedResult['rows'];
                                }
                            }
                            $maxAllowedResults = $checkMaxAllowedResults && $sugar_config['asolReportsMaxAllowedResults'] < $productResults;
                            $maxAllowedNotIndexedOrderBy = $checkMaxAllowedNotIndexedOrderBy && $sugar_config['asolReportsMaxAllowedNotIndexedOrderBy'] < $totalEntries;
                            $entriesPhpProcessed = $hasNoPagination || $allowExportGeneratedFile ? $totalEntries : $entriesPerPage;
                            $maxAllowedDisplayed = $checkMaxAllowedDisplayed && $sugar_config['asolReportsMaxAllowedDisplayed'] < $entriesPhpProcessed;
                            $maxAllowedParseMultiTable = $checkMaxAllowedParseMultiTable && $multiModuleReport && $sugar_config['asolReportsMaxAllowedParseMultiTable'] < $entriesPhpProcessed;
                            if ($maxAllowedResults) {
                                asol_Report::manageMaxAllowedResultsReached($schedulerCall, $productResults, $sqlSelect . $sqlFrom . $sqlJoin . $sqlWhere . $sqlGroup . $sqlLimit);
                            }
                            if ($maxAllowedDisplayed || $maxAllowedParseMultiTable) {
                                $oversizedReport = true;
                            }
                        }
                        if (!$oversizedReport) {
                            //***********************************//
                            //*******Get Queries [OrderBy]*******//
                            //***********************************//
                            $initialSortDirection = $sort_direction;
                            $orderQueryArray = asol_ReportsGenerateQuery::getSqlOrderByQuery($selectedFields, $report_table, $alternativeDb, $maxAllowedNotIndexedOrderBy, $sort_field, $sort_direction, $sort_index);
                            $hasDeletedNotIndexedOrderBy = $orderQueryArray['hasDeletedNotIndexedOrderBy'];
                            $sqlOrder = $orderQueryArray["query"];
                            $sort_direction = $orderQueryArray["sortDirection"];
                            $sort_type = $orderQueryArray["sortType"];
                            //***********************************//
                            //*******Pagination Management*******//
                            //***********************************//
                            if ($hasNoPagination) {
                                $sqlLimit = "";
                                $sqlLimitExport = "";
                                $total_entries_basic = $totalEntries;
                            } else {
                                //*********************************//
                                //*******Get Queries [Limit]*******//
                                //*********************************//
                                $orderQueryArray = asol_ReportsGenerateQuery::getSqlLimitQuery($report_data['results_limit'], $entriesPerPage, $page_number, $totalEntries, $externalCall);
                                $sqlLimit = $orderQueryArray["querys"]["Limit"];
                                $sqlLimitExport = $orderQueryArray["querys"]["LimitExport"];
                                $total_entries_basic = $orderQueryArray["totalEntriesBasic"];
                            }
                            //******************************************//
                            //*****Correct Fields for Empty Reports*****//
                            //******************************************//
                            $correctedEmptyReport = asol_ReportsGenerationFunctions::correctEmptyReport($sqlSelect, $sqlTotals);
                            $columns[0] = $correctedEmptyReport["select"] !== null ? $correctedEmptyReport["select"] : $columns[0];
                            $sqlSelect .= $correctedEmptyReport["select"] !== null ? $correctedEmptyReport["select"] : "";
                            $sqlOrder .= $correctedEmptyReport["select"] !== null ? $correctedEmptyReport["select"] : "";
                            $sqlTotals .= $correctedEmptyReport["totals"]["sql"] !== null ? $correctedEmptyReport["totals"]["sql"] : "";
                            $totals[0]['alias'] = $correctedEmptyReport["totals"]["column"] !== null ? $correctedEmptyReport["totals"]["column"] : $totals[0]['alias'];
                            //*******************************************************//
                            //*****Get Extended Where Clause for Limited Reports*****//
                            //*******************************************************//
                            $sqlLimitSubSet = asol_ReportsGenerateQuery::getSqlSubSetLimitQuery($focus->alternative_database, $report_data['results_limit'], $totalEntries, $entriesPerPage, $page_number, $report_table, $report_table_primary_key, $sqlFrom, $sqlJoin, $sqlWhere, $sqlGroup);
                            if ($audited_report) {
                                //************************************//
                                //********Manage Audited Field********//
                                //************************************//
                                $auditedFieldTypeArray = asol_Report::getFieldInfoFromVardefs($report_module, $filterValuesData[0]['parameters']['first'][0]);
                                $auditedFieldType = $auditedFieldTypeArray["values"];
                                $auditedAppliedFields = array($report_table . "_audit.before_value_string", $report_table . "_audit.after_value_string", $report_table . "_audit.before_value_text", $report_table . "_audit.after_value_text");
                            }
                            //************************************************************//
                            //********Override Chart Names If Http Request Enabled********//
                            //************************************************************//
                            $chartsHttpQueryUrls = !isset($_REQUEST['chartsHttpQueryUrls']) ? array() : explode('${pipe}', $_REQUEST['chartsHttpQueryUrls']);
                            //*************************//
                            //******DETAIL REPORT******//
                            //*************************//
                            if ($isDetailedReport) {
                                asol_ReportsUtils::reports_log('debug', 'Detailed Report', __FILE__, __METHOD__, __LINE__);
                                //***************************************//
                                //******Initialize Detail Variables******//
                                //***************************************//
                                $currentSubGroups = array();
                                $currentSubTotals = array();
                                $currentSubTotalsC = array();
                                $i = 0;
                                $detailFieldInfo = $details[$i];
                                switch ($detailFieldInfo['grouping']) {
                                    case "Detail":
                                        //***********************************************//
                                        //*****Calculate Detail Pagination Variables*****//
                                        //***********************************************//
                                        $orderPaginationDetailVars = asol_ReportsGenerationFunctions::getOrderPaginationSingleDetailVars($detailFieldInfo, $detailMultiQuery, $report_data['results_limit'], $sqlFrom, $sqlJoin, $sqlWhere, $sqlGroup, $useExternalDbConnection, $alternativeDb);
                                        $rsGroups = $orderPaginationDetailVars["rsGroups"];
                                        $sizes = $orderPaginationDetailVars["sizes"];
                                        $fullSizes = $orderPaginationDetailVars["fullSizes"];
                                        break;
                                    case "Minute Detail":
                                    case "Quarter Hour Detail":
                                    case "Hour Detail":
                                    case "Day Detail":
                                    case "DoW Detail":
                                    case "WoY Detail":
                                    case "Month Detail":
                                    case "Natural Quarter Detail":
                                    case "Fiscal Quarter Detail":
                                    case "Natural Year Detail":
                                    case "Fiscal Year Detail":
                                        //*************************************************************//
                                        //*****Calculate Day/DoW/Month Detail Pagination Variables*****//
                                        //*************************************************************//
                                        $orderPaginationMonthDayDetailVars = asol_ReportsGenerationFunctions::getOrderPaginationDateDetailVars($detailFieldInfo, $detailMultiQuery, $report_data['results_limit'], $sqlFrom, $sqlJoin, $sqlWhere, $useExternalDbConnection, $alternativeDb, $week_start);
                                        $rsGroups = $orderPaginationMonthDayDetailVars["rsGroups"];
                                        $sizes = $orderPaginationMonthDayDetailVars["sizes"];
                                        $fullSizes = $orderPaginationMonthDayDetailVars["fullSizes"];
                                        $reorderDetailGroups = false;
                                        break;
                                }
                                //*************************************//
                                //*****Manage Pagination Variables*****//
                                //*************************************//
                                $paginationMainVariables = asol_ReportsGenerationFunctions::getPaginationMainVariables($page_number, $entriesPerPage, $sizes);
                                $init_group = $paginationMainVariables["init_group"];
                                $end_group = $paginationMainVariables["end_group"];
                                $current_entries = $paginationMainVariables["current_entries"];
                                $first_entry = $paginationMainVariables["first_entry"];
                                $groupField = array();
                                $subGroup = array();
                                if ($report_charts != "Char" || $hasStackChart && (count($groups) != 0 && strtolower($groups[0]['display']) == 'yes') || $report_data['results_limit'] != 'all') {
                                    $subGroupsExport = array();
                                    $subTotalsExport = array();
                                    $subTotalsExportNoFormat = array();
                                    $groupField = array();
                                    $subGroup = array();
                                    if ($detailMultiQuery) {
                                        foreach ($rsGroups as $index => $currentGroup) {
                                            if ($report_data['results_limit'] == "all" && !$allowExportGeneratedFile && ($index < $init_group || $index > $end_group)) {
                                                continue;
                                            }
                                            //********************************************//
                                            //******Limit Clause For Detail Grouping******//
                                            //********************************************//
                                            $detailWhereGrouping = asol_ReportsGenerateQuery::getDetailWhereGrouping($sqlWhere, $currentGroup['group'], $detailFieldInfo);
                                            $subGroup = $detailWhereGrouping["subGroup"];
                                            $sqlDetailWhere = $detailWhereGrouping["sqlDetailWhere"];
                                            $sqlLimit = asol_ReportsGenerateQuery::getSqlDetailLimitQuery($report_data['results_limit'], $fullSizes[$index]);
                                            $sqlDetailQuery = $sqlSelect . $sqlFrom . $sqlJoin . $sqlDetailWhere . $sqlGroup . $sqlOrder . $sqlLimit;
                                            $rsDetail = asol_Report::getSelectionResults($sqlDetailQuery, null, $useExternalDbConnection, $alternativeDb);
                                            //***************************//
                                            //******Format SubGroup******//
                                            //***************************//
                                            if ($detailFieldInfo['function'] == '0') {
                                                $subGroup = asol_ReportsGenerateQuery::formatDateSpecialsGroup($reportId, $dashletId, $subGroup, $detailFieldInfo, $userDateFormat, $userTZ, $focus->currency_id, $gmtDates);
                                            }
                                            if (empty($subGroup) && $subGroup !== "0") {
                                                continue;
                                            }
                                            foreach ($rsDetail as $currentDetail) {
                                                if ($index >= $init_group && $index <= $end_group) {
                                                    $currentSubGroups[$subGroup][] = $currentDetail;
                                                }
                                                $subGroupsExport[$subGroup][] = $currentDetail;
                                            }
                                            //***********************************************//
                                            //*******Subtotals Query for Current Group*******//
                                            //***********************************************//
                                            if ($displaySubtotals) {
                                                $limitedGroupTotals = array();
                                                if ($report_data['results_limit'] == "all" && !$hasGroupedFunctionWithSQL) {
                                                    $sqlSubQueryTotals = $sqlTotals . $sqlFrom . $sqlCountJoin . $sqlDetailWhere;
                                                    $rsSubTotals = asol_Report::getSelectionResults($sqlSubQueryTotals, null, $useExternalDbConnection, $alternativeDb);
                                                } else {
                                                    if (!$isGroupedReport) {
                                                        $limitedIds = array();
                                                        $limitIds = asol_Report::getSelectionResults("SELECT " . $report_table . "." . $report_table_primary_key . " " . $sqlFrom . $sqlCountJoin . $sqlDetailWhere . $sqlOrder . $sqlLimit, null, $useExternalDbConnection, $alternativeDb);
                                                        foreach ($limitIds as $limitId) {
                                                            $limitedIds[] = $limitId[$report_table_primary_key];
                                                        }
                                                        $sqlLimitWhere = " AND " . $report_table . "." . $report_table_primary_key . " IN ('" . implode("','", $limitedIds) . "')";
                                                        $sqlSubQueryTotals = $sqlTotals . $sqlFrom . $sqlCountJoin . $sqlDetailWhere . $sqlLimitWhere;
                                                        $rsSubTotals = asol_Report::getSelectionResults($sqlSubQueryTotals, null, $useExternalDbConnection, $alternativeDb);
                                                    } else {
                                                        //**************************************//
                                                        //******Generate SubTotals Manually*****//
                                                        //**************************************//
                                                        $limitedGroupTotals = $limitedGroupTotalsExport = asol_ReportsGenerateQuery::generateManuallySubTotals($rsDetail, $totals, $report_data['results_limit']);
                                                    }
                                                }
                                                $rsSubTotalsExport = $rsSubTotals;
                                                if (!empty($limitedGroupTotalsExport[0])) {
                                                    if ($index >= $init_group && $index <= $end_group) {
                                                        $rsSubTotals[0] = $limitedGroupTotals[0];
                                                    }
                                                    $rsSubTotalsExport[0] = $limitedGroupTotalsExport[0];
                                                }
                                                //Obtenemos el resultado de la query de los SubTotales para el subgrupo actual
                                                $subTotalsLimit[] = $rsSubTotalsExport[0];
                                                $subTotalsExportNoFormat[$subGroup] = $rsSubTotalsExport[0];
                                                //**********************************//
                                                //******Apply Displaying Format*****//
                                                //**********************************//
                                                $rsSubTotals = asol_ReportsGenerateQuery::formatGroupTotals($reportId, $dashletId, $rsSubTotals, $totals, $userDateFormat, $userDateTimeFormat, $userTZ, $focus->currency_id, $gmtDates, $audited_report, $auditedAppliedFields, $auditedFieldType);
                                                $rsSubTotalsExport = asol_ReportsGenerateQuery::formatGroupTotals($reportId, $dashletId, $rsSubTotalsExport, $totals, $userDateFormat, $userDateTimeFormat, $userTZ, $focus->currency_id, $gmtDates, $audited_report, $auditedAppliedFields, $auditedFieldType);
                                                $currentSubTotals[$subGroup] = $rsSubTotals[0];
                                                $subTotalsExport[$subGroup] = $rsSubTotalsExport[0];
                                            }
                                        }
                                        //***********************//
                                        //***AlineaSol Premium***//
                                        //***********************//
                                        $extraParams = array('isGroupedReport' => $isGroupedReport, 'groups' => $groups, 'currentSubGroups' => $currentSubGroups, 'subGroups' => $subGroups, 'resulsetTotals' => $totals, 'moduleIteration' => $moduleIteration);
                                        $returnedSubGroups = asol_ReportsUtils::managePremiumFeature("dynamicTablesReport", "reportFunctions.php", "parseMergeDetailResultsets", $extraParams);
                                        $subGroups = $subGroupsExport = $returnedSubGroups !== false ? $returnedSubGroups : $currentSubGroups;
                                        //***********************//
                                        //***AlineaSol Premium***//
                                        //***********************//
                                        //***********************//
                                        //***AlineaSol Premium***//
                                        //***********************//
                                        $extraParams = array('currentSubTotals' => $currentSubTotals, 'subTotals' => $subTotals, 'resulsetTotals' => $totals, 'moduleIteration' => $moduleIteration, 'isChartsTotals' => false);
                                        $returnedSubTotals = asol_ReportsUtils::managePremiumFeature("dynamicTablesReport", "reportFunctions.php", "parseMergeDetailTotalsResultsets", $extraParams);
                                        $subTotals = $returnedSubTotals !== false ? $returnedSubTotals : $currentSubTotals;
                                        //***********************//
                                        //***AlineaSol Premium***//
                                        //***********************//
                                        if ($hasNoPagination) {
                                            $subTotalsExport = $subTotals;
                                        }
                                    } else {
                                        $formatInfo = array('reportId' => $reportId, 'dashletId' => $dashletId, 'userDateFormat' => $userDateFormat, 'userTZ' => $userTZ, 'currencyId' => $focus->currency_id, 'gmtDates' => $gmtDates);
                                        $sqlDetailGroupBy = !empty($sqlGroup) ? $sqlGroup . ', ' . $detailFieldInfo['field'] : '';
                                        $sqlDetailQuery = $sqlSelect . "," . $detailFieldInfo['field'] . " AS 'asol_grouping_field' " . $sqlFrom . $sqlJoin . $sqlWhere . $sqlDetailGroupBy . $sqlOrder;
                                        $rsDetail = asol_Report::getSelectionResults($sqlDetailQuery, null, $useExternalDbConnection, $alternativeDb, $detailFieldInfo, $formatInfo, false);
                                        if ($hasNoPagination) {
                                            if ($report_data['results_limit'] !== "all") {
                                                foreach ($rsDetail as $subGroup => $currentDetail) {
                                                    $res_limit = explode('${dp}', $report_data['results_limit']);
                                                    if ($res_limit[1] == 'first') {
                                                        $currentDetail = array_slice($currentDetail, 0, $res_limit[2]);
                                                    } else {
                                                        if ($res_limit[1] == 'last') {
                                                            $currentDetail = array_slice($currentDetail, -$res_limit[2]);
                                                        }
                                                    }
                                                    $currentSubGroups[$subGroup] = $currentDetail;
                                                }
                                            } else {
                                                $currentSubGroups = $rsDetail;
                                            }
                                            //***********************//
                                            //***AlineaSol Premium***//
                                            //***********************//
                                            $extraParams = array('isGroupedReport' => $isGroupedReport, 'groups' => $groups, 'currentSubGroups' => $currentSubGroups, 'subGroups' => $subGroups, 'resulsetTotals' => $totals, 'moduleIteration' => $moduleIteration);
                                            $returnedSubGroups = asol_ReportsUtils::managePremiumFeature("dynamicTablesReport", "reportFunctions.php", "parseMergeDetailResultsets", $extraParams);
                                            $subGroups = $subGroupsExport = $returnedSubGroups !== false ? $returnedSubGroups : $currentSubGroups;
                                            //***********************//
                                            //***AlineaSol Premium***//
                                            //***********************//
                                        } else {
                                            $index = 0;
                                            foreach ($rsDetail as $subGroup => $currentDetail) {
                                                if ($report_data['results_limit'] !== "all") {
                                                    $res_limit = explode('${dp}', $report_data['results_limit']);
                                                    if ($res_limit[1] == 'first') {
                                                        $currentDetail = array_slice($currentDetail, 0, $res_limit[2]);
                                                    } else {
                                                        if ($res_limit[1] == 'last') {
                                                            $currentDetail = array_slice($currentDetail, -$res_limit[2]);
                                                        }
                                                    }
                                                }
                                                if ($index >= $init_group && $index <= $end_group) {
                                                    $currentSubGroups[$subGroup] = $currentDetail;
                                                }
                                                if ($allowExportGeneratedFile || $report_data['report_charts'] != 'Tabl') {
                                                    $subGroupsExport[$subGroup] = $currentDetail;
                                                }
                                                $index++;
                                            }
                                            $subGroups = $currentSubGroups;
                                        }
                                        if ($displaySubtotals) {
                                            $limitedGroupTotals = array();
                                            if ($report_data['results_limit'] == "all" && !$hasGroupedFunctionWithSQL) {
                                                $sqlDetailGroupBy = ' GROUP BY ' . $detailFieldInfo['field'];
                                                $sqlSubQueryTotals = $sqlTotals . "," . $detailFieldInfo['field'] . " AS 'asol_grouping_field' " . $sqlFrom . $sqlCountJoin . $sqlWhere . $sqlDetailGroupBy;
                                                $rsSubTotals = asol_Report::getSelectionResults($sqlSubQueryTotals, null, $useExternalDbConnection, $alternativeDb, null, null, false);
                                            } else {
                                                if (!$isGroupedReport) {
                                                    $sqlDetailGroupBy = ' GROUP BY ' . $report_table . "." . $report_table_primary_key;
                                                    $sqlSubQueryTotals = $sqlTotals . "," . $detailFieldInfo['field'] . " AS 'asol_grouping_field' " . $sqlFrom . $sqlCountJoin . $sqlWhere . $sqlDetailGroupBy;
                                                    $sqlSubQueryTotals .= $report_data['results_limit'] == "all" ? '' : $sqlOrder;
                                                    $rsSubTotals = asol_Report::getSelectionResults($sqlSubQueryTotals, null, $useExternalDbConnection, $alternativeDb, null, null, false);
                                                    //**************************************//
                                                    //******Generate SubTotals Manually*****//
                                                    //**************************************//
                                                    $rsSubTotals = asol_ReportsGenerateQuery::generateManuallySubTotals($rsSubTotals, $totals, $report_data['results_limit'], true);
                                                } else {
                                                    $sqlDetailGroupBy = !empty($sqlGroup) ? $sqlGroup . ', ' . $detailFieldInfo['field'] : '';
                                                    $sqlSubQueryTotals = $sqlTotals . "," . $detailFieldInfo['field'] . " AS 'asol_grouping_field' " . $sqlFrom . $sqlCountJoin . $sqlWhere . $sqlDetailGroupBy;
                                                    $sqlSubQueryTotals .= $report_data['results_limit'] == "all" ? '' : $sqlOrder;
                                                    $rsSubTotals = asol_Report::getSelectionResults($sqlSubQueryTotals, null, $useExternalDbConnection, $alternativeDb, null, null, false);
                                                    //**************************************//
                                                    //******Generate SubTotals Manually*****//
                                                    //**************************************//
                                                    $rsSubTotals = asol_ReportsGenerateQuery::generateManuallySubTotals($rsSubTotals, $totals, $report_data['results_limit'], true);
                                                }
                                            }
                                            foreach ($rsSubTotals as $rsSubTotal) {
                                                //**********************************//
                                                //******Apply Displaying Format*****//
                                                //**********************************//
                                                $theGroup = asol_ReportsGenerateQuery::formatDateSpecialsGroup($reportId, $dashletId, $rsSubTotal['asol_grouping_field'], $detailFieldInfo, $userDateFormat, $userTZ, $focus->currency_id, $gmtDates);
                                                $theGroup = $theGroup === '' ? $mod_strings['LBL_REPORT_NAMELESS'] : $theGroup;
                                                $currentSubTotals[$theGroup] = $rsSubTotal;
                                            }
                                            //***********************//
                                            //***AlineaSol Premium***//
                                            //***********************//
                                            $extraParams = array('currentSubTotals' => $currentSubTotals, 'subTotals' => $subTotals, 'resulsetTotals' => $totals, 'moduleIteration' => $moduleIteration, 'isChartsTotals' => false);
                                            $returnedSubTotals = asol_ReportsUtils::managePremiumFeature("dynamicTablesReport", "reportFunctions.php", "parseMergeDetailTotalsResultsets", $extraParams);
                                            $subTotals = $returnedSubTotals !== false ? $returnedSubTotals : $currentSubTotals;
                                            //***********************//
                                            //***AlineaSol Premium***//
                                            //***********************//
                                            if ($lastModuleIteration) {
                                                foreach ($subTotals as &$subTotal) {
                                                    //**********************************//
                                                    //******Apply Displaying Format*****//
                                                    //**********************************//
                                                    unset($subTotal['asol_grouping_field']);
                                                    $subTotal = asol_ReportsGenerateQuery::formatGroupTotals($reportId, $dashletId, array($subTotal), $totals, $userDateFormat, $userDateTimeFormat, $userTZ, $focus->currency_id, $gmtDates, $audited_report, $auditedAppliedFields, $auditedFieldType);
                                                    $subTotal = $subTotal[0];
                                                }
                                            }
                                            $subTotalsExport = $subTotals;
                                        }
                                    }
                                    //Order resultset for grouped totals
                                    if ($reorderDetailGroups) {
                                        if ($details[0]['order'] == 'DESC') {
                                            krsort($subGroups);
                                            krsort($subGroupsExport);
                                        } else {
                                            if ($details[0]['order'] == 'ASC') {
                                                ksort($subGroups);
                                                ksort($subGroupsExport);
                                            }
                                        }
                                    }
                                }
                                //***********************//
                                //***AlineaSol Premium***//
                                //***********************//
                                $extraParams = array('subGroups' => $subGroups, 'resulsetFields' => $resulset_fields, 'referenceAlias' => $referenceAlias);
                                $returnedPhpSubGroups = asol_ReportsUtils::managePremiumFeature("reportPhpFunctions", "reportFunctions.php", "formatPhpDetailResultSet", $extraParams);
                                $subGroups = $returnedPhpSubGroups !== false ? $returnedPhpSubGroups : $subGroups;
                                //***********************//
                                //***AlineaSol Premium***//
                                //***********************//
                                if ($report_data['results_limit'] != "all" || $allowExportGeneratedFile) {
                                    //***********************//
                                    //***AlineaSol Premium***//
                                    //***********************//
                                    $extraParams = array('subGroups' => $subGroupsExport, 'resulsetFields' => $resulset_fields, 'referenceAlias' => $referenceAlias);
                                    $returnedPhpSubGroups = asol_ReportsUtils::managePremiumFeature("reportPhpFunctions", "reportFunctions.php", "formatPhpDetailResultSet", $extraParams);
                                    $subGroupsExport = $returnedPhpSubGroups !== false ? $returnedPhpSubGroups : $subGroupsExport;
                                    //***********************//
                                    //***AlineaSol Premium***//
                                    //***********************//
                                }
                                //**********************************************//
                                //******Generate Values for Chart Totals********//
                                //**********************************************//
                                if ($report_charts != "Tabl" && count($chartInfo) > 0 && strlen($sqlTotalsC) > 7) {
                                    if ($report_data['results_limit'] != 'all') {
                                        $currentSubTotalsC = $subTotalsExportNoFormat;
                                    } else {
                                        switch ($detailFieldInfo['grouping']) {
                                            case "Detail":
                                                $rsSubTotalsC = asol_Report::getSelectionResults($sqlTotalsC . "," . $detailFieldInfo['field'] . " AS 'asol_grouping_field' " . $sqlFrom . $sqlCountJoin . $sqlWhere . $sqlChartGroup, null, $useExternalDbConnection, $alternativeDb);
                                                foreach ($rsSubTotalsC as $rsSubTotalC) {
                                                    $theGroup = $rsSubTotalC['asol_grouping_field'];
                                                    unset($rsSubTotalC['asol_grouping_field']);
                                                    $theGroup = $theGroup === '' ? $mod_strings['LBL_REPORT_NAMELESS'] : $theGroup;
                                                    $theGroup = asol_ReportsGenerateQuery::formatSubGroup($reportId, $dashletId, $theGroup, $detailFieldInfo, $userTZ, $currency_id, $gmtDates);
                                                    if (!$massiveData) {
                                                        $currentSubTotalsC[$theGroup] = $rsSubTotalC;
                                                    } else {
                                                        $currentSubTotalsC[$theGroup][] = $rsSubTotalC;
                                                    }
                                                }
                                                break;
                                            case "Minute Detail":
                                            case "Quarter Hour Detail":
                                            case "Hour Detail":
                                            case "Day Detail":
                                            case "DoW Detail":
                                            case "WoY Detail":
                                            case "Month Detail":
                                            case "Natural Quarter Detail":
                                            case "Fiscal Quarter Detail":
                                            case "Natural Year Detail":
                                            case "Fiscal Year Detail":
                                                foreach ($rsGroups as $currentGroup) {
                                                    $monthDayDetailGroupWhereExtensionQuery = asol_ReportsGenerationFunctions::getDateDetailGroupWhereExtensionQuery($sqlWhere, $detailFieldInfo['field'], $detailFieldInfo['grouping'], $currentGroup['group']);
                                                    $subGroupC = $monthDayDetailGroupWhereExtensionQuery['subGroup'];
                                                    $sqlDetailWhereC = $monthDayDetailGroupWhereExtensionQuery['sqlDetailWhere'];
                                                    //***************************//
                                                    //******Format SubGroup******//
                                                    //***************************//
                                                    if ($detailFieldInfo['function'] == '0') {
                                                        $subGroupC = asol_ReportsGenerateQuery::formatDateSpecialsGroup($reportId, $dashletId, $subGroupC, $detailFieldInfo, $userDateFormat, $userTZ, $focus->currency_id, $gmtDates);
                                                    }
                                                    //Obtenemos el resultado de la query de los SubTotales para el subgrupo actual
                                                    $sqlSubQueryTotalsC = $sqlTotalsC . $sqlFrom . $sqlCountJoin . $sqlDetailWhereC;
                                                    $rsSubTotalsC = asol_Report::getSelectionResults($sqlSubQueryTotalsC, null, $useExternalDbConnection, $alternativeDb);
                                                    $currentSubTotalsC[$subGroupC] = $massiveData ? $rsSubTotalsC : $rsSubTotalsC[0];
                                                }
                                                break;
                                        }
                                    }
                                    //***********************//
                                    //***AlineaSol Premium***//
                                    //***********************//
                                    $extraParams = array('currentSubTotals' => $currentSubTotalsC, 'subTotals' => $subTotalsC, 'resulsetTotals' => $chartInfo, 'moduleIteration' => $moduleIteration, 'isChartsTotals' => true);
                                    $returnedSubTotalsC = asol_ReportsUtils::managePremiumFeature("dynamicTablesReport", "reportFunctions.php", "parseMergeDetailTotalsResultsets", $extraParams);
                                    $subTotalsC = $returnedSubTotalsC !== false ? $returnedSubTotalsC : $currentSubTotalsC;
                                    //***********************//
                                    //***AlineaSol Premium***//
                                    //***********************//
                                    if ($lastModuleIteration) {
                                        //********************************//
                                        //***Data For Charts Generation***//
                                        //********************************//
                                        $dataForChartsGeneration = asol_ReportsCharts::getDataForChartsGeneration($chartInfo, $chartConfig, $selectedFields, $subTotalsC, $subGroupsExport, $massiveData, true, $isGroupedReport, $hasFunctionField, $groups, $groupExport, $userDateFormat);
                                        $subGroupsChart = $dataForChartsGeneration['subGroupsChart'];
                                        $chartValues = $dataForChartsGeneration['chartValues'];
                                        $chartConfigs = $dataForChartsGeneration['chartConfigs'];
                                        $chartYAxisLabels = $dataForChartsGeneration['chartYAxisLabels'];
                                        //********************************//
                                        //***Data For Charts Generation***//
                                        //********************************//
                                        //**************************************//
                                        //***Generate Chart Files & ExtraData***//
                                        //**************************************//
                                        $chartFilesWithExtraData = asol_ReportsCharts::getChartFilesWithExtraData($focus->report_charts_engine, true, $massiveData, $chartInfo, $chartConfigs, $chartYAxisLabels, $chartValues, $subGroupsChart, $reportId, $report_module, $chartsHttpQueryUrls, $isGroupedReport, $isStoredReport);
                                        $urlChart = $chartFilesWithExtraData['urlChart'];
                                        $chartSubGroupsValues = $chartFilesWithExtraData['chartSubGroupsValues'];
                                        //**************************************//
                                        //***Generate Chart Files & ExtraData***//
                                        //**************************************//
                                    }
                                }
                                //**********************************//
                                //******Apply Displaying Format*****//
                                //**********************************//
                                if ($lastModuleIteration) {
                                    $subGroups = asol_ReportsGenerateQuery::formatDetailResultSet($reportId, $dashletId, $subGroups, $resulset_fields, $userDateFormat, $userDateTimeFormat, $userTZ, $currency_id, $gmtDates, $isGroupedReport, $audited_report, $auditedAppliedFields, $auditedFieldType, $referenceAlias);
                                    $subGroups = asol_ReportsGenerateQuery::formatDetailGroupedFields($subGroups, $resulset_fields, $userDateFormat);
                                }
                                //Order resultsetExport for grouped totals
                                $subGroupsExport = empty($subGroupsExport) ? array() : $subGroupsExport;
                                if (($report_data['results_limit'] != "all" || $allowExportGeneratedFile) && $lastModuleIteration) {
                                    $subGroupsExport = asol_ReportsGenerateQuery::formatDetailResultSet($reportId, $dashletId, $subGroupsExport, $resulset_fields, $userDateFormat, $userDateTimeFormat, $userTZ, $currency_id, $gmtDates, $isGroupedReport, $audited_report, $auditedAppliedFields, $auditedFieldType, $referenceAlias);
                                    $subGroupsExport = asol_ReportsGenerateQuery::formatDetailGroupedFields($subGroupsExport, $resulset_fields, $userDateFormat);
                                }
                                //Obtenemos los valores relaciones con el paginado
                                if ($report_data['results_limit'] != "all") {
                                    $total_entries_basic = 0;
                                    foreach ($subGroupsExport as $subExp) {
                                        $total_entries_basic += count($subExp);
                                    }
                                    $data['total_entries'] = $total_entries_basic;
                                } else {
                                    $data['total_entries'] = $totalEntries;
                                }
                                $data['first_entry'] = $first_entry;
                                $data['current_entries'] = !empty($current_entries_limit) ? $current_entries_limit : $current_entries;
                                $data['page_number'] = $page_number;
                                //Calcular numero de paginas en funciones de array sizes
                                $parcial = 0;
                                $num_pages = 0;
                                foreach ($sizes as $currentSize) {
                                    $parcial += $currentSize;
                                    if ($parcial >= $entriesPerPage) {
                                        $num_pages++;
                                        $parcial = 0;
                                    }
                                }
                                $data['num_pages'] = $parcial == 0 ? $num_pages - 1 : $num_pages;
                                //*************************//
                                //******SIMPLE REPORT******//
                                //*************************//
                            } else {
                                asol_ReportsUtils::reports_log('debug', 'Simple Report', __FILE__, __METHOD__, __LINE__);
                                $sqlLimit = !empty($sqlLimitSubSet) ? $sqlLimitSubSet : $sqlLimit;
                                //Obtenemos el resultado de la Query generada
                                $sqlQuery = $sqlSelect . $sqlFrom . $sqlJoin . $sqlWhere . $sqlGroup . $sqlOrder . $sqlLimit;
                                $currentRs = asol_Report::getSelectionResults($sqlQuery, null, $useExternalDbConnection, $alternativeDb);
                                //***********************//
                                //***AlineaSol Premium***//
                                //***********************//
                                $extraParams = array('isGroupedReport' => $isGroupedReport, 'groups' => $groups, 'currentRs' => $currentRs, 'rs' => $rs, 'resulsetTotals' => $totals, 'moduleIteration' => $moduleIteration);
                                $returnedRs = asol_ReportsUtils::managePremiumFeature("dynamicTablesReport", "reportFunctions.php", "parseMergeSingleResultsets", $extraParams);
                                $rs = $returnedRs !== false ? $returnedRs : $currentRs;
                                $extraParams = array('rs' => $rs, 'resulsetFields' => $resulset_fields, 'referenceAlias' => $referenceAlias);
                                $returnedPhpRs = asol_ReportsUtils::managePremiumFeature("reportPhpFunctions", "reportFunctions.php", "formatPhpResultSet", $extraParams);
                                $rs = $returnedPhpRs !== false ? $returnedPhpRs : $rs;
                                //***********************//
                                //***AlineaSol Premium***//
                                //***********************//
                                if ($multiModuleReport && $lastModuleIteration) {
                                    asol_ReportsGenerationFunctions::sortAssocArray($rs, $sort_field, $initialSortDirection === 'ASC', in_array($sort_type, array('int', 'bigint', 'decimal', 'double', 'currency')));
                                }
                                if ($allowExportGeneratedFile || $report_data['report_charts'] != 'Tabl') {
                                    if ($hasNoPagination) {
                                        $rsExport = $rs;
                                    } else {
                                        $sqlQueryExport = $sqlSelect . $sqlFrom . $sqlJoin . $sqlWhere . $sqlGroup . $sqlOrder . $sqlLimitExport;
                                        $rsExport = asol_Report::getSelectionResults($sqlQueryExport, null, $useExternalDbConnection, $alternativeDb);
                                        //***********************//
                                        //***AlineaSol Premium***//
                                        //***********************//
                                        $extraParams = array('rs' => $rsExport, 'resulsetFields' => $resulset_fields, 'referenceAlias' => $referenceAlias);
                                        $returnedPhpRs = asol_ReportsUtils::managePremiumFeature("reportPhpFunctions", "reportFunctions.php", "formatPhpResultSet", $extraParams);
                                        $rsExport = $returnedPhpRs !== false ? $returnedPhpRs : $rsExport;
                                        //***********************//
                                        //***AlineaSol Premium***//
                                        //***********************//
                                        if ($multiModuleReport && $lastModuleIteration) {
                                            asol_ReportsGenerationFunctions::sortAssocArray($rsExport, $sort_field, $initialSortDirection === 'ASC', in_array($sort_type, array('int', 'bigint', 'decimal', 'double', 'currency')));
                                        }
                                    }
                                }
                                //********************************************//
                                //********** SINGLE REPORTS CHARTS ***********//
                                //********************************************//
                                if ($isGroupedReport) {
                                    //********************************//
                                    //***Data For Charts Generation***//
                                    //********************************//
                                    $dataForChartsGeneration = asol_ReportsCharts::getDataForChartsGeneration($chartInfo, $chartConfig, $selectedFields, $rsExport, null, null, false, true, $hasFunctionField, $groups, null, $userDateFormat);
                                    $subGroupsChart = $dataForChartsGeneration['subGroupsChart'];
                                    $chartValues = $dataForChartsGeneration['chartValues'];
                                    $chartConfigs = $dataForChartsGeneration['chartConfigs'];
                                    $chartYAxisLabels = $dataForChartsGeneration['chartYAxisLabels'];
                                    //********************************//
                                    //***Data For Charts Generation***//
                                    //********************************//
                                    //**************************************//
                                    //***Generate Chart Files & ExtraData***//
                                    //**************************************//
                                    $chartFilesWithExtraData = asol_ReportsCharts::getChartFilesWithExtraData($focus->report_charts_engine, false, false, $chartInfo, $chartConfigs, $chartYAxisLabels, $chartValues, $subGroupsChart, $reportId, $report_module, $chartsHttpQueryUrls, false, $isStoredReport);
                                    $urlChart = $chartFilesWithExtraData['urlChart'];
                                    $chartSubGroupsValues = $chartFilesWithExtraData['chartSubGroupsValues'];
                                    //**************************************//
                                    //***Generate Chart Files & ExtraData***//
                                    //**************************************//
                                }
                                //********************************************//
                                //********** SINGLE REPORTS CHARTS ***********//
                                //********************************************//
                                // Totals beginning
                                if ($displayTotals) {
                                    if ($isGroupedReport && ($report_data['results_limit'] != 'all' || $multiModuleReport) || $hasGroupedFunctionWithSQL) {
                                        //**************************************//
                                        //******Generate SubTotals Manually*****//
                                        //**************************************//
                                        $limitedTotals = asol_ReportsGenerateQuery::generateManuallySubTotals($rsExport, $totals, $report_data['results_limit'], false, $subTotalsLimit);
                                    }
                                }
                                // Totals end
                                //***********************************//
                                //********ResultSet Formatting*******//
                                //***********************************//
                                if ($lastModuleIteration) {
                                    $rs = asol_ReportsGenerateQuery::formatResultSet($reportId, $dashletId, $rs, $resulset_fields, $userDateFormat, $userDateTimeFormat, $userTZ, $currency_id, $gmtDates, $isGroupedReport, $audited_report, $auditedAppliedFields, $auditedFieldType, $referenceAlias);
                                    $rs = asol_ReportsGenerateQuery::formatGroupedFields($rs, $resulset_fields, $userDateFormat);
                                }
                                //***********************************//
                                //********ResultSet Formatting*******//
                                //***********************************//
                                //***********************************//
                                //***Exported ResultSet Formatting***//
                                //***********************************//
                                if ($lastModuleIteration && $allowExportGeneratedFile) {
                                    $rsExport = asol_ReportsGenerateQuery::formatResultSet($reportId, $dashletId, $rsExport, $resulset_fields, $userDateFormat, $userDateTimeFormat, $userTZ, $currency_id, $gmtDates, $isGroupedReport, $audited_report, $auditedAppliedFields, $auditedFieldType, $referenceAlias);
                                    $rsExport = asol_ReportsGenerateQuery::formatGroupedFields($rsExport, $resulset_fields, $userDateFormat);
                                }
                                //***********************************//
                                //***Exported ResultSet Formatting***//
                                //***********************************//
                                $data['total_entries'] = $total_entries_basic;
                                $data['entriesPerPage'] = $entriesPerPage;
                                $data['current_entries'] = count($rs);
                                $data['page_number'] = $page_number;
                                $data['num_pages'] = $data['total_entries'] % $entriesPerPage != 0 ? floor($data['total_entries'] / $entriesPerPage) : floor($data['total_entries'] / $entriesPerPage) - 1;
                            }
                            $hasDisplayedCharts = count($urlChart) > 0 && $report_data['report_charts'] != 'Tabl';
                            $data['page_number_label'] = $data['page_number'] + 1;
                            $data['num_pages_label'] = $data['num_pages'] + 1;
                            // Totals beginning
                            if ($displayTotals) {
                                $sqlQueryTotals = $sqlTotals . $sqlFrom . $sqlCountJoin . $sqlWhere;
                                $currentRsTotals = asol_Report::getSelectionResults($sqlQueryTotals, null, $useExternalDbConnection, $alternativeDb);
                                //***********************//
                                //***AlineaSol Premium***//
                                //***********************//
                                $extraParams = array('currentRsTotals' => $currentRsTotals, 'rsTotals' => $rsTotals, 'resulsetTotals' => $totals, 'moduleIteration' => $moduleIteration);
                                $returnedRsTotals = asol_ReportsUtils::managePremiumFeature("dynamicTablesReport", "reportFunctions.php", "parseMergeTotalsResultsets", $extraParams);
                                $rsTotals = $returnedRsTotals !== false ? $returnedRsTotals : $currentRsTotals;
                                //**********************************//
                                //******Apply Displaying Format*****//
                                //**********************************//
                                if ($lastModuleIteration) {
                                    $rsTotals = asol_ReportsGenerateQuery::formatGroupTotals($reportId, $dashletId, $rsTotals, $totals, $userDateFormat, $userDateTimeFormat, $userTZ, $focus->currency_id, $gmtDates, $audited_report, $auditedAppliedFields, $auditedFieldType);
                                    if ($report_data['results_limit'] != "all" || $allowExportGeneratedFile) {
                                        $limitedTotals = asol_ReportsGenerateQuery::formatGroupTotals($reportId, $dashletId, $limitedTotals, $totals, $userDateFormat, $userDateTimeFormat, $userTZ, $focus->currency_id, $gmtDates, $audited_report, $auditedAppliedFields, $auditedFieldType);
                                    }
                                    $rsTotals = !empty($limitedTotals) ? $limitedTotals : $rsTotals;
                                }
                            }
                            // Totals end
                        }
                    }
                }
                if (!$oversizedReport) {
                    $columnsDataTypes = array();
                    $columnsDataVisible = array();
                    foreach ($resulset_fields as $currentField) {
                        $currentType = !empty($currentField['format']['type']) ? $currentField['format']['type'] : $currentField['type'];
                        $currentVisible = $currentField['visible'];
                        $parenthesesPosition = strpos($currentType, '(');
                        if ($parenthesesPosition != false) {
                            $currentType = substr($currentType, 0, $parenthesesPosition);
                        }
                        //***********************//
                        //***AlineaSol Premium***//
                        //***********************//
                        $extraParams = array('dataType' => $currentType, 'dataFormat' => $currentField['format']);
                        $buttonTypeResult = asol_ReportsUtils::managePremiumFeature("reportButtonFormat", "reportFunctions.php", "getButtonTypeClass", $extraParams);
                        $buttonTypeClass = $buttonTypeResult['class'];
                        $delimiterToken = empty($buttonTypeResult['delimiter']) ? $delimiterToken : $buttonTypeResult['delimiter'];
                        //***********************//
                        //***AlineaSol Premium***//
                        //***********************//
                        $columnsDataTypes[$currentField['alias']] = $buttonTypeClass !== false ? $buttonTypeClass : $currentType;
                        $columnsDataVisible[$currentField['alias']] = $currentVisible;
                    }
                    //**************************************//
                    //****Save Report Data into Txt File****//
                    //**************************************//
                    if ($allowExportGeneratedFile) {
                        $exportedReport = array();
                        $exportedReport['id'] = $reportId;
                        $exportedReport['reportName'] = $report_name;
                        $exportedReport['report_type'] = $report_data['report_type'];
                        $exportedReport['report_type_stored_data'] = $report_data['report_type_stored_data'];
                        $exportedReport['module'] = $app_list_strings["moduleList"][$report_module];
                        $exportedReport['description'] = $report_data['description'];
                        $exportedReport['report_charts'] = $report_data['report_charts'];
                        $exportedReport['report_charts_engine'] = $report_data['report_charts_engine'];
                        $exportedReport['report_attachment_format'] = $report_data['report_attachment_format'];
                        $exportedReport['row_index_display'] = $report_data['row_index_display'];
                        $exportedReport['results_limit'] = $report_data['results_limit'];
                        $exportedReport['email_list'] = $focus->email_list;
                        $exportedReport['created_by'] = $focus->created_by;
                        if (asol_ReportsUtils::isDomainsInstalled()) {
                            $exportedReport['asol_domain_id'] = $focus->asol_domain_id;
                            $exportedReport['asol_domain_external'] = BeanFactory::getBean('asol_Domains', $focus->asol_domain_id)->external_id;
                        }
                        $exportedReport['pdf_orientation'] = $pdf_orientation;
                        $exportedReport['pdf_img_scaling_factor'] = $pdf_img_scaling_factor;
                        $exportedReport['totals'] = $rsTotals;
                        $exportedReport['headers'] = $columns;
                        $exportedReport['types'] = $types;
                        $exportedReport['headersTotals'] = $totals;
                        $exportedReport['current_user_id'] = $current_user->id;
                        $exportedReport['context_domain_id'] = $reportDomain;
                        $exportedReport['isDetailedReport'] = $isDetailedReport;
                        $exportedReport['hasDisplayedCharts'] = $hasDisplayedCharts;
                        $exportedReport['reportScheduledType'] = $focus->report_scheduled_type;
                        if ($isDetailedReport) {
                            $exportedReport['resultset'] = $subGroupsExport;
                            $exportedReport['subTotals'] = $subTotalsExport;
                        } else {
                            $exportedReport['resultset'] = $rsExport;
                        }
                        $exportedReport['columnsDataTypes'] = $columnsDataTypes;
                        $exportedReport['columnsDataVisible'] = $columnsDataVisible;
                        $exportedReport['currentReportCss'] = $currentReportCss;
                        //Guardamos el fichero en disco por si surge un export
                        $exportedReportName = preg_replace('/[^a-zA-Z0-9]/', '', $report_data['report_name']);
                        $reportNameNoSpaces = strtolower(str_replace(":", "", str_replace(" ", "_", $exportedReportName)));
                        $exportedReportFile = $reportNameNoSpaces . "_" . dechex(time()) . dechex(rand(0, 999999)) . ".txt";
                        $exportFolder = "modules/asol_Reports/tmpReportFiles/";
                        $storedReportsSubFolder = "storedReports/";
                        //If Scheduled-Stored Report, save report in StoredReports subfolder & update Report with reportFileName
                        if ($report_data['report_type'] == 'stored') {
                            $storedReportData = empty($exportedReport['report_type_stored_data']) ? array() : unserialize(base64_decode($exportedReport['report_type_stored_data']));
                            $chartFiles = array();
                            foreach ($chartInfo as $key => $info) {
                                if (!empty($urlChart[$key])) {
                                    $chartFiles[] = array('file' => $urlChart[$key], 'type' => $info["type"], 'subGroups' => $info["subgroups"]);
                                }
                            }
                            $accessKey = asol_ReportsUtils::isDomainsInstalled() ? $reportDomain : 'base';
                            $storedReportData[$accessKey] = array('infoTxt' => $storedReportsSubFolder . $exportedReportFile, 'chartFiles' => $chartFiles);
                            $updatedSerializedStoredData = base64_encode(serialize($storedReportData));
                            $setStoredReportFile = "UPDATE asol_reports SET report_type = 'stored:" . $updatedSerializedStoredData . "' WHERE id = '" . $reportId . "' LIMIT 1";
                            $db->query($setStoredReportFile);
                            $exportFolder .= $storedReportsSubFolder;
                        }
                        $exportFile = fopen($exportFolder . $exportedReportFile, "w");
                        fwrite($exportFile, serialize($exportedReport));
                        fclose($exportFile);
                    }
                    //********************************************//
                    //****Do Final Action for Executed Reports****//
                    //********************************************//
                    if (!isset($_REQUEST['return_action']) && !$hasVardefFilter) {
                        asol_ReportsGenerationFunctions::doFinalExecuteReportActions($reportId, $dispatcherMaxRequests);
                    }
                }
                if (!$externalCall && empty($vardefFilters)) {
                    echo '<link rel="stylesheet" type="text/css" href="modules/asol_Reports/include_basic/css/style.css?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '">
				<script type="text/javascript" src="modules/asol_Reports/include_basic/js/LAB.min.js?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '"></script>
				<script type="text/javascript" src="modules/asol_Reports/include_basic/js/reports.min.js?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '"></script>';
                }
                $externalCssUsage = isset($_REQUEST['useExternalCss']) && $_REQUEST['useExternalCss'] == 'true';
                if ($focus->report_type === 'external' && $externalCssUsage) {
                    echo '<link rel="stylesheet" type="text/css" href="modules/asol_Reports/include_basic/css/external.css?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '">';
                }
                if (!$externalCall && $getLibraries) {
                    if ($report_data['report_charts'] != "Tabl") {
                        echo asol_ReportsCharts::getChartEngineLibraries($focus->report_charts_engine, $isDashlet);
                    }
                    if (empty($vardefFilters)) {
                        echo '<link rel="stylesheet" type="text/css" href="modules/asol_Reports/include_basic/css/style.css?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '">
					<script type="text/javascript" src="modules/asol_Reports/include_basic/js/LAB.min.js?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '"></script>
					' . asol_ReportsManagementFunctions::getLoadJqueryScript(true, true) . '
					<script type="text/javascript" src="modules/asol_Reports/include_basic/js/reports.min.js?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '"></script>';
                    }
                    //***********************//
                    //***AlineaSol Premium***//
                    //***********************//
                    $extendedFunctionsScript = asol_ReportsUtils::managePremiumFeature("ExtendedJavascriptFunctions", "reportFunctions.php", "getExtendedJavaScriptFunctions", null);
                    if ($extendedFunctionsScript !== false && empty($vardefFilters)) {
                        echo $extendedFunctionsScript;
                    }
                    //***********************//
                    //***AlineaSol Premium***//
                    //***********************//
                }
                //***********************//
                //***AlineaSol Premium***//
                //***********************//
                $extraParams = array('overrideParam' => !isset($vardefFilters) ? null : $vardefFilters);
                $vardefFilters = asol_ReportsUtils::managePremiumFeature("reportFieldsManagement", "reportFunctions.php", "getVardefFilterRequest", $extraParams);
                //***********************//
                //***AlineaSol Premium***//
                //***********************//
                ?>
<script type="text/javascript"><?php 
                echo asol_ReportsGenerationFunctions::getReloadCurrentDashletScriptFunction($reportId, $isDashlet, $dashletId, $getLibraries, $vardefFilters, $override_entries, $current_user->id, true);
                ?>
</script><?php 
                if (!empty($chartInfo)) {
                    require_once "modules/asol_Reports/include_basic/manageReportsFunctions.php";
                    switch ($focus->report_charts_engine) {
                        case "flash":
                            $flashArray = asol_ReportsCharts::getCrmChartHtml($focus->id, $focus->report_charts_engine, false, $urlChart, $chartInfo, $current_language, $theme, $isStoredReport, $isDashlet);
                            $chartScript .= $flashArray["chartHtml"];
                            break;
                        case "html5":
                            $html5Array = asol_ReportsCharts::getCrmChartHtml($focus->id, $focus->report_charts_engine, true, $urlChart, $chartInfo, $current_language, $theme, $isStoredReport, $isDashlet);
                            $chartScript .= $html5Array["chartHtml"];
                            $html5Chart = $html5Array["returnedCharts"];
                            break;
                        case "nvd3":
                            $nvd3Array = asol_ReportsCharts::getCrmChartHtml($focus->id, $focus->report_charts_engine, true, $urlChart, $chartInfo, $current_language, $theme, $isStoredReport, $isDashlet);
                            $chartScript .= $nvd3Array["chartHtml"];
                            $nvd3Chart = $nvd3Array["returnedCharts"];
                            break;
                        default:
                            break;
                    }
                    $returnedChartScript = "\r\n\t\t\t\t<script>\r\n\t\t\t\tfunction setUpCharts_" . $fixedReportId . "() {\r\n\t\t\t\t\t" . $chartScript . "\r\n\t\t\t\t}\r\n\t\t\t\t</script>\r\n\t\t\t\t";
                    $returnedChartScript .= asol_ReportsManagementFunctions::getLoadJqueryScript(true, false, 'setUpCharts_' . $fixedReportId);
                }
                //Asignamos los valores para el ordenado
                $report_data['sort_field'] = $sort_field;
                $report_data['sort_direction'] = $sort_direction;
                $report_data['sort_index'] = $sort_index;
                if (!empty($limitedTotals)) {
                    $rsTotals = $limitedTotals;
                }
                if (empty($rsTotals)) {
                    $rsTotals = array();
                }
                $reportFields = $isDetailedReport ? $subGroups : $rs;
                if ($isHttpReportRequest) {
                    if (isset($_REQUEST['schedulerCall']) && $_REQUEST['schedulerCall'] == 'true') {
                        //Scheduled Reports
                        if ($report_data['report_type'] == "scheduled") {
                            $reportScheduledTypeArray = explode('${dollar}', $focus->report_scheduled_type);
                            $reportScheduledType = empty($reportScheduledTypeArray[0]) ? 'email' : $reportScheduledTypeArray[0];
                            if ($reportScheduledType == 'email') {
                                //Send Email
                                //$exportedReportFile
                                $tmpFilesDir = "modules/asol_Reports/tmpReportFiles/";
                                $descriptionArray = unserialize(base64_decode($report_data['description']));
                                //************************//
                                //****Get Email Arrays****//
                                //************************//
                                $emailReportInfo = asol_ReportsGenerationFunctions::getEmailInfo($focus->email_list);
                                $emailFrom = $emailReportInfo['emailFrom'];
                                $emailArrays = $emailReportInfo['emailArrays'];
                                $users_to = $emailArrays["users_to"];
                                $users_cc = $emailArrays["users_cc"];
                                $users_bcc = $emailArrays["users_bcc"];
                                $roles_to = $emailArrays["roles_to"];
                                $roles_cc = $emailArrays["roles_cc"];
                                $roles_bcc = $emailArrays["roles_bcc"];
                                $emails_to = $emailArrays["emails_to"];
                                $emails_cc = $emailArrays["emails_cc"];
                                $emails_bcc = $emailArrays["emails_bcc"];
                                //Generar array con emails a enviar Report
                                $mail = new SugarPHPMailer();
                                $mail->setMailerForSystem();
                                $user = new User();
                                //created by
                                $mail_config = $user->getEmailInfo($report_data['created_by']);
                                $mail->From = !empty($emailFrom) ? $emailFrom : (isset($sugar_config["asolReportsEmailsFrom"]) ? $sugar_config["asolReportsEmailsFrom"] : $mail_config['email']);
                                $mail->FromName = isset($sugar_config["asolReportsEmailsFromName"]) ? $sugar_config["asolReportsEmailsFromName"] : $mail_config['name'];
                                //Timeout del envio de correo
                                $mail->Timeout = 30;
                                $mail->CharSet = "UTF-8";
                                asol_ReportsGenerationFunctions::setSendEmailAddresses($mail, $emailArrays, $reportDomain);
                                if ($report_data['scheduled_images'] == "1") {
                                    $chartFiles = array();
                                    foreach ($chartInfo as $key => $info) {
                                        if (!empty($urlChart[$key])) {
                                            $chartFiles[] = array('file' => $urlChart[$key], 'type' => $info["type"], 'subGroups' => $info["subgroups"]);
                                        }
                                    }
                                    $accessKey = 'base';
                                    $storedReportData[$accessKey] = array('infoTxt' => $exportedReportFile, 'chartFiles' => $chartFiles);
                                    $serializedStoredData = base64_encode(serialize($storedReportData));
                                    $uri = !empty($host_name) ? $host_name : $sugar_config['site_url'];
                                    $uri .= "/index.php";
                                    $uri .= "?entryPoint=scheduledEmailReport&module=asol_Reports&storedReportInfo=" . $serializedStoredData;
                                    asol_ReportsUtils::reports_log('asol', 'scheduledImages is enabled - URI Rebuild: ' . $uri, __FILE__, __METHOD__, __LINE__);
                                    //Generamos la url para reconstruir el report en un entryPoint
                                }
                                //Datos del email en si
                                if (asol_ReportsUtils::isDomainsInstalled()) {
                                    $reportDomain = $contextDomainId !== null ? $contextDomainId : $current_user->asol_default_domain;
                                    $mail->Subject = "[" . BeanFactory::getBean('asol_Domains', $reportDomain)->name . "] " . $mod_strings['LBL_REPORT_REPORTS_ACTION'] . ": " . $report_data['report_name'];
                                } else {
                                    $mail->Subject = $mod_strings['LBL_REPORT_REPORTS_ACTION'] . ": " . $report_data['report_name'];
                                }
                                $mail->Body = "<b>" . $mod_strings['LBL_REPORT_NAME'] . ": </b>" . $report_data['report_name'] . "<br>";
                                $mail->Body .= "<b>" . $mod_strings['LBL_REPORT_MODULE'] . ": </b>" . $app_list_strings["moduleList"][$report_data['report_module']] . "<br>";
                                $mail->Body .= "<b>" . $mod_strings['LBL_REPORT_DESCRIPTION'] . ": </b>" . $descriptionArray['public'];
                                if ($report_data['scheduled_images'] == "1") {
                                    $mail->Body .= "<br><br>";
                                    $mail->Body .= "<a href='" . $uri . "'>" . $mod_strings['LBL_REPORT_EMAIL_TTL_TEXT_1'] . "</a> " . $mod_strings['LBL_REPORT_EMAIL_TTL_TEXT_2'] . "<br><br>";
                                    $mail->Body .= "<i>" . $mod_strings['LBL_REPORT_EMAIL_AVAILABLE_TEXT_1'] . " " . $scheduled_files_ttl . " " . $mod_strings['LBL_REPORT_EMAIL_AVAILABLE_TEXT_2'] . "</i>";
                                }
                                //Mensaje en caso de que el destinatario no admita emails en formato html
                                $mail->AltBody = $mod_strings['LBL_REPORT_NAME'] . ": " . $report_data['report_name'] . "\n";
                                $mail->AltBody .= $mod_strings['LBL_REPORT_MODULE'] . ": " . $app_list_strings["moduleList"][$report_data['report_module']] . "\n";
                                $mail->AltBody .= $mod_strings['LBL_REPORT_DESCRIPTION'] . ": " . $descriptionArray['public'];
                                if ($scheduled_images == "1") {
                                    $mail->AltBody .= "\n\n";
                                    $mail->AltBody .= $mod_strings['LBL_REPORT_ALT_EMAIL_TTL_TEXT'] . ": " . $uri . "\n\n";
                                    $mail->AltBody .= $mod_strings['LBL_REPORT_EMAIL_AVAILABLE_TEXT_1'] . " " . $scheduled_files_ttl . " " . $mod_strings['LBL_REPORT_EMAIL_AVAILABLE_TEXT_2'];
                                }
                                if (!$isDetailedReport) {
                                    $rsExport = $rs;
                                    $subTotalsExport = "";
                                } else {
                                    $rsExport = $subGroups;
                                    $subTotalsExport = $subTotals;
                                }
                                if ($report_data['report_charts'] != 'Char') {
                                    //If only charts Report, do not attach a generated file
                                    $descriptionArray = unserialize(base64_decode($report_data["description"]));
                                    $description = $descriptionArray['public'];
                                    switch ($report_data['report_attachment_format']) {
                                        case "PDF":
                                            $adjunto = generateFile($focus->report_charts_engine, $report_data['report_name'], $app_list_strings["moduleList"][$report_data['report_module']], $description, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, $pdf_orientation, array(), array(), false, true, 100, time(), $userTZlabel, $report_data['row_index_display'], $report_data['report_charts'], $columnsDataTypes, $columnsDataVisible, $currentReportCss, $reportDomain);
                                            break;
                                        case "HTML":
                                            $adjunto = generateFile($focus->report_charts_engine, $report_data['report_name'], $app_list_strings["moduleList"][$report_data['report_module']], $description, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, $pdf_orientation, array(), array(), true, true, 100, time(), $userTZlabel, $report_data['row_index_display'], $report_data['report_charts'], $columnsDataTypes, $columnsDataVisible, $currentReportCss, $reportDomain);
                                            break;
                                        case "CSV":
                                            $adjunto = generateCsv($report_data['report_name'], $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $report_data['row_index_display']);
                                            break;
                                        case "CSVC":
                                            $adjunto = generateCsv($report_data['report_name'], $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $report_data['row_index_display'], true, true, false, true, true);
                                            break;
                                        case "XLS":
                                            $adjunto = generateXls($report_data['report_name'], $columns, null, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $report_data['row_index_display']);
                                            break;
                                        case "XLSC":
                                            $adjunto = generateXls($report_data['report_name'], $columns, null, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $report_data['row_index_display'], true, true, false, true, true);
                                            break;
                                    }
                                    //Añadimos el Report como fichero adjunto del e-mail
                                    $mail->AddAttachment(getcwd() . "/" . $tmpFilesDir . $adjunto, $adjunto);
                                }
                                $success = $mail->Send();
                                $tries = 1;
                                while (!$success && $tries < 5) {
                                    sleep(5);
                                    $success = $mail->Send();
                                    $tries++;
                                }
                                if ($report_data['report_charts'] != 'Char') {
                                    unlink(getcwd() . "/" . $tmpFilesDir . $adjunto);
                                }
                            } else {
                                // Send Application
                                //***********************//
                                //***AlineaSol Premium***//
                                //***********************//
                                $extraParams = array('reportScheduledType' => $focus->report_scheduled_type, 'cvsData' => array('reportName' => $report_data['report_name'], 'resultset' => $rsExport, 'subtotals' => $subTotalsExport, 'isDetailed' => $isDetailedReport, 'rowIndexDisplay' => $report_data['row_index_display']));
                                asol_ReportsUtils::managePremiumFeature("externalApplicationReports", "reportFunctions.php", "sendReportToExternalApplication", $extraParams);
                                //***********************//
                                //***AlineaSol Premium***//
                                //***********************//
                            }
                        }
                    } else {
                        $tmpFilesDir = "modules/asol_Reports/tmpReportFiles/";
                        $httpHtmlFile = $_REQUEST['httpHtmlFile'];
                        $noDataReport = empty($urlChart) && asol_ReportsGenerationFunctions::isEmptyResultSet($reportFields);
                        $reportedError = asol_Report::$reported_error;
                        if ($returnHtml) {
                            return include "modules/asol_Reports/include_basic/DetailViewHttpSave.php";
                        } else {
                            include "modules/asol_Reports/include_basic/DetailViewHttpSave.php";
                        }
                    }
                } else {
                    $justDisplay = true;
                    $noDataReport = empty($urlChart) && asol_ReportsGenerationFunctions::isEmptyResultSet($reportFields);
                    $reportedError = asol_Report::$reported_error;
                    if ($returnHtml) {
                        return include "modules/asol_Reports/include_basic/DetailViewHttpSave.php";
                    } else {
                        include "modules/asol_Reports/include_basic/DetailViewHttpSave.php";
                        exit;
                    }
                }
            } else {
                require_once 'modules/asol_Reports/include_basic/ReportChart.php';
                require_once 'modules/asol_Reports/include_basic/generateQuery.php';
                require_once 'modules/asol_Reports/include_basic/generateReportsFunctions.php';
                require_once 'modules/asol_Reports/include_basic/manageReportsFunctions.php';
                asol_ReportsUtils::reports_log('debug', 'HttpRequest REPORT!!', __FILE__, __METHOD__, __LINE__);
                $hasSearchCriteria = !isset($_REQUEST['search_criteria']) ? false : true;
                $pageNumber = empty($_REQUEST['page_number']) ? "" : "&page_number=" . $_REQUEST['page_number'];
                $sortingField = empty($_REQUEST['sort_field']) ? "" : "&sort_field=" . $_REQUEST['sort_field'] . "&sort_direction=" . $_REQUEST['sort_direction'] . "&sort_index=" . $_REQUEST['sort_index'];
                $externalFilters = !isset($_REQUEST['external_filters']) ? "" : "&external_filters=" . html_entity_decode($_REQUEST['external_filters']);
                //***********************//
                //***AlineaSol Premium***//
                //***********************//
                $extraParams = array('overrideParam' => !isset($vardefFilters) ? null : $vardefFilters);
                $vardefFilters = asol_ReportsUtils::managePremiumFeature("reportFieldsManagement", "reportFunctions.php", "getVardefFilterRequest", $extraParams);
                //***********************//
                //***AlineaSol Premium***//
                //***********************//
                $overrideEntries = empty($override_entries) ? "" : "&overrideEntries=" . $override_entries;
                $searchCriteria = !isset($_REQUEST['search_criteria']) ? "" : "&search_criteria=1";
                $filtersHiddenInputs = empty($_REQUEST['filters_hidden_inputs']) ? "" : "&filters_hidden_inputs=" . $_REQUEST['filters_hidden_inputs'];
                $currentUserId = isset($_REQUEST['currentUserId']) ? "&currentUserId=" . $_REQUEST['currentUserId'] : "&currentUserId=" . $current_user->id;
                $contextDomain = isset($contextDomainId) ? "&contextDomainId=" . $contextDomainId : "";
                $returnHtmlParam = isset($returnHtml) && $returnHtml ? "&returnHtml=true" : "";
                $isDashletQuery = !empty($isDashlet) ? "&dashlet=true" : "";
                $isDashletQuery .= !empty($dashletId) ? "&dashletId=" . $dashletId : "";
                $focus = BeanFactory::getBean('asol_Reports', $reportId);
                //*************************************//
                //********Manage Report Domain*********//
                //*************************************//
                if (asol_ReportsUtils::isDomainsInstalled()) {
                    $reportDomain = $contextDomainId !== null ? $contextDomainId : $current_user->asol_default_domain;
                    if (!asol_ReportsGenerationFunctions::manageReportDomain($reportId, $reportDomain, $focus->asol_domain_id)) {
                        $availableReport = false;
                        include "modules/asol_Reports/include_basic/DetailViewHttpSave.php";
                        exit;
                    }
                }
                //Ver si hay charts para pasar los nombres
                $rsHttp = asol_Report::getSelectionResults("SELECT * FROM asol_reports WHERE id = '" . $reportId . "' LIMIT 1", null, false);
                $chartsUrls = array();
                $chartsInfo = array();
                $filtersArray = unserialize(base64_decode($rsHttp[0]['report_filters']));
                //Check if there is some user_input fiter to show
                $hasUserInputsFilters = false;
                foreach ($filtersArray['data'] as $currentFilter) {
                    if ($currentFilter['behavior'] == 'user_input') {
                        $hasUserInputsFilters = true;
                        break;
                    }
                }
                //Check if there is some user_inut fiter to show
                // Execute report with default filter values
                if (isset($filtersArray['config']['initialExecution']) && $filtersArray['config']['initialExecution']) {
                    $hasSearchCriteria = true;
                    $searchCriteria = "&search_criteria=1";
                }
                // Execute report with default filter values
                //Guardamos el fichero en disco por si surge un export
                $exportedReportName = preg_replace('/[^a-zA-Z0-9]/', '', $rsHttp[0]['name']);
                $reportNameNoSpaces = strtolower(str_replace(":", "", str_replace(" ", "_", $exportedReportName)));
                $httpHtmlFile = $reportNameNoSpaces . "_" . dechex(time()) . dechex(rand(0, 999999)) . ".html";
                $selectedCharts = unserialize(base64_decode($rsHttp[0]['report_charts_detail']));
                $chartsUrls = asol_ReportsGenerationFunctions::generateChartFileNames($focus->report_charts_engine, $selectedCharts);
                $chartsQueryUrls = empty($chartsUrls) ? "" : "&chartsHttpQueryUrls=" . implode('${pipe}', $chartsUrls);
                if (empty($vardefFilters)) {
                    echo '<script type="text/javascript" src="modules/asol_Reports/include_basic/js/LAB.min.js?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '"></script>
				' . asol_ReportsManagementFunctions::getLoadJqueryScript(true);
                }
                if ($getLibraries) {
                    if ($report_data['report_charts'] != "Tabl") {
                        echo asol_ReportsCharts::getChartEngineLibraries($focus->report_charts_engine, $isDashlet);
                    }
                    echo '<link rel="stylesheet" type="text/css" href="modules/asol_Reports/include_basic/css/style.css?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '">';
                    echo '
				<script type="text/javascript" src="modules/asol_Reports/include_basic/js/LAB.min.js?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '"></script>	
				' . asol_ReportsManagementFunctions::getLoadJqueryScript(true) . '
				<script type="text/javascript" src="modules/asol_Reports/include_basic/js/reports.min.js?version=' . str_replace('.', '', asol_ReportsUtils::$reports_version) . '"></script>';
                    //***********************//
                    //***AlineaSol Premium***//
                    //***********************//
                    $extendedFunctionsScript = asol_ReportsUtils::managePremiumFeature("ExtendedJavascriptFunctions", "reportFunctions.php", "getExtendedJavaScriptFunctions", null);
                    if ($extendedFunctionsScript !== false) {
                        echo $extendedFunctionsScript;
                    }
                    //***********************//
                    //***AlineaSol Premium***//
                    //***********************//
                }
                //***********************//
                //***AlineaSol Premium***//
                //***********************//
                if ($currentReportCss !== false) {
                    echo $currentReportCss;
                }
                //***********************//
                //***AlineaSol Premium***//
                //***********************//
                $setUpInputCalendarsScript = asol_ReportsGenerationFunctions::getSetUpInputCalendarsScriptFunction($reportId, $filtersArray['data']);
                if (isset($setUpInputCalendarsScript)) {
                    echo '<script>' . $setUpInputCalendarsScript . '</script>';
                }
                $waitForReport = false;
                $reportRequestId = "";
                $asolUrlQuery = $pageNumber . $sortingField . $overrideEntries . $externalFilters . $vardefFilters . $searchCriteria . $filtersHiddenInputs . $currentUserId . $contextDomain . $returnHtmlParam . $isDashletQuery;
                $baseRequestedUrl = isset($sugar_config["asolReportsCurlRequestUrl"]) ? $sugar_config["asolReportsCurlRequestUrl"] : $sugar_config["site_url"];
                $curlRequestedUrl = $baseRequestedUrl . '/index.php?entryPoint=viewReport&record=' . $reportId . '&language=' . $current_language . '&sourceCall=httpReportRequest' . $chartsQueryUrls . $asolUrlQuery . '&httpHtmlFile=' . $httpHtmlFile . $reportRequestId;
                //REPORTS DISPATCHER
                $hasVardefFilter = !empty($vardefFilters);
                $manageDispatcher = $dispatcherMaxRequests > 0 && (!$hasUserInputsFilters || $hasUserInputsFilters && isset($_REQUEST['external_filters'])) && !$hasVardefFilter;
                if ($manageDispatcher) {
                    $requestId = create_guid();
                    $currentGMTTime = time();
                    $currentGMTDate = date('Y-m-d H:i:s', $currentGMTTime);
                    asol_ReportsUtils::reports_log('debug', 'Init GMDate(): ' . $currentGMTDate, __FILE__, __METHOD__, __LINE__);
                    $reportRequestId = "&reportRequestId=" . $requestId;
                    $initRequestTimeStamp = "&initRequestDateTimeStamp=" . $currentGMTTime;
                    $curlRequestedUrl .= $reportRequestId . $initRequestTimeStamp;
                    asol_ReportsUtils::reports_log('debug', 'Reporting Queue Feature Enabled.', __FILE__, __METHOD__, __LINE__);
                    $reportsDispatcherSql = "SELECT COUNT(id) as 'reportsThreads' FROM asol_reports_dispatcher WHERE status = 'executing'";
                    $reportsDispatcherRs = $db->query($reportsDispatcherSql);
                    $reportsDispatcherRow = $db->fetchByAssoc($reportsDispatcherRs);
                    $currentReportsRunningThreads = $reportsDispatcherRow["reportsThreads"];
                    $waitForReport = $currentReportsRunningThreads >= $dispatcherMaxRequests;
                    $dispatcherReportSql = "INSERT INTO asol_reports_dispatcher VALUES ('" . $requestId . "', '" . $reportId . "', '" . $curlRequestedUrl . "', '" . ($waitForReport ? 'waiting' : 'executing') . "', '" . $currentGMTDate . "', '" . $currentGMTDate . "', 'manual', '" . $current_user->id . "')";
                    $db->query($dispatcherReportSql);
                }
                //REPORTS DISPATCHER
                if (!$waitForReport) {
                    //Execute report if not is waiting in queue
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $curlRequestedUrl);
                    curl_setopt($ch, CURLOPT_HEADER, 0);
                    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
                    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
                    curl_exec($ch);
                    curl_close($ch);
                }
                $checkHttpFileTimeout = isset($sugar_config["asolReportsCheckHttpFileTimeout"]) ? $sugar_config["asolReportsCheckHttpFileTimeout"] : "1000";
                echo '
				<script>';
                if (!isset($_REQUEST['entryPoint'])) {
                    echo asol_ReportsGenerationFunctions::getSendAjaxRequestScriptFunction($reportId, $dashletId, $checkHttpFileTimeout, $httpHtmlFile, $reportRequestId, $initRequestTimeStamp, $hasCalendarInputs);
                    echo asol_ReportsGenerationFunctions::getInitialAjaxRequest2GenerateReportScript($reportId);
                }
                echo asol_ReportsGenerationFunctions::getReloadCurrentDashletScriptFunction($reportId, $isDashlet, $dashletId, $getLibraries, $vardefFilters, $override_entries, $current_user->id, true);
                echo '
				</script>';
                if (!$isDashlet) {
                    echo asol_ReportsGenerationFunctions::getStandByReportHtml('', false);
                }
            }
        }
    }
}
Esempio n. 18
0
 public static function enviarEmail($asunto, $mensaje, $direcciones, $from)
 {
     require_once "include/SugarPHPMailer.php";
     $mailer = new SugarPHPMailer();
     $mailer->Subject = $asunto;
     $mailer->From = $from['from'];
     $mailer->FromName = $from['from_name'];
     foreach ($direcciones as $email) {
         $mailer->AddAddress($email);
     }
     $mailer->Body = $mensaje;
     $mailer->prepForOutbound();
     $mailer->setMailerForSystem();
     $mailer->IsHTML(true);
     if ($mailer->Send()) {
         return true;
     } else {
         $GLOBALS['log']->info("No se ha podido enviar el correo electronico:  " . $mailer->ErrorInfo);
         return false;
     }
 }
Esempio n. 19
0
     $note->filename = $focus->report_result_name;
     if ($_REQUEST['parent_module'] == 'Contacts') {
         $note->contact_id = $_REQUEST['parent_id'];
     } else {
         $note->parent_type = $_REQUEST['parent_module'];
         $note->parent_id = $_REQUEST['parent_id'];
     }
     $note->save();
     $uf = new UploadFile("upload");
     $uf->set_for_soap($focus->report_result_name, file_get_contents($focus->report_result));
     $uf->stored_file_name = $uf->create_stored_filename();
     $uf->final_move($note->id);
     $note_url = "index.php?action=DetailView&module=Notes&record=" . $note->id . "&return_module=ZuckerReports&return_action=ReportOnDemand";
 }
 if (!empty($_REQUEST['send_email'])) {
     $mail = new SugarPHPMailer();
     $emails = split(",", $_REQUEST['send_email']);
     foreach ($emails as $email) {
         $mail->AddAddress($email);
     }
     $admin = new Administration();
     $admin->retrieveSettings();
     if ($admin->settings['mail_sendtype'] == "SMTP") {
         $mail->Mailer = "smtp";
         $mail->Host = $admin->settings['mail_smtpserver'];
         $mail->Port = $admin->settings['mail_smtpport'];
         if ($admin->settings['mail_smtpauth_req']) {
             $mail->SMTPAuth = TRUE;
             $mail->Username = $admin->settings['mail_smtpuser'];
             $mail->Password = $admin->settings['mail_smtppass'];
         }
Esempio n. 20
0
 /**
  * This function handles create the email notifications email.
  * @param string $notify_user the user to send the notification email to
  */
 function create_notification_email($notify_user)
 {
     global $sugar_version;
     global $sugar_config;
     global $app_list_strings;
     global $current_user;
     global $locale;
     global $beanList;
     $OBCharset = $locale->getPrecedentPreference('default_email_charset');
     require_once "include/SugarPHPMailer.php";
     $notify_address = $notify_user->emailAddress->getPrimaryAddress($notify_user);
     $notify_name = $notify_user->full_name;
     $GLOBALS['log']->debug("Notifications: user has e-mail defined");
     $notify_mail = new SugarPHPMailer();
     $notify_mail->AddAddress($notify_address, $locale->translateCharsetMIME(trim($notify_name), 'UTF-8', $OBCharset));
     if (empty($_SESSION['authenticated_user_language'])) {
         $current_language = $sugar_config['default_language'];
     } else {
         $current_language = $_SESSION['authenticated_user_language'];
     }
     $xtpl = new XTemplate(get_notify_template_file($current_language));
     if ($this->module_dir == "Cases") {
         $template_name = "Case";
         //we should use Case, you can refer to the en_us.notify_template.html.
     } else {
         $template_name = $beanList[$this->module_dir];
         //bug 20637, in workflow this->object_name = strange chars.
     }
     $this->current_notify_user = $notify_user;
     if (in_array('set_notification_body', get_class_methods($this))) {
         $xtpl = $this->set_notification_body($xtpl, $this);
     } else {
         $xtpl->assign("OBJECT", $this->object_name);
         $template_name = "Default";
     }
     if (!empty($_SESSION["special_notification"]) && $_SESSION["special_notification"]) {
         $template_name = $beanList[$this->module_dir] . 'Special';
     }
     if ($this->special_notification) {
         $template_name = $beanList[$this->module_dir] . 'Special';
     }
     $xtpl->assign("ASSIGNED_USER", $this->new_assigned_user_name);
     $xtpl->assign("ASSIGNER", $current_user->name);
     $port = '';
     if (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
         $port = $_SERVER['SERVER_PORT'];
     }
     if (!isset($_SERVER['HTTP_HOST'])) {
         $_SERVER['HTTP_HOST'] = '';
     }
     $httpHost = $_SERVER['HTTP_HOST'];
     if ($colon = strpos($httpHost, ':')) {
         $httpHost = substr($httpHost, 0, $colon);
     }
     $parsedSiteUrl = parse_url($sugar_config['site_url']);
     $host = $parsedSiteUrl['host'];
     if (!isset($parsedSiteUrl['port'])) {
         $parsedSiteUrl['port'] = 80;
     }
     $port = $parsedSiteUrl['port'] != 80 ? ":" . $parsedSiteUrl['port'] : '';
     $path = !empty($parsedSiteUrl['path']) ? $parsedSiteUrl['path'] : "";
     $cleanUrl = "{$parsedSiteUrl['scheme']}://{$host}{$port}{$path}";
     $xtpl->assign("URL", $cleanUrl . "/index.php?module={$this->module_dir}&action=DetailView&record={$this->id}");
     $xtpl->assign("SUGAR", "Sugar v{$sugar_version}");
     $xtpl->parse($template_name);
     $xtpl->parse($template_name . "_Subject");
     $notify_mail->Body = from_html(trim($xtpl->text($template_name)));
     $notify_mail->Subject = from_html($xtpl->text($template_name . "_Subject"));
     // cn: bug 8568 encode notify email in User's outbound email encoding
     $notify_mail->prepForOutbound();
     return $notify_mail;
 }
Esempio n. 21
0
 private function sendCreationEmail(aCase $bean, $contact)
 {
     if (!isAOPEnabled()) {
         return;
     }
     require_once "include/SugarPHPMailer.php";
     $mailer = new SugarPHPMailer();
     $admin = new Administration();
     $admin->retrieveSettings();
     $mailer->prepForOutbound();
     $mailer->setMailerForSystem();
     $email_template = new EmailTemplate();
     $aop_config = $this->getAOPConfig();
     $email_template = $email_template->retrieve($aop_config['case_creation_email_template_id']);
     if (!$aop_config['case_creation_email_template_id'] || !$email_template) {
         $GLOBALS['log']->warn("CaseUpdatesHook: sendCreationEmail template is empty");
         return false;
     }
     $emailSettings = getPortalEmailSettings();
     $text = $this->populateTemplate($email_template, $bean, $contact);
     $mailer->Subject = $text['subject'];
     $mailer->Body = $text['body'];
     $mailer->IsHTML(true);
     $mailer->AltBody = $text['body_alt'];
     $mailer->From = $emailSettings['from_address'];
     $mailer->FromName = $emailSettings['from_name'];
     $email = $contact->emailAddress->getPrimaryAddress($contact);
     if (empty($email) && !empty($contact->email1)) {
         $email = $contact->email1;
     }
     $mailer->AddAddress($email);
     if (!$mailer->Send()) {
         $GLOBALS['log']->info("CaseUpdatesHook: Could not send email:  " . $mailer->ErrorInfo);
         return false;
     } else {
         $this->logEmail($email, $mailer, $bean->id);
         return true;
     }
 }
Esempio n. 22
0
 public function sendEmail($emailTo, $emailSubject, $emailToname, $emailBody, $altemailBody, SugarBean $relatedBean = null, $attachments = array())
 {
     $emailObj = new Email();
     $defaults = $emailObj->getSystemDefaultEmail();
     $mail = new SugarPHPMailer();
     $mail->setMailerForSystem();
     $mail->From = $defaults['email'];
     $mail->FromName = $defaults['name'];
     $mail->ClearAllRecipients();
     $mail->ClearReplyTos();
     $mail->Subject = from_html($emailSubject);
     $mail->Body = $emailBody;
     $mail->AltBody = $altemailBody;
     $mail->handleAttachments($attachments);
     $mail->prepForOutbound();
     $mail->AddAddress($emailTo);
     //now create email
     if (@$mail->Send()) {
         $emailObj->to_addrs = '';
         $emailObj->type = 'out';
         $emailObj->deleted = '0';
         $emailObj->name = $mail->Subject;
         $emailObj->description = $mail->AltBody;
         $emailObj->description_html = $mail->Body;
         $emailObj->from_addr = $mail->From;
         if ($relatedBean instanceof SugarBean && !empty($relatedBean->id)) {
             $emailObj->parent_type = $relatedBean->module_dir;
             $emailObj->parent_id = $relatedBean->id;
         }
         $emailObj->date_sent = TimeDate::getInstance()->nowDb();
         $emailObj->modified_user_id = '1';
         $emailObj->created_by = '1';
         $emailObj->status = 'sent';
         $emailObj->save();
         return true;
     } else {
         return false;
     }
 }
Esempio n. 23
0
<?php

if (!defined('sugarEntry') || !sugarEntry) {
    die('Not A Valid Entry Point');
}
echo "Here I am";
require_once 'include/SugarPHPMailer.php';
$emailObj = new Email();
$defaults = $emailObj->getSystemDefaultEmail();
$mail = new SugarPHPMailer();
$mail->setMailerForSystem();
//$mail->From = $defaults['email'];
$mail->IsSMTP();
// telling the class to use SMTP
$mail->Host = "mail.vinksoftware.com";
// SMTP server
$mail->SMTPDebug = 2;
// enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
$mail->SMTPAuth = true;
// enable SMTP authentication
//$mail->SMTPSecure = 'tls';
$mail->Port = 26;
// set the SMTP port for the GMAIL server
$mail->Username = "******";
// SMTP account username
$mail->Password = "******";
// SMTP account password
$mail->SetFrom('*****@*****.**', 'Vinay Hooloomann');
//$mail->AddReplyTo('*****@*****.**', 'Vinay Hooloomann');
Esempio n. 24
0
 function sendEmail($emailTo, $emailSubject, $emailBody, $altemailBody, SugarBean $relatedBean = null, $emailCc = array(), $emailBcc = array(), $attachments = array())
 {
     require_once 'modules/Emails/Email.php';
     require_once 'include/SugarPHPMailer.php';
     $emailObj = new Email();
     $defaults = $emailObj->getSystemDefaultEmail();
     $mail = new SugarPHPMailer();
     $mail->setMailerForSystem();
     $mail->From = $defaults['email'];
     $mail->FromName = $defaults['name'];
     $mail->ClearAllRecipients();
     $mail->ClearReplyTos();
     $mail->Subject = from_html($emailSubject);
     $mail->Body = $emailBody;
     $mail->AltBody = $altemailBody;
     $mail->handleAttachments($attachments);
     $mail->prepForOutbound();
     if (empty($emailTo)) {
         return false;
     }
     foreach ($emailTo as $to) {
         $mail->AddAddress($to);
     }
     if (!empty($emailCc)) {
         foreach ($emailCc as $email) {
             $mail->AddCC($email);
         }
     }
     if (!empty($emailBcc)) {
         foreach ($emailBcc as $email) {
             $mail->AddBCC($email);
         }
     }
     //now create email
     if (@$mail->Send()) {
         $emailObj->to_addrs = implode(',', $emailTo);
         $emailObj->cc_addrs = implode(',', $emailCc);
         $emailObj->bcc_addrs = implode(',', $emailBcc);
         $emailObj->type = 'out';
         $emailObj->deleted = '0';
         $emailObj->name = $mail->Subject;
         $emailObj->description = $mail->AltBody;
         $emailObj->description_html = $mail->Body;
         $emailObj->from_addr = $mail->From;
         if ($relatedBean instanceof SugarBean && !empty($relatedBean->id)) {
             $emailObj->parent_type = $relatedBean->module_dir;
             $emailObj->parent_id = $relatedBean->id;
         }
         $emailObj->date_sent = TimeDate::getInstance()->nowDb();
         $emailObj->modified_user_id = '1';
         $emailObj->created_by = '1';
         $emailObj->status = 'sent';
         $emailObj->save();
         return true;
     }
     return false;
 }
Esempio n. 25
0
$excelreport->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
$excelreport->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
$excelreport->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
$excelreport->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
$excelreport->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
$excelreport->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
/* Set Formatting on Sheet */
$excelreport->getActiveSheet()->getStyle('A1:G2')->getFont()->setBold(true);
$excelreport->getActiveSheet()->getStyle('A2:G2')->getBorders()->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);
/* Write it out to a temp file */
$objWriter = PHPExcel_IOFactory::createWriter($excelreport, 'Excel2007');
$objWriter->save('/tmp/Tetra-Monthly-Report.xlsx');
/* Send out emails */
$emailObj = new Email();
$defaults = $emailObj->getSystemDefaultEmail();
$mail = new SugarPHPMailer();
$mail->setMailerForSystem();
$mail->From = $defaults['email'];
$mail->FromName = $defaults['name'];
$mail->ClearAllRecipients();
$mail->ClearReplyTos();
$mail->Subject = "Tetra Monthly Report Draft";
$mail->IsHTML(true);
$mail->Body = $emailbody;
$mail->AltBody = $emailbody;
$mail->AddAttachment('/tmp/Tetra-Monthly-Report.xlsx');
$mail->prepForOutbound();
$mail->AddAddress('*****@*****.**');
$mail->Send();
/* Clean up shop */
$mail->SMTPClose();
 public static function processDownloadRequest($report, $userTZ, $fileTime, $fileType, $somePngs, $someLegends)
 {
     global $mod_strings, $sugar_config;
     require_once "include/SugarPHPMailer.php";
     require_once "modules/asol_Reports/include_basic/ReportFile.php";
     require_once "modules/asol_Reports/include_basic/ReportExcel.php";
     require_once "modules/asol_Reports/include_basic/generateReportsFunctions.php";
     $fileContent = null;
     $exportFolder = "modules/asol_Reports/tmpReportFiles/";
     $currentDir = getcwd() . "/";
     $fileName = $exportFolder . $fileName;
     //Volcamos el contenido del report exportado en variables
     $report_name = $report["reportName"];
     $report_module = $report["module"];
     $descriptionArray = unserialize(base64_decode($report["description"]));
     $description = $descriptionArray['public'];
     $isDetailedReport = $report["isDetailedReport"];
     $reportScheduledType = $report["reportScheduledType"];
     $hasDisplayedCharts = $report["hasDisplayedCharts"];
     $pdf_orientation = $report["pdf_orientation"];
     $pdf_img_scaling_factor = $report["pdf_img_scaling_factor"];
     //Only if AlineaSolDomains installed
     $reportDomainId = isset($report["asol_domain_id"]) ? $report["asol_domain_id"] : null;
     //Only if AlineaSolDomains installed
     $report_charts = $report["report_charts"];
     $report_charts_engine = $report["report_charts_engine"];
     $report_attachment_format = $report["report_attachment_format"];
     $row_index_display = $report["row_index_display"];
     $email_list = $report["email_list"];
     $created_by = $report["created_by"];
     $columns = $report["headers"];
     $types = $report["types"];
     $totals = $report["headersTotals"];
     $rsTotals = $report["totals"];
     $rs = $report["resultset"];
     $subGroups = $report["resultset"];
     $subTotals = $report["subTotals"];
     $columnsDataTypes = $report['columnsDataTypes'];
     $columnsDataVisible = $report['columnsDataVisible'];
     $currentReportCss = $report['currentReportCss'];
     //Only if AlineaSolDomains installed
     $contextDomainId = $report["context_domain_id"];
     //Only if AlineaSolDomains installed
     $rsExport = $isDetailedReport ? $subGroups : $rs;
     $subTotalsExport = $isDetailedReport ? $subTotals : "";
     if ($fileType == 'email') {
         //Generar array con emails a enviar Report
         $mail = new SugarPHPMailer();
         //************************//
         //****Get Email Arrays****//
         //************************//
         $emailReportInfo = asol_ReportsGenerationFunctions::getEmailInfo($email_list);
         $emailFrom = $emailReportInfo['emailFrom'];
         $emailArrays = $emailReportInfo['emailArrays'];
         $users_to = $emailArrays['users_to'];
         $users_cc = $emailArrays['users_cc'];
         $users_bcc = $emailArrays['users_bcc'];
         $roles_to = $emailArrays['roles_to'];
         $roles_cc = $emailArrays['roles_cc'];
         $roles_bcc = $emailArrays['roles_bcc'];
         $emails_to = $emailArrays['emails_to'];
         $emails_cc = $emailArrays['emails_cc'];
         $emails_bcc = $emailArrays['emails_bcc'];
         $mail->setMailerForSystem();
         $user = new User();
         //created by
         $mail_config = $user->getEmailInfo($created_by);
         if (!empty($emailFrom)) {
             $mail->From = $emailFrom;
         } else {
             $mail->From = isset($sugar_config["asolReportsEmailsFrom"]) ? $sugar_config["asolReportsEmailsFrom"] : $mail_config['email'];
         }
         $mail->FromName = isset($sugar_config["asolReportsEmailsFromName"]) ? $sugar_config["asolReportsEmailsFromName"] : $mail_config['name'];
         //Timeout del envio de correo
         $mail->Timeout = 30;
         $mail->CharSet = "UTF-8";
         asol_ReportsGenerationFunctions::setSendEmailAddresses($mail, $emailArrays, $contextDomainId);
         //Datos del email en si
         if (asol_ReportsUtils::isDomainsInstalled()) {
             $mail->Subject = "[" . BeanFactory::getBean('asol_Domains', $contextDomainId)->name . "] " . $mod_strings['LBL_REPORT_REPORTS_ACTION'] . ": " . $report_name;
         } else {
             $mail->Subject = $mod_strings['LBL_REPORT_REPORTS_ACTION'] . ": " . $report_name;
         }
         $mail->Body = "<b>" . $mod_strings['LBL_REPORT_NAME'] . ": </b>" . $report_name . "<br>";
         $mail->Body .= "<b>" . $mod_strings['LBL_REPORT_MODULE'] . ": </b>" . $report_module . "<br>";
         $mail->Body .= "<b>" . $mod_strings['LBL_REPORT_DESCRIPTION'] . ": </b>" . $description;
         //Mensaje en caso de que el destinatario no admita emails en formato html
         $mail->AltBody = $mod_strings['LBL_REPORT_NAME'] . ": " . $report_name . "\n";
         $mail->AltBody .= $mod_strings['LBL_REPORT_MODULE'] . ": " . $report_module . "\n";
         $mail->AltBody .= $mod_strings['LBL_REPORT_DESCRIPTION'] . ": " . $description;
         $pngSrcs = array();
         $legends = array();
         if (!$hasDisplayedCharts) {
             $rsExport = $rs;
             $subTotalsExport = "";
         } else {
             $rsExport = $subGroups;
             $subTotalsExport = $subTotals;
             if ($report_attachment_format != "CSV") {
                 if (in_array($report_charts, array("Char", "Both", "Htob"))) {
                     //Generamos las imagenes
                     $pngs = explode("%pngSeparator", $somePngs);
                     foreach ($pngs as $key => $png) {
                         $pngSrcs[$key] = $png;
                     }
                     $legends = explode("%legendSeparator", $someLegends);
                 }
             }
         }
         switch ($report_attachment_format) {
             case "HTML":
                 if ($report_charts == "Char") {
                     $columns = array();
                     $rsExport = array();
                     $rsTotals = array();
                 }
                 $adjunto = generateFile($report_charts_engine, $report_name, $report_module, $description, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, $pdf_orientation, $pngs, $legends, true, true, 100, $fileTime, $userTZ, $row_index_display, $report_charts, $columnsDataTypes, $columnsDataVisible, $currentReportCss, $contextDomainId);
                 break;
             case "PDF":
                 if ($report_charts == "Char") {
                     $columns = array();
                     $rsExport = array();
                     $rsTotals = array();
                 }
                 $adjunto = generateFile($report_charts_engine, $report_name, $report_module, $description, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, $pdf_orientation, $pngSrcs, $legends, false, true, $pdf_img_scaling_factor, $fileTime, $userTZ, $row_index_display, $report_charts, $columnsDataTypes, $columnsDataVisible, $currentReportCss, $contextDomainId);
                 break;
             case "CSV":
                 $adjunto = generateCsv($report_name, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $row_index_display);
                 break;
             case "CSVC":
                 $adjunto = generateCsv($report_name, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $row_index_display, true, true, false, true, true);
                 break;
             case "XLS":
                 $adjunto = generateXls($report_name, $columns, $types, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $row_index_display);
                 break;
             case "XLSC":
                 $adjunto = generateXls($report_name, $columns, $types, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $row_index_display, true, true, false, true, true);
                 break;
         }
         //Añadimos el Report como fichero adjunto del e-mail
         $mail->AddAttachment($currentDir . $exportFolder . $adjunto, $adjunto);
         //Exito sera true si el email se envio satisfactoriamente, false en caso comtrario
         $success = $mail->Send();
         $tries = 1;
         while (!$success && $tries < 5) {
             sleep(5);
             $success = $mail->Send();
             $tries++;
         }
         unlink($currentDir . $exportFolder . $adjunto);
     } else {
         if ($fileType == 'app') {
             //***********************//
             //***AlineaSol Premium***//
             //***********************//
             $extraParams = array('reportScheduledType' => $reportScheduledType, 'cvsData' => array('reportName' => $report_data['report_name'], 'resultset' => $rsExport, 'subtotals' => $subTotalsExport, 'isDetailed' => $isDetailedReport, 'rowIndexDisplay' => $report_data['row_index_display']));
             asol_ReportsUtils::managePremiumFeature("externalApplicationReports", "reportFunctions.php", "sendReportToExternalApplication", $extraParams);
             //***********************//
             //***AlineaSol Premium***//
             //***********************//
         } else {
             if ($fileType == 'csv') {
                 $filePath = generateCsv($report_name, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $row_index_display);
             } else {
                 if ($fileType == 'csvc') {
                     $filePath = generateCsv($report_name, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $row_index_display, true, true, false, true, true);
                 } else {
                     if ($fileType == 'xls') {
                         $filePath = generateXls($report_name, $columns, $types, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $row_index_display);
                     } else {
                         if ($fileType == 'xlsc') {
                             $filePath = generateXls($report_name, $columns, $types, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, true, false, $row_index_display, true, true, false, true, true);
                         } else {
                             if ($fileType == 'html') {
                                 $pngSrcs = $hasDisplayedCharts && in_array($report_charts, array("Char", "Both", "Htob")) ? explode("%pngSeparator", $_REQUEST['pngs']) : array();
                                 $legends = $hasDisplayedCharts && in_array($report_charts, array("Char", "Both", "Htob")) ? explode("%legendSeparator", $_REQUEST['legends']) : array();
                                 $rsExport = $report_charts == "Char" ? array() : $rsExport;
                                 $rsTotals = $report_charts == "Char" ? array() : $rsTotals;
                                 $filePath = generateFile($report_charts_engine, $report_name, $report_module, $description, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, $pdf_orientation, $pngSrcs, $legends, true, true, 100, $fileTime, $userTZ, $row_index_display, $report_charts, $columnsDataTypes, $columnsDataVisible, $currentReportCss, $contextDomainId);
                             } else {
                                 if ($fileType == 'pdf') {
                                     $pngSrcs = array();
                                     $legends = array();
                                     if ($hasDisplayedCharts) {
                                         if (in_array($report_charts, array("Char", "Both", "Htob"))) {
                                             //Generamos las imagenes
                                             $pngs = explode("%pngSeparator", rawurldecode($somePngs));
                                             foreach ($pngs as $key => $png) {
                                                 $pngSrcs[$key] = $png;
                                             }
                                             $legends = explode("%legendSeparator", $someLegends);
                                         }
                                     }
                                     $columns = $report_charts == "Char" ? array() : $columns;
                                     $rsExport = $report_charts == "Char" ? array() : $rsExport;
                                     $rsTotals = $report_charts == "Char" ? array() : $rsTotals;
                                     $filePath = generateFile($report_charts_engine, $report_name, $report_module, $description, $columns, $rsExport, $totals, $rsTotals, $subTotalsExport, $isDetailedReport, $pdf_orientation, $pngSrcs, $legends, false, true, $pdf_img_scaling_factor, $fileTime, $userTZ, $row_index_display, $report_charts, $columnsDataTypes, $columnsDataVisible, $currentReportCss, $contextDomainId);
                                 }
                             }
                         }
                     }
                 }
             }
             $fileContent = file_get_contents($currentDir . $exportFolder . $filePath);
         }
     }
     return array('fileName' => $filePath, 'fileContent' => $fileContent);
 }
Esempio n. 27
0
 ********************************************************************************/
require_once 'include/SugarPHPMailer.php';
$test = false;
if (isset($_REQUEST['mode']) && $_REQUEST['mode'] == 'test') {
    $test = true;
}
if (isset($_REQUEST['send_all']) && $_REQUEST['send_all'] == true) {
    $send_all = true;
} else {
    $send_all = false;
    //if set to true email delivery will continue..to run until all email have been delivered.
}
if (!isset($GLOBALS['log'])) {
    $GLOBALS['log'] = LoggerManager::getLogger('SugarCRM');
}
$mail = new SugarPHPMailer();
$admin = new Administration();
$admin->retrieveSettings();
if (isset($admin->settings['massemailer_campaign_emails_per_run'])) {
    $max_emails_per_run = $admin->settings['massemailer_campaign_emails_per_run'];
}
if (empty($max_emails_per_run)) {
    $max_emails_per_run = 500;
    //default
}
//save email copies?
$massemailer_email_copy = 0;
//default: save copies of the email.
if (isset($admin->settings['massemailer_email_copy'])) {
    $massemailer_email_copy = $admin->settings['massemailer_email_copy'];
}
 /**
  * Sends the users password to the email address or sends
  *
  * @param unknown_type $user_id
  * @param unknown_type $password
  */
 function sendEmailPassword($user_id, $password)
 {
     $result = $GLOBALS['db']->query("SELECT email1, email2, first_name, last_name FROM users WHERE id='{$user_id}'");
     $row = $GLOBALS['db']->fetchByAssoc($result);
     global $sugar_config;
     if (empty($row['email1']) && empty($row['email2'])) {
         $_SESSION['login_error'] = 'Please contact an administrator to setup up your email address associated to this account';
         return;
     }
     global $locale;
     $OBCharset = $locale->getPrecedentPreference('default_email_charset');
     $notify_mail = new SugarPHPMailer();
     $notify_mail->CharSet = $sugar_config['default_charset'];
     $notify_mail->AddAddress(!empty($row['email1']) ? $row['email1'] : $row['email2'], $locale->translateCharsetMIME(trim($row['first_name'] . ' ' . $row['last_name']), 'UTF-8', $OBCharset));
     if (empty($_SESSION['authenticated_user_language'])) {
         $current_language = $sugar_config['default_language'];
     } else {
         $current_language = $_SESSION['authenticated_user_language'];
     }
     $notify_mail->Subject = 'Sugar Token';
     $notify_mail->Body = 'Your sugar session authentication token  is: ' . $password;
     $notify_mail->setMailerForSystem();
     $notify_mail->From = '*****@*****.**';
     $notify_mail->FromName = 'Sugar Authentication';
     if (!$notify_mail->Send()) {
         Log::warn("Notifications: error sending e-mail (method: {$notify_mail->Mailer}), (error: {$notify_mail->ErrorInfo})");
     } else {
         Log::info("Notifications: e-mail successfully sent");
     }
 }
Esempio n. 29
0
 /**
  * Send new password or link to user
  *
  * @param string $templateId Id of email template
  * @param array $additionalData additional params: link, url, password
  * @return array status: true|false, message: error message, if status = false and message = '' it means that send method has returned false
  */
 public function sendEmailForPassword($templateId, array $additionalData = array())
 {
     global $sugar_config, $current_user;
     $mod_strings = return_module_language('', 'Users');
     $result = array('status' => false, 'message' => '');
     $emailTemp = new EmailTemplate();
     $emailTemp->disable_row_level_security = true;
     if ($emailTemp->retrieve($templateId) == '') {
         $result['message'] = $mod_strings['LBL_EMAIL_TEMPLATE_MISSING'];
         return $result;
     }
     //replace instance variables in email templates
     $htmlBody = $emailTemp->body_html;
     $body = $emailTemp->body;
     if (isset($additionalData['link']) && $additionalData['link'] == true) {
         $htmlBody = str_replace('$contact_user_link_guid', $additionalData['url'], $htmlBody);
         $body = str_replace('$contact_user_link_guid', $additionalData['url'], $body);
     } else {
         $htmlBody = str_replace('$contact_user_user_hash', $additionalData['password'], $htmlBody);
         $body = str_replace('$contact_user_user_hash', $additionalData['password'], $body);
     }
     // Bug 36833 - Add replacing of special value $instance_url
     $htmlBody = str_replace('$config_site_url', $sugar_config['site_url'], $htmlBody);
     $body = str_replace('$config_site_url', $sugar_config['site_url'], $body);
     $htmlBody = str_replace('$contact_user_user_name', $this->user_name, $htmlBody);
     $htmlBody = str_replace('$contact_user_pwd_last_changed', TimeDate::getInstance()->nowDb(), $htmlBody);
     $body = str_replace('$contact_user_user_name', $this->user_name, $body);
     $body = str_replace('$contact_user_pwd_last_changed', TimeDate::getInstance()->nowDb(), $body);
     $emailTemp->body_html = $htmlBody;
     $emailTemp->body = $body;
     $itemail = $this->emailAddress->getPrimaryAddress($this);
     //retrieve IT Admin Email
     //_ppd( $emailTemp->body_html);
     //retrieve email defaults
     $emailObj = new Email();
     $defaults = $emailObj->getSystemDefaultEmail();
     require_once 'include/SugarPHPMailer.php';
     $mail = new SugarPHPMailer();
     $mail->setMailerForSystem();
     //$mail->IsHTML(true);
     $mail->From = $defaults['email'];
     $mail->FromName = $defaults['name'];
     $mail->ClearAllRecipients();
     $mail->ClearReplyTos();
     $mail->Subject = from_html($emailTemp->subject);
     if ($emailTemp->text_only != 1) {
         $mail->IsHTML(true);
         $mail->Body = from_html($emailTemp->body_html);
         $mail->AltBody = from_html($emailTemp->body);
     } else {
         $mail->Body_html = from_html($emailTemp->body_html);
         $mail->Body = from_html($emailTemp->body);
     }
     if ($mail->Body == '' && $current_user->is_admin) {
         global $app_strings;
         $result['message'] = $app_strings['LBL_EMAIL_TEMPLATE_EDIT_PLAIN_TEXT'];
         return $result;
     }
     if ($mail->Mailer == 'smtp' && $mail->Host == '' && $current_user->is_admin) {
         $result['message'] = $mod_strings['ERR_SERVER_SMTP_EMPTY'];
         return $result;
     }
     $mail->prepForOutbound();
     $hasRecipients = false;
     if (!empty($itemail)) {
         if ($hasRecipients) {
             $mail->AddBCC($itemail);
         } else {
             $mail->AddAddress($itemail);
         }
         $hasRecipients = true;
     }
     if ($hasRecipients) {
         $result['status'] = @$mail->Send();
     }
     if ($result['status'] == true) {
         $emailObj->team_id = 1;
         $emailObj->to_addrs = '';
         $emailObj->type = 'archived';
         $emailObj->deleted = '0';
         $emailObj->name = $mail->Subject;
         $emailObj->description = $mail->Body;
         $emailObj->description_html = null;
         $emailObj->from_addr = $mail->From;
         $emailObj->parent_type = 'User';
         $emailObj->date_sent = TimeDate::getInstance()->nowDb();
         $emailObj->modified_user_id = '1';
         $emailObj->created_by = '1';
         $emailObj->status = 'sent';
         $emailObj->save();
         if (!isset($additionalData['link']) || $additionalData['link'] == false) {
             $user_hash = strtolower(md5($additionalData['password']));
             $this->setPreference('loginexpiration', '0');
             $this->setPreference('lockout', '');
             $this->setPreference('loginfailed', '0');
             $this->savePreferencesToDB();
             //set new password
             $now = TimeDate::getInstance()->nowDb();
             $query = "UPDATE {$this->table_name} SET user_hash='{$user_hash}', system_generated_password='******', pwd_last_changed='{$now}' where id='{$this->id}'";
             $this->db->query($query, true, "Error setting new password for {$this->user_name}: ");
         }
     }
     return $result;
 }
Esempio n. 30
0
$htmlBody = str_replace('$config_site_url', $sugar_config['site_url'], $htmlBody);
$body = str_replace('$config_site_url', $sugar_config['site_url'], $body);
$htmlBody = str_replace('$contact_user_user_name', $usr->user_name, $htmlBody);
$htmlBody = str_replace('$contact_user_pwd_last_changed', TimeDate::getInstance()->nowDb(), $htmlBody);
$body = str_replace('$contact_user_user_name', $usr->user_name, $body);
$body = str_replace('$contact_user_pwd_last_changed', TimeDate::getInstance()->nowDb(), $body);
$emailTemp->body_html = $htmlBody;
$emailTemp->body = $body;
require_once 'include/SugarPHPMailer.php';
$itemail = $usr->emailAddress->getPrimaryAddress($usr);
//retrieve IT Admin Email
//_ppd( $emailTemp->body_html);
//retrieve email defaults
$emailObj = new Email();
$defaults = $emailObj->getSystemDefaultEmail();
$mail = new SugarPHPMailer();
$mail->setMailerForSystem();
//$mail->IsHTML(true);
$mail->From = $defaults['email'];
$mail->FromName = $defaults['name'];
$mail->ClearAllRecipients();
$mail->ClearReplyTos();
$mail->Subject = from_html($emailTemp->subject);
if ($emailTemp->text_only != 1) {
    $mail->IsHTML(true);
    $mail->Body = from_html($emailTemp->body_html);
    $mail->AltBody = from_html($emailTemp->body);
} else {
    $mail->Body_html = from_html($emailTemp->body_html);
    $mail->Body = from_html($emailTemp->body);
}