<?php

class pruebasPruebaTask extends sfBaseTask
{
  protected function configure()
  {
    // // add your own arguments here
    // $this->addArguments(array(
    //   new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
    // ));

    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name'),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
      // add your own options here
    ));

    $this->namespace        = 'pruebas';
    $this->name             = 'prueba';
    $this->briefDescription = '';
    $this->detailedDescription = <<<EOF
The [pruebas:prueba|INFO] task does things.
Call it with:

  [php symfony pruebas:prueba|INFO]
EOF;
  }

  public function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    $databaseManager = new sfDatabaseManager($this->configuration);
    $conn = Doctrine_Manager::connection();
	
    $config = HTMLPurifier_Config::createDefault();
    $purifier = new HTMLPurifier($config);
   
    	

    $sql = "select tab0.* from co_detalle_ep tab0";
    $records = $conn->execute($sql)->fetchAll();
	foreach($records as $records){
	
	     $id_detalle_ep = $records['ID_DETALLE_EP'];
             $valor = $this->htmlClear($purifier->purify($records['VALOR']));
	
		
	      $sql="update co_detalle_ep set valor='".$valor."' where id_detalle_ep = ".$id_detalle_ep;
	      $conn->execute($sql);
	      

	}

    }


private function htmlClear($string) {
        
	        
	//El formato de tamaño de fuente no se debe ejecutar en el envío de correos

        $string = str_replace('<font size="10">', '<font size="2">', $string);
        $string = str_replace('<font size="12">', '<font size="3">', $string);
        $string = str_replace('<font size="14">', '<font size="4">', $string);
        $string = str_replace('<font size="18">', '<font size="5">', $string);
        $string = str_replace('<font size="24">', '<font size="6">', $string);
        $string = str_replace('<font size="36">', '<font size="7">', $string);
	 
        $string = str_replace('size="10"', 'size="1"', $string);
        $string = str_replace('size="10"', 'size="2"', $string);
        $string = str_replace('size="12"', 'size="3"', $string);
        $string = str_replace('size="14"', 'size="4"', $string);
        $string = str_replace('size="18"', 'size="5"', $string);
        $string = str_replace('size="24"', 'size="6"', $string);
        $string = str_replace('size="36"', 'size="7"', $string);
	$string = str_replace("font-family:'Times New Roman'", 'font-family:"Times New Roman"', $string);

	

	return trim($string);
    }

    public static function envioCorreo($report_params, $datos_usuario, $subject, $currentUri, $ruta, $adjunto, $progress_key, $array_adjuntos, $body) {



        /**
         * Variables
         */
        $i = 0;




        /**
         * PHPMailer
         */
        // Instanciar PHPMailer una primera Vez
        $mail = new PHPMailer(); // defaults to using php "mail()"
	$mail->IsSMTP(); // telling the class to use SMTP
        $mail->SMTPSecure = "ssl";//tsl o ssl
        $mail->Host = "smtp.gmail.com";      // SMTP server
        $mail->SMTPAuth = true;                  // enable SMTP authentication
        $mail->Port = 465;                    // set the SMTP port for the GMAIL server
        $mail->Username = "websafi@sgc.gov.co";              // SMTP account username
        $mail->Password = '0pennms$KApp.+';           // SMTP account password
        $email_envio = "modulocontratacion@sgc.gov.co";
        $mail->SetFrom($email_envio, utf8_decode('Contratación Websafi'));
        $mail->Subject = $subject;

        
        foreach ($datos_usuario as $value) {


//            // Guardar un valor en el proceso largo
//            if ($i_porcentaje % $brecha == 0) {
//                MemcacheHandler::getInstance()->set($progress_key, round(($i_porcentaje / $cantidad_array) * 100, 0));
//            }



            $datos = explode(';', $value);

            //Datos del funcionario para el envio del correo
            $report_params["num_doc"] = $datos[0];
            $report_params["id_tipo_doc"] = $datos[1];
            $report_params["email"] = $datos[2];
            $nombre_completo = $report_params["nombre_completo"] = $datos[3];

            //mensaje_extra
            if (isset($report_params["mensaje_extra"])) {
                $report_params["mensaje_extra"] = "<br/><br/>" . $datos[4];
            }

            //arrayadjuntos
            if (isset($report_params["arrayadjuntos"])) {
                $array_adjuntos = array();
                $cant_adjuntos = $report_params["arrayadjuntos"];
                for ($i = 1; $i <= $cant_adjuntos; $i++) {
                    $datos_adj = explode('+', $datos[3 + $i]);
                    $key_datos = $datos_adj[1];
                    $array_adjuntos[$key_datos] = str_replace("+", "/", $datos[3 + $i]);
                }
            }



            /*
             * Operacion con el archivo
             */
            if (true) {

                /*
                 * $mail->AddReplyTo($report_params["email"], $report_params["username"]);
                 */

                // Agregar El correo
                // Agregar el Attachment
                // Cambiar el body
                $address = $report_params["email"];
                $mail->AddAddress("contratos@sofhouse.net", "Seguimiento Contratos");

                /**
                 * Reemplazo de caracteres
                 */
                $subject = str_replace("ó", "&oacute;", $subject);
                $report_params["mensaje_extra"] = "";
                $report_params["mensaje_extra"] = str_replace("ó", "&oacute;", $report_params["mensaje_extra"]);
                $report_params["mensaje_extra"] = str_replace(",", "<br/>", $report_params["mensaje_extra"]);
                $report_params["mensaje_extra"] = str_replace("null", " ", $report_params["mensaje_extra"]);


                //$mail->AltBody = "This is the body in plain text for non-HTML mail clients"; // optional, comment out and test

                $body = str_replace("á", "&aacute;", $body);
                $body = str_replace("é", "&eacute;", $body);
                $body = str_replace("í", "&iacute;", $body);
                $body = str_replace("ó", "&oacute;", $body);
                $body = str_replace("ú", "&uacute;", $body);
                $body = str_replace("ñ", "&ntilde;", $body);
                $mail->MsgHTML($body);
                /**
                 * Si el envio es con adjunto de jasper
                 */
                if ($adjunto) {
//                    $mail->AddAttachment("$ruta/nivel/2- Competencias comunes.docx", "ManualNomina.pdf");      // attachment
//                    $mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
                    foreach ($array_adjuntos as $key => $value) {
                        $mail->AddAttachment("$ruta/$value", $key);      // attachment                        
                    }
                }

                /*
                 *  Enviar el correo
                 */
                if (!$mail->Send()) {
                        echo "Mailer Error: " . $mail->ErrorInfo;
                } else {
                        echo "Message sent! ";
                }

                /*
                 * Limpiar datos del correo
                 */
                $mail->ClearAllRecipients();
                $mail->ClearAttachments();
            } else {
                header('Content-type: application/pdf');
                header('Content-Disposition: attachment; filename="ManualNomina.pdf"');
                readfile("$ruta/Comprobante$i.pdf");
            }

            //Contadores
            $i = $i + 1;
            $i_porcentaje = $i_porcentaje + 1;
//                echo 'Correo enviado por el usuario ' . $report_params["username"] . ' al funcionario ' .
//                $report_params["nombre_completo"] . ' al correo ' . $report_params["email"];
//                echo '<br/>';
        }

        //Actualizar el Memcache
        //MemcacheHandler::getInstance()->set($progress_key, 99);
    }

          
}
