Author: Chris Corbyn
Inheritance: extends Swift_EmbeddedFile
 protected function embed($path)
 {
     if (!$path instanceof Swift_Image) {
         $path = Swift_Image::fromPath($path);
     }
     return $this->message->embed($path);
 }
 /**
  * @param string $templateName
  * @param array  $context
  * @param string $fromEmail
  * @param string $toEmail
  */
 protected function sendMessage($templateName, $context, $fromEmail, $toEmail)
 {
     //new instance
     $message = \Swift_Message::newInstance();
     $context = $this->twig->mergeGlobals($context);
     //merge context
     $template = $this->twig->loadTemplate($templateName);
     //espacio para agregar imágenes
     $context['image_src'] = $message->embed(\Swift_Image::fromPath('images/email_header.png'));
     //attach image 1
     $context['fb_image'] = $message->embed(\Swift_Image::fromPath('images/fb.gif'));
     //attach image 2
     $context['tw_image'] = $message->embed(\Swift_Image::fromPath('images/tw.gif'));
     //attach image 3
     $context['right_image'] = $message->embed(\Swift_Image::fromPath('images/right.gif'));
     //attach image 4
     $context['left_image'] = $message->embed(\Swift_Image::fromPath('images/left.gif'));
     //attach image 5
     $subject = $template->renderBlock('subject', $context);
     $textBody = $template->renderBlock('body_text', $context);
     $htmlBody = $template->renderBlock('body_html', $context);
     $message->setSubject($subject)->setFrom($fromEmail)->setTo($toEmail);
     if (!empty($htmlBody)) {
         $message->setBody($htmlBody, 'text/html')->addPart($textBody, 'text/plain');
     } else {
         $message->setBody($textBody);
     }
     $this->mailer->send($message);
 }
 /**
  * Inserts images without using getTemplate.
  *
  * @param string $message
  * @param string $content
  *
  * @return mixed
  */
 public function insertImages($message, $content)
 {
     foreach ($this->images as $name => $image_path) {
         $image_embed = $message->embed(\Swift_Image::fromPath($image_path));
         $content = str_replace(rawurlencode('{{ ' . $name . ' }}'), $image_embed, $content);
     }
     return $content;
 }
Beispiel #4
0
 /**
  *
  * @return RedirectResponse|Response
  */
 public function postAction()
 {
     $urlFrom = $this->getReferer();
     if (null == $urlFrom || trim($urlFrom) == '') {
         $urlFrom = $this->generateUrl('_front_devis');
     }
     $devisNewForm = $this->createForm(DevisNewTForm::class);
     $request = $this->getRequest();
     $reqData = $request->request->all();
     if (isset($reqData['DevisNewForm'])) {
         $devisNewForm->handleRequest($request);
         if ($devisNewForm->isValid()) {
             $from = $this->getParameter('mail_from');
             $fromName = $this->getParameter('mail_from_name');
             $subject = $this->translate('_mail.devis.subject', array(), 'messages');
             $mvars = array();
             $mvars['firstname'] = $devisNewForm['firstname']->getData();
             $mvars['lastname'] = $devisNewForm['lastname']->getData();
             $mvars['email'] = $devisNewForm['email']->getData();
             $mvars['phone'] = $devisNewForm['phone']->getData();
             $mvars['entreprise'] = $devisNewForm['entreprise']->getData();
             $mvars['entrepriseForm'] = $devisNewForm['entrepriseForm']->getData();
             $mvars['activity'] = $devisNewForm['activity']->getData();
             $mvars['dtActivation'] = $devisNewForm['dtActivation']->getData();
             $mvars['address'] = $devisNewForm['address']->getData();
             $mvars['zipCode'] = $devisNewForm['zipCode']->getData();
             $mvars['town'] = $devisNewForm['town']->getData();
             $mvars['caYear'] = $devisNewForm['caYear']->getData();
             $mvars['nbrInvoicesBuy'] = $devisNewForm['nbrInvoicesBuy']->getData();
             $mvars['nbrInvoicesSale'] = $devisNewForm['nbrInvoicesSale']->getData();
             $mvars['nbrSalaries'] = $devisNewForm['nbrSalaries']->getData();
             $mvars['hasexpert'] = $devisNewForm['hasexpert']->getData();
             $mvars['otherInfos'] = $devisNewForm['otherInfos']->getData();
             try {
                 $admins = $this->getParameter('mailtos');
                 $message = \Swift_Message::newInstance()->setFrom($from, $fromName);
                 foreach ($admins as $admin) {
                     $message->addTo($admin['email'], $admin['name']);
                     $message->setReplyTo($mvars['email'], $mvars['lastname'] . ' ' . $mvars['firstname']);
                 }
                 $message->setSubject($subject);
                 $mvars['logo'] = $message->embed(\Swift_Image::fromPath($this->getParameter('kernel.root_dir') . '/../web/bundles/acfres/images/logo_acf.jpg'));
                 $message->setBody($this->renderView('AcfFrontBundle:Mail:devis.html.twig', $mvars), 'text/html');
                 $this->sendmail($message);
             } catch (\Exception $e) {
                 $logger = $this->getLogger();
                 $logger->addError($e->getMessage());
             }
             $this->flashMsgSession('success', $this->translate('_front.devis.success'));
             return $this->redirect($this->generateUrl('_front_devis'));
         } else {
             $this->gvars['DevisNewForm'] = $devisNewForm->createView();
             $this->flashMsgSession('error', $this->translate('_front.devis.error'));
             return $this->renderResponse('AcfFrontBundle:Default:devis.html.twig', $this->gvars);
         }
     }
     return $this->redirect($urlFrom);
 }
Beispiel #5
0
 /**
  * @param \Swift_Message $messageInstance
  * @param $contentHtml
  * @param array $embeddedImages
  *
  * @return mixed
  */
 protected function _embedContentImages(\Swift_Message $messageInstance, $contentHtml, array $embeddedImages)
 {
     if ($embeddedImages !== NULL) {
         foreach ($embeddedImages as $stackIndex => $pathImage) {
             $cid = $messageInstance->embed(\Swift_Image::fromPath($pathImage));
             $contentHtml = str_replace('{{imageStackIndex:' . $stackIndex . '}}', $cid, $contentHtml);
         }
     }
     return $contentHtml;
 }
 /**
  * Embed the image in message and replace the image link by attachment id.
  *
  * @param \Swift_Message $message The swift mailer message
  * @param \DOMAttr       $node    The dom attribute of image
  * @param array          $images  The map of image ids passed by reference
  */
 protected function embedImage(\Swift_Message $message, \DOMAttr $node, array &$images)
 {
     if (0 === strpos($node->nodeValue, 'cid:')) {
         return;
     }
     if (isset($images[$node->nodeValue])) {
         $node->nodeValue = $images[$node->nodeValue];
     } else {
         $node->nodeValue = EmbedImageUtil::getLocalPath($node->nodeValue, $this->webDir, $this->hostPattern);
         $cid = $message->embed(\Swift_Image::fromPath($node->nodeValue));
         $images[$node->nodeValue] = $cid;
         $node->nodeValue = $cid;
     }
 }
Beispiel #7
0
 public static function sendMail($name, $email, $template)
 {
     $message = Swift_Message::newInstance()->setSubject($template->getSubject())->setFrom(array('*****@*****.**' => 'Dahlen'))->setTo(array($email => $name));
     $imageMatches = array();
     $html = $template->getHTML();
     if (preg_match_all('/<img.*?src="(.*?)".*?\\/>/', $html, $imageMatches, PREG_PATTERN_ORDER) > 0) {
         foreach ($imageMatches[0] as $index => $fullMatch) {
             $html = str_replace($imageMatches[1][$index], $message->embed(Swift_Image::fromPath(str_replace('http://' . $_SERVER['SERVER_NAME'], ROOT_DIR, $imageMatches[1][$index]), $html)), $html);
         }
     }
     $message->setBody($html, 'text/html')->addPart($template->getPlainText(), 'text/plain');
     $transport = Swift_SmtpTransport::newInstance(self::$SMTP_SERVER, 25)->setUsername(self::$USERNAME)->setPassword(self::$PASSWORD);
     $mailer = Swift_Mailer::newInstance($transport);
     return $mailer->send($message);
 }
 public function envoyerMailTousLesAbonnes(Notification $notif)
 {
     //On récupère tous les abonnés en base de donnée
     $abonnes = $this->repo->findAll();
     //On construit le mail à envoyer (objet, corps du message, inclusion d'images)
     $objet = str_replace("{SUJET}", $notif->getSujet(), $this->mailSubject);
     $message = \Swift_Message::newInstance($objet);
     $urlLogoSopra = "http://localhost" . $this->container->get('templating.helper.assets')->getUrl('images/logo.png');
     $urlLogoSopra = $message->embed(\Swift_Image::fromPath($urlLogoSopra));
     $message->setFrom($this->mailSender)->setBody($this->templating->render('AbonnementBundle:Abonne:mail.html.twig', array("lien" => $notif->getLien(), "resume" => $notif->getResume(), "urlImage" => $urlLogoSopra)), 'text/html');
     //On envoie un mail à chaque abonné :
     foreach ($abonnes as $abonne) {
         $message->setTo($abonne->getMail());
         $this->mailer->send($message);
     }
 }
 public function testEmbeddedFilesWithMultipartDataCreateMultipartRelatedContentAsAnAlternative()
 {
     $message = Swift_Message::newInstance();
     $message->setCharset('utf-8');
     $message->setSubject('test subject');
     $message->addPart('plain part', 'text/plain');
     $image = Swift_Image::newInstance('<image data>', 'image.gif', 'image/gif');
     $cid = $message->embed($image);
     $message->setBody('<img src="' . $cid . '" />', 'text/html');
     $message->setTo(array('*****@*****.**' => 'User'));
     $message->setFrom(array('*****@*****.**' => 'Other'));
     $message->setSender(array('*****@*****.**' => 'Other'));
     $id = $message->getId();
     $date = preg_quote(date('r', $message->getDate()), '~');
     $boundary = $message->getBoundary();
     $cidVal = $image->getId();
     $this->assertRegExp('~^' . 'Sender: Other <*****@*****.**>' . "\r\n" . 'Message-ID: <' . $id . '>' . "\r\n" . 'Date: ' . $date . "\r\n" . 'Subject: test subject' . "\r\n" . 'From: Other <*****@*****.**>' . "\r\n" . 'To: User <*****@*****.**>' . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Type: multipart/alternative;' . "\r\n" . ' boundary="' . $boundary . '"' . "\r\n" . "\r\n\r\n" . '--' . $boundary . "\r\n" . 'Content-Type: text/plain; charset=utf-8' . "\r\n" . 'Content-Transfer-Encoding: quoted-printable' . "\r\n" . "\r\n" . 'plain part' . "\r\n\r\n" . '--' . $boundary . "\r\n" . 'Content-Type: multipart/related;' . "\r\n" . ' boundary="(.*?)"' . "\r\n" . "\r\n\r\n" . '--\\1' . "\r\n" . 'Content-Type: text/html; charset=utf-8' . "\r\n" . 'Content-Transfer-Encoding: quoted-printable' . "\r\n" . "\r\n" . '<img.*?/>' . "\r\n\r\n" . '--\\1' . "\r\n" . 'Content-Type: image/gif; name=image.gif' . "\r\n" . 'Content-Transfer-Encoding: base64' . "\r\n" . 'Content-Disposition: inline; filename=image.gif' . "\r\n" . 'Content-ID: <' . $cidVal . '>' . "\r\n" . "\r\n" . preg_quote(base64_encode('<image data>'), '~') . "\r\n\r\n" . '--\\1--' . "\r\n" . "\r\n\r\n" . '--' . $boundary . '--' . "\r\n" . '$~D', $message->toString());
 }
 public function rechazarAction($id)
 {
     //Enviar correo al estudiante
     $em = $this->getDoctrine()->getManager();
     $solicitud = $em->getRepository('EstudianteBundle:Solicitud')->find($id);
     $estudiante = $solicitud->getEstudiante();
     /*         * ********************Mail ****************************** */
     $message = \Swift_Message::newInstance('Solicitud Rechazada');
     $message->setFrom('*****@*****.**');
     $message->setTo($estudiante->getCorreo());
     $message->setBody('<html>' . ' <head> <img src="' . $message->embed(\Swift_Image::fromPath('images/logoHeader.png')) . '" /></head>' . ' <body>' . ' <br><br><br><span style="font-size:18px">Estimado estudiante, su solicitud a la sección ' . $solicitud->getSeccion()->getMateria()->getNombre() . '-' . $solicitud->getSeccion()->getCodigo() . ' ha sido rechazada por el profesor. </span> ' . ' </body>' . '<br><br><br><footer>EvaluaUcab Todos los derechos reservados</footer>' . '</html>', 'text/html');
     $this->get('mailer')->send($message);
     $solicitud->setStatus('Rechazada');
     /*         * ****************************************************** */
     $em->remove($solicitud);
     $em->flush();
     $this->getRequest()->getSession()->getFlashBag()->add('warning', '¡Solicitud Rechazada!');
     return $this->render('ProfesorBundle:Default:solicitudes.html.twig');
 }
 /**
  * @param Swift_Mime_Message $message
  * @param Swift_Mime_MimeEntity $part
  *
  * @return string
  */
 protected function embedImages(Swift_Mime_Message $message, Swift_Mime_MimeEntity $part = null)
 {
     $body = $part === null ? $message->getBody() : $part->getBody();
     $dom = new \DOMDocument('1.0');
     $dom->loadHTML($body);
     $images = $dom->getElementsByTagName('img');
     foreach ($images as $image) {
         $src = $image->getAttribute('src');
         /**
          * Prevent beforeSendPerformed called twice
          * see https://github.com/swiftmailer/swiftmailer/issues/139
          */
         if (strpos($src, 'cid:') === false) {
             $entity = \Swift_Image::fromPath($src);
             $message->setChildren(array_merge($message->getChildren(), [$entity]));
             $image->setAttribute('src', 'cid:' . $entity->getId());
         }
     }
     return $dom->saveHTML();
 }
Beispiel #12
0
 public function sendTemplateMail(SendTemplateMailCommand $command)
 {
     $message = \Swift_Message::newInstance();
     $ext = $command->format === 'text/html' ? 'html' : 'txt';
     $tplIdentifier = 'Email/' . $command->template . '.' . $ext;
     $template = $this->cr->getContent($tplIdentifier);
     $templateData = $command->templateData;
     if ($command->image !== null) {
         $templateData['image'] = $message->embed(\Swift_Image::fromPath($command->image));
     }
     // Subject
     $env = new \Twig_Environment(new \Twig_Loader_String());
     $subject = $template->getProperties()->containsKey('subject') ? $template->getProperties()->get('subject') : $this->mailFromName;
     $subject = $env->render($subject, $templateData);
     // Body
     $body = $this->templating->render('bcrm_content:' . $tplIdentifier, $templateData);
     $message->setCharset('UTF-8');
     $message->setFrom($this->mailFromEmail, $this->mailFromName)->setSubject($subject)->setTo($command->email)->setBody($body, $command->format);
     $this->mailer->send($message);
 }
 public function testEmbeddedImagesAreEmbedded()
 {
     $message = Swift_Message::newInstance()->setFrom('*****@*****.**')->setTo('*****@*****.**')->setSubject('test');
     $cid = $message->embed(Swift_Image::fromPath(__DIR__ . '/../../_samples/files/swiftmailer.png'));
     $message->setBody('<img src="' . $cid . '" />', 'text/html');
     $that = $this;
     $messageValidation = function (Swift_Mime_Message $message) use($that) {
         preg_match('/cid:(.*)"/', $message->toString(), $matches);
         $cid = $matches[1];
         preg_match('/Content-ID: <(.*)>/', $message->toString(), $matches);
         $contentId = $matches[1];
         $that->assertEquals($cid, $contentId, 'cid in body and mime part Content-ID differ');
         return true;
     };
     $failedRecipients = array();
     $transport = m::mock('Swift_Transport');
     $transport->shouldReceive('isStarted')->andReturn(true);
     $transport->shouldReceive('send')->with(m::on($messageValidation), $failedRecipients)->andReturn(1);
     $memorySpool = new Swift_MemorySpool();
     $memorySpool->queueMessage($message);
     $memorySpool->flushQueue($transport, $failedRecipients);
 }
 /**
  * {@inheritdoc)
  */
 public function transform(\Swift_Mime_Message $message)
 {
     $body = $message->getBody();
     $body = preg_replace_callback('/(src|background)="(http[^"]*)"/', function ($matches) use($message) {
         $attribute = $matches[1];
         $imagePath = $matches[2];
         if ($fp = fopen($imagePath, "r")) {
             $imagePath = $message->embed(\Swift_Image::fromPath($imagePath));
             fclose($fp);
         }
         return sprintf('%s="%s"', $attribute, $imagePath);
     }, $body);
     $body = preg_replace_callback('/url\\((http[^"]*)\\)/', function ($matches) use($message) {
         $imagePath = $matches[1];
         if ($fp = fopen($imagePath, "r")) {
             $imagePath = $message->embed(\Swift_Image::fromPath($imagePath));
             fclose($fp);
         }
         return sprintf('url(%s)', $imagePath);
     }, $body);
     $message->setBody($body, 'text/html');
 }
 function sendMail($smtp_server, $to, $from, $subject, $body, $cc, $bcc, $attachments = null, $smtp_port = 25, $smtp_username = null, $smtp_password = '', $type = 'text/plain', $transport = 0, $message_id = null, $in_reply_to = null, $inline_images = null, &$complete_mail, $att_version)
 {
     //Load in the files we'll need
     Env::useLibrary('swift');
     try {
         $mail_transport = Swift_SmtpTransport::newInstance($smtp_server, $smtp_port, $transport);
         $smtp_authenticate = $smtp_username != null;
         if ($smtp_authenticate) {
             $mail_transport->setUsername($smtp_username);
             $mail_transport->setPassword(self::ENCRYPT_DECRYPT($smtp_password));
         }
         $mailer = Swift_Mailer::newInstance($mail_transport);
         // init Swift logger
         if (defined('LOG_SWIFT') && LOG_SWIFT > 0) {
             $swift_logger = new Swift_Plugins_Loggers_ArrayLogger();
             $mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($swift_logger));
             $swift_logger_level = LOG_SWIFT;
             // 0: no log, 1: log only errors, 2: log everything
         } else {
             $swift_logger_level = 0;
         }
         if (is_string($from)) {
             $pos = strrpos($from, "<");
             if ($pos !== false) {
                 $sender_name = trim(substr($from, 0, $pos));
                 $sender_address = str_replace(array("<", ">"), array("", ""), trim(substr($from, $pos, strlen($from) - 1)));
             } else {
                 $sender_name = "";
                 $sender_address = $from;
             }
             $from = array($sender_address => $sender_name);
         }
         //Create a message
         $message = Swift_Message::newInstance($subject)->setFrom($from)->setContentType($type);
         $to = self::prepareEmailAddresses($to);
         $cc = self::prepareEmailAddresses($cc);
         $bcc = self::prepareEmailAddresses($bcc);
         foreach ($to as $address) {
             $message->addTo(array_var($address, 0), array_var($address, 1, ""));
         }
         foreach ($cc as $address) {
             $message->addCc(array_var($address, 0), array_var($address, 1, ""));
         }
         foreach ($bcc as $address) {
             $message->addBcc(array_var($address, 0), array_var($address, 1, ""));
         }
         if ($in_reply_to) {
             if (str_starts_with($in_reply_to, "<")) {
                 $in_reply_to = substr($in_reply_to, 1, -1);
             }
             $validator = new SwiftHeaderValidator();
             if ($validator->validate_id_header_value($in_reply_to)) {
                 $message->getHeaders()->addIdHeader("In-Reply-To", $in_reply_to);
             }
         }
         if ($message_id) {
             if (str_starts_with($message_id, "<")) {
                 $message_id = substr($message_id, 1, -1);
             }
             $message->setId($message_id);
         }
         // add attachments
         if (is_array($attachments)) {
             foreach ($attachments as $att) {
                 if ($att_version < 2) {
                     $swift_att = Swift_Attachment::newInstance($att["data"], $att["name"], $att["type"]);
                 } else {
                     $swift_att = Swift_Attachment::fromPath($att['path'], $att['type']);
                     $swift_att->setFilename($att["name"]);
                 }
                 if (substr($att['name'], -4) == '.eml') {
                     $swift_att->setEncoder(Swift_Encoding::get7BitEncoding());
                     $swift_att->setContentType('message/rfc822');
                 }
                 $message->attach($swift_att);
             }
         }
         // add inline images
         if (is_array($inline_images)) {
             foreach ($inline_images as $image_url => $image_path) {
                 $cid = $message->embed(Swift_Image::fromPath($image_path));
                 $body = str_replace($image_url, $cid, $body);
             }
         }
         self::adjustBody($message, $type, $body);
         $message->setBody($body);
         //Send the message
         $complete_mail = self::retrieve_original_mail_code($message);
         $result = $mailer->send($message);
         if ($swift_logger_level >= 2 || $swift_logger_level > 0 && !$result) {
             file_put_contents(CACHE_DIR . "/swift_log.txt", "\n" . gmdate("Y-m-d H:i:s") . " DEBUG:\n" . $swift_logger->dump() . "----------------------------------------------------------------------------", FILE_APPEND);
             $swift_logger->clear();
         }
         return $result;
     } catch (Exception $e) {
         Logger::log("ERROR SENDING EMAIL: " . $e->getTraceAsString(), Logger::ERROR);
         //if there is an error with the connection, let the user know about it
         $mail_error = $e->getMessage();
         $mail_error = stristr($mail_error, 'Log data:', true);
         flash_error(lang('mail not sent') . " '" . $mail_error . "'");
         if ($swift_logger_level > 0) {
             $dump = $swift_logger->dump();
             if ($dump != '') {
                 file_put_contents(CACHE_DIR . "/swift_log.txt", "\n" . gmdate("Y-m-d H:i:s") . " DEBUG:\n" . $dump . "----------------------------------------------------------------------------", FILE_APPEND);
                 $swift_logger->clear();
             }
         }
         throw $e;
     }
 }
function attachImagesToMessageAndSetBody(&$message, $body)
{
    $imagesInMessage = getImagesInMessage($body);
    foreach ($imagesInMessage as $imageUrl) {
        try {
            $cid = $message->embed(Swift_Image::fromPath($imageUrl));
            $body = str_replace($imageUrl, $cid, $body);
        } catch (Exception $exp) {
        }
    }
    $message->setBody($body, 'text/html');
}
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::NewInstance()->setSubject(__("Recent Data Center Installations Report"));
// Set from address
try {
    $message->setFrom($config->ParameterArray['MailFromAddr']);
} catch (Swift_RfcComplianceException $e) {
    $error .= __("MailFrom") . ": <span class=\"errmsg\">" . $e->getMessage() . "</span><br>\n";
}
// Add data center team to the list of recipients
try {
    $message->addTo($config->ParameterArray['FacMgrMail']);
} catch (Swift_RfcComplianceException $e) {
    $error .= __("Facility Manager email address") . ": <span class=\"errmsg\">" . $e->getMessage() . "</span><br>\n";
}
$logo = getcwd() . '/images/' . $config->ParameterArray["PDFLogoFile"];
$logo = $message->embed(Swift_Image::fromPath($logo)->setFilename('logo.png'));
$htmlMessage = sprintf("<!doctype html><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><meta http-equiv=\"CACHE-CONTROL\" content=\"NO-CACHE\"><meta http-equiv=\"expires\" content=\"Mon, 01 Jan 1997 01:00:00 GMT\"><meta http-equiv=\"PRAGMA\" content=\"NO-CACHE\"><title>ITS Data Center Inventory</title></head><body><div id=\"header\" style=\"padding: 5px 0;background: %s;\"><center><img src=\"%s\"></center></div><div class=\"page\"><p><h3>Installations in the Past 7 Days</h3>\n", $config->ParameterArray["HeaderColor"], $logo);
$htmlMessage .= sprintf("<p>The following systems have been entered into openDCIM, with an Install Date set to within the past %d days.  Please review these entries to determine if follow-up documentation is required.</p>", $config->ParameterArray["NewInstallsPeriod"]);
if (sizeof($devList) == 0) {
    $htmlMessage .= "<p>There are no recorded installations within the date range specified.</p>\n";
} else {
    $cab = new Cabinet();
    $dc = new DataCenter();
    $dept = new Department();
    $htmlMessage .= "<table>\n<tr><th>Installed Date</th><th>Reserved</th><th>Data Center</th><th>Location</th><th>Label</th><th>Owner</th></tr>\n";
    foreach ($devList as $devRow) {
        $cab->CabinetID = $devRow->Cabinet;
        $cab->GetCabinet();
        $dc->DataCenterID = $cab->DataCenterID;
        $dc->GetDataCenter();
        $dept->DeptID = $devRow->Owner;
Beispiel #18
0
 /**
  * Embed an image
  *
  * @param   string  image path
  * @return  Embedded image
  */
 public function embed($image_path)
 {
     return $this->_message->embed(Swift_Image::fromPath($image_path));
 }
 /**
  *
  * @param string $uid
  * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
  */
 public function editPostAction($uid)
 {
     $urlFrom = $this->getReferer();
     if (null == $urlFrom || trim($urlFrom) == '') {
         $urlFrom = $this->generateUrl('_admin_company_list');
     }
     $em = $this->getEntityManager();
     try {
         $customer = $em->getRepository('AcfDataBundle:Customer')->find($uid);
         if (null == $customer) {
             $this->flashMsgSession('warning', $this->translate('Customer.edit.notfound'));
         } else {
             $traces = $em->getRepository('AcfDataBundle:Trace')->getAllByEntityId($customer->getId(), Trace::AE_CUSTOMER);
             $this->gvars['traces'] = array_reverse($traces);
             $customerUpdateForm = $this->createForm(CustomerUpdateTForm::class, $customer);
             $customerUpdateDocsForm = $this->createForm(CustomerUpdateDocsTForm::class, $customer, array('company' => $customer->getCompany()));
             $doc = new Doc();
             $doc->setCompany($customer->getCompany());
             $docNewForm = $this->createForm(DocNewTForm::class, $doc, array('company' => $customer->getCompany()));
             $this->gvars['tabActive'] = $this->getSession()->get('tabActive', 2);
             $this->getSession()->remove('tabActive');
             $this->gvars['stabActive'] = $this->getSession()->get('stabActive', 1);
             $this->getSession()->remove('stabActive');
             $request = $this->getRequest();
             $reqData = $request->request->all();
             $cloneCustomer = clone $customer;
             if (isset($reqData['CustomerUpdateForm'])) {
                 $this->gvars['tabActive'] = 2;
                 $this->getSession()->set('tabActive', 2);
                 $customerUpdateForm->handleRequest($request);
                 if ($customerUpdateForm->isValid()) {
                     $em->persist($customer);
                     $em->flush();
                     $this->flashMsgSession('success', $this->translate('Customer.edit.success', array('%customer%' => $customer->getLabel())));
                     $this->traceEntity($cloneCustomer, $customer);
                     return $this->redirect($urlFrom);
                 } else {
                     $em->refresh($customer);
                     $this->flashMsgSession('error', $this->translate('Customer.edit.failure', array('%customer%' => $customer->getLabel())));
                 }
             } elseif (isset($reqData['DocNewForm'])) {
                 $this->gvars['tabActive'] = 3;
                 $this->getSession()->set('tabActive', 3);
                 $this->gvars['stabActive'] = 1;
                 $this->getSession()->set('stabActive', 1);
                 $docNewForm->handleRequest($request);
                 if ($docNewForm->isValid()) {
                     $docs = array();
                     $docFiles = $docNewForm['fileName']->getData();
                     $docDir = $this->getParameter('kernel.root_dir') . '/../web/res/docs';
                     $docNames = '';
                     foreach ($docFiles as $docFile) {
                         $originalName = $docFile->getClientOriginalName();
                         $fileName = sha1(uniqid(mt_rand(), true)) . '.' . strtolower($docFile->getClientOriginalExtension());
                         $mimeType = $docFile->getMimeType();
                         $docFile->move($docDir, $fileName);
                         $size = filesize($docDir . '/' . $fileName);
                         $md5 = md5_file($docDir . '/' . $fileName);
                         $doc = new Doc();
                         $doc->setCompany($customer->getCompany());
                         $doc->setFileName($fileName);
                         $doc->setOriginalName($originalName);
                         $doc->setSize($size);
                         $doc->setMimeType($mimeType);
                         $doc->setMd5($md5);
                         $doc->setDescription($docNewForm['description']->getData());
                         $em->persist($doc);
                         $customer->addDoc($doc);
                         $docNames .= $doc->getOriginalName() . ' ';
                         $docs[] = $doc;
                     }
                     $em->persist($customer);
                     $em->flush();
                     $this->flashMsgSession('success', $this->translate('Doc.add.success', array('%doc%' => $docNames)));
                     $from = $this->getParameter('mail_from');
                     $fromName = $this->getParameter('mail_from_name');
                     $subject = $this->translate('_mail.newdocsCloud.subject', array(), 'messages');
                     $company = $customer->getCompany();
                     $acfCloudRole = $em->getRepository('AcfDataBundle:Role')->findOneBy(array('name' => 'ROLE_CLIENT1'));
                     $users = array();
                     foreach ($company->getUsers() as $user) {
                         if ($user->hasRole($acfCloudRole)) {
                             $users[] = $user;
                         }
                     }
                     if (\count($users) != 0) {
                         foreach ($users as $user) {
                             $mvars = array();
                             $mvars['company'] = $company;
                             $mvars['docs'] = $docs;
                             $message = \Swift_Message::newInstance();
                             $message->setFrom($from, $fromName);
                             $message->addTo($user->getEmail(), $user->getFullname());
                             $message->setSubject($subject);
                             $mvars['logo'] = $message->embed(\Swift_Image::fromPath($this->getParameter('kernel.root_dir') . '/../web/bundles/acfres/images/logo_acf.jpg'));
                             $message->setBody($this->renderView('AcfAdminBundle:Doc:sendmail.html.twig', $mvars), 'text/html');
                             $this->sendmail($message);
                         }
                     }
                     $this->gvars['stabActive'] = 3;
                     $this->getSession()->set('stabActive', 3);
                     $this->traceEntity($cloneCustomer, $customer);
                     return $this->redirect($urlFrom);
                 } else {
                     $em->refresh($customer);
                     $this->flashMsgSession('error', $this->translate('Doc.add.failure'));
                 }
             } elseif (isset($reqData['CustomerUpdateDocsForm'])) {
                 $this->gvars['tabActive'] = 3;
                 $this->getSession()->set('tabActive', 3);
                 $this->gvars['stabActive'] = 2;
                 $this->getSession()->set('stabActive', 2);
                 $customerUpdateDocsForm->handleRequest($request);
                 if ($customerUpdateDocsForm->isValid()) {
                     $em->persist($customer);
                     $em->flush();
                     $this->flashMsgSession('success', $this->translate('Customer.edit.success', array('%customer%' => $customer->getLabel())));
                     $this->gvars['stabActive'] = 3;
                     $this->getSession()->set('stabActive', 3);
                     $this->traceEntity($cloneCustomer, $customer);
                     return $this->redirect($urlFrom);
                 } else {
                     $em->refresh($customer);
                     $this->flashMsgSession('error', $this->translate('Customer.edit.failure', array('%customer%' => $customer->getLabel())));
                 }
             }
             $this->gvars['customer'] = $customer;
             $this->gvars['doc'] = $doc;
             $this->gvars['CustomerUpdateForm'] = $customerUpdateForm->createView();
             $this->gvars['CustomerUpdateDocsForm'] = $customerUpdateDocsForm->createView();
             $this->gvars['DocNewForm'] = $docNewForm->createView();
             $customersConstStr = $em->getRepository('AcfDataBundle:ConstantStr')->findOneBy(array('name' => 'customersPrefix'));
             if (null == $customersConstStr) {
                 $customersConstStr = new ConstantStr();
                 $customersConstStr->setName('customersPrefix');
                 $customersConstStr->setValue('411');
                 $em->persist($customersConstStr);
                 $em->flush();
             }
             $customersPrefix = $customersConstStr->getValue();
             $this->gvars['customersPrefix'] = $customersPrefix;
             $this->gvars['pagetitle'] = $this->translate('pagetitle.customer.edit', array('%customer%' => $customer->getLabel()));
             $this->gvars['pagetitle_txt'] = $this->translate('pagetitle.customer.edit.txt', array('%customer%' => $customer->getLabel()));
             return $this->renderResponse('AcfAdminBundle:Customer:edit.html.twig', $this->gvars);
         }
     } catch (\Exception $e) {
         $logger = $this->getLogger();
         $logger->addCritical($e->getLine() . ' ' . $e->getMessage() . ' ' . $e->getTraceAsString());
     }
     return $this->redirect($urlFrom);
 }
Beispiel #20
0
 /**
  * embed images to the given body
  *
  * @param  string $body
  * @return string
  */
 protected function embedImages($body)
 {
     foreach ($this->embedded as $image) {
         if (false !== strpos($body, $this->embeddedUrl . $image)) {
             $cid = $this->message->embed(Swift_Image::fromPath($this->embeddedDir . $image));
             $body = str_replace($this->embeddedUrl . $image, $cid, $body);
         }
     }
     return $body;
 }
 public function embed($image)
 {
     return $this->emailObj->embed(\Swift_Image::fromPath($image));
 }
 /**
  * Short for swift image
  */
 public function image($path)
 {
     return \Swift_Image::fromPath($path);
 }
 /**
  *
  * @return Response
  */
 public function joinAction()
 {
     $request = $this->getRequest();
     $civ = $request->request->get('civ');
     $fname = $request->request->get('fname');
     $lname = $request->request->get('lname');
     $email = $request->request->get('email');
     $subject = $request->request->get('subject');
     $message = $request->request->get('message');
     $cv = $request->files->get('cv');
     $motiv = $request->files->get('motiv');
     $mvars = array();
     $mvars['msg'] = $message;
     $from = $this->getParameter('mail_from');
     $fromName = $this->getParameter('mail_from_name');
     $subject = $this->translate('_mail.join.subject', array(), 'messages') . $subject;
     try {
         $admins = $this->getParameter('mailtos');
         $message = \Swift_Message::newInstance()->setFrom($from, $fromName);
         foreach ($admins as $admin) {
             $message->addTo($admin['email'], $admin['name']);
         }
         $message->setReplyTo($email, $civ . ' ' . $fname . ' ' . $lname);
         $message->setSubject($subject);
         $mvars['logo'] = $message->embed(\Swift_Image::fromPath($this->getParameter('kernel.root_dir') . '/../web/bundles/acfres/images/logo_acf.jpg'));
         $message->setBody($this->renderView('AcfFrontBundle:Mail:contact.html.twig', $mvars), 'text/html');
         if (null != $cv) {
             $message->attach(\Swift_Attachment::fromPath($cv)->setFilename($cv->getClientOriginalName()));
         }
         if (null != $motiv) {
             $message->attach(\Swift_Attachment::fromPath($motiv)->setFilename($motiv->getClientOriginalName()));
         }
         $this->sendmail($message);
     } catch (\Exception $e) {
         // ne rien faire
     }
     $response = new Response();
     $response->setContent('Votre Message a été envoyé et sera traité dans les plus bref délais');
     return $response;
 }
Beispiel #24
0
 /**
  *
  * @param string $uid
  *
  * @return Response
  */
 public function editPostAction($uid)
 {
     $urlFrom = $this->getReferer();
     if (null == $urlFrom || trim($urlFrom) == '') {
         $urlFrom = $this->generateUrl('_admin_company_list');
     }
     $em = $this->getEntityManager();
     try {
         $mpaye = $em->getRepository('AcfDataBundle:MPaye')->find($uid);
         if (null == $mpaye) {
             $this->flashMsgSession('warning', $this->translate('MPaye.edit.notfound'));
         } else {
             $msalaryImportForm = $this->createForm(MSalaryImportTForm::class);
             $doc = new Doc();
             $doc->setCompany($mpaye->getCompany());
             $docNewForm = $this->createForm(DocNewTForm::class, $doc, array('company' => $mpaye->getCompany()));
             $this->gvars['tabActive'] = $this->getSession()->get('tabActive', 2);
             $this->getSession()->remove('tabActive');
             $this->gvars['stabActive'] = $this->getSession()->get('stabActive', 1);
             $this->getSession()->remove('stabActive');
             $request = $this->getRequest();
             $reqData = $request->request->all();
             if (isset($reqData['MSalaryImportForm'])) {
                 $this->gvars['tabActive'] = 2;
                 $this->getSession()->set('tabActive', 2);
                 $this->gvars['stabActive'] = 1;
                 $this->getSession()->set('stabActive', 1);
                 $msalaryImportForm->handleRequest($request);
                 if ($msalaryImportForm->isValid()) {
                     $lineDel = 0;
                     foreach ($mpaye->getSalaries() as $oldSalary) {
                         $em->remove($oldSalary);
                         $lineDel++;
                     }
                     $em->flush();
                     ini_set('memory_limit', '1024M');
                     ini_set('max_execution_time', '0');
                     $extension = $msalaryImportForm['excel']->getData()->guessExtension();
                     if ($extension == 'zip') {
                         $extension = 'xlsx';
                     }
                     $filename = uniqid() . '.' . $extension;
                     $msalaryImportForm['excel']->getData()->move($this->getParameter('adapter_files'), $filename);
                     $fullfilename = $this->getParameter('adapter_files');
                     $fullfilename .= '/' . $filename;
                     $excelObj = $this->get('phpexcel')->createPHPExcelObject($fullfilename);
                     $log = '';
                     $iterator = $excelObj->getWorksheetIterator();
                     $activeSheetIndex = -1;
                     $i = 0;
                     foreach ($iterator as $worksheet) {
                         $worksheetTitle = $worksheet->getTitle();
                         $highestRow = $worksheet->getHighestRow();
                         // e.g. 10
                         $highestColumn = $worksheet->getHighestColumn();
                         // e.g 'F'
                         $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
                         $log .= "Feuille : '" . $worksheetTitle . "' trouvée contenant " . $highestRow . ' lignes et ' . $highestColumnIndex . ' colonnes avec comme plus grand index ' . $highestColumn . ' <br>';
                         if (\trim($worksheetTitle) == 'Sage') {
                             $activeSheetIndex = $i;
                         }
                         $i++;
                     }
                     if ($activeSheetIndex == -1) {
                         $log .= "Aucune Feuille de Titre 'Sage' trouvée tentative d'import depuis le première Feuille<br>";
                         $activeSheetIndex = 0;
                     }
                     $excelObj->setActiveSheetIndex($activeSheetIndex);
                     $worksheet = $excelObj->getActiveSheet();
                     $highestRow = $worksheet->getHighestRow();
                     $lineRead = 0;
                     $msalaryNew = 0;
                     $lineUnprocessed = 0;
                     $lineError = 0;
                     for ($row = 2; $row <= $highestRow; $row++) {
                         $lineRead++;
                         $haserror = false;
                         $col = 0;
                         // A
                         $matricule = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // B
                         $nom = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // C
                         $prenom = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // D
                         $actif = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // E
                         $fonction = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // F
                         $regime = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // G
                         $dtStartContrat = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // H
                         $dtEndContrat = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // I
                         $departement = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // J
                         $categorie = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // K
                         $echelon = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // L
                         $cin = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // M
                         $cnss = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // N
                         $birthday = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // O
                         $adresse = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // P
                         $tel = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // Q
                         $email = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // R
                         $banque = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // S
                         $rib = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // T
                         $familyChef = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // U
                         $familySituation = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // V
                         $handicap = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // W
                         $childWoBourse = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // X
                         $nbrDaysWork = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // Y
                         $nbrDaysAbs = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // Z
                         $nbrDaysFerry = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // AA
                         $nbrH075Sup = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // AB
                         $nbrH100Sup = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // AC
                         $nbrDSup = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // AD
                         $remboursement = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // AE
                         $buysFromCompany = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // AF
                         $salaryAdvance = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // AG
                         $salaryBrut = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // AH
                         $salaryNet = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // AI
                         $advantageNature = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // AJ
                         $ticketResto = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // AK
                         $ticketCadeau = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // AL
                         $lifeAssurance = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // AM
                         $ceaAccount = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $col++;
                         // AN
                         $others = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         if (null == $matricule || $matricule == '') {
                             $haserror = true;
                             $log .= 'ligne ' . $lineRead . ", erreur : Matricule<br>";
                         }
                         if (null == $nom || $nom == '') {
                             $haserror = true;
                             $log .= 'ligne ' . $lineRead . ", erreur : Nom<br>";
                         }
                         if (null == $prenom || $prenom == '') {
                             $haserror = true;
                             $log .= 'ligne ' . $lineRead . ", erreur : Prenom<br>";
                         }
                         if ($haserror == false) {
                             $msalaryNew++;
                             $msalary = new MSalary();
                             $msalary->setPaye($mpaye);
                             $msalary->setMatricule($matricule);
                             $msalary->setNom($nom);
                             $msalary->setPrenom($prenom);
                             $msalary->setActif($actif);
                             $msalary->setFonction($fonction);
                             $msalary->setRegime($regime);
                             $msalary->setDtStartContrat($dtStartContrat);
                             $msalary->setDtEndContrat($dtEndContrat);
                             $msalary->setDepartement($departement);
                             $msalary->setCategorie($categorie);
                             $msalary->setEchelon($echelon);
                             $msalary->setCin($cin);
                             $msalary->setCnss($cnss);
                             $msalary->setBirthday($birthday);
                             $msalary->setAdresse($adresse);
                             $msalary->setTel($tel);
                             $msalary->setEmail($email);
                             $msalary->setBanque($banque);
                             $msalary->setRib($rib);
                             $msalary->setFamilyChef($familyChef);
                             $msalary->setFamilySituation($familySituation);
                             $msalary->setHandicap($handicap);
                             $msalary->setChildWoBourse($childWoBourse);
                             $msalary->setNbrDaysWork($nbrDaysWork);
                             $msalary->setNbrDaysAbs($nbrDaysAbs);
                             $msalary->setNbrDaysFerry($nbrDaysFerry);
                             $msalary->setNbrH075Sup($nbrH075Sup);
                             $msalary->setNbrH100Sup($nbrH100Sup);
                             $msalary->setNbrDSup($nbrDSup);
                             $msalary->setRemboursement($remboursement);
                             $msalary->setBuysFromCompany($buysFromCompany);
                             $msalary->setSalaryAdvance($salaryAdvance);
                             $msalary->setSalaryBrut($salaryBrut);
                             $msalary->setSalaryNet($salaryNet);
                             $msalary->setAdvantageNature($advantageNature);
                             $msalary->setTicketResto($ticketResto);
                             $msalary->setTicketCadeau($ticketCadeau);
                             $msalary->setLifeAssurance($lifeAssurance);
                             $msalary->setCeaAccount($ceaAccount);
                             $msalary->setOthers($others);
                             $em->persist($msalary);
                             $em->persist($mpaye);
                         } else {
                             $lineError++;
                             $log .= 'la ligne ' . $lineRead . ' contient des erreurs<br>';
                         }
                     }
                     $em->flush();
                     $log .= '<br>';
                     $log .= $lineDel . ' anciennes fiches supprimées<br>';
                     $log .= $lineRead . ' lignes lues<br>';
                     $log .= $msalaryNew . ' nouvelles fiches de paye<br>';
                     $log .= $lineUnprocessed . ' Fiche déjà dans la base<br>';
                     $log .= $lineError . ' lignes contenant des erreurs<br>';
                     // */
                     $from = $this->getParameter('mail_from');
                     $fromName = $this->getParameter('mail_from_name');
                     $subject = $this->translate('_mail.newmpaye.subject', array(), 'messages');
                     $user = $this->getSecurityTokenStorage()->getToken()->getUser();
                     $company = $mpaye->getCompany();
                     $admins = $company->getAdmins();
                     if (\count($admins) != 0) {
                         $mvars = array();
                         $mvars['mpaye'] = $mpaye;
                         $mvars['user'] = $user;
                         $mvars['company'] = $company;
                         $message = \Swift_Message::newInstance();
                         $message->setFrom($from, $fromName);
                         foreach ($admins as $admin) {
                             $message->addTo($admin->getEmail(), $admin->getFullname());
                         }
                         $message->setSubject($subject);
                         $mvars['logo'] = $message->embed(\Swift_Image::fromPath($this->getParameter('kernel.root_dir') . '/../web/bundles/acfres/images/logo_acf.jpg'));
                         $message->setBody($this->renderView('AcfPayrollBundle:Mail:MPayenew.html.twig', $mvars), 'text/html');
                         $this->sendmail($message);
                     }
                     $this->flashMsgSession('log', $log);
                     $this->flashMsgSession('success', $this->translate('MSalary.import.success'));
                     $this->gvars['tabActive'] = 1;
                     $this->getSession()->set('tabActive', 1);
                     return $this->redirect($urlFrom);
                 } else {
                     $em->refresh($mpaye);
                     $this->flashMsgSession('error', $this->translate('MSalary.import.failure'));
                 }
             } elseif (isset($reqData['DocNewForm'])) {
                 $this->gvars['tabActive'] = 3;
                 $this->getSession()->set('tabActive', 3);
                 $this->gvars['stabActive'] = 1;
                 $this->getSession()->set('stabActive', 1);
                 $docNewForm->handleRequest($request);
                 if ($docNewForm->isValid()) {
                     $docFiles = $docNewForm['fileName']->getData();
                     $docs = array();
                     $docDir = $this->getParameter('kernel.root_dir') . '/../web/res/docs';
                     $docNames = '';
                     foreach ($docFiles as $docFile) {
                         $originalName = $docFile->getClientOriginalName();
                         $fileName = sha1(uniqid(mt_rand(), true)) . '.' . strtolower($docFile->getClientOriginalExtension());
                         $mimeType = $docFile->getMimeType();
                         $docFile->move($docDir, $fileName);
                         $size = filesize($docDir . '/' . $fileName);
                         $md5 = md5_file($docDir . '/' . $fileName);
                         $doc = new Doc();
                         $doc->setCompany($mpaye->getCompany());
                         $doc->setFileName($fileName);
                         $doc->setOriginalName($originalName);
                         $doc->setSize($size);
                         $doc->setMimeType($mimeType);
                         $doc->setMd5($md5);
                         $doc->setDescription($docNewForm['description']->getData());
                         $em->persist($doc);
                         $mpaye->addDoc($doc);
                         $docNames .= $doc->getOriginalName() . ' ';
                         $docs[] = $doc;
                     }
                     $em->persist($mpaye);
                     $em->flush();
                     $this->flashMsgSession('success', $this->translate('Doc.add.success', array('%doc%' => $docNames)));
                     $this->gvars['stabActive'] = 3;
                     $this->getSession()->set('stabActive', 3);
                     $from = $this->getParameter('mail_from');
                     $fromName = $this->getParameter('mail_from_name');
                     $subject = $this->translate('_mail.newdocsMP.subject', array(), 'messages');
                     $user = $this->getSecurityTokenStorage()->getToken()->getUser();
                     $company = $mpaye->getCompany();
                     $admins = $company->getAdmins();
                     if (\count($admins) != 0) {
                         $mvars = array();
                         $mvars['mpaye'] = $mpaye;
                         $mvars['user'] = $user;
                         $mvars['company'] = $company;
                         $mvars['docs'] = $docs;
                         $message = \Swift_Message::newInstance();
                         $message->setFrom($from, $fromName);
                         foreach ($admins as $admin) {
                             $message->addTo($admin->getEmail(), $admin->getFullname());
                         }
                         $message->setSubject($subject);
                         $mvars['logo'] = $message->embed(\Swift_Image::fromPath($this->getParameter('kernel.root_dir') . '/../web/bundles/acfres/images/logo_acf.jpg'));
                         $message->setBody($this->renderView('AcfPayrollBundle:Mail:MPayenewdoc.html.twig', $mvars), 'text/html');
                         $this->sendmail($message);
                     }
                     return $this->redirect($urlFrom);
                 } else {
                     $em->refresh($mpaye);
                     $this->flashMsgSession('error', $this->translate('Doc.add.failure'));
                 }
             }
             $this->gvars['mpaye'] = $mpaye;
             $this->gvars['doc'] = $doc;
             $this->gvars['MSalaryImportForm'] = $msalaryImportForm->createView();
             $this->gvars['DocNewForm'] = $docNewForm->createView();
             $this->gvars['pagetitle'] = $this->translate('pagetitle.mpaye.edit', array('%mpaye%' => $mpaye->getRef()));
             $this->gvars['pagetitle_txt'] = $this->translate('pagetitle.mpaye.edit.txt', array('%mpaye%' => $mpaye->getRef()));
             return $this->renderResponse('AcfPayrollBundle:MPaye:edit.html.twig', $this->gvars);
         }
     } catch (\Exception $e) {
         $logger = $this->getLogger();
         $logger->addCritical($e->getLine() . ' ' . $e->getMessage() . ' ' . $e->getTraceAsString());
     }
     return $this->redirect($urlFrom);
 }
Beispiel #25
0
 public function embed_image($image_path)
 {
     return $this->mail_set->embed(\Swift_Image::fromPath($image_path));
 }
Beispiel #26
0
 /**
  *
  * @param string $uid
  * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
  */
 public function sendmailAction($uid)
 {
     if (!$this->hasRole('ROLE_SUPERADMIN')) {
         return $this->redirect($this->generateUrl('_admin_homepage'));
     }
     $urlFrom = $this->getReferer();
     if (null == $urlFrom || trim($urlFrom) == '') {
         $urlFrom = $this->generateUrl('_admin_order_list');
     }
     $em = $this->getEntityManager();
     try {
         $order = $em->getRepository('AcfDataBundle:OnlineOrder')->find($uid);
         if (null == $order) {
             $this->flashMsgSession('warning', $this->translate('Order.edit.notfound'));
         } else {
             $from = $this->getParameter('mail_from');
             $fromName = $this->getParameter('mail_from_name');
             $subject = $this->translate('_mail.order.subject', array('%order%' => $order->getRef()), 'messages');
             $mvars = array();
             $mvars['order'] = $order;
             $message = \Swift_Message::newInstance();
             $message->setFrom($from, $fromName);
             $message->setTo($order->getUser()->getEmail(), $order->getUser()->getFullname());
             $message->setSubject($subject);
             $mvars['logo'] = $message->embed(\Swift_Image::fromPath($this->getParameter('kernel.root_dir') . '/../web/bundles/acfres/images/logo_acf.jpg'));
             $message->setBody($this->renderView('AcfAdminBundle:Order:mail.html.twig', $mvars), 'text/html');
             $this->sendmail($message);
             $this->flashMsgSession('success', $this->translate('Order.mail.success', array('%order%' => $order->getRef())));
         }
     } catch (\Exception $e) {
         $logger = $this->getLogger();
         $logger->addCritical($e->getLine() . ' ' . $e->getMessage() . ' ' . $e->getTraceAsString());
     }
     return $this->redirect($urlFrom);
 }
Beispiel #27
0
 /**
  * Get an embed string for an attachment
  *
  * @param   mixed  $attachment  File path (string) or object (Swift_Image)
  * @return  object
  */
 public function getEmbed($attachment)
 {
     if (!$attachment instanceof \Swift_Image) {
         $attachment = \Swift_Image::fromPath($attachment);
     }
     return $this->embed($attachment);
 }
Beispiel #28
0
 public function sendAction($request)
 {
     $account = $this->repo('Account')->find($request->get('account'));
     if (!$account) {
         return $this->responseAJAX(['status' => 'error', 'message' => 'Brak skonfigurowanego konta pocztowego, z którego można wysłać wiadomość.']);
     }
     $this->repo('Account')->decryptPasswords($account);
     $this->completeAccountWithPassword($account);
     try {
         $to = new EmailAddressParser($request->get('to'));
         $cc = new EmailAddressParser($request->get('cc'));
         $bcc = new EmailAddressParser($request->get('bcc'));
         $message = \Swift_Message::newInstance();
         $content = $request->get('content');
         $contentObj = \SimpleHtmlDom\str_get_html($content);
         if ($request->get('originalMessageId')) {
             $originalMessage = $this->openBoxFromRequest($request)->readMessage($request->get('originalMessageId'), MailReader::READ_BODY_ATTACHMENTS);
             if ($originalMessage) {
                 foreach ($originalMessage->attachments as $attachment) {
                     /**
                      * Add attachment to new message, and retrive it's ID.
                      */
                     $newAttId = $message->embed(\Swift_Image::fromPath($attachment->filePath));
                     /**
                      * Search for elements with given attribute and given ID of attachment.
                      */
                     $elements = $contentObj->find('*[data-attid="cid:' . $attachment->id . '"]');
                     foreach ($elements as $element) {
                         /**
                          * Few lines abowe we add attachment to new mail, so we save it's id
                          * in searched src of image (inline attachment). Old SRC we replace by
                          * new attachment's ID.
                          */
                         $element->src = $newAttId;
                         /**
                          * We only add this attribute to tage the ID of attachment in original message.
                          * Now we only remove it, couse we don't need it anymore.
                          */
                         $element->removeAttribute('data-attid');
                     }
                 }
             }
         }
         $content = $contentObj->save();
         $message->setSubject($request->get('subject'))->setFrom(array($account->getSmtpUsername() => $account->getSenderName()))->setTo($to->getAsPairs())->setBody($content, 'text/html');
         if ($cc->hasAny()) {
             $message->setCc($cc->getAsPairs());
         }
         if ($bcc->hasAny()) {
             $message->setBcc($bcc->getAsPairs());
         }
         $attachmentsDir = BASEPATH . '/app/Cache/outgoing-attachments/' . $this->request()->getSession()->getId() . '/' . $request->request->get('windowId');
         if (is_dir($attachmentsDir)) {
             foreach (new \DirectoryIterator($attachmentsDir) as $fileInfo) {
                 if ($fileInfo->isDot() || $fileInfo->isDir()) {
                     continue;
                 }
                 $message->attach(\Swift_Attachment::fromPath($fileInfo->getPathname()));
             }
         }
         $transport = \Swift_SmtpTransport::newInstance($account->getSmtpHost(), $account->getSmtpPort(), $account->getSmtpSecurity())->setUsername($account->getSmtpUsername())->setPassword($account->getSmtpPassword());
         $mailer = \Swift_Mailer::newInstance($transport);
         // Send the message
         $result = $mailer->send($message);
         $this->openBoxFromRequest($request)->appendMessage($message->toString(), $this->imap($account)->getSentBoxName(), '\\Seen');
         // Save stat
         if ($this->openSettings('app')->get('mod.mail.stat.savesentmailsinfo') == 1) {
             $stat = new SentMail();
             $stat->setUserId($this->user()->getId());
             $stat->setDate(time());
             $this->repo('SentMail')->save($stat);
         }
     } catch (\Exception $e) {
         return $this->responseAJAX(['status' => 'error', 'message' => $e->getMessage()]);
     }
     return $this->responseAJAX(['status' => $result ? 'success' : 'error', 'message' => 'Wiadomość została wysłana.']);
 }
Beispiel #29
0
 /**
  * Embed files into message
  * Note: Is better to use the Message object directly
  * 
  * @param string Path or dynamic
  * @param string|mixed Path to file or file content when type is dynamic 
  * @param string File name
  * @param string Mime type of image
  * @return int
  */
 public function embed($type, $file = '', $name = null, $content_type = null)
 {
     switch ($type) {
         case 'path':
             if ($file == '') {
                 return;
             }
             return $this->swMessage->embed(Swift_Image::fromPath($file));
             break;
         case 'dynamic':
             if ($file == null || $file == '') {
                 return;
             }
             return $this->swMessage->embed(Swift_Image::newInstance($file, $name, $content_type));
     }
 }
Beispiel #30
0
 protected function newDocNotifyAdmin(Buy $buy, $docs)
 {
     $from = $this->getParameter('mail_from');
     $fromName = $this->getParameter('mail_from_name');
     $subject = $this->translate('_mail.newdocs.subject', array(), 'messages');
     $user = $this->getSecurityTokenStorage()->getToken()->getUser();
     $company = $buy->getCompany();
     $admins = $company->getAdmins();
     if (\count($admins) != 0) {
         $mvars = array();
         $mvars['buy'] = $buy;
         $mvars['user'] = $user;
         $mvars['company'] = $company;
         $mvars['docs'] = $docs;
         $message = \Swift_Message::newInstance();
         $message->setFrom($from, $fromName);
         foreach ($admins as $admin) {
             $message->addTo($admin->getEmail(), $admin->getFullname());
         }
         $message->setSubject($subject);
         $mvars['logo'] = $message->embed(\Swift_Image::fromPath($this->getParameter('kernel.root_dir') . '/../web/bundles/acfres/images/logo_acf.jpg'));
         $message->setBody($this->renderView('AcfClientBundle:Mail:Buynewdoc.html.twig', $mvars), 'text/html');
         $this->sendmail($message);
     }
 }