/**
     * Brightcove - Send error notification by mail
     */
    static function bcSendMail()
    {
        $args = func_get_args();
        if( !empty($args[0]) && isset( $args[0]['id'] ) && isset( $args[0]['job'] ) )
        {
            $id = $args[0]['id'];

            $eZBrightcoveObject = eZBrightcoveObject::fetch( array( 'id' => $id ) );
            if( $eZBrightcoveObject instanceof eZBrightcoveObject )
            {
                $siteIni = eZINI::instance( 'site.ini' );
                $to = $siteIni->variable( 'EventManager', 'Mail' );

                $job = $args[0]['job'];
                $subject = 'Brightcove - Error on '.$job.' job';
                $message = 'Error on eZBrightcove '.$job.' job'.'<br/><br/>'.
                           'Brightcove ID : '.$eZBrightcoveObject->attribute( 'brightcove_id' ).'<br/>'.
                           'ErrorLog : '.$eZBrightcoveObject->attribute( 'error_log' ).'<br/>';
                $from = eZINI::instance()->variable('MailSettings', 'EmailSender');

                //Send mail
                $email = new MailTool( $subject, $from, $to, $message, 'mmeventmanager.log');
                $email->sendMail();
            }
        }
    }
    /**
     * Form submission handler for sending sms
     * @return mixed
     */
    public function sm()
    {
        $subject = "Demande d'article full text - centre de doc msd";
        $message = $this->prepareMessageText();

        $email = new MailTool( $subject, $this->fromEmail, $this->toEmail, $message, 'mmfulltext_email.log');
        return $email->sendMail();
    }
    /**
     * Form submission handler for sending sms
     *
     * @return bool
     */
    public function sm()
    {
        $http = BlockDefault::http();
        $researchType = $http->hasPostVariable( 'typeOfResearch' ) ? stripslashes( $http->postVariable( 'typeOfResearch' ) ) : '';
        if(!empty($researchType)){
            $this->researchType = $researchType;
            $this->recipientEmail = SolrSafeOperatorHelper::getCustomParameter($this->applicationObject->identifier, $this->researchType, 'application');
        }

        if(empty($this->senderEmail) || empty($this->recipientEmail)){
            return false;
        }

        $message = $this->prepareMessageText();
        $mailObject = $this->prepareMailObjectText();

        $email = new MailTool( $mailObject, $this->senderEmail, $this->recipientEmail, $message, self::DOC_REQUEST_LOG_NAME);
        return $email->sendMail();

        return $sendStatus;
    }
    /**
     * Sends an alert if necessary for quarentaines
     */
    protected function sendAlert()
    {
        if ( count($this->quarantaineFiles) > 0 )
        {
            $envArray    = array(
                ContextTool::ENVIRONMENT_DEV => "dev",
                ContextTool::ENVIRONMENT_STAGING => "stg",
                ContextTool::ENVIRONMENT_PROD => "prod",
            );
            $environment = ContextTool::instance()->environment();
            $subject     = "[MERCK-IMPORT][{$envArray[$environment]}] Article putted on quarantaine";
            $from        = eZINI::instance()->variable('MailSettings', 'EmailSender');
            $to          = array(XMLImportMonitor::EMAIL_LIST);
            $body        = "Hello,\n\nthe following article has reached the maximum of import attempts and has been putted on quarantaine :\n%s\n\nRegards,\nAdministrator";
            $body        = sprintf($body, $this->implodeQuarentaineText());

            if ( $envArray[$environment] == "prod" )
                $to[] = '*****@*****.**';

            $email = new MailTool( $subject, $from, $to, $body, 'import_monitoring_email.log');
            $email->sendMail();
        }
    }
    public function run()
    {
        $articles = NewRelicImportMonitoring::getNonVisibleArticles();
        if( $articles )
        {
            foreach( $articles as $article )
            {
                $this->article = $article;
                $this->keyword = $this->article->attribute( 'article_title' );
                if( ( time() - (int)$this->article->attribute( 'date_insert' ) ) > self::MAX_IMPORT_TIME )
                {
                    // Article still not visible, will be reported to New Relic
                    $this->article->setAttribute( 'new_relic_report', 1 );
                    $this->article->store();

                    $this->expiredArticles[] = $this->keyword;
                }
                else
                {
                    if( is_null( $this->article->attribute( 'date_front' ) ) )
                        $this->searchInFront();

                    if( is_null( $this->article->attribute( 'date_newsletter' ) ) )
                        $this->searchInNewsletter();
                }
            }
            if( count( $this->expiredArticles ) > 0 )
            {
                $this->reportToNewRelic( $this->newRelicMetricName, count( $this->expiredArticles ) );

                // Alert email
                $to = $this->emailReceiver;
                $from = eZINI::instance()->variable('MailSettings', 'EmailSender');
                $subject = '[MERCK] Import monitoring';

                $message = '<p>The following test articles were uploaded to FTP more than 2 hours ago and are still not visible on front and/or newsletter:</p><ul>';
                foreach( $this->expiredArticles as $a )
                    $message .= "<li>$a</li>";
                $message .= '</ul>';

                $email = new MailTool( $subject, $from, $to, $message, 'new_relic_import_monitoring_email.log');
                $email->sendMail();
            }
        }
        else
        {
            $lastInjectedArticle = NewRelicImportMonitoring::getLastInjectedArticle();
            if( $lastInjectedArticle )
            {
                if( ( time() - (int)$lastInjectedArticle->attribute( 'date_insert' ) ) > self::NEW_ARTICLE_SEND_TIME )
                {
                    $this->uploadXMLtoFTP( $this->simpleArticleFileName, self::SIMPLE_ARTICLE );
                    $this->uploadXMLtoFTP( $this->complexArticleFileName, self::COMPLEX_ARTICLE );
                }
            }
        }
    }
    /**
     * Sends email with summary.
     *
     * @param string $emailBody
     * @return "eZMailTransport::send status"
     */
    public static function sendEmail( $emailBody = "" )
    {
        $subject = "[" . date('ymd') . "] New PDF Tracking Available" ;
        $message = "Hello,

New PDF Tracking File is available on the FTP.
{$emailBody}
Regards,
";
        $to = array(
            '*****@*****.**',
            '*****@*****.**',
            '*****@*****.**',
        );
        $from = eZINI::instance()->variable('MailSettings', 'EmailSender');

        $email = new MailTool( $subject, $from, $to, $message, 'mmtrackingpdf_email.log');
        return $email->sendMail();
    }
    if ( $messageReport == '' )
    {
        $message = 'No import today';
    }
    else
    {
        if ( count ($csvMessages) > 0 )
        {
            $now = date('Ymd');
            $messageReport.= "\n<a href='http://www.30.merck.recette.kaliop.net/var/log/import/report_$now.csv'>Full error/warning report</a>";
        }
        else
        {
            $messageReport.= "\nNo error or warning reported";
        }

        $message = str_replace("\n", "<br />", $messageReport);
    }

    $email = new MailTool( $subject, $from, $eMailRecipients, $message, "output_log_email.log");
    $email->sendMail();
}
elseif ( !isset($cronMode) )
{
    echo $messageReport;
    echo 'Memory Peak Usage : ' . round( memory_get_peak_usage(true)/1024/1024, 2 ) . "M\n";
}

$script->shutdown( 0 );
                    ? json_decode( file_get_contents($previousEntriesFile), true )
                    : array();

foreach ( $previousEntries as $date => $row )
{
    if ( ( time() - strtotime($date) ) <= $alertPeriod )
    {
        if ( ( $retriesCount - $row['retriesCount'] ) >= $alertThreshold )
        {
            // Alert!!!
            $to = '*****@*****.**';
            $from = eZINI::instance()->variable('MailSettings', 'EmailSender');
            $subject = '[' . ContextTool::instance()->environment() . '] Solr Pending list Alert!! Threshold reached for index errors';
            $message = ( $retriesCount - $row['retriesCount'] ) . " objects failed to index within the last " . $alertPeriod . " seconds";

            $email = new MailTool( $subject, $from, $to, $message, 'solrpendingmonitor_email.log');
            return $email->sendMail();
        }
    }
    else
    {
        unset( $previousEntries[$date] );
    }
}


$previousEntries[date('Y-m-d H:i:s')] = array(
    'retriesCount'  => $retriesCount,
    'retriesMin'    => $retriesMin,
    'retriesMax'    => $retriesMax
);
$fileName = 'emails.csv';
if ( isset( $options['csvFileName'] ) ) {
    $fileName = $options['csvFileName'];
}

$script->startup();
$script->initialize();

//[0]Date,[1]Subject,"[2]From email","[3]To email",[4]Message,"[5]Send status"
if (($fp = fopen("emails.csv", "r")) !== FALSE) {
    $cli->output( 'Sending emails in batch of 10.' );
    $i=0;
    while (($email = fgetcsv($fp)) !== FALSE) {
        //Send mail
        if ( ($i % 10) == 0 ) {
            $cli->output("Send {$i} emails.");
            sleep( 2 );
        }
        $subject = $email[1] . ' - Unsend email from ' . $email[0];
        $sender = $email[2];
        $recipient = $email[3];
        $message = $email[4];
        $email = new MailTool( $subject, $sender, $recipient, $message, 'mailing_script.log');
        $cli->output( 'Send status: ' . $email->sendMail() );
        $i++;
    }
    fclose($fp);
}

$script->shutdown( 0 );
    /**
     * Form submission handler for sending sms
     * @return array
     */
    public function sm()
    {
        $subject = ezpI18n::tr( 'application/contactus', 'MAIL SUBJECT' );
        $message = $this->prepareMessageText();

        if (SolrSafeOperatorHelper::featureIsActive('ContactForm') && SolrSafeOperatorHelper::feature('ContactForm', 'AnonymousPrivacyPolicyCheckbox') && MMUsers::getCurrentUserObject() == null)
        {
            if (!isset($_POST['Privacy_policy'])) {
                return array(
                    'error' => 1,
                );
            }
        }

        if ($this->shouldAppendCountryOfRegistration())
        {
            $prefix = !empty($_POST['countryOfResidence']) ? '[' . $_POST['countryOfResidence'] . ']' : '';
            $subject = "{$prefix} " . $subject;
        }

        //Send mail
        $emailTool = new MailTool( $subject, $this->fromEmail, $this->toEmail, $message, self::CONTACTUS_LOG_NAME );
        $emailTool->sendMail();

        return array(
            'redirect_url' => $this->redirectUrl
        );
    }
    /**
     * @return array
     */
    public function stc()
    {
        if( !self::user() ) {
            return false;
        }
        $http = BlockDefault::http();

        //get current user infos
        $serviceUser = ServiceUser::getInstance();
        $parameters = $serviceUser->getFormParameters();
        $userInfos = $serviceUser->callWSHandler( $serviceUser->getEsbInterface( 'read' ), $parameters );

        $appname = $http->hasPostVariable( 'appname' ) ? stripslashes( $http->postVariable( 'appname' ) ) : '';

        $sender = $userInfos['Data']['Params']['Firstname'] . $userInfos['Data']['Params']['Lastname'];
        $senderName = $userInfos['Data']['Params']['Firstname'] . $userInfos['Data']['Params']['Lastname'];
        $senderEmail = $userInfos['Data']['Params']['Email_address'];

        //get comment

        if(!$http->hasPostVariable( 'token' ) || !SecurityTool::isUserTokenValid($http->postVariable( 'token' )))
        {
            return array(
                'Error' =>  'Invalid token',
            );
        }

        $message = $http->hasPostVariable( 'comment' ) ? stripslashes( $http->postVariable( 'comment' ) ) : '';

        //get recipient email
        $recipient = $http->hasPostVariable( 'Recipient_email' ) ? stripslashes( preg_replace( '/\s/', '', $http->postVariable( 'Recipient_email' ) ) ) : '';
        $recipients = array_unique( explode( ';', $recipient ) );

        //get Article nodeID
        $extract = $title = '';
        $articleRemoteID = $http->hasPostVariable( 'remote_id' ) ? $http->postVariable( 'remote_id' ) : null;
        if(!is_null($articleRemoteID))
        {
            $fieldsQuery = array (
                '(meta_remote_id_ms:' . $articleRemoteID . ')',
                '(meta_class_identifier_ms:article)'
            );

            $fields = array (
                'attr_promo_description_t',
                'attr_headline_t',
            );

            //fetch solr
            $params = array(
                'indent'        => 'on',
                'q'             => '*:*',
                'start'         => 0,
                'rows'          => 1,
                'fq'            => implode(' AND ', $fieldsQuery),
                'fl'            => implode(',', $fields),
                'qt'            => '',
                'explainOther'  => '',
                'hl.fl'         => '',
            );

            $raw = SolrTool::rawSearch($params);
            $article = $raw['response']['docs'][0];

            if(strlen($article['attr_promo_description_t']) > 150)
            {
                $extract = mb_substr($article['attr_promo_description_t'], 0, 150, 'utf-8') . '...';
            }
            else
            {
                $extract = $article['attr_promo_description_t'];
            }

            $title = $article['attr_headline_t'];
        }

        $destUrl = $http->hasPostVariable( 'destURL' ) ? stripslashes( filter_var($http->postVariable( 'destURL' ), FILTER_VALIDATE_URL) ) : '';

        $preparedMessage = $this->prepareMessage( $sender, htmlentities( $message ), $extract, $destUrl );

        if( SolrSafeOperatorHelper::featureIsActive( 'ExactTarget' ) && SolrSafeOperatorHelper::featureIsActive( 'UUMP' ) )
        {
            $message = nl2br($message);
            
            foreach( $recipients as $recipient )
            {
                ExactTarget::sendToAColleague(
                    self::user()->attribute( 'uuid' ),
                    $recipient,
                    $message,
                    $appname,
                    $destUrl,
                    $extract,
                    $title
                );
            }
        }
        else
        {
            // Below code is no longer used, since all clusters are using ExactTarget feature.
            $email = new MailTool( $title, $senderName, array(), $preparedMessage, 'sendtocolleague_email.log');
            foreach ( $recipients as $recipient )
            {
                $to = filter_var( $recipient, FILTER_VALIDATE_EMAIL );
                if ( $to === false ) {
                    continue;
                }
                $email->setRecipients( $to );
                $email->sendMail();
            }
        }

        return array(
            'redirect_url' => $this->redirectUrl
        );
    }