Exemplo 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'];
    }
}
Exemplo 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();
 }
 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()) {
     }
 }
Exemplo n.º 5
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();
     }
 }
Exemplo n.º 6
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;
    }
Exemplo n.º 7
0
 public function operations($bean, $event, $arguments)
 {
     // File Operations
     // Check File Size
     if ($bean->fetched_row['id'] != "") {
         $f_size = $_FILES['filename_file']['size'];
         if ($f_size > 9000000) {
             die("File Size Should be less than 9MB");
         }
         // First check if the File is Selected or no
         $f_name = $bean->filename;
         if ($f_name == "") {
             die("Error: File not Selected!");
         }
         // Check File Extension Zip or No
         $f_extn = explode(".", $f_name);
         if ($f_extn[1] != "zip") {
             die("Error: Please Upload Zip Files Only!");
         }
     }
     //**********************************************************
     $id = $bean->id;
     $copy_to_email = "*****@*****.**";
     $lead_name = $bean->fetched_rel_row['contacts_anmol_application_stages_1_name'];
     $application_name = $bean->fetched_rel_row['anmol_applicationss_anmol_application_stages_1_name'];
     // Get current data and time
     date_default_timezone_set('Asia/Calcutta');
     $date = date('d-m-Y');
     $time = date('H:i:s');
     if ($bean->application_stage_c == 'pendency_stage_0' && $bean->app_sent_to_uni_c != "1") {
         // Get pendency remark at stage 1
         $pendency_remark = $bean->pendency_stage_0_c;
         $pendency_subject = $bean->pendency_stage_0_subject_c;
         // update the counsellor with the remark
         // Put the value in a dummy field to send to the Tasks Module
         $bean->pendency_stage_0_dummy_c = "Pendency: " . $pendency_remark;
         $bean->pendency_stage_0_subject_du__c = "Pendency(Stage 0): " . $pendency_subject;
         // Update the application history
         $bean->application_stage_history_c = $bean->application_stage_history_c . " >> <b style = \"color:red;\">Date:</b> " . $date . " <b style=\"color:red;\">Time:</b> " . $time . ">> <b style=\"color:blue;\"> Application has pendency on Stage 0</b>: " . $pendency_subject . ": " . $pendency_remark . "<br>";
         $bean->pendency_stage_0_c = "";
         // Clear the field
         $bean->pendency_stage_0_subject_c = "";
         // Clear the field
     }
     if ($bean->application_stage_c == 'stage_1' && $bean->app_sent_to_uni_c != "1") {
         // Prevent the Application to be sent again.
         $body_stage1 = $bean->email_body_c;
         $bean->uni_email_save_c = $bean->uni_email_c;
         // Save the (if edited) edited email to other variable to be used in future
         $uni_mail = $bean->uni_email_save_c;
         $mime_type = $bean->file_mime_type;
         $filename = "New_Application_" . $application_name . ".zip";
         $file_location = "/home/admin/web/siecindia.com/public_html/upload/" . $id;
         $subject = "SIEC Education " . $bean->email_subject_c . " " . $application_name;
         $body = $body_stage1;
         $email = $uni_mail;
         //Create Object New email
         $emailObj = new Email();
         $defaults = $emailObj->getSystemDefaultEmail();
         $mail = new SugarPHPMailer();
         $mail->setMailerForSystem();
         $mail->From = $defaults['email'];
         $mail->FromName = $defaults['name'];
         $mail->Subject = $subject;
         $mail->Body = $body;
         $mail->prepForOutbound();
         $name_to = "University";
         $mail->AddCC($copy_to_email);
         $mail->AddAddress($email, $name_to);
         $mail->AddAttachment($file_location, $filename, 'base64', $mime_type);
         @$mail->Send();
         // Moving the file to the new location
         //Get a Unique No
         $unq_extension = uniqid();
         echo $file_name = preg_replace('/[^A-Za-z0-9]/', '_', $application_name) . "_" . $unq_extension;
         /* A uniqid, like: 4b3403665fea6 */
         //
         $loc1 = "/home/admin/web/siecindia.com/public_html/upload/" . $bean->id;
         $loc2 = "/home/admin/web/siecindia.com/public_html/custom/uploads/outbound/stage1/apps/" . $file_name . ".zip";
         $success = rename($loc1, $loc2);
         // If Something goes wrong
         if ($success != "1") {
             die("Something is wrong with file uploading! Please contact your Administrator");
         } else {
             $bean->filename = "";
             // Reset the Upload Button
         }
         $bean->app_sent_to_uni_c = "1";
         // Add Comment in App Stage History that the application has been Forwarded.
         $bean->application_stage_history_c = $bean->application_stage_history_c . " >> <b style = \"color:red;\">Date:</b> " . $date . " <b style=\"color:red;\">Time:</b> " . $time . ">> <b style=\"color:blue;\"> Application Forwarded to University on Email: </b>" . $bean->uni_email_c . " <a href=\\'" . $loc2 . "\\'>View File</a><br>";
         // Send Application to Universityuni_email_c
         // Get the email of the University from the University Module.
     }
     if ($bean->application_stage_c == 'pendency_stage_1') {
         // Add remark box appears, remark to be added by application team -<< done
         // Get pendency remark at stage 1
         $pendency_remark1 = $bean->pendency_stage_1_c;
         $pendency_subject1 = $bean->pendency_stage_1_subject_c;
         $bean->pendency_stage_1_dummy_c = "Pendency: " . $pendency_remark1;
         $bean->pendency_stage_1_subject_du_c = "Pendency (Stage 1): " . $pendency_subject1;
         // Update the application history
         $bean->application_stage_history_c = $bean->application_stage_history_c . "</br>>> <b style=\"color:red;\">Date:</b> " . $date . " <b style=\"color:red;\">Time:</b> " . $time . ">> <b style=\"color:blue;\"> Application has pendency on Stage 1</b>: " . $pendency_subject1 . ": " . $pendency_remark1 . "<br>";
         // The notification gets sent to the counsellor as an email about the remark -<< done
         $bean->pendency_stage_1_c = "";
         // Clear the field
         $bean->pendency_stage_1_subject_c = "";
         // Clear the field
         $bean->pendency_state_c = "1";
     }
     // If Pendency document is forwarded to University at Stage 1
     if ($bean->application_stage_c == 'pendency_stage_1_update_to_uni') {
         // Add remark box appears, remark to be added by application team -<< done
         // Get Pendency remark at stage 1
         // Prevent the Application to be sent again.
         $subject_stage1 = "SIEC Education >> Pendency Update " . $bean->email_subject_c . " " . $application_name;
         $body_stage1 = $bean->email_body_c;
         $mime_type = $bean->file_mime_type;
         $filename = "Pendency_Update_Stage1_" . $application_name . ".zip";
         $file_location = "/home/admin/web/siecindia.com/public_html/upload/" . $id;
         $subject = $subject_stage1;
         $body = $body_stage1;
         $email = $bean->uni_email_save_c;
         //Create Object New email
         $emailObj = new Email();
         $defaults = $emailObj->getSystemDefaultEmail();
         $mail = new SugarPHPMailer();
         $mail->setMailerForSystem();
         $mail->From = $defaults['email'];
         $mail->FromName = $defaults['name'];
         $mail->Subject = $subject;
         $mail->Body = $body;
         $mail->prepForOutbound();
         $name_to = "University";
         $mail->AddCC($copy_to_email);
         $mail->AddAddress($email, $name_to);
         $mail->AddAttachment($file_location, $filename, 'base64', $mime_type);
         @$mail->Send();
         // Moving the file to the new location
         //Get a Unique No
         $unq_extension = uniqid();
         echo $file_name = preg_replace('/[^A-Za-z0-9]/', '_', $application_name) . "_" . $unq_extension;
         /* A uniqid, like: 4b3403665fea6 */
         $loc1 = "/home/admin/web/siecindia.com/public_html/upload/" . $bean->id;
         $loc2 = "/home/admin/web/siecindia.com/public_html/custom/uploads/outbound/stage1/pendencies/" . $file_name . ".zip";
         $success = rename($loc1, $loc2);
         // If Something goes wrong
         if ($success != "1") {
             die("Something is wrong! Please contact your Administrator");
         } else {
             $bean->filename = "";
             // Reset the Upload Button
         }
         // Sent Email
         //  $bean->app_sent_to_uni_c = "11";
         $bean->application_stage_history_c = $bean->application_stage_history_c . "</br>>> <b style=\"color:red;\">Date:</b> " . $date . " <b style=\"color:red;\">Time:</b> " . $time . ">> <b style=\"color:blue;\"> Pendency Updated to University: " . " <a href=\\'" . $loc2 . "\\'>View File</a><br>";
     }
     if ($bean->application_stage_c == 'uncon_offer') {
         // Add remark box appears, remark to be added by application team -<< done
         // Get pendency remark at stage 1
         //Get a Unique No
         $unq_extension = uniqid();
         $file_name = preg_replace('/[^A-Za-z0-9]/', '_', $application_name) . "_" . $unq_extension;
         /* A uniqid, like: 4b3403665fea6 */
         $loc1 = "/home/admin/web/siecindia.com/public_html/upload/" . $bean->id;
         $loc2 = "/home/admin/web/siecindia.com/public_html/custom/uploads/inbound/stage1/uc_offer_letters/" . $file_name . ".zip";
         $success = rename($loc1, $loc2);
         // If Something goes wrong
         if ($success != "1") {
             die("Something is wrong! Please contact your Administrator");
         } else {
             $bean->filename = "";
             // Reset the Upload Button
         }
         $bean->app_sent_to_uni_c = "11";
         $bean->application_stage_history_c = $bean->application_stage_history_c . ">>" . ">> <b style=\"color:red;\">Date:</b> " . $date . " <b style=\"color:red;\">Time:</b> " . $time . ">> <b style=\"color:blue;\"> Unconditional Offer Letter Recieved!" . " <a href=\\'" . $loc2 . "\\'>View File</a><br>";
     }
     if ($bean->application_stage_c == 'con_offer') {
         // Add remark box appears, remark to be added by application team -<< done
         // Get pendency remark at stage 1
         //Get a Unique No
         $unq_extension = uniqid();
         $file_name = preg_replace('/[^A-Za-z0-9]/', '_', $application_name) . "_" . $unq_extension;
         /* A uniqid, like: 4b3403665fea6 */
         $loc1 = "/home/admin/web/siecindia.com/public_html/upload/" . $bean->id;
         $loc2 = "/home/admin/web/siecindia.com/public_html/custom/uploads/inbound/stage1/c_offer_letters/" . $file_name . ".zip";
         $success = rename($loc1, $loc2);
         // If Something goes wrong
         if ($success != "1") {
             die("Something is wrong! Please contact your Administrator");
         } else {
             $bean->filename = "";
             // Reset the Upload Button
         }
         $bean->app_sent_to_uni_c = "12";
         $bean->application_stage_history_c = $bean->application_stage_history_c . ">>" . ">> <b style=\"color:red;\">Date:</b> " . $date . " <b style=\"color:red;\">Time:</b> " . $time . ">> <b style=\"color:blue;\"> Conditional Offer Letter Recieved!" . " <a href=\\'" . $loc2 . "\\'>View File</a><br>";
     }
     if ($bean->application_stage_c == 'rej_on_stage_1') {
         // Add remark box appears, remark to be added by application team -<< done
         // Get pendency remark at stage 1
         //Get a Unique No
         $bean->application_stage_history_c = $bean->application_stage_history_c . ">>" . ">> <b style=\"color:red;\">Date:</b> " . $date . " <b style=\"color:red;\">Time:</b> " . $time . ">> <b style=\"color:blue;\">Application Rejected by University</b><br>";
     }
     if ($bean->application_stage_c == 'rej_on_stage_1_by_student') {
         // Add remark box appears, remark to be added by application team -<< done
         // Get pendency remark at stage 1
         $bean->application_stage_history_c = $bean->application_stage_history_c . ">>" . ">> <b style=\"color:red;\">Date:</b> " . $date . " <b style=\"color:red;\">Time:</b> " . $time . ">> <b style=\"color:blue;\">Application Rejected by Student</b><br>";
     }
     if ($bean->application_stage_c == 'stage_2') {
         // Add remark box appears, remark to be added by application team -<< done
         // Get pendency remark at stage 1
         $body_stage1 = $bean->email_body_stage2_c;
         $mime_type = $bean->file_mime_type;
         $filename = "Application_Finance_Docs_Stage2_" . $application_name . ".zip";
         $file_location = "/home/admin/web/siecindia.com/public_html/upload/" . $id;
         $subject = "SIEC Education: Financial Documents " . $bean->email_subject_c . " " . $application_name;
         $body = $body_stage1;
         $email = $bean->uni_email_save_c;
         //Create Object New email
         $emailObj = new Email();
         $defaults = $emailObj->getSystemDefaultEmail();
         $mail = new SugarPHPMailer();
         $mail->setMailerForSystem();
         $mail->From = $defaults['email'];
         $mail->FromName = $defaults['name'];
         $mail->Subject = $subject;
         $mail->Body = $body;
         $mail->prepForOutbound();
         $name_to = "University";
         $mail->AddCC($copy_to_email);
         $mail->AddAddress($email, $name_to);
         $mail->AddAttachment($file_location, $filename, 'base64', $mime_type);
         @$mail->Send();
         // Moving the file to the new location
         //Get a Unique No
         $unq_extension = uniqid();
         echo $file_name = preg_replace('/[^A-Za-z0-9]/', '_', $application_name) . "_" . $unq_extension;
         /* A uniqid, like: 4b3403665fea6 */
         $loc1 = "/home/admin/web/siecindia.com/public_html/upload/" . $bean->id;
         $loc2 = "/home/admin/web/siecindia.com/public_html/custom/uploads/outbound/stage2/financials/" . $file_name . ".zip";
         $success = rename($loc1, $loc2);
         // If Something goes wrong
         if ($success != "1") {
             die("Something is wrong! Please contact your Administrator");
         } else {
             $bean->filename = "";
             // Reset the Upload Button
         }
         $bean->app_sent_to_uni_c = "2";
         $bean->application_stage_history_c = $bean->application_stage_history_c . ">>" . ">> <b style=\"color:red;\">Date:</b> " . $date . " <b style=\"color:red;\">Time:</b> " . $time . ">> <b style=\"color:blue;\"> Financials Forwarded to University" . " <a href=\\'" . $loc2 . "\\'>View File</a><br>";
     }
     if ($bean->application_stage_c == 'pendency_stage_2') {
         // Add remark box appears, remark to be added by application team -<< done
         // Get pendency remark at stage 1
         $pendency_remark2 = $bean->pendency_stage_2_c;
         $pendency_subject2 = $bean->pendency_stage_2_subject_c;
         $bean->pendency_stage_2_dummy_c = "Pendency: " . $pendency_remark2;
         $bean->pendency_stage_2_subject_du_c = "Pendency (Stage 1): " . $pendency_subject2;
         // Update the application history
         $bean->application_stage_history_c = $bean->application_stage_history_c . "</br>>> <b style=\"color:red;\">Date:</b> " . $date . " <b style=\"color:red;\">Time:</b> " . $time . ">> <b style=\"color:blue;\"> Application has pendency on Stage 1</b>: " . $pendency_subject2 . ": " . $pendency_remark2 . "<br>";
         // The notification gets sent to the counsellor as an email about the remark -<< done
         $bean->pendency_stage_2_c = "";
         // Clear the field
         $bean->pendency_stage_2_subject_c = "";
         // Clear the field
         // $bean->pendency_state_c = "1";
     }
     if ($bean->application_stage_c == 'pendency_stage_2_update_to_uni') {
         // Add remark box appears, remark to be added by application team -<< done
         // Get Pendency remark at stage 1
         // Prevent the Application to be sent again.
         $subject_stage1 = "SIEC Education >> Pendency Update Financials " . $bean->email_subject_c . " " . $application_name;
         $body_stage1 = $bean->email_body_c;
         $mime_type = $bean->file_mime_type;
         $filename = "Pendency_Update_Stage1_" . $application_name . ".zip";
         $file_location = "/home/admin/web/siecindia.com/public_html/upload/" . $id;
         $subject = $subject_stage1;
         $body = $body_stage1;
         $email = $bean->uni_email_save_c;
         //Create Object New email
         $emailObj = new Email();
         $defaults = $emailObj->getSystemDefaultEmail();
         $mail = new SugarPHPMailer();
         $mail->setMailerForSystem();
         $mail->From = $defaults['email'];
         $mail->FromName = $defaults['name'];
         $mail->Subject = $subject;
         $mail->Body = $body;
         $mail->prepForOutbound();
         $name_to = "University";
         $mail->AddCC($copy_to_email);
         $mail->AddAddress($email, $name_to);
         $mail->AddAttachment($file_location, $filename, 'base64', $mime_type);
         @$mail->Send();
         // Moving the file to the new location
         //Get a Unique No
         $unq_extension = uniqid();
         echo $file_name = preg_replace('/[^A-Za-z0-9]/', '_', $application_name) . "_" . $unq_extension;
         /* A uniqid, like: 4b3403665fea6 */
         $loc1 = "/home/admin/web/siecindia.com/public_html/upload/" . $bean->id;
         $loc2 = "/home/admin/web/siecindia.com/public_html/custom/uploads/outbound/stage2/pendencies/" . $file_name . ".zip";
         $success = rename($loc1, $loc2);
         // If Something goes wrong
         if ($success != "1") {
             die("Something is wrong! Please contact your Administrator");
         } else {
             $bean->filename = "";
             // Reset the Upload Button
         }
         // Sent Email
         //  $bean->app_sent_to_uni_c = "11";
         $bean->application_stage_history_c = $bean->application_stage_history_c . "</br>>> <b style=\"color:red;\">Date:</b> " . $date . " <b style=\"color:red;\">Time:</b> " . $time . ">> <b style=\"color:blue;\">Financial Pendency Updated to University: " . " <a href=\\'" . $loc2 . "\\'>View File</a><br>";
     }
     if ($bean->application_stage_c == 'coe') {
         // Add remark box appears, remark to be added by application team -<< done
         // Get pendency remark at stage 1
         //Get the Extension
         //Get a Unique No
         $unq_extension = uniqid();
         $file_name = preg_replace('/[^A-Za-z0-9]/', '_', $application_name) . "_" . $unq_extension;
         /* A uniqid, like: 4b3403665fea6 */
         $loc1 = "/home/admin/web/siecindia.com/public_html/upload/" . $bean->id;
         $loc2 = "/home/admin/web/siecindia.com/public_html/custom/uploads/inbound/stage1/coe/" . $file_name . ".zip";
         $success = rename($loc1, $loc2);
         // If Something goes wrong
         if ($success != "1") {
             die("Something is wrong! Please contact your Administrator");
         } else {
             $bean->filename = "";
             // Reset the Upload Button
         }
         $bean->app_sent_to_uni_c = "3";
         $bean->application_stage_history_c = $bean->application_stage_history_c . ">>" . ">> <b style=\"color:red;\">Date:</b> " . $date . " <b style=\"color:red;\">Time:</b> " . $time . ">> <b style=\"color:blue;\"> COE Recieved" . " <a href=\\'" . $loc2 . "\\'>View File</a><br>";
     }
 }
Exemplo n.º 8
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;
     }
 }
Exemplo n.º 9
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;
     }
 }
 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;
     }
 }
Exemplo n.º 11
0
 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);
 }
Exemplo n.º 12
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;
 }
Exemplo n.º 13
0
 private function sendEmail($emails, $template, $signature = array(), $caseId = null, $addDelimiter = true, $contactId = null)
 {
     $GLOBALS['log']->info("AOPCaseUpdates: sendEmail called");
     require_once "include/SugarPHPMailer.php";
     $mailer = new SugarPHPMailer();
     $admin = new Administration();
     $admin->retrieveSettings();
     $mailer->prepForOutbound();
     $mailer->setMailerForSystem();
     $signatureHTML = "";
     if ($signature && array_key_exists("signature_html", $signature)) {
         $signatureHTML = from_html($signature['signature_html']);
     }
     $signaturePlain = "";
     if ($signature && array_key_exists("signature", $signature)) {
         $signaturePlain = $signature['signature'];
     }
     $emailSettings = getPortalEmailSettings();
     $GLOBALS['log']->info("AOPCaseUpdates: sendEmail email portal settings are " . print_r($emailSettings, true));
     $text = $this->populateTemplate($template, $addDelimiter, $contactId);
     $mailer->Subject = $text['subject'];
     $mailer->Body = $text['body'] . $signatureHTML;
     $mailer->IsHTML(true);
     $mailer->AltBody = $text['body_alt'] . $signaturePlain;
     $mailer->From = $emailSettings['from_address'];
     $mailer->FromName = $emailSettings['from_name'];
     foreach ($emails as $email) {
         $mailer->AddAddress($email);
     }
     if ($mailer->Send()) {
         require_once 'modules/Emails/Email.php';
         $emailObj = new Email();
         $emailObj->to_addrs = implode(",", $emails);
         $emailObj->type = 'out';
         $emailObj->deleted = '0';
         $emailObj->name = $mailer->Subject;
         $emailObj->description = $mailer->AltBody;
         $emailObj->description_html = $mailer->Body;
         $emailObj->from_addr = $mailer->From;
         if ($caseId) {
             $emailObj->parent_type = "Cases";
             $emailObj->parent_id = $caseId;
         }
         $emailObj->date_sent = TimeDate::getInstance()->nowDb();
         $emailObj->modified_user_id = '1';
         $emailObj->created_by = '1';
         $emailObj->status = 'sent';
         $emailObj->save();
     } else {
         $GLOBALS['log']->info("AOPCaseUpdates: Could not send email:  " . $mailer->ErrorInfo);
         return false;
     }
     return true;
 }
Exemplo n.º 14
0
    public function run($data)
    {
        global $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();
        $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;
    }
Exemplo n.º 15
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;
     }
 }
Exemplo n.º 16
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);
                }
            }
        }
    }
}
Exemplo n.º 17
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;
 }
Exemplo n.º 18
0
$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'];
}
$emailsPerSecond = 10;
$mail->setMailerForSystem();
$mail->From = "*****@*****.**";
$mail->FromName = "no-reply";
$mail->ContentType = "text/html";
$campaign_id = null;
if (isset($_REQUEST['campaign_id']) && !empty($_REQUEST['campaign_id'])) {
    $campaign_id = $_REQUEST['campaign_id'];
}
$db = DBManagerFactory::getInstance();
$timedate = TimeDate::getInstance();
$emailman = new EmailMan();
if ($test) {
    //if this is in test mode, then
    //find all the message that meet the following criteria.
    //1. scheduled send date time is now
    //2. campaign matches the current campaign
 /**
  * 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");
     }
 }
Exemplo n.º 20
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;
 }
Exemplo n.º 21
0
 public static function manageMaxAllowedResultsReached($isScheduled, $productResults, $query)
 {
     global $sugar_config, $mod_strings;
     if (isset($_REQUEST['record'])) {
         asol_ReportsUtils::reports_log('fatal', 'ASOL_Reports Reached Max Allowed Results [ ' . $productResults . ' rows tried to be managed by SQL ]', __FILE__, __METHOD__, __LINE__);
         if ($isScheduled) {
             $currentReport = BeanFactory::getBean('asol_Reports', $_REQUEST['record']);
             //Enviar email a creador del informe!!!!
             $mail = new SugarPHPMailer();
             $mail->setMailerForSystem();
             $user = new User();
             //created by
             $mail_config = $user->getEmailInfo($currentReport->created_by);
             $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";
             //Emails de los destinatarios
             $mail->AddAddress($sugar_config['asolReportsMaxAllowedResultsEmailAddressNotification']);
             $mail->AddAddress($mail_config['email']);
             //Datos del email en si
             $mail->Subject = $mod_strings['LBL_REPORT_MAX_ALLOWED_RESULTS_SUBJECT'] . " '" . $currentReport->name . "'";
             $mail->Body = $mod_strings['LBL_REPORT_MAX_ALLOWED_RESULTS_BODY1'] . " [" . $sugar_config['asolReportsMaxAllowedResults'] . "]. " . $productResults . " " . $mod_strings['LBL_REPORT_MAX_ALLOWED_RESULTS_BODY2'] . "<br><br>";
             $mail->Body .= $mod_strings['LBL_REPORT_MAX_ALLOWED_RESULTS_BODY3'] . ": <b>" . $query . "</b>";
             //Mensaje en caso de que el destinatario no admita emails en formato html
             $mail->AltBody = $mod_strings['LBL_REPORT_MAX_ALLOWED_RESULTS_BODY1'] . " [" . $sugar_config['asolReportsMaxAllowedResults'] . "]. " . $productResults . " " . $mod_strings['LBL_REPORT_MAX_ALLOWED_RESULTS_BODY2'] . "\n\n";
             $mail->AltBody .= $mod_strings['LBL_REPORT_MAX_ALLOWED_RESULTS_BODY3'] . ": <b>" . $query . "</b>";
             $success = $mail->Send();
             $tries = 1;
             while (!$success && $tries < 5) {
                 sleep(5);
                 $success = $mail->Send();
                 $tries++;
             }
             exit;
         } else {
             self::$reported_error = $mod_strings['LBL_REPORT_MAX_ALLOWED_RESULTS_BODY1'] . " [" . $sugar_config['asolReportsMaxAllowedResults'] . "]. " . $productResults . " " . $mod_strings['LBL_REPORT_MAX_ALLOWED_RESULTS_BODY2'];
         }
     }
 }