jesse1981
8/30/2018 - 11:38 PM

WooCommerce: Cloudinary product upload handlers

<?php
class wc_cloudinary {
  var $inProd = false;
  var $conn = "";

  public function __construct() {
    //$this->inProd = true;
    $load = false;
    if (php_sapi_name()=="cli") $success = true;
    else {
      $user = new user;
      $user->validate(array("Administrator"));
      $success = true;
    }
    if ($success) $this->loadDb();
  }

  protected function loadDb() {
    $options = array(
      "TYPE"  => "mysql",
      "SERVER"=> ($this->inProd) ? IGAREWARDS_LIVE_SERVER:IGAREWARDS_TEST_SERVER,
      "PORT"  => "3306",
      "NAME"  => ($this->inProd) ? IGAREWARDS_LIVE_DB_NAME:IGAREWARDS_TEST_DB_NAME,
      "USER"  => ($this->inProd) ? IGAREWARDS_LIVE_USER:IGAREWARDS_TEST_USER,
      "PASS"  => ($this->inProd) ? IGAREWARDS_LIVE_PASS:IGAREWARDS_TEST_PASS,
    );
    $this->conn = new database($options);
  }

  private function _cloudinaryPosts($sqlIdOnly=false) {
    $results  = array();
    $offset   = 0;
    $limit    = 300;

    if (!$sqlIdOnly) {
      while (true) {
        $sql = "SELECT  target.`post_id`,
                    		source.`meta_value` as url,
                    		target.`meta_value` as meta
                FROM wp_postmeta source
                INNER JOIN wp_postmeta target ON target.`post_id` = source.`post_id` AND target.`meta_key` = '_wp_attachment_metadata'
                WHERE source.`meta_key` = '_wc_attachment_source' AND source.`meta_value` LIKE '%res.cloudinary.com%'
                LIMIT $limit
                OFFSET $offset";
        $res = $this->conn->query($sql);
        if (count($res)) $results = array_merge($results,$res);
        if (count($res) < $limit) break;
        $offset += $limit;
      }
    }
    else {
      $res = "SELECT target.`post_id`
              FROM wp_postmeta source
              INNER JOIN wp_postmeta target ON target.`post_id` = source.`post_id` AND target.`meta_key` = '_wp_attachment_metadata'
              WHERE source.`meta_key` = '_wc_attachment_source' AND source.`meta_value` LIKE '%res.cloudinary.com%'";
    }

    return $res;
  }
  public function clearCloudinaryAttachments() {
    $postmeta = "DELETE FROM wp_postmeta WHERE post_id IN (".$this->_cloudinaryPosts(true).")";
    $posts    = "DELETE FROM wp_posts WHERE ID IN (".$this->_cloudinaryPosts(true).")";

    $this->conn->query($postmeta);
    $this->conn->query($posts);
  }
  public function clearProducts($pref="wp_") {
    $remove_cats = false;

    $relationships = "DELETE relations.*".( $remove_cats ? ", taxes.* , terms.* " : "" ).
                  		"FROM ".$pref."term_relationships AS relations
                  		INNER JOIN ".$pref."term_taxonomy AS taxes ON relations.term_taxonomy_id=taxes.term_taxonomy_id
                  		INNER JOIN ".$pref."terms AS terms ON taxes.term_id=terms.term_id
                  		WHERE object_id IN (SELECT ID FROM ".$pref."posts WHERE post_type='product');";
    $taxonomies = "UPDATE ".$pref."term_taxonomy SET count = 0 WHERE taxonomy LIKE 'product%';";
    $product_meta = "DELETE FROM ".$pref."postmeta WHERE post_id IN (SELECT ID FROM ".$pref."posts WHERE post_type = 'product');";
    $variation_meta = "DELETE FROM ".$pref."postmeta WHERE post_id IN (SELECT ID FROM ".$pref."posts WHERE post_type = 'product_variation');";
    $products = "DELETE FROM ".$pref."posts WHERE post_type = 'product';";
    $variations = "DELETE FROM ".$pref."posts WHERE post_type = 'product_variation';";

    foreach (array("relationships","taxonomies","product_meta","variation_meta","products","variations") as $k) {
      $this->conn->query($$k);
    }
  }
  public function updateCloudinaryAttachments() {
    $res = $this->_cloudinaryPosts();

    foreach ($res as $item) {
      $meta = unserialize($item["meta"]);
      foreach ($meta["sizes"] as $k=>$v) {
        $file = $meta["sizes"][$k]["file"];
        $meta["sizes"][$k]["file"] = substr($file,0,strpos($file,"-"));
      }
      $this->setPostMeta($item["post_id"],array("_wp_attachment_metadata"=>serialize($meta)));
    }
  }

  public function setPostMeta($pid,$metaValues) {
    $t   = "wp_postmeta";
    foreach ($metaValues as $key=>$value) {
      $sql = "SELECT meta_id
              FROM $t
              WHERE post_id = :post_id
                AND meta_key = :key";
      $res = $this->conn->query($sql,array(
        "post_id"   => $pid,
        "meta_key"  => $key
      ));
      if (isset($res[0])) {
        $par = array(
          "id"    => $res[0]["meta_id"],
          "value" => $v
        );
        $sql = "UPDATE $t
                SET meta_value = :value
                WHERE meta_id = :id";
      }
      else {
        $par = array(
          "post_id"     => $pid,
          "meta_key"    => $k,
          "meta_value"  => $v
        );
        $sql = "INSERT INTO $t (post_id,meta_key,meta_value)
                VALUES (:post_id,:meta_key,:meta_value)";
      }
      $this->conn->query($sql,$par);
    }
  }
}
?>
<?php
namespace Cloudinary {
    class Cli
    {
        protected $plugin;
        public function __construct($plugin)
        {
            $this->plugin = $plugin;
        }
        public function __invoke()
        {
            $this->plugin->config();
            $args = array(
                'post_type' => 'attachment',
                'post_mime_type' => 'image',
                'post_status' => 'inherit',
                'posts_per_page' => -1,
            );
            $images = get_posts($args);
            \WP_CLI::line('Uploading ' . count($images) . ' media images to Cloudinary.');
            if (count($images) > 0) {
                foreach ($images as $attachment) {
                    $upload = $this->uploadAttachment($attachment);
                    \WP_CLI::line(basename($attachment->guid) . ': ' . ($upload ? $upload : 'Uploaded.'));
                }
            }
        }
        public function uploadAttachment($attachment)
        {
            return $this->plugin->upload_to_cloudinary($attachment->ID, true);
        }
    }
}
function cIsMigrated($attachment_id) {
  global $wpdb;

  // Query Images
	$sql = "SELECT 	target.`post_id`,
									source.`meta_value` as new_url,
									target.`meta_value` as old_url
					FROM wp_postmeta source
					INNER JOIN wp_postmeta target ON target.`post_id` = source.`post_id` AND target.`meta_key` = '_wp_attached_file'
					WHERE source.`meta_key` = '_wc_attachment_source'
					  AND source.`meta_value` LIKE '%res.cloudinary.com%'";

	// Query Single
	$sql = "SELECT 	target.`post_id`,
              		source.`meta_value` as source,
              		target.`meta_value` as target
          FROM wp_postmeta source
          INNER JOIN wp_postmeta target ON target.`post_id` = source.`post_id` AND target.`meta_key` = '_wp_attached_file'
          WHERE source.`meta_key` = '_wc_attachment_source' AND source.`meta_value` LIKE '%res.cloudinary.com%'
            AND target.`post_id` = $attachment_id";
	$res = $wpdb->get_results($sql);

  return $res;
}
function cMigrate($attachment_id) {
  $res = cIsMigrated($attachment_id);

  if (!isset($res[0])) return;
	// Get Attachment
	$attachment = get_post($attachment_id);

	$title = $attachment->post_title;
	$caption = $attachment->post_content;
	$post_parent = $attachment->post_parent;

	$new_url = $res[0]->source;
	$new_attachment = array(
    'ID'							=> intval($attachment_id),
    'post_mime_type'	=> "image/png",
    'guid' 						=> $new_url,
    'post_parent' 		=> $post_parent,
    'post_title'      => $title,
    'post_content'    => $caption
	);

	$id = wp_insert_attachment($new_attachment, $new_url, $post_parent);

  // Delete Uploaded Copy
  unlink("../wp-content/uploads/".$res[0]->target);
}
function cMigrateUrl($url, $attachment_id) {
  $res = cIsMigrated($attachment_id);
  if (isset($res[0])) $url = $res[0]->source;
  return $url;
}
add_action('add_attachment','cMigrate',5,1);
add_filter('wp_get_attachment_url', 'cMigrateUrl', 10, 2);