Changeset 5604 for trunk/expressoMail1_2/inc/class.imap_functions.inc.php
- Timestamp:
- 03/02/12 03:48:47 (12 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/expressoMail1_2/inc/class.imap_functions.inc.php
r5548 r5604 2531 2531 } 2532 2532 2533 function send_mail($params) 2534 { 2535 require_once dirname(__FILE__) . '/../../services/class.servicelocator.php'; 2536 $mailService = ServiceLocator::getService('mail'); 2537 2538 include_once("class.db_functions.inc.php"); 2539 $db = new db_functions(); 2540 $fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : ""; 2541 $message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false; 2542 2543 ## 2544 # @AUTHOR Rodrigo Souza dos Santos 2545 # @DATE 2008/09/17$fileName 2546 # @BRIEF Checks if the user has permission to send an email with the email address used. 2547 ## 2548 if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) ) 2549 { 2550 $deny = true; 2551 foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val ) 2552 if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] ) 2553 $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']); 2554 2555 if ( $deny ) 2556 return "The server denied your request to send a mail, you cannot use this mail address."; 2557 } 2558 2559 $toaddress = $db->getAddrs(explode(',',$params['input_to']));//implode(',',); 2560 $ccaddress = $db->getAddrs(explode(',',$params['input_cc']));//implode(',',); 2561 $ccoaddress = $db->getAddrs(explode(',',$params['input_cco']));//implode(',',); 2562 2563 if($toaddress["False"] || $ccaddress["False"] || $ccoaddress["False"]){ 2564 return $this->parse_error("Invalid Mail:", ($toaddress["False"] ? $toaddress["False"] : ($ccaddress["False"] ? $ccaddress["False"] : $ccoaddress["False"]))); 2565 } 2566 2567 $toaddress = implode(',', $toaddress); 2568 $ccaddress = implode(',', $ccaddress); 2569 $ccoaddress = implode(',', $ccoaddress); 2570 2571 if($toaddress == "" && $ccaddress == "" && $ccoaddress == ""){ 2572 return $this->parse_error("Invalid Mail:", ($params['input_to'] ? $params['input_to'] :($params['input_cc'] ? $params['input_cc'] : $params['input_cco'])) ); 2573 } 2574 2575 $toaddress = preg_replace('/<\s+/', '<', $toaddress); 2576 $toaddress = preg_replace('/\s+>/', '>', $toaddress); 2577 2578 $ccaddress = preg_replace('/<\s+/', '<', $ccaddress); 2579 $ccaddress = preg_replace('/\s+>/', '>', $ccaddress); 2580 2581 $ccoaddress = preg_replace('/<\s+/', '<', $ccoaddress); 2582 $ccoaddress = preg_replace('/\s+>/', '>', $ccoaddress); 2583 2584 $replytoaddress = $params['input_replyto']; 2585 $subject = $params['input_subject']; 2586 $msg_uid = $params['msg_id']; 2587 $return_receipt = $params['input_return_receipt']; 2588 $is_important = $params['input_important_message']; 2589 $encrypt = $params['input_return_cripto']; 2590 $signed = $params['input_return_digital']; 2591 2592 $message_attachments = $params['message_attachments']; 2593 2594 if(substr($params['input_to'],-1) == ',') 2595 $params['input_to'] = substr($params['input_to'],0,-1); 2596 2597 if(substr($params['input_cc'],-1) == ',') 2598 $params['input_cc'] = substr($params['input_cc'],0,-1); 2599 2600 if(substr($params['input_cco'],-1) == ',') 2601 $params['input_cco'] = substr($params['input_cco'],0,-1); 2602 2603 // Valida numero Maximo de Destinatarios 2604 if($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients'] > 0) 2605 { 2606 $sendersNumber = count(explode(',',$params['input_to'])); 2607 2608 if($params['input_cc']) 2609 $sendersNumber += count(explode(',',$params['input_cc'])); 2610 if($params['input_cco']) 2611 $sendersNumber += count(explode(',',$params['input_cco'])); 2612 2613 $userMaxmimumSenders = $db->getMaximumRecipientsUser($this->username); 2614 if($userMaxmimumSenders) 2615 { 2616 if($sendersNumber > $userMaxmimumSenders) 2617 return $this->functions->getLang('Number of recipients greater than allowed'); 2618 } 2619 else 2620 { 2621 $ldap = new ldap_functions(); 2622 $groupsToUser = $ldap->get_user_groups($this->username); 2623 2624 $groupMaxmimumSenders = $db->getMaximumRecipientsGroup($groupsToUser); 2625 2626 if($groupMaxmimumSenders > 0) 2627 { 2628 if($sendersNumber > $groupMaxmimumSenders) 2629 return $this->functions->getLang('Number of recipients greater than allowed'); 2630 } 2631 else 2632 { 2633 if($sendersNumber > $_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients']) 2634 return $this->functions->getLang('Number of recipients greater than allowed'); 2635 } 2636 } 2637 2638 } 2639 //Fim Valida numero maximo de destinatarios 2640 2641 2642 //Valida envio de email para shared accounts 2643 if($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoMail_block_institutional_comunication'] == 'true') 2644 { 2533 function send_mail($params) { 2534 2535 require_once dirname(__FILE__) . '/../../services/class.servicelocator.php'; 2536 require_once dirname(__FILE__) . '/../../prototype/api/controller.php'; 2537 $mailService = ServiceLocator::getService('mail'); 2538 2539 include_once("class.db_functions.inc.php"); 2540 $db = new db_functions(); 2541 $fromaddress = $params['input_from'] ? explode(';', $params['input_from']) : ""; 2542 $message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false; 2543 2544 ## 2545 # @AUTHOR Rodrigo Souza dos Santos 2546 # @DATE 2008/09/17$fileName 2547 # @BRIEF Checks if the user has permission to send an email with the email address used. 2548 ## 2549 if (is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email'])) { 2550 $deny = true; 2551 foreach ($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val) 2552 if (array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1]) 2553 $deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']); 2554 2555 if ($deny) 2556 return "The server denied your request to send a mail, you cannot use this mail address."; 2557 } 2558 2559 $toaddress = $db->getAddrs(explode(',', $params['input_to'])); //implode(',',); 2560 $ccaddress = $db->getAddrs(explode(',', $params['input_cc'])); //implode(',',); 2561 $ccoaddress = $db->getAddrs(explode(',', $params['input_cco'])); //implode(',',); 2562 2563 if ($toaddress["False"] || $ccaddress["False"] || $ccoaddress["False"]) { 2564 return $this->parse_error("Invalid Mail:", ($toaddress["False"] ? $toaddress["False"] : ($ccaddress["False"] ? $ccaddress["False"] : $ccoaddress["False"]))); 2565 } 2566 2567 $toaddress = implode(',', $toaddress); 2568 $ccaddress = implode(',', $ccaddress); 2569 $ccoaddress = implode(',', $ccoaddress); 2570 2571 if ($toaddress == "" && $ccaddress == "" && $ccoaddress == "") { 2572 return $this->parse_error("Invalid Mail:", ($params['input_to'] ? $params['input_to'] : ($params['input_cc'] ? $params['input_cc'] : $params['input_cco']))); 2573 } 2574 2575 $toaddress = preg_replace('/<\s+/', '<', $toaddress); 2576 $toaddress = preg_replace('/\s+>/', '>', $toaddress); 2577 2578 $ccaddress = preg_replace('/<\s+/', '<', $ccaddress); 2579 $ccaddress = preg_replace('/\s+>/', '>', $ccaddress); 2580 2581 $ccoaddress = preg_replace('/<\s+/', '<', $ccoaddress); 2582 $ccoaddress = preg_replace('/\s+>/', '>', $ccoaddress); 2583 2584 $replytoaddress = $params['input_replyto']; 2585 $subject = $params['input_subject']; 2586 $return_receipt = $params['input_return_receipt']; 2587 $is_important = $params['input_important_message']; 2588 $encrypt = $params['input_return_cripto']; 2589 $signed = $params['input_return_digital']; 2590 2591 $message_attachments = $params['message_attachments']; 2592 2593 if (substr($params['input_to'], -1) == ',') 2594 $params['input_to'] = substr($params['input_to'], 0, -1); 2595 2596 if (substr($params['input_cc'], -1) == ',') 2597 $params['input_cc'] = substr($params['input_cc'], 0, -1); 2598 2599 if (substr($params['input_cco'], -1) == ',') 2600 $params['input_cco'] = substr($params['input_cco'], 0, -1); 2601 2602 // Valida numero Maximo de Destinatarios 2603 if ($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients'] > 0) { 2604 $sendersNumber = count(explode(',', $params['input_to'])); 2605 2606 if ($params['input_cc']) 2607 $sendersNumber += count(explode(',', $params['input_cc'])); 2608 if ($params['input_cco']) 2609 $sendersNumber += count(explode(',', $params['input_cco'])); 2610 2611 $userMaxmimumSenders = $db->getMaximumRecipientsUser($this->username); 2612 if ($userMaxmimumSenders) { 2613 if ($sendersNumber > $userMaxmimumSenders) 2614 return $this->functions->getLang('Number of recipients greater than allowed'); 2615 } 2616 else { 2645 2617 $ldap = new ldap_functions(); 2646 $arrayF = explode(';', $params['input_from']); 2618 $groupsToUser = $ldap->get_user_groups($this->username); 2619 2620 $groupMaxmimumSenders = $db->getMaximumRecipientsGroup($groupsToUser); 2621 2622 if ($groupMaxmimumSenders > 0) { 2623 if ($sendersNumber > $groupMaxmimumSenders) 2624 return $this->functions->getLang('Number of recipients greater than allowed'); 2625 } 2626 else { 2627 if ($sendersNumber > $_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients']) 2628 return $this->functions->getLang('Number of recipients greater than allowed'); 2629 } 2630 } 2631 } 2632 //Fim Valida numero maximo de destinatarios 2633 //Valida envio de email para shared accounts 2634 if ($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoMail_block_institutional_comunication'] == 'true') { 2635 $ldap = new ldap_functions(); 2636 $arrayF = explode(';', $params['input_from']); 2637 2638 /* 2639 * Verifica se o remetente n?o ? uma conta compartilhada 2640 */ 2641 if (!$ldap->isSharedAccountByMail($arrayF[1])) { 2642 $groupsToUser = $ldap->get_user_groups($this->username); 2643 $sharedAccounts = $ldap->returnSharedsAccounts($toaddress, $ccaddress, $ccoaddress); 2647 2644 2648 2645 /* 2649 * Verifica se o remetente n?o ? uma conta compartilhada2646 * Pega o UID do remetente 2650 2647 */ 2651 if(!$ldap->isSharedAccountByMail($arrayF[1])) 2652 { 2653 $groupsToUser = $ldap->get_user_groups($this->username); 2654 $sharedAccounts = $ldap->returnSharedsAccounts($toaddress, $ccaddress, $ccoaddress); 2655 2656 /* 2657 * Pega o UID do remetente 2658 */ 2659 $uidFrom = $ldap->mail2uid($arrayF[1]); 2660 2661 /* 2662 * Remove a conta compartilhada caso o uid do remetente exista na conta compartilhada 2663 */ 2664 foreach ($sharedAccounts as $key => $value) 2665 { 2666 if($value) 2667 $acl = $this->getaclfrombox($value); 2668 2669 if (array_key_exists($uidFrom, $acl)) 2670 unset($sharedAccounts[$key]); 2671 2672 } 2673 2674 /* 2675 * Caso ainda exista contas compartilhadas, verifica se existe alguma exce??o para estas contas 2676 */ 2677 if(count($sharedAccounts) > 0) 2678 $accountsBlockeds = $db->validadeSharedAccounts($this->username, $groupsToUser, $sharedAccounts); 2679 2680 /* 2681 * Retorna as contas compartilhadas bloqueadas 2682 */ 2683 if(count($accountsBlockeds) > 0) 2684 { 2685 $return = ''; 2686 2687 foreach ($accountsBlockeds as $accountBlocked) 2688 $return.= $accountBlocked.', '; 2689 2690 $return = substr($return,0,-2); 2691 2692 return $this->functions->getLang('you are blocked from sending mail to the following addresses').': '.$return; 2648 $uidFrom = $ldap->mail2uid($arrayF[1]); 2649 2650 /* 2651 * Remove a conta compartilhada caso o uid do remetente exista na conta compartilhada 2652 */ 2653 foreach ($sharedAccounts as $key => $value) { 2654 if ($value) 2655 $acl = $this->getaclfrombox($value); 2656 2657 if (array_key_exists($uidFrom, $acl)) 2658 unset($sharedAccounts[$key]); 2659 } 2660 2661 /* 2662 * Caso ainda exista contas compartilhadas, verifica se existe alguma exce??o para estas contas 2663 */ 2664 if (count($sharedAccounts) > 0) 2665 $accountsBlockeds = $db->validadeSharedAccounts($this->username, $groupsToUser, $sharedAccounts); 2666 2667 /* 2668 * Retorna as contas compartilhadas bloqueadas 2669 */ 2670 if (count($accountsBlockeds) > 0) { 2671 $return = ''; 2672 2673 foreach ($accountsBlockeds as $accountBlocked) 2674 $return.= $accountBlocked . ', '; 2675 2676 $return = substr($return, 0, -2); 2677 2678 return $this->functions->getLang('you are blocked from sending mail to the following addresses') . ': ' . $return; 2679 } 2680 } 2681 } 2682 // Fim Valida envio de email para shared accounts 2683 // TODO - implementar tratamento SMIME no novo serviço de envio de emails e retirar o AND false abaixo 2684 if ($params['smime'] AND false) { 2685 $body = $params['smime']; 2686 $mail->SMIME = true; 2687 // A MSG assinada deve ser testada neste ponto. 2688 // Testar o certificado e a integridade da msg.... 2689 include_once(dirname(__FILE__) . "/../../security/classes/CertificadoB.php"); 2690 $erros_acumulados = ''; 2691 $certificado = new certificadoB(); 2692 $validade = $certificado->verificar($body); 2693 if (!$validade) { 2694 foreach ($certificado->erros_ssl as $linha_erro) { 2695 $erros_acumulados .= $linha_erro; 2696 } 2697 } else { 2698 // Testa o CERTIFICADO: se o CPF he o do usuario logado, se pode assinar msgs e se nao esta expirado... 2699 if ($certificado->apresentado) { 2700 if ($certificado->dados['EXPIRADO']) 2701 $erros_acumulados .='Certificado expirado.'; 2702 $this->cpf = isset($GLOBALS['phpgw_info']['server']['certificado_atributo_cpf']) && $GLOBALS['phpgw_info']['server']['certificado_atributo_cpf'] != '' ? $_SESSION['phpgw_info']['expressomail']['user'][$GLOBALS['phpgw_info']['server']['certificado_atributo_cpf']] : $this->username; 2703 if ($certificado->dados['CPF'] != $this->cpf) 2704 $erros_acumulados .=' CPF no certificado diferente do logado no expresso.'; 2705 if (!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) 2706 $erros_acumulados .=' Certificado nao permite assinar mensagens.'; 2707 } 2708 else { 2709 $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg'; 2710 } 2711 } 2712 if (!$erros_acumulados == '') { 2713 return $erros_acumulados; 2714 } 2715 } else { 2716 //Compatibilização com Outlook, ao encaminhar a mensagem 2717 $body = mb_ereg_replace('<!--\[', '<!-- [', $params['body']); 2718 } 2719 2720 $attachments = $_FILES; 2721 $forwarding_attachments = $params['forwarding_attachments']; 2722 $local_attachments = $params['local_attachments']; 2723 2724 //Test if must be saved in shared folder and change if necessary 2725 if ($fromaddress[2] == 'y') { 2726 //build shared folder path 2727 $newfolder = "user" . $this->imap_delimiter . $fromaddress[3] . $this->imap_delimiter . $this->imap_sentfolder; 2728 if ($this->folder_exists($newfolder)) 2729 $folder = $newfolder; 2730 else 2731 $folder = $params['folder']; 2732 } else { 2733 $folder = $params['folder']; 2734 } 2735 2736 $folder = mb_convert_encoding($folder, 'UTF7-IMAP', 'ISO_8859-1'); 2737 $folder = preg_replace('/INBOX[\/.]/i', 'INBOX' . $this->imap_delimiter, $folder); 2738 $folder_name = $params['folder_name']; 2739 2740 // TODO - tratar assinatura e remover o AND false 2741 if ($signed && !$params['smime'] AND false) { 2742 $mail->Mailer = "smime"; 2743 $mail->SignedBody = true; 2744 } 2745 2746 2747 if ($fromaddress) 2748 $mailService->setFrom('"' . $fromaddress[0] . '" <' . $fromaddress[1] . '>'); 2749 else 2750 $mailService->setFrom('"' . $_SESSION['phpgw_info']['expressomail']['user']['firstname'] . ' ' . $_SESSION['phpgw_info']['expressomail']['user']['lastname'] . '" <' . $_SESSION['phpgw_info']['expressomail']['user']['email'] . '>'); 2751 2752 $bol = $this->add_recipients('to', $toaddress, $mailService); 2753 if (!$bol) { 2754 return $this->parse_error("Invalid Mail:", $toaddress); 2755 } 2756 $bol = $this->add_recipients('cc', $ccaddress, $mailService); 2757 if (!$bol) { 2758 return $this->parse_error("Invalid Mail:", $ccaddress); 2759 } 2760 $allow = $_SESSION['phpgw_info']['server']['expressomail']['allow_hidden_copy']; 2761 2762 if ($allow) { 2763 //$mailService->addBcc($ccoaddress); 2764 $bol = $this->add_recipients('cco', $ccoaddress, $mailService); 2765 2766 if (!$bol) { 2767 return $this->parse_error("Invalid Mail:", $ccoaddress); 2768 } 2769 } 2770 2771 //Implementação para o In-Reply-To e References 2772 $msg_numb = $params['messageNum']; 2773 $msg_folder = $params['messageFolder']; 2774 $this->mbox = $this->open_mbox($msg_folder); 2775 2776 $header = $this->get_header($msg_numb); 2777 $header_ = imap_fetchheader($this->mbox, $msg_numb, FT_UID); 2778 $pattern = '/^[ \t]*Disposition-Notification-To:[ ]*<?[[:alnum:]\._-]+@[[:alnum:]_-]+[\.[:alnum:]]+>?/sm'; 2779 if (preg_match($pattern, $header_, $fields)) { 2780 if (preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/', $fields[0], $matches)) { 2781 $return['DispositionNotificationTo'] = "<" . $matches[0] . ">"; 2782 } 2783 } 2784 2785 $message_id = $header->message_id; 2786 $references = array(); 2787 if ($message_id != "") { 2788 $mailService->addHeaderField('In-Reply-To', $message_id); 2789 2790 if (isset($header->references)) { 2791 array_push($references, $header->references); 2792 } 2793 array_push($references, $message_id); 2794 $mailService->addHeaderField('References', $references); 2795 } 2796 2797 2798 $mailService->setSubject($subject); 2799 $isHTML = ( (array_key_exists('type', $params) && in_array(strtolower($params['type']), array('html', 'plain')) ) ? 2800 strtolower($params['type']) != 'plain' : true ); 2801 2802 2803 // TODO - tratar mensagem criptografada e remover o AND false abaixo 2804 if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed) AND false) { // a msg deve ser enviada cifrada... 2805 $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress . ',' . $ccoaddress); 2806 $email = explode(",", $email); 2807 // Deve ser testado se foram obtidos os certificados de todos os destinatarios. 2808 // Deve ser verificado um numero limite de destinatarios. 2809 // Deve ser verificado se os certificados sao validos. 2810 // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario. 2811 // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes. 2812 $numero_maximo = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher']; // Este valor dever ser configurado pelo administrador do site .... 2813 $erros_acumulados = ""; 2814 $aux_mails = array(); 2815 $mail_list = array(); 2816 if (count($email) > $numero_maximo) { 2817 $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A); 2818 return $erros_acumulados; 2819 } 2820 // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados.. 2821 $email[] = $_SESSION['phpgw_info']['expressomail']['user']['email']; 2822 foreach ($email as $item) { 2823 $certificate = $db->get_certificate(strtolower($item)); 2824 if (!$certificate) { 2825 $erros_acumulados .= "Chamada com parametro invalido. e-Mail nao pode ser vazio." . chr(0x0A); 2826 return $erros_acumulados; 2827 } 2828 2829 if (array_key_exists("dberr1", $certificate)) { 2830 2831 $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A); 2832 return $erros_acumulados; 2833 } 2834 if (array_key_exists("dberr2", $certificate)) { 2835 $erros_acumulados .= $item . ' : Nao pode cifrar a msg. Certificado nao localizado.' . chr(0x0A); 2836 //continue; 2837 } 2838 /* Retirado este teste para evitar mensagem de erro duplicada. 2839 if (!array_key_exists("certs", $certificate)) 2840 { 2841 $erros_acumulados .= $item . ' : Nao pode cifrar a msg. Certificado nao localizado.' . chr(0x0A); 2842 continue; 2843 } 2844 */ 2845 include_once(dirname(__FILE__) . "/../../security/classes/CertificadoB.php"); 2846 2847 foreach ($certificate['certs'] as $registro) { 2848 $c1 = new certificadoB(); 2849 $c1->certificado($registro['chave_publica']); 2850 if ($c1->apresentado) { 2851 $c2 = new Verifica_Certificado($c1->dados, $registro['chave_publica']); 2852 if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status) { 2853 $aux_mails[] = $registro['chave_publica']; 2854 $mail_list[] = strtolower($item); 2855 } else { 2856 if ($c1->dados['EXPIRADO'] || $c2->revogado) { 2857 $db->update_certificate($c1->dados['SERIALNUMBER'], $c1->dados['EMAIL'], $c1->dados['AUTHORITYKEYIDENTIFIER'], $c1->dados['EXPIRADO'], $c2->revogado); 2858 } 2859 2860 $erros_acumulados .= $item . ': ' . $c2->msgerro . chr(0x0A); 2861 foreach ($c2->erros_ssl as $linha) { 2862 $erros_acumulados .= $linha . chr(0x0A); 2863 } 2864 $erros_acumulados .= 'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A); 2865 $erros_acumulados .= $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A); 2866 } 2867 } else { 2868 $erros_acumulados .= $item . ' : Nao pode cifrar a msg. Certificado invalido.' . chr(0x0A); 2693 2869 } 2694 2870 } 2871 if (!(in_array(strtolower($item), $mail_list)) && !empty($erros_acumulados)) { 2872 return $erros_acumulados; 2873 } 2695 2874 } 2696 // Fim Valida envio de email para shared accounts 2697 2698 2699 // TODO - implementar tratamento SMIME no novo serviço de envio de emails e retirar o AND false abaixo 2700 if($params['smime'] AND false) 2701 { 2702 $body = $params['smime']; 2703 $mail->SMIME = true; 2704 // A MSG assinada deve ser testada neste ponto. 2705 // Testar o certificado e a integridade da msg.... 2706 include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php"); 2707 $erros_acumulados = ''; 2708 $certificado = new certificadoB(); 2709 $validade = $certificado->verificar($body); 2710 if(!$validade) 2875 2876 $mail->Certs_crypt = $aux_mails; 2877 } 2878 2879 $attachment = json_decode($params['attachments'],TRUE); 2880 2881 foreach ($attachment as &$value) 2711 2882 { 2712 foreach($certificado->erros_ssl as $linha_erro)2883 if((int)$value > 0) //BD attachment 2713 2884 { 2714 $erros_acumulados .= $linha_erro; 2885 $att = Controller::read(array('id'=> $value , 'concept' => 'mailAttachment')); 2886 2887 if($att['disposition'] == 'embedded') 2888 { 2889 $body = str_replace('"../prototype/getArchive.php?mailAttachment='.$att['id'].'"', $att['name'], $body); 2890 $mailService->addStringImage(base64_decode($att['source']), $att['type'], $att['name']); 2891 } 2892 else 2893 $mailService->addStringAttachment(base64_decode($att['source']), $att['name'], $att['type'], 'base64', isset($att['disposition']) ? $att['disposition'] :'attachment' ); 2894 2895 unset($att); 2896 } 2897 else //message attachment 2898 { 2899 $value = json_decode($value, true); 2900 $sub = $value['name'] ? $value['name'].'.eml' :'no title.eml'; 2901 $mbox_stream = $this->open_mbox($value['folder']); 2902 $rawmsg = $this->getRawHeader($value['uid']) . "\r\n\r\n" . $this->getRawBody($value['uid']); 2903 $mailService->addStringAttachment($rawmsg, $sub, 'message/rfc822', '7bit', 'attachment' ); 2904 $message_size_total += mb_strlen($rawmsg); //Adiciona o tamanho do anexo a variavel que controlao tamanho da msg. 2905 unset($rawmsg); 2906 } 2907 2908 } 2909 2910 $message_size_total += strlen($params['body']); /* Tamanho do corpo da mensagem. */ 2911 2912 //////////////////////////////////////////////////////////////////////////////////////////////////// 2913 /** 2914 * Faz a validação pelo tamanho máximo de mensagem permitido para o usuário. Se o usuário não estiver em nenhuma regra, usa o tamanho padrão. 2915 */ 2916 $default_max_size_rule = $db->get_default_max_size_rule(); 2917 if (!$default_max_size_rule) { 2918 $default_max_size_rule = str_replace("M", "", ini_get('upload_max_filesize')) * 1024 * 1024; /* hack para não bloquear o envio de email quando não for configurado um tamanho padrão */ 2919 } else { 2920 foreach ($default_max_size_rule as $i => $value) { 2921 $default_max_size_rule = $value['config_value']; 2715 2922 } 2716 2923 } 2717 else 2718 { 2719 // Testa o CERTIFICADO: se o CPF he o do usuario logado, se pode assinar msgs e se nao esta expirado... 2720 if ($certificado->apresentado) 2721 { 2722 if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.'; 2723 $this->cpf = isset($GLOBALS['phpgw_info']['server']['certificado_atributo_cpf'])&&$GLOBALS['phpgw_info']['server']['certificado_atributo_cpf']!=''?$_SESSION['phpgw_info']['expressomail']['user'][$GLOBALS['phpgw_info']['server']['certificado_atributo_cpf']]:$this->username; 2724 if($certificado->dados['CPF'] != $this->cpf) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.'; 2725 if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.'; 2726 } 2727 else 2728 { 2729 $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg'; 2924 2925 $default_max_size_rule = $default_max_size_rule * 1024 * 1024; /* Tamanho da regra padrão, em bytes */ 2926 $id_user = $_SESSION['phpgw_info']['expressomail']['user']['userid']; 2927 2928 2929 $ldap = new ldap_functions(); 2930 $groups_user = $ldap->get_user_groups($id_user); 2931 2932 $size_rule_by_group = array(); 2933 foreach ($groups_user as $k => $value_) { 2934 $rule_in_group = $db->get_rule_by_user_in_groups($k); 2935 if ($rule_in_group != "") 2936 array_push($size_rule_by_group, $rule_in_group); 2937 } 2938 2939 $n_rule_groups = 0; 2940 $maior_valor_regra_grupo = 0; 2941 foreach ($size_rule_by_group as $i => $value) { 2942 if (is_array($value[0])) { 2943 $n_rule_groups++; 2944 if ($value[0]['email_max_recipient'] > $maior_valor_regra_grupo) 2945 $maior_valor_regra_grupo = $value[0]['email_max_recipient']; 2730 2946 } 2731 2947 } 2732 if(!$erros_acumulados =='') 2733 { 2734 return $erros_acumulados; 2735 } 2736 } 2737 else 2738 { 2739 //Compatibilização com Outlook, ao encaminhar a mensagem 2740 $body = mb_ereg_replace('<!--\[', '<!-- [', $params['body']); 2741 } 2742 2743 $attachments = $_FILES; 2744 $forwarding_attachments = $params['forwarding_attachments']; 2745 $local_attachments = $params['local_attachments']; 2746 2747 //Test if must be saved in shared folder and change if necessary 2748 if( $fromaddress[2] == 'y' ){ 2749 //build shared folder path 2750 $newfolder = "user".$this->imap_delimiter.$fromaddress[3].$this->imap_delimiter.$this->imap_sentfolder; 2751 if($this->folder_exists($newfolder)) 2752 $folder = $newfolder; 2753 else 2754 $folder = $params['folder']; 2755 2756 } else { 2757 $folder = $params['folder']; 2758 } 2759 2760 $folder = mb_convert_encoding($folder, 'UTF7-IMAP','ISO_8859-1'); 2761 $folder = preg_replace('/INBOX[\/.]/i', 'INBOX'.$this->imap_delimiter, $folder); 2762 $folder_name = $params['folder_name']; 2763 2764 // TODO - tratar assinatura e remover o AND false 2765 if($signed && !$params['smime'] AND false) 2766 { 2767 $mail->Mailer = "smime"; 2768 $mail->SignedBody = true; 2769 } 2770 2771 2772 if($fromaddress) 2773 $mailService->setFrom ('"'.$fromaddress[0].'" <'.$fromaddress[1].'>'); 2774 else 2775 $mailService->setFrom ('"'.$_SESSION['phpgw_info']['expressomail']['user']['firstname'].' '.$_SESSION['phpgw_info']['expressomail']['user']['lastname'].'" <'.$_SESSION['phpgw_info']['expressomail']['user']['email'].'>'); 2776 //$mailService->addTo($toaddress); 2777 //$mailService->addCc($ccaddress); 2778 $bol = $this->add_recipients('to', $toaddress, $mailService); 2779 if(!$bol){ 2780 return $this->parse_error("Invalid Mail:", $toaddress); 2781 } 2782 $bol = $this->add_recipients('cc', $ccaddress, $mailService); 2783 if(!$bol){ 2784 return $this->parse_error("Invalid Mail:", $ccaddress); 2785 } 2786 $allow = $_SESSION['phpgw_info']['server']['expressomail']['allow_hidden_copy']; 2787 2788 if($allow) 2789 { 2790 //$mailService->addBcc($ccoaddress); 2791 $bol = $this->add_recipients('cco', $ccoaddress, $mailService); 2792 2793 if(!$bol){ 2794 return $this->parse_error("Invalid Mail:", $ccoaddress); 2795 } 2796 } 2797 2798 //Implementação para o In-Reply-To e References 2799 $msg_numb = $params['messageNum']; 2800 $msg_folder = $params['messageFolder']; 2801 $this->mbox = $this->open_mbox($msg_folder); 2802 2803 $header = $this->get_header($msg_numb); 2804 $header_ = imap_fetchheader($this->mbox, $msg_numb, FT_UID); 2805 $pattern = '/^[ \t]*Disposition-Notification-To:[ ]*<?[[:alnum:]\._-]+@[[:alnum:]_-]+[\.[:alnum:]]+>?/sm'; 2806 if (preg_match($pattern, $header_, $fields)) 2807 { 2808 if(preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/',$fields[0], $matches)){ 2809 $return['DispositionNotificationTo'] = "<".$matches[0].">"; 2810 } 2811 } 2812 2813 $message_id = $header->message_id; 2814 $references = array(); 2815 if($message_id != "") 2816 { 2817 $mailService->addHeaderField('In-Reply-To',$message_id); 2818 2819 if(isset($header->references)){ 2820 array_push($references, $header->references); 2821 } 2822 array_push($references, $message_id); 2823 $mailService->addHeaderField('References',$references); 2824 2825 } 2826 2827 2828 $mailService->setSubject($subject); 2829 $isHTML = ( (array_key_exists('type', $params) && in_array(strtolower($params['type']), array('html', 'plain')) ) ? 2830 strtolower($params['type']) != 'plain' : true ); 2831 2832 2833 // TODO - tratar mensagem criptografada e remover o AND false abaixo 2834 if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed) AND false) // a msg deve ser enviada cifrada... 2835 { 2836 $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress); 2837 $email = explode(",",$email); 2838 // Deve ser testado se foram obtidos os certificados de todos os destinatarios. 2839 // Deve ser verificado um numero limite de destinatarios. 2840 // Deve ser verificado se os certificados sao validos. 2841 // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario. 2842 // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes. 2843 $numero_maximo = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher']; // Este valor dever ser configurado pelo administrador do site .... 2844 $erros_acumulados = ""; 2845 $aux_mails = array(); 2846 $mail_list = array(); 2847 if(count($email) > $numero_maximo) 2848 { 2849 $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A); 2850 return $erros_acumulados; 2851 } 2852 // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados.. 2853 $email[] = $_SESSION['phpgw_info']['expressomail']['user']['email']; 2854 foreach($email as $item) 2855 { 2856 $certificate = $db->get_certificate(strtolower($item)); 2857 if(!$certificate) 2858 { 2859 $erros_acumulados .= "Chamada com parametro invalido. e-Mail nao pode ser vazio." . chr(0x0A); 2860 return $erros_acumulados; 2948 2949 if ($default_max_size_rule) { 2950 $size_rule = $db->get_rule_by_user($_SESSION['phpgw_info']['expressomail']['user']['userid']); 2951 2952 if (!$size_rule && $n_rule_groups == 0) /* O usuário não está em nenhuma regra por usuário nem por grupo. Vai usar a regra padrão. */ { 2953 if ($message_size_total > $default_max_size_rule) 2954 return $this->functions->getLang("Message size greateruler than allowed (Default rule)"); 2861 2955 } 2862 2956 2863 if (array_key_exists("dberr1", $certificate)) 2864 { 2865 2866 $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A); 2867 return $erros_acumulados; 2868 } 2869 if (array_key_exists("dberr2", $certificate)) 2870 { 2871 $erros_acumulados .= $item . ' : Nao pode cifrar a msg. Certificado nao localizado.' . chr(0x0A); 2872 //continue; 2873 } 2874 /* Retirado este teste para evitar mensagem de erro duplicada. 2875 if (!array_key_exists("certs", $certificate)) 2876 { 2877 $erros_acumulados .= $item . ' : Nao pode cifrar a msg. Certificado nao localizado.' . chr(0x0A); 2878 continue; 2879 } 2880 */ 2881 include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php"); 2882 2883 foreach ($certificate['certs'] as $registro) 2884 { 2885 $c1 = new certificadoB(); 2886 $c1->certificado($registro['chave_publica']); 2887 if ($c1->apresentado) 2888 { 2889 $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']); 2890 if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status) 2891 { 2892 $aux_mails[] = $registro['chave_publica']; 2893 $mail_list[] = strtolower($item); 2957 else { 2958 if (count($size_rule) > 0) /* Verifica se existe regra por usuário. Se houver, ela vai se sobresair das regras por grupo. */ { 2959 $regra_mais_permissiva = 0; 2960 foreach ($size_rule as $i => $value) { 2961 if ($regra_mais_permissiva < $value['email_max_recipient']) 2962 $regra_mais_permissiva = $value['email_max_recipient']; 2894 2963 } 2895 else 2896 { 2897 if ($c1->dados['EXPIRADO'] || $c2->revogado) 2898 { 2899 $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'], 2900 $c1->dados['EXPIRADO'],$c2->revogado); 2901 } 2902 2903 $erros_acumulados .= $item . ': ' . $c2->msgerro . chr(0x0A); 2904 foreach($c2->erros_ssl as $linha) 2905 { 2906 $erros_acumulados .= $linha . chr(0x0A); 2907 } 2908 $erros_acumulados .= 'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A); 2909 $erros_acumulados .= $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A); 2910 } 2964 $regra_mais_permissiva = $regra_mais_permissiva * 1024 * 1024; 2965 if ($message_size_total > $regra_mais_permissiva) 2966 return $this->functions->getLang("Message size greater than allowed (Rule By User)"); 2911 2967 } 2912 else 2913 { 2914 $erros_acumulados .= $item . ' : Nao pode cifrar a msg. Certificado invalido.' . chr(0x0A); 2968 else /* Regra por grupo */ { 2969 $maior_valor_regra_grupo = $maior_valor_regra_grupo * 1024 * 1024; 2970 if ($message_size_total > $maior_valor_regra_grupo) 2971 return $this->functions->getLang("Message size greater than allowed (Rule By Group)"); 2915 2972 } 2916 2973 } 2917 if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))2918 {2919 return $erros_acumulados;2920 }2921 2974 } 2922 2923 $mail->Certs_crypt = $aux_mails; 2924 } 2925 2926 if( count($forwarding_attachments) > 0 )// Build CID images 2927 $this->buildEmbeddedImages($mailService,$msg_uid,$forwarding_attachments, $body); 2928 2929 // Build Uploading Attachments!!! 2930 if (count($attachments)>0) //Caso seja forward normal... 2931 { 2932 $total_uploaded_size = 0; 2933 foreach ($attachments as $attach) 2934 { 2935 if($attach['error'] == UPLOAD_ERR_INI_SIZE) 2936 return $this->parse_error("message file too big"); 2937 if($attach['name']=='Unknown') 2938 continue; 2939 $mailService->addFileAttachment($attach['tmp_name'], $attach['name'], $this->get_file_type($attach['name']), 'base64', 'attachment'); 2940 $total_uploaded_size = $total_uploaded_size + $attach['size']; 2941 } 2942 if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) 2943 { 2944 2945 $upload_max_filesize = str_replace('M','',$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024; 2946 if( $total_uploaded_size > $upload_max_filesize) 2947 return $this->parse_error("message file too big"); 2948 } 2949 } 2950 if(count($local_attachments)>0) { //Caso seja forward de mensagens locais 2951 2952 $total_uploaded_size = 0; 2953 2954 foreach($local_attachments as $local_attachment) { 2955 $file_description = unserialize(rawurldecode($local_attachment)); 2956 $tmp = array_values($file_description); 2957 foreach($file_description as $i => $descriptor){ 2958 $tmp[$i] = eregi_replace('\'*\'','',$descriptor); 2959 } 2960 $mailService->addFileAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], $this->get_file_type($tmp[2]), 'base64', 'attachment'); 2961 $total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size']; 2962 } 2963 if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) 2964 { 2965 $upload_max_filesize = str_replace('M','',$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024; 2966 if( $total_uploaded_size > $upload_max_filesize) 2967 return $this->parse_error("message file too big"); 2968 } 2969 } 2970 2971 // Build Forwarding Attachments!!! 2972 if (count($forwarding_attachments) > 0) 2973 { 2974 // Bug fixed for array_search function 2975 $name_cid_files = array(); 2976 if(count($name_cid_files) > 0) { 2977 $name_cid_files[count($name_cid_files)] = $name_cid_files[0]; 2978 $name_cid_files[0] = null; 2979 } 2980 2981 foreach($forwarding_attachments as $forwarding_attachment) 2982 { 2983 $file_description = unserialize(rawurldecode($forwarding_attachment)); 2984 2985 foreach($file_description as $i => $item) 2986 $file_description[$i] = urldecode($item); 2987 2988 $tmp = array_values($file_description); 2989 foreach($file_description as $i => $descriptor){ 2990 $tmp[$i] = eregi_replace('\'*\'','',$descriptor); 2991 } 2992 $file_description = $tmp; 2993 $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]); 2994 $fileName = $file_description[2]; 2995 if(!array_search(trim($fileName),$name_cid_files)) { 2996 $filename_dec = html_entity_decode(rawurldecode($fileName)); 2997 $mailService->addStringAttachment($fileContent, $filename_dec, $this->get_file_type($file_description[2]), $file_description[4] ); 2998 2999 } 3000 } 3001 } 3002 3003 //Build Message Attachments!!! 3004 if(count($message_attachments) > 0 ) 3005 { 3006 foreach($message_attachments as $folder_name => $messages) 3007 { 3008 foreach ($messages as $message_number => $message_subject) 3009 { 3010 if (!$message_subject) 3011 $message_subject = 'no title.eml'; 3012 else 3013 $message_subject .= '.eml'; 3014 3015 if( $message_attachments_contents && isset($message_attachments_contents[$folder_name]) ) 3016 $rawmsg = base64_decode( $message_attachments_contents[$folder_name][$message_number] ); 3017 else{ 3018 $mbox_stream = $this->open_mbox($folder_name); 3019 $rawmsg = $this->getRawHeader($message_number) . "\r\n\r\n" . $this->getRawBody($message_number); 3020 } 3021 3022 $return_forward[] = array( 'name' => $message_subject, 'size' => mb_strlen($rawmsg)); 3023 $mailService->addStringAttachment($rawmsg, $message_subject, 'message/rfc822', '7bit', 'attachment' ); 3024 } 3025 } 3026 } 3027 3028 $message_size_total += strlen($params['body']); /* Tamanho do corpo da mensagem. */ 3029 $message_size_total += $total_uploaded_size; /* Incrementa com os anexos da nova mensagem, se houver. */ 3030 3031 //////////////////////////////////////////////////////////////////////////////////////////////////// 3032 /** 3033 * Faz a validação pelo tamanho máximo de mensagem permitido para o usuário. Se o usuário não estiver em nenhuma regra, usa o tamanho padrão. 3034 */ 3035 $default_max_size_rule = $db->get_default_max_size_rule(); 3036 if(!$default_max_size_rule) 3037 { 3038 $default_max_size_rule = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024; /* hack para não bloquear o envio de email quando não for configurado um tamanho padrão */ 3039 } 3040 else 3041 { 3042 foreach($default_max_size_rule as $i=>$value) 3043 { 3044 $default_max_size_rule = $value['config_value']; 3045 } 3046 } 3047 3048 $default_max_size_rule = $default_max_size_rule * 1024 * 1024; /* Tamanho da regra padrão, em bytes */ 3049 $id_user = $_SESSION['phpgw_info']['expressomail']['user']['userid']; 3050 3051 3052 $ldap = new ldap_functions(); 3053 $groups_user = $ldap->get_user_groups($id_user); 3054 3055 $size_rule_by_group = array(); 3056 foreach($groups_user as $k=>$value_) 3057 { 3058 $rule_in_group = $db->get_rule_by_user_in_groups($k); 3059 if ($rule_in_group != "") 3060 array_push($size_rule_by_group, $rule_in_group); 3061 } 3062 3063 $n_rule_groups = 0; 3064 $maior_valor_regra_grupo = 0; 3065 foreach($size_rule_by_group as $i=>$value) 3066 { 3067 if(is_array($value[0])) 3068 { 3069 $n_rule_groups++; 3070 if($value[0]['email_max_recipient'] > $maior_valor_regra_grupo) 3071 $maior_valor_regra_grupo = $value[0]['email_max_recipient']; 3072 } 3073 } 3074 3075 if($default_max_size_rule) 3076 { 3077 $size_rule = $db->get_rule_by_user($_SESSION['phpgw_info']['expressomail']['user']['userid']); 3078 3079 if(!$size_rule && $n_rule_groups == 0) /* O usuário não está em nenhuma regra por usuário nem por grupo. Vai usar a regra padrão. */ 3080 { 3081 if($message_size_total > $default_max_size_rule) 3082 return $this->functions->getLang("Message size greateruler than allowed (Default rule)"); 3083 } 3084 3085 else 3086 { 3087 if(count($size_rule) > 0) /* Verifica se existe regra por usuário. Se houver, ela vai se sobresair das regras por grupo. */ 3088 { 3089 $regra_mais_permissiva = 0; 3090 foreach($size_rule as $i=>$value) 3091 { 3092 if($regra_mais_permissiva < $value['email_max_recipient']) 3093 $regra_mais_permissiva = $value['email_max_recipient']; 3094 } 3095 $regra_mais_permissiva = $regra_mais_permissiva * 1024 * 1024; 3096 if($message_size_total > $regra_mais_permissiva) 3097 return $this->functions->getLang("Message size greater than allowed (Rule By User)"); 3098 } 3099 else /* Regra por grupo */ 3100 { 3101 $maior_valor_regra_grupo = $maior_valor_regra_grupo * 1024 * 1024; 3102 if($message_size_total > $maior_valor_regra_grupo) 3103 return $this->functions->getLang("Message size greater than allowed (Rule By Group)"); 3104 3105 3106 } 3107 } 3108 } 3109 /** 3110 * Fim da validação do tamanho da regra do tamanho de mensagem. 3111 */ 3112 //////////////////////////////////////////////////////////////////////////////////////////////////// 3113 3114 3115 3116 3117 3118 if($isHTML) 3119 $mailService->setBodyHtml($body); 3120 else 3121 $mailService->setBodyText($body); 3122 3123 if($is_important) 3124 $mailService->addHeaderField('Importance','High'); 3125 3126 if($return_receipt) 3127 $mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']); 3128 3129 3130 if ($folder != 'null'){ 3131 $mbox_stream = $this->open_mbox($folder); 3132 @imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen"); 3133 } 3134 3135 $sent = $mailService->send(); 3136 3137 if($sent !== true) 3138 { 3139 return $this->parse_error($sent); 3140 } 3141 else 3142 { 3143 if ($signed && !$params['smime']) 3144 { 3145 return $sent; 3146 } 3147 if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True") 3148 { 3149 $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid']; 3150 $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip']; 3151 $now = date("d/m/y H:i:s"); 3152 $addrs = $toaddress.$ccaddress.$ccoaddress; 3153 $sent = trim($sent); 3154 error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log"); 3155 } 3156 if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) { 3157 $contacts = new dynamic_contacts(); 3158 $new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress); 3159 return array("success" => true, "new_contacts" => $new_contacts); 3160 } 3161 return array("success" => true); 3162 } 3163 } 2975 /** 2976 * Fim da validação do tamanho da regra do tamanho de mensagem. 2977 */ 2978 //////////////////////////////////////////////////////////////////////////////////////////////////// 2979 2980 if ($isHTML) 2981 $mailService->setBodyHtml($body); 2982 else 2983 $mailService->setBodyText($body); 2984 2985 if ($is_important) 2986 $mailService->addHeaderField('Importance', 'High'); 2987 2988 if ($return_receipt) 2989 $mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']); 2990 2991 2992 if ($folder != 'null') { 2993 $mbox_stream = $this->open_mbox($folder); 2994 @imap_append($mbox_stream, "{" . $this->imap_server . ":" . $this->imap_port . "}" . $folder, $mailService->getMessage(), "\\Seen"); 2995 } 2996 2997 $sent = $mailService->send(); 2998 2999 if ($sent !== true) { 3000 return $this->parse_error($sent); 3001 } else { 3002 if ($signed && !$params['smime']) { 3003 return $sent; 3004 } 3005 if ($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True") { 3006 $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid']; 3007 $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip']; 3008 $now = date("d/m/y H:i:s"); 3009 $addrs = $toaddress . $ccaddress . $ccoaddress; 3010 $sent = trim($sent); 3011 error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log"); 3012 } 3013 if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) { 3014 $contacts = new dynamic_contacts(); 3015 $new_contacts = $contacts->add_dynamic_contacts($toaddress . "," . $ccaddress . "," . $ccoaddress); 3016 return array("success" => true, "new_contacts" => $new_contacts); 3017 } 3018 3019 if($params['uids_save'] ) 3020 $this->delete_msgs(array('folder'=> $params['save_folder'] , 'msgs_number' => $params['uids_save'])); 3021 3022 3023 return array("success" => true); 3024 3025 } 3026 } 3164 3027 3165 3028 3166 /**3167 * @license http://www.gnu.org/copyleft/gpl.html GPL3168 * @author Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)3169 * @param $mail email3170 * @param $msg_uid uid da mensagem3171 * @param $forwarding_attachments anexos3172 */3173 3174 function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments ,&$body)3175 {3176 //Procura e retorna em $cids_imgs imagens embarcadas no corpo do e-mail3177 $pattern = '/src=("[^"]*?get_archive.php\?msgFolder=(.+)?&(amp;)?msgNumber=(.+)?&(amp;)?indexPart=(.+)?")/isU';3178 $cid_imgs = '';3179 preg_match_all( $pattern , $body , $cid_imgs , PREG_PATTERN_ORDER );3180 //-------------------------------------------------------------------//3181 3182 $attPostions = array(); //Array que linka a possição da imagem com o indice que esta se encontra no array $forwarding_attachments3183 3184 foreach ($forwarding_attachments as $i => $v){ // Monta o array de link3185 $desc = unserialize(rawurldecode($v));3186 $attPostions[$desc[3]] = $i;3187 }3188 3189 //Intera as imagens encontradas3190 foreach($cid_imgs[6] as $j => $val)3191 {3192 $cid = base_convert(microtime().$j, 10, 36); //Gera um cid3193 $body = str_replace($cid_imgs[1][$j], '"cid:'.$cid.'"', $body ); //tira o src da imagem e coloca o cid.3194 $count = strlen($cid_imgs[6][$j]);3195 3196 $attach_img = $forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']];3197 $file_description = unserialize(rawurldecode($attach_img));3198 3199 if (is_array($file_description))3200 foreach($file_description as $i => $descriptor)3201 $file_description[$i] = mb_ereg_replace('\'*\'','',$descriptor);3202 3203 // The image is not in the same mail?3204 if ($msg_uid != $cid_imgs[4][$j])3205 {3206 $fa = $this->get_forwarding_attachment2($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');3207 $fileContent = &$fa['binary'];3208 $fileName = $fa['name'];3209 $fileCode = $fa['encoding'];3210 $fileType = $fa['type'];3211 $file_attached[0] = $cid_imgs[2][$j];3212 $file_attached[1] = $cid_imgs[4][$j];3213 $file_attached[2] = $fileName;3214 $file_attached[3] = '0.'.(string)($j+1);3215 $file_attached[4] = 'base64';3216 $file_attached[5] = strlen($fileContent); //Size of file3217 $file_attached[6] = $cid_imgs[6][$j];3218 $return_forward[] = $file_attached;3219 3220 if ($file_attached[3] == $file_description[3] || $msg_uid == 'undefined')3221 unset($forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]);3222 3223 }3224 else3225 {3226 $fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');3227 $fileName = $file_description[2];3228 $fileCode = $file_description[4];3229 $file_description[3] = '0.'.(string)($j+1);3230 $file_description[6] = $cid_imgs[6][$j];3231 $fileType = $this->get_file_type($file_description[2]);3232 unset($forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]);3233 if (!empty($file_description))3234 {3235 $file_description[5] = strlen($fileContent); //Size of file3236 $return_forward[] = $file_description;3237 }3238 }3239 3240 if ($fileContent)3241 $mail->addStringImage($fileContent,$fileType,$fileName, $cid);3242 }3243 3244 return $return_forward;3245 }3246 3029 function add_recipients_cert($full_address) 3247 3030 { … … 3664 3447 } 3665 3448 } 3666 3667 3668 function save_msg($params)3669 {3670 3671 require_once dirname(__FILE__) . '/../../services/class.servicelocator.php';3672 $mailService = ServiceLocator::getService('mail');3673 3674 $return_receipt = $params['input_return_receipt'];3675 $is_important = $params['input_important_message'];3676 3677 $msg_uid = $params['msg_id'];3678 $body = $params['body'];3679 $body = str_replace("%nbsp;"," ",$body);3680 $body = preg_replace("/\n/"," ",$body);3681 $body = preg_replace("/\r/","" ,$body);3682 $body = html_entity_decode ( $body, ENT_QUOTES , 'ISO-8859-1' );3683 $forwarding_attachments = $params['forwarding_attachments'];3684 $message_attachments = $params['message_attachments'];3685 $attachments = $params['FILES'];3686 $return_files = $params['FILES'];3687 $message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false;3688 3689 if(is_array($params['local_attachments'])){3690 foreach ($params['local_attachments'] as $key => $local_attach) {3691 $tmp = unserialize(urldecode($local_attach));3692 $attachments[$key]['name'] = urldecode($tmp[2]);3693 $return_files[$key]['name'] = urldecode($tmp[2]);3694 }3695 }3696 3697 $folder = mb_convert_encoding($params['folder'], "UTF7-IMAP","ISO-8859-1, UTF-8");3698 $folder = @eregi_replace("INBOX[/.]", "INBOX".$this->imap_delimiter, $folder);3699 3700 $mailService->setFrom ('"'.$fromaddress[0].'" <'.$fromaddress[1].'>');3701 $mailService->addTo($params['input_to']);3702 $mailService->addCc( $params['input_cc']);3703 $mailService->addBcc($params['input_cco']);3704 $mailService->setSubject($params['input_subject']);3705 3706 if($is_important){3707 $mailService->addHeaderField('Importance','High');3708 }3709 3710 if($return_receipt)3711 $mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']);3712 3713 $isHTML = ( ( array_key_exists( 'type', $params ) && in_array( strtolower( $params[ 'type' ] ), array( 'html', 'plain' ) ) ) ? strtolower( $params[ 'type' ] ) != 'plain' : true );3714 3715 3716 if( count($forwarding_attachments) > 0 )3717 $return_forward = $this->buildEmbeddedImages($mailService, $msg_uid, $forwarding_attachments , $body);3718 3719 //Build Message Attachments!!!3720 if(count($message_attachments) > 0 )3721 {3722 foreach($message_attachments as $folder_name => $messages)3723 {3724 foreach ($messages as $message_number => $message_subject)3725 {3726 if (!$message_subject)3727 $message_subject = 'no title.eml';3728 else3729 $message_subject .= '.eml';3730 3731 if( $message_attachments_contents && isset($message_attachments_contents[$folder_name]) )3732 $rawmsg = base64_decode( $message_attachments_contents[$folder_name][$message_number] );3733 else{3734 $mbox_stream = $this->open_mbox($folder_name);$mbox_stream = $this->open_mbox($folder_name);3735 $rawmsg = $this->getRawHeader($message_number) . "\r\n\r\n" . $this->getRawBody($message_number);3736 }3737 3738 $return_forward[] = array( 'name' => $message_subject, 'size' => mb_strlen($rawmsg));3739 $mailService->addStringAttachment($rawmsg, $message_subject, 'message/rfc822', '7bit', 'attachment' );3740 }3741 }3742 }3743 3744 $imagesParts = array();3745 3746 if(count($return_forward) > 0 )3747 foreach ($return_forward as $value)3748 $imagesParts[$value[6]] = $value[3];3749 3750 //Build Forwarding Attachments!!!3751 if(count($forwarding_attachments) > 0 )3752 {3753 foreach($forwarding_attachments as $forwarding_attachment)3754 {3755 3756 $file_description = unserialize(rawurldecode($forwarding_attachment));3757 foreach($file_description as $i => $item)3758 $file_description[$i] = urldecode($item);3759 3760 $file_description = array_values($file_description);3761 3762 foreach($file_description as $i => $descriptor)3763 $file_description[$i] = eregi_replace('\'*\'','',$descriptor);3764 3765 $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);3766 $file_description[2] = html_entity_decode($file_description[2]);3767 3768 $file_description[5] = strlen($fileContent); //Size of file3769 $return_forward[] = $file_description;3770 $mailService->addStringAttachment($fileContent, $file_description[2], $this->get_file_type($file_description[2]), $file_description[4] );3771 }3772 }3773 3774 if ((count($return_forward) > 0) && (count($return_files) > 0))3775 $return_files = array_merge_recursive($return_forward,$return_files);3776 else if (count($return_files) < 1)3777 $return_files = $return_forward;3778 3779 //Build Uploading Attachments!!!3780 $sizeof_attachments = count($attachments);3781 if ($sizeof_attachments)3782 foreach ($attachments as $numb => $attach)3783 $mailService->addFileAttachment($attach['tmp_name'], $attach['name'],$attach['type'], 'base64', 'attachment');3784 3785 3786 if (!$body)3787 $body = ' ';3788 3789 if($isHTML)3790 $mailService->setBodyHtml($body);3791 else3792 $mailService->setBodyText($body);3793 3794 3795 $mbox_stream = $this->open_mbox($folder);3796 $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen \\Draft");3797 3798 $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);3799 $return['msg_no'] = $status->uidnext - 1;3800 $return['folder_id'] = $folder;3801 $return['imagesParts'] = $imagesParts;3802 3803 if($mbox_stream)3804 imap_close($mbox_stream);3805 3806 $returnFiles = array();3807 $ii = 0;3808 3809 if(count($return_files) > 0)3810 {3811 foreach ($return_files as $index => $_attachment)3812 {3813 if (array_key_exists("name", $_attachment))3814 {3815 $returnFiles[$ii]['name'] = base64_encode(mb_convert_encoding( $_attachment['name'], 'UTF-8', 'UTF-8, ISO-8859-1') );3816 $returnFiles[$ii]['size'] = $_attachment['size'];3817 $ii++;3818 }3819 else if($_attachment[2])3820 {3821 $returnFiles[$ii]['name'] = base64_encode(mb_convert_encoding( $_attachment[2], 'UTF-8', 'UTF-8, ISO-8859-1'));3822 $returnFiles[$ii]['size'] = $_attachment[5];3823 $ii++;3824 }3825 }3826 }3827 $return['files'] = serialize($returnFiles);3828 $return["subject"] = $params['input_subject'];3829 if (!$return['append']) $return['append'] = imap_last_error();3830 3831 return $return;3832 }3833 3834 3449 3835 3450 function set_messages_flag_from_search($params){
Note: See TracChangeset
for help on using the changeset viewer.