/**
  * Perform a Backup.
  *
  * ## OPTIONS
  *
  * [--files_only]
  * : Backup files only, default to off
  *
  * [--database_only]
  * : Backup database only, defaults to off
  *
  * [--destination]
  * : dir that the backup should be save in, defaults to your existing backups directory
  *
  * [--root]
  * : dir that should be backed up, defaults to site root.
  *
  * [--archive_filename]
  * : filename for the resulting zip file
  *
  * [--excludes]
  * : list of paths you'd like to exclude
  *
  * ## Usage
  *
  *     wp backupwordpress backup [--files_only] [--database_only] [--path<dir>] [--root<dir>] [--zip_command_path=<path>] [--mysqldump_command_path=<path>]
  *
  * @todo errors should be bubbled from Backup, Scheduled_Backup and the like instead of being repeated.
  */
 public function backup($args, $assoc_args)
 {
     add_action('hmbkp_mysqldump_started', function () {
         \WP_CLI::line(__('Backup: Dumping database...', 'backupwordpress'));
     });
     add_action('hmbkp_archive_started', function () {
         \WP_CLI::line(__('Backup: Zipping everything up...', 'backupwordpress'));
     });
     if (!empty($assoc_args['destination'])) {
         Path::get_instance()->set_path($assoc_args['destination']);
     }
     Path::get_instance()->cleanup();
     if (!empty($assoc_args['root'])) {
         Path::get_instance()->set_root($assoc_args['root']);
     }
     if (!is_dir(Path::get_path())) {
         \WP_CLI::error(__('Invalid backup path', 'backupwordpress'));
         return false;
     }
     if (!is_dir(Path::get_root()) || !is_readable(Path::get_root())) {
         \WP_CLI::error(__('Invalid root path', 'backupwordpress'));
         return false;
     }
     $filename = 'backup.zip';
     if (isset($assoc_args['archive_filename'])) {
         $filename = $assoc_args['archive_filename'];
     }
     $hm_backup = new Backup($filename);
     if (!empty($assoc_args['files_only'])) {
         $hm_backup->set_type('file');
     }
     if (!empty($assoc_args['database_only'])) {
         $hm_backup->set_type('database');
     }
     if (!empty($assoc_args['excludes'])) {
         $hm_backup->set_excludes($assoc_args['excludes']);
     }
     $hm_backup->run();
     if (file_exists($hm_backup->get_backup_filepath())) {
         \WP_CLI::success(__('Backup Complete: ', 'backupwordpress') . $hm_backup->get_backup_filepath());
     } else {
         \WP_CLI::error(__('Backup Failed', 'backupwordpress'));
     }
 }
 public function runUpdate($task)
 {
     if ($this->isLocked('update', $task->task_id)) {
         $task->addMinute(15);
     } else {
         $task->start();
         $this->data['update_info'] = $this->update->getInfo();
         if ($this->request->server['REQUEST_METHOD'] == 'POST') {
             $this->modelSetting->editMaintenance(1);
             $backup = new Backup($this->registry);
             $backup->run();
             $this->update->run();
             $this->modelSetting->editMaintenance(0);
         }
         foreach ($task->getTaskQueue() as $key => $queue) {
             if ($count >= 50) {
                 break;
             }
             $params = unserialize($queue['params']);
             $cached = $this->cache->get("campaign.html.{$params['campaign_id']}.{$params['contact_id']}");
             if ($cached) {
                 $htmlbody = html_entity_decode($cached);
             } else {
                 $htmlbody = str_replace("%7B", "{", $htmlbody);
                 $htmlbody = str_replace("%7D", "}", $htmlbody);
                 $htmlbody = str_replace("{%contact_id%}", $params['contact_id'], $htmlbody);
                 $htmlbody = str_replace("{%campaign_id%}", $params['campaign_id'], $htmlbody);
                 $htmlbody = str_replace("{%fullname%}", $params['name'], $htmlbody);
                 $htmlbody = str_replace("{%rif%}", $params['rif'], $htmlbody);
                 $htmlbody = str_replace("{%company%}", $params['company'], $htmlbody);
                 $htmlbody = str_replace("{%email%}", $params['email'], $htmlbody);
                 $htmlbody = str_replace("{%telephone%}", $params['telephone'], $htmlbody);
                 $htmlbody = $this->prepareTemplate($htmlbody, $params);
                 $dom = new DOMDocument();
                 $dom->preserveWhiteSpace = false;
                 $dom->loadHTML($htmlbody);
                 /*
                 if ($params['embed_image']) {
                     $images = $dom->getElementsByTagName('img');
                     foreach ($images as $image) {
                         $src = $image->getAttribute('src');
                         $src = str_replace(HTTP_IMAGE,DIR_IMAGE,$src);
                         if (file_exists($src)) {
                             $img    = file_get_contents($src);
                             $ext    = substr($src,(strrpos($src,'.')+1));
                             $embed  = base64_encode($img); 
                             $image->setAttribute('src',"data:image/$ext;base64,$embed");
                             $total_embed_images++;
                         }
                         $total_images++;
                     }
                 }
                 */
                 $vars = array('contact_id' => $params['contact_id'], 'campaign_id' => $params['campaign_id'], 'referencedBy' => $params['email']);
                 /* trace the email */
                 $trace_url = Url::createUrl("marketing/campaign/trace", $vars, 'NONSSL', HTTP_HOME);
                 $trackEmail = $dom->createElement('img');
                 $trackEmail->setAttribute('src', $trace_url);
                 $dom->appendChild($trackEmail);
                 /* trace the clicks */
                 $links = $dom->getElementsByTagName('a');
                 foreach ($links as $link) {
                     $href = $link->getAttribute('href');
                     if (empty($href) || $href == "#" || strpos($href, "mailto:") || strpos($href, "callto:") || strpos($href, "skype:") || strpos($href, "tel:")) {
                         continue;
                     }
                     //TODO: validar enlaces
                     //TODO: sanitizar enlaces
                     $vars['link_index'] = $link_index = md5(time() . mt_rand(1000000, 9999999) . $href);
                     $_link = Url::createUrl("marketing/campaign/link", $vars, 'NONSSL', HTTP_HOME);
                     $this->db->query("INSERT INTO " . DB_PREFIX . "campaign_link SET \r\n                          `campaign_id` = '" . (int) $params['campaign_id'] . "',\r\n                          `url`         = '" . $this->db->escape($_link) . "',\r\n                          `redirect`    = '" . $this->db->escape($href) . "',\r\n                          `link`        = '" . $this->db->escape($link_index) . "',\r\n                          `date_added`  = NOW()");
                     $link->setAttribute('href', $_link);
                     //TODO: agregar valor a la etiqueta title si esta vacia
                 }
                 $htmlbody = html_entity_decode(htmlentities($dom->saveHTML()));
             }
             $this->mailer->AddAddress($params['email'], $params['name']);
             $this->mailer->IsHTML();
             $this->mailer->SetFrom($campign_info['from_email'], $campign_info['from_name']);
             $this->mailer->AddReplyTo($campign_info['replyto_email'], $campign_info['from_name']);
             $this->mailer->Subject = $campign_info['subject'];
             $this->mailer->Body = $htmlbody;
             $this->mailer->Send();
             $this->mailer->ClearAllRecipients();
             $task->setQueueDone($key);
             $count++;
         }
         if (count($task->getTaskDos($task->task_id))) {
             $task->addMinute(15);
         } else {
             $task->setTaskDone();
         }
     }
     $task->update();
 }