Subversion Repositories cheapmusic

Rev

Rev 129 | Rev 143 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

<?php
include_once ('php/constants.php');

error_reporting(E_ALL);
// Get linkshare listings
function get_linkshare($query, $searchCondition) {
    $vendors = Vendors::getInstance();
    $config = $vendors->getVendor(Vendors::LINKSHARE);

    $token = getLinkshareToken($config);
    if ($token === false) {
        return [];
    }

    $arr = [];
    foreach ($config["advertiser"] as $advertiser) {
        $arrTemp = get_linkshareAdvertiser($config, $token, $query, $searchCondition, $advertiser);
        foreach($arrTemp as $temp) {
            $arr[] = $temp;
        }
    }

    return ($arr);
}

// Get linkshare listings by advertiser id
function get_linkshareAdvertiser($config, $token, $query, $searchCondition, $advertiserId) {
    // API request variables
    $numResults = $config['numResults'];
    $numResultsMid = $config['numResultsMid'];
    $resultsMid = [];
    $url = '[cached]';

    $result = getSearchCache($advertiserId, $query, $searchCondition);
    if ($result === false) {
        $params = [];
        $params["keyword"] = $query;
        $params["max"] = $numResults;
        $params["pagenumber"] = "1";
        $params["sort"] = "retailprice";
        $params["sorttype"] = "asc";
        $params["mid"] = $advertiserId;

        $pairs = array();
        foreach ($params as $key => $value) {
            array_push($pairs, rawurlencode($key)."=".rawurlencode($value));
        }
        $canonical_query_string = join("&", $pairs);

        $url = "https://api.rakutenmarketing.com/productsearch/1.0?" . $canonical_query_string;

        $header = array(
            'Content-Type: application/x-www-form-urlencoded',
            'Accept: application/xml',
            'Accept-Language: en-US,en;q=0.5',
            'Accept-Charset: UTF-8,*;q=0.5',
            'Authorization: Bearer ' . $token
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        saveSearchCache($advertiserId, $query, $searchCondition, $result);
        curl_close($ch);
    }

    $result = utf8_encode($result);
    $result = simplexml_load_string($result);

    //echo "$url<br><pre>";print_r($result);echo "</pre>";
    $arr = [];

    // Check to see if the request found any results
    if (isset($result->TotalMatches)) {
        // If the response was loaded, parse it and store in array
        foreach ($result->item as $item) {
            $merchantId = strval($item->mid);
            $merchantName = (string)$item->merchantname;
            $barcode = (string)$item->upccode;
            $barcodeType = clsLibGTIN::GTINCheck($barcode, false, 1);

            $title = (string)$item->productname;
            $pic = str_replace('http://', 'https://', (string)$item->imageurl);
            if (empty($pic)) {
                continue;
            }
            $url = str_replace('http://', 'https://', (string)$item->linkurl);
            if (empty($url)) {
                continue;
            }

            $country = 'US';

            switch ($merchantId) {
                case 35126: // Sam Ash Music
                    $merchantName = "Sam Ash";
                    if ($item->category->primary == "Books/Dvds") {
                        $condition = 'New';
                        $detailCondition = "Brand New";
                        $mediaType = "Book";
                        $freeShippingCap = 0.00; // 9.99 on webpage
                        $handlingTime = 1;
                        $shippingCost = 0.00;
                        $shippingEstimated = false;
                        $shippingCurrency = 'USD';
                    }
                    else {
                        continue 2; // next loop
                        
                    }
                break;

                case 13770: // Music Notes
                    $condition = 'New';
                    $detailCondition = "Brand New";
                    $mediaType = "Book";
                    $freeShippingCap = 0.00;
                    $handlingTime = 1;
                    $shippingCost = 0.00;
                    $shippingEstimated = false;
                    $shippingCurrency = 'USD';
                break;

                case 2653: // alibris
                    /* fall through */
                case 24390: // alibris uk
                    $merchantName = "Alibris";
                    if ($merchantId == 24390) {
                        $merchantName .= " UK";
                    }
                    if ($item->category->primary == "Media > Music" || $item->category->primary == "Media > Dvds & Movies") {
                        $mediaType = "CD";
                    }
                    else {
                        $mediaType = "Book";
                    }
                    $condition = 'Used';
                    $detailCondition = "Used";
                    $handlingTime = 1;
                    if ($merchantId == 2653) {
                        $shippingCost = 3.99;
                        $freeShippingCap = 39.00;
                    }
                    else { /* 24390 */
                        $shippingCost = 4.25;
                        $freeShippingCap = 0.00;
                        $country = 'GB';
                    }
                    $shippingEstimated = true;
                    $shippingCurrency = 'USD';
                break;

                case 2149: // Walmart
                    continue 2;

                default:
                    $condition = 'Used';
                    $detailCondition = "Used";
                    $mediaType = "CD";
                    $freeShippingCap = 0.00;
                    $handlingTime = - 1;
                    $shippingEstimated = true;
                    $shippingCost = 0.00;
                    $shippingCurrency = 'USD';
                break;
            }

            $bestOffer = false;

            $price = 0;
            if (!empty($item->price) && !empty($item->saleprice)) {
                $price = minNotNull(array(
                    $item->price,
                    $item->saleprice
                ));
            }
            else if (!empty($item->price)) {
                $price = $item->price;
            }
            else if (!empty($item->saleprice)) {
                $price = $item->saleprice;
            }
            $price = number_format(floatval($price) , 2, '.', '');
            if ($price <= "0.00") {
                continue;
            }

            $currency = 'USD';
            $timeLeft = 0;
            $listingType = 'Fixed';
            $location = 'US';
            $zip = '';
            $feedbackScore = - 1;
            $feedbackPercent = - 1;
            $sellerName = '';

            // bugbug
            //ls_cj_csv(array($merchantName,(string)$item->category->primary,(string)$item->productname,(string)$item->description->short,"'".$barcode,$barcodeType,minNotNull(array($item->price, (string)$item->saleprice)),(string)$item->linkurl));
            // this is last after all checks
            $resultsMid[] = $merchantId;
            if ($numResultsMid > array_count_values($resultsMid) [$merchantId]) {
                $arr[] = array(
                    "Merchant" => $merchantName,
                    "Condition" => $condition,
                    "Title" => $title,
                    "Barcode" => $barcode,
                    "BarcodeType" => $barcodeType,
                    "Image" => $pic,
                    "URL" => $url,
                    "MediaType" => $mediaType,
                    "DetailCondition" => $detailCondition,
                    "Country" => $country,
                    "BestOffer" => $bestOffer,
                    "TimeLeft" => $timeLeft,
                    "Price" => $price,
                    "Currency" => $currency,
                    "ListingType" => $listingType,
                    "Location" => $location,
                    "Zip" => $zip,
                    "FeedbackScore" => $feedbackScore,
                    "FeedbackPercent" => $feedbackPercent,
                    "SellerName" => $sellerName,
                    "HandlingTime" => $handlingTime,
                    "ShippingCost" => $shippingCost,
                    "ShippingEstimated" => $shippingEstimated,
                    "ShippingCurrency" => $shippingCurrency,
                    "FreeShippingCap" => $freeShippingCap,
                    "Show" => true
                );
            }
        }
    }
    // If the response does not indicate 'Success,' log the error(s)
    else {
        if (!empty($result->Errors)) {
            foreach ($result->Errors as $error) {
                if ($error->ErrorID != "7186919") { // no product found, not an error
                    my_error_log($url);
                    my_error_log("$error->ErrorText ($error->ErrorId)");
                }
            }
        } else {
            my_error_log($url);
            my_error_log("No result or error message.");
        }
    }

    return $arr;
}

// Get Linkshare Bearer Token
function getLinkshareToken($config) {
    static $expiration = 0;
    static $accessToken = '';
    static $refreshToken = '';

    if ($expiration == 0 || time() > $expiration) {
        $url = "https://api.rakutenmarketing.com/token";
        $postdata = "grant_type=password&username=" . $config['user'] . "&password=" . $config['password'] . "&scope=" . $config['scope'];
        $header = array(
            'Content-Type: application/x-www-form-urlencoded',
            'Authorization: ' . $config['authorizationToken']
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        curl_setopt($ch, CURLOPT_POST, 1);
        $result = curl_exec($ch);
        $result = json_decode($result);
        curl_close($ch);

        if (empty($result)) {
            return false;
        }

        $expiration = time() + $result->{'expires_in'};
        $accessToken = $result->{'access_token'};
        $refreshToken = $result->{'refresh_token'};
        $tokenType = $result->{'token_type'};
    }

    return $accessToken;
}

// get linkshare coupon codes
function get_linkshareCoupons() {
    $vendors = Vendors::getInstance();
    $config = $vendors->getVendor(Vendors::LINKSHARE);

    $token = getLinkshareToken($config);
    if ($token === false) {
        return [];
    }

    // Construct the findItemsByKeywords HTTP GET call
    $url = "https://api.rakutenmarketing.com/coupon/1.0?category=22&network=1&resultsperpage=100&pagenumber=1";

    $header = array(
        'Content-Type: application/x-www-form-urlencoded',
        'Accept: application/xml',
        'Accept-Language: en-US,en;q=0.5',
        'Accept-Charset: UTF-8,*;q=0.5',
        'Authorization: Bearer ' . $token
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);

    $result = utf8_encode($result);
    $result = simplexml_load_string($result);

    curl_close($ch);

    //echo "$url<br><pre>";print_r($result);echo "</pre>";
    $arr = [];

    // Check to see if the request found any results
    if (isset($result->TotalMatches)) {
        // If the response was loaded, parse it and store in array
        foreach ($result->link as $link) {
            echo "NULL";
            echo "," . $link->advertisername;
            echo "," . $link->offerstartdate;
            echo "," . $link->offerenddate;
            echo ",\"" . $link->offerdescription . "\"";
            echo "," . $link->couponcode;
            echo "," . str_replace('http://', 'https://', (string)$link->clickurl);
            echo "," . str_replace('http://', 'https://', (string)$link->impressionpixel);
            echo "<br>";
        }
    }
    // If the response does not indicate 'Success,' log the error(s)
    else {
        foreach ($result->Errors as $error) {
            if ($error->ErrorID != "7186919") { // no product found, not an error
                my_error_log($url);
                my_error_log("$error->ErrorText ($error->ErrorId)");
            }
        }
    }

    return $arr;
}