/**
  * Bulk import redirects from a CSV file matching the following structure:
  *
  * redirect_from_path,(redirect_to_post_id|redirect_to_path|redirect_to_url)
  *
  * @subcommand import-from-csv
  * @synopsis --csv=<path-to-csv>
  */
 function import_from_csv($args, $assoc_args)
 {
     define('WP_IMPORTING', true);
     if (empty($assoc_args['csv']) || !file_exists($assoc_args['csv'])) {
         WP_CLI::error("Invalid 'csv' file");
     }
     global $wpdb;
     if (($handle = fopen($assoc_args['csv'], "r")) !== FALSE) {
         while (($data = fgetcsv($handle, 2000, ",")) !== FALSE) {
             $row++;
             $redirect_from = $data[0];
             $redirect_to = $data[1];
             WP_CLI::line("Adding (CSV) redirect for {$redirect_from} to {$redirect_to}");
             WP_CLI::line("-- at {$row}");
             WPCOM_Legacy_Redirector::insert_legacy_redirect($redirect_from, $redirect_to);
             if (0 == $row % 100) {
                 if (function_exists('stop_the_insanity')) {
                     stop_the_insanity();
                 }
                 sleep(1);
             }
         }
         fclose($handle);
     }
 }
        if (false === $redirect_post_id) {
            $redirect_post_id = self::get_redirect_post_id($url);
            wp_cache_add($url_hash, $redirect_post_id, self::CACHE_GROUP);
        }
        if ($redirect_post_id) {
            $redirect_post = get_post($redirect_post_id);
            if (0 !== $redirect_post->post_parent) {
                return get_permalink($redirect_post->post_parent);
            } elseif (!empty($redirect_post->post_excerpt)) {
                return esc_url_raw($redirect_post->post_excerpt);
            }
        }
        return false;
    }
    static function get_redirect_post_id($url)
    {
        global $wpdb;
        $url_hash = self::get_url_hash($url);
        $redirect_post_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_type = %s AND post_name = %s LIMIT 1", self::POST_TYPE, $url_hash));
        if (!$redirect_post_id) {
            $redirect_post_id = 0;
        }
        return $redirect_post_id;
    }
    private static function get_url_hash($url)
    {
        return md5($url);
    }
}
WPCOM_Legacy_Redirector::start();