Subversion Repositories cheapmusic

Rev

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

<?php
include_once('php/clsLibGTIN.php');
include_once('php/exchangeRates.php');
include_once('php/countryCodes.php');
include_once('php/constants.php');
include_once('php/ebay.php');
include_once('php/discogs.php');

$max_pb = 5; // max progressbar steps

  // search
function performSearch() {
    global $max_pb;
    
    $currentMd5SearchTerm = md5SearchTerm();
    if ($currentMd5SearchTerm == $_SESSION['md5LastSearch']) {
        return;
    }
    $_SESSION['md5LastSearch'] = $currentMd5SearchTerm;

        $_SESSION["currentView"] = 'All';
        $_SESSION["barcode"]["Type"] = clsLibGTIN::GTINCheck($_SESSION["searchTerm"], false, 1);
        $_SESSION["barcode"]["Value"] = clsLibGTIN::GTINCheck($_SESSION["searchTerm"]);

        $_SESSION["resultArr"] = [];
        $_SESSION["resultArr"] = searchAll($_SESSION["searchTerm"]);

        $_SESSION["lowestPrice"]["Used"] = findLowest("Used");
        $_SESSION["lowestPrice"]["New"] = findLowest("New");
        $_SESSION["lowestPrice"]["Digital"] = findLowest("Digital");
        $_SESSION["lowestPrice"]["All"] = 0.00;
        if (array_sum($_SESSION["lowestPrice"]) > 0) {
                $_SESSION["lowestPrice"]["All"] = minNotNull($_SESSION["lowestPrice"]);
        }

        saveSearchResult();
    updatePbFile($max_pb, 4);

    findDiscogsMaster($_SESSION["searchTerm"]);
    updatePbFile($max_pb, 5);
}

function resetSessionVars() {
    $_SESSION["searchTerm"] = '';
    $_SESSION['md5LastSearch'] = '';
        $_SESSION["currentView"] = 'All';
        $_SESSION["barcode"]["Type"] = '';
        $_SESSION["barcode"]["Value"] = '';

        $_SESSION["resultArr"] = [];

        $_SESSION["lowestPrice"]["Used"] = 0.00;
        $_SESSION["lowestPrice"]["New"] = 0.00;
        $_SESSION["lowestPrice"]["Digital"] = 0.00;
        $_SESSION["lowestPrice"]["All"] = 0.00;
}

  // search for items on all sites
function searchAll($searchKey)
{
    global $handler;
    global $max_pb;
        $arr = [];
        $newArr = [];

    updatePbFile($max_pb, 0);
        
        if ($_SESSION["filterCondition"]["New"]) {
                $arr = get_ebay($searchKey, constant("NEW"));
        }
    updatePbFile($max_pb, 1);
        
        if ($_SESSION["filterCondition"]["Used"]) {
                $newArr = get_ebay($searchKey, constant("USED"));
        }
    updatePbFile($max_pb, 2);
        
        $arr = array_merge($arr, $newArr);
        $arr = applyExchangeRates($arr);
        usort($arr, 'compare_price');
    updatePbFile($max_pb, 3);

        return $arr;
}

  // check search filters
function checkSearchFilters() {
    $_SESSION["filterWarnings"] = "";
    $filterOk = true;

        if (!$_SESSION["filterCondition"]["New"] && !$_SESSION["filterCondition"]["Used"]) {
                $_SESSION["filterWarnings"] .= '<div class="alert alert-danger"><i class="fas fa-filter mr-1"></i> Please select at least one Condition (New or Used)</div>';
                $filterOk = false;
        }

        if (!$_SESSION["filterMediaType"]["CD"] && !$_SESSION["filterMediaType"]["Record"] && !$_SESSION["filterMediaType"]["Digital"]) {
                $_SESSION["filterWarnings"] .= '<div class="alert alert-danger"><i class="fas fa-filter mr-1"></i> Please select at least one Media Type (CD, Record or Digital)</div>';
                $filterOk = false;
        }

        return($filterOk);
}

  // filter results for types All, New, Used or Digital
function filterResults()
{
        foreach ($_SESSION["resultArr"] as &$value) {
                if ($_SESSION["currentView"] == 'All') {
                        $value["Show"] = true;
                } else {
                        $value["Show"] = ($_SESSION["currentView"] == $value["Type"]);
                }
        }
}

  // build HTML table from array
function buildTable()
{
        $str = "<div>";
        $str .= "<table class=\"table table-striped table-condensed small\">";
        $str .= "<thead class=\"thead-dark sticky-top\"><tr><th>Image</th><th class=\"text-left\">Title / Merchant</th><th>Condition</th><th class=\"hide-small\">Price</th><th class=\"hide-small\">S/H</th><th>Total</th><th class=\"hide-extra-small\"></th></tr></thead>";
        $str .= "<tbody>";

    if (count($_SESSION["resultArr"]) > 0) {
        foreach ($_SESSION["resultArr"] as $value) {
                if (!$value["Show"]) {
                        continue;
                }

                $url = base64_encode($value["URL"]);

                $str .= "<tr>";

            // Image
                $str .= "<td><a href=\"/redirect.php?target=" . $url . "\" target=\"_blank\"><img class=\"img-fluid\" src=\"" . $value["Image"] . "\" alt=\"Item Image\"></a></td>";

            // Title / Merchant
                $str .= "<td class=\"text-left\"><span class=\"font-weight-bold\"><a href=\"/redirect.php?target=" . $url . "\" target=\"_blank\">" . $value["Title"] . "</a></span><br/><br/>";
                $str .= "<span class=\"font-weight-bold\">" . $value["Merchant"] . "</span>";
                $str .= "<span class=\"hide-extra-small\"><br/>" . $value["SellerName"] . " (" . number_format($value["FeedbackScore"], 0, "", ",") . " / " . $value["FeedbackPercent"] . "%)</span></td>";

            // Condition
                $str .= "<td>";
                $categoryIcon = "";
                $categoryStyle = "";
                $tooltip = "";
                switch ($value["Category"]) {
                        case "CD":
                                $categoryIcon = "fas fa-compact-disc";
                                $categoryStyle = "color:silver;";
                                $tooltip = "Compact Disc";
                                break;

                        case "Record":
                                $categoryIcon = "fas fa-dot-circle";
                                $tooltip = "Vinyl Record";
                                break;

                        case "Digital":
                                $categoryIcon = "digital";
                                $tooltip = "Digital Download";
                                break;
                }
                $str .= "<span class=\"font-weight-bold\">" . $value["Condition"] . "</span>";
                $str .= "<br/><br/>";
                $str .= "<i class=\"" . $categoryIcon . "\" style=\"font-size:32px;text-shadow:2px 2px 4px #000000;" . $categoryStyle . "\" title=\"" . $tooltip . "\" data-toggle=\"tooltip\" data-placement=\"right\" data-delay=\"200\"></i>";
                $str .= "</td>";

            // Price
                $str .= "<td class=\"hide-small\">" . print_monetary($value["Price"], $value["Currency"]);
                if ($value["Currency"] != $_SESSION["buyer"]["Currency"]) {
                        $str .= "<br/>&asymp; " . print_monetary($value["ConvertedPrice"], $_SESSION["buyer"]["Currency"]);
                }
                $str .= "</td>";

            // Shipping and Handling Cost
                $str .= "<td class=\"hide-small\">";
                if ($value["ShippingCost"] == 0.00) {
                        $str .= "Free Shipping";
                } else {
                        $str .= print_monetary($value["ShippingCost"], $value["ShippingCurrency"]);
                }
                if ($value["ShippingCost"] > 0.00 && $value["ShippingCurrency"] != $_SESSION["buyer"]["Currency"]) {
                        $str .= "<br/>&asymp; " . print_monetary($value["ConvertedShippingCost"], $_SESSION["buyer"]["Currency"]);
                }
                $str .= "<br/><img class=\"img-fluid\" title=\"Ships from " . getCountry($value["Country"]) . "\" data-toggle=\"tooltip\" data-placement=\"right\" data-delay=\"200\" src=\"/images/flags/" . $value["Country"] . ".png\" alt=\"" . getCountry($value["Country"]) . " Flag\"></td>";

            // Total Price
                $str .= "<td class=\"font-weight-bolder\">" . print_monetary($value["ConvertedTotalPrice"], $_SESSION["buyer"]["Currency"]) . "</td>";

            // Link
                $str .= "<td class=\"hide-extra-small\"><a class=\"btn btn-danger\" role=\"button\" href=\"/redirect.php?target=" . $url . "\" target=\"_blank\"><i class=\"fas fa-shopping-cart\" style=\"font-size:20px\"></i><span class=\"hide-small\"><br>Buy It Now</span></a></td>";

                $str .= "</tr>";
        }
    } else {
        $str .= "<tr class=\"text-center bg-warning\"><td colspan=\"7\"><span class=\"display-5\">No listings found</span></td></tr>";
    }

        $str .= "</tbody>";
        $str .= "<tfoot class=\"text-right\"><tr><td colspan=\"7\">Prices retrieved on " . gmdate("Y-m-d H:i") . " UTC<br>Daily exchange rates update</td></tr></tfoot>";
        $str .= "</table>";
        $str .= "</div>";

        return ($str);
}

  // print summary/header on top of listing table
function printTableHeader()
{
    global $handler;

    $str = '<div class="d-flex flex-wrap justify-content-center p-2">';
        $str .= '    <button name="submit" value="All" type="' . getButtonType("All") . '" class="btn filterButton mx-2 ' . getBackgroundColor("All") . '"';
        if ($_SESSION["lowestPrice"]["All"] <= 0) {
                $str .= ' disabled';
        }
        $str .= '><span class="display-5 font-weight-bolder">All</span><span class="display-7"> from</span><br><span class="display-6 font-weight-bolder">' . print_monetary($_SESSION["lowestPrice"]["All"], $_SESSION["buyer"]["Currency"]) . '</span>';
        $str .= '    </button>';
        $str .= '    <button name="submit" value="New" type="' . getButtonType("New") . '" class="btn filterButton mx-2 ' . getBackgroundColor("New") . '"';
        if ($_SESSION["lowestPrice"]["New"] <= 0) {
                $str .= ' disabled';
        }
        $str .= '><span class="display-5 font-weight-bolder">New</span><span class="display-7"> from</span><br><span class="display-6 font-weight-bolder">' . print_monetary($_SESSION["lowestPrice"]["New"], $_SESSION["buyer"]["Currency"]) . '</span>';
        $str .= '    </button>';
        $str .= '    <button name="submit" value="Used" type="' . getButtonType("Used") . '" class="btn filterButton mx-2 ' . getBackgroundColor("Used") . '"';
        if ($_SESSION["lowestPrice"]["Used"] <= 0) {
                $str .= ' disabled';
        }
        $str .= '><span class="display-5 font-weight-bolder">Used</span><span class="display-7"> from</span><br><span class="display-6 font-weight-bolder">' . print_monetary($_SESSION["lowestPrice"]["Used"], $_SESSION["buyer"]["Currency"]) . '</span>';
        $str .= '    </button>';
        /*
    $str .= '    <button name="submit" value="Digital" type="' . getButtonType("Digital") . '" class="btn filterButton mx-2 ' . getBackgroundColor("Digital"). '"';
    if ($_SESSION["lowestPrice"]["Digital"] <= 0) {
        $str .= ' disabled';
    }
    $str .= '><span class="display-5 font-weight-bolder">Digital</span><span class="display-7"> from</span><br><span class="display-6 font-weight-bolder">' . print_monetary($_SESSION["lowestPrice"]["Digital"], $_SESSION["buyer"]["Currency"]) . '</span>';
    $str .= '    </button>';
*/
    $str .= '</div>';

        return $str;
}

  // get top button background color
function getBackgroundColor($sel)
{
        if ($_SESSION["currentView"] == $sel) {
                return ("btn-primary active");
        }

        return ("btn-primary text-dark");
}

  // get top button type
function getButtonType($sel)
{
        if ($_SESSION["currentView"] == $sel) {
                return ("button");
        }

        return ("submit");
}

  // compare price for sort low to high
function compare_price($a, $b)
{
        return strnatcmp($a['ConvertedTotalPrice'], $b['ConvertedTotalPrice']);
}

  // print monetary values with correct symbol and thousands/decimal delimiters
function print_monetary($num, $curr)
{
        if ($curr == "USD") {
                return ("$" . number_format($num, 2, '.', ','));
        } else if ($curr == "CAD") {
                return ("C $" . number_format($num, 2, '.', ','));
        } else if ($curr == "EUR") {
                return (number_format($num, 2, ',', '.') . "&euro;");
        } else if ($curr == "GBP") {
                return ("&pound;" . number_format($num, 2, '.', ','));
        } else if ($curr == "AUD") {
                return ("AU $" . number_format($num, 2, '.', ','));
        }

        return ($curr . " " . number_format($num, 2, '.', ','));
}

  // find lowest used / new prices and return their array index
function findLowest($type)
{
        foreach ($_SESSION["resultArr"] as $value) {
                if (!$value["Show"]) {
                        continue;
                }

                if ($type == $value["Type"]) {
                        return ($value["ConvertedTotalPrice"]);
                }
        }

        return (0);
}

  // find lowest non-zero double value in array
function minNotNull(Array $values)
{
        return min(array_diff(array_map('doubleval', $values), array(0)));
}

  // apply exchange rates
function applyExchangeRates($arr)
{
        foreach ($arr as &$value) {
                $value["ConvertedPrice"] = $value["Price"];
                $value["ConvertedShippingCost"] = $value["ShippingCost"];

                if ($_SESSION["buyer"]["Currency"] != $value["Currency"]) {
                        $value["ConvertedPrice"] = number_format($value["Price"] / getExchangeRate($_SESSION["buyer"]["Currency"], $value["Currency"]), 2, '.', '');
                }

                if ($_SESSION["buyer"]["Currency"] != $value["ShippingCurrency"]) {
                        $value["ConvertedShippingCost"] = number_format($value["ShippingCost"] / getExchangeRate($_SESSION["buyer"]["Currency"], $value["ShippingCurrency"]), 2, '.', '');
                }

                $value["ConvertedTotalPrice"] = number_format($value["ConvertedPrice"] + $value["ConvertedShippingCost"], 2, '.', '');
        }

        return ($arr);
}

  // sanitize user input
function sanitizeInput($data)
{
        $data = trim(preg_replace('/[\t\n\r\s]+/', ' ', $data));
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
}

// convert certain utf-8 characters to ascii
function cleanString($str) {
    $utf8 = array(
        '/[áàâãªä]/u'   =>   'a',
        '/[ÁÀÂÃÄ]/u'    =>   'A',
        '/[ÍÌÎÏ]/u'     =>   'I',
        '/[íìîï]/u'     =>   'i',
        '/[éèêë]/u'     =>   'e',
        '/[ÉÈÊË]/u'     =>   'E',
        '/[óòôõºö]/u'   =>   'o',
        '/[ÓÒÔÕÖ]/u'    =>   'O',
        '/[úùûü]/u'     =>   'u',
        '/[ÚÙÛÜ]/u'     =>   'U',
        '/ç/'           =>   'c',
        '/Ç/'           =>   'C',
        '/ñ/'           =>   'n',
        '/Ñ/'           =>   'N',
        '/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
        '/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
        '/[“”«»„]/u'    =>   ' ', // Double quote
        '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
    );

    return preg_replace(array_keys($utf8), array_values($utf8), $str);
}

// Clean the search string
function searchFriendlyString($str) {
    $str = strip_tags($str);
    $str = stripslashes($str);
    $str = cleanString($str);
    $str = str_replace(array("[", "]", "<", ">", "(", ")", " - ", " & "," / "), " ", $str);    // eliminate single '-', '&', '/' and brackets
    $str = trim(preg_replace('/[\t\n\r\s]+/', ' ', $str));          // delete extra whitespaces
    return ucwords($str);
}

  // get a SESSION value, return empty string if not set
function getSV($var)
{
        if (!isset($_SESSION[$var])) {
                return ('');
        }

        return ($_SESSION[$var]);
}

  // initialize a SESSION value if not set
function initSV($var, $value)
{
        if (!isset($_SESSION[$var])) {
                $_SESSION[$var] = $value;
        }
}

  // initialize sessions variables
function initSessionVariables()
{
        initSV("resultArr", []);
        initSV("barcode", array("Type" => "", "Value" => ""));
        initSV("buyer", array("Country" => "United States", "Currency" => "USD", "Zip" => ""));
        initSV("filterCondition", array("New" => true, "Used" => true));
        initSV("filterMediaType", array("CD" => true, "Record" => false, "Digital" => false));
        initSV("currentView", "All");
        initSV("lowestPrice", array("Used" => 0.00, "New" => 0.00, "Digital" => 0.00, "All" => 0.00));
        initSV("filterWarnings", "");
        initSV("md5LastSearch", "");
}

function md5SearchTerm() {
    $data = array();
    $data['cond'] = $_SESSION['filterCondition'];
    $data['type'] = $_SESSION['filterMediaType'];
    $data['term'] = array($_SESSION['searchTerm']);

    return(md5(json_encode($data)));
}

  // check POST value, return true if set and false if not
function checkPV($var)
{
        if (isset($_POST[$var])) {
                return (true);
        }

        return (false);
}

  // get POST value, return empty if not set
function getPV($var)
{
        if (isset($_POST[$var])) {
                return ($_POST[$var]);
        }

        return ("");
}

// print search filter modal with current selection
function printSearchFilterModal()
{
    global $handler;

        $str = '';
        $str .= '<div class="modal fade" id="filterModal">';
        $str .= '    <div class="modal-dialog">';
        $str .= '        <div class="modal-content">';
        $str .= '';
        $str .= '            <div class="modal-header bg-primary">';
        $str .= '                <h4 class="modal-title">Search Filters</h4>';
        $str .= '            </div>';
        $str .= '';
        $str .= '            <form method="post" action="/index.php">';
    $str .= '                <input type="hidden" name="sessionTab" value="' . $handler->getSessionTab() . '">';
        $str .= '                <div class="modal-body">';
        $str .= '                    <div class="card-group">';
        $str .= '';
        $str .= '                        <div class="card m-2">';
        $str .= '                            <div class="card-header font-weight-bold">Condition</div>';
        $str .= '                            <div class="card-body">';
        $str .= '                                <div class="form-check">';
        $str .= '                                    <label class="form-check-label">';
        $str .= '                                        <input name="filterConditionNew" type="checkbox" class="form-check-input" value="New"' . ($_SESSION["filterCondition"]["New"] ? " checked" : "") . '>New';
        $str .= '                                    </label>';
        $str .= '                                </div>';
        $str .= '                                <div class="form-check">';
        $str .= '                                    <label class="form-check-label">';
        $str .= '                                        <input name="filterConditionUsed" type="checkbox" class="form-check-input" value="Used"' . ($_SESSION["filterCondition"]["Used"] ? " checked" : "") . '>Used';
        $str .= '                                    </label>';
        $str .= '                                </div>';
        $str .= '                            </div>';
        $str .= '                        </div>';
        $str .= '';
        $str .= '                        <div class="card m-2">';
        $str .= '                            <div class="card-header font-weight-bold">Media Type</div>';
        $str .= '                            <div class="card-body">';
        $str .= '                                <div class="form-check">';
        $str .= '                                    <label class="form-check-label">';
        $str .= '                                        <input name="filterMediaTypeCD" type="checkbox" class="form-check-input" value="CD"' . ($_SESSION["filterMediaType"]["CD"] ? " checked" : "") . '><i class="fas fa-compact-disc" style="color:silver;"></i> Compact Disc';
        $str .= '                                    </label>';
        $str .= '                                </div>';
        $str .= '                                <div class="form-check">';
        $str .= '                                    <label class="form-check-label">';
        $str .= '                                        <input name="filterMediaTypeRecord" type="checkbox" class="form-check-input" value="Record"' . ($_SESSION["filterMediaType"]["Record"] ? " checked" : "") . '><i class="fas fa-dot-circle"></i> Vinyl Record';
        $str .= '                                    </label>';
        $str .= '                                </div>';
        $str .= '                                <div class="form-check">';
        $str .= '                                    <label class="form-check-label">';
        $str .= '                                        <input name="filterMediaTypeDigital" type="checkbox" class="form-check-input" value="Digital"' . ($_SESSION["filterMediaType"]["Digital"] ? " checked" : "") . '><i class="fas fa-download"></i> Digital';
        $str .= '                                    </label>';
        $str .= '                                </div>';
        $str .= '                            </div>';
        $str .= '                        </div>';
        $str .= '                    </div>';
        $str .= '                </div>';
        $str .= '';
        $str .= '                <div class="modal-footer bg-primary">';
        $str .= '                    <button type="submit" class="btn btn-success" name="submit" value="Save">Save</button>';
        $str .= '                    <button type="button" class="btn btn-danger" data-dismiss="modal">Discard</button>';
        $str .= '                </div>';
        $str .= '            </form>';
        $str .= '        </div>';
        $str .= '    </div>';
        $str .= '</div>';

        return ($str);
}

// print search info modal
function printSearchInfoModal()
{
        $str = '';
        $str .= '<div class="modal fade" id="searchInfoModal">';
        $str .= '    <div class="modal-dialog">';
        $str .= '        <div class="modal-content">';
        $str .= '';
        $str .= '            <div class="modal-header bg-primary">';
        $str .= '                <h4 class="modal-title">Search Tips</h4>';
        $str .= '                <button type="button" class="close" data-dismiss="modal"><i class="fas fa-window-close" style="font-size:24px"></i></button>';
        $str .= '            </div>';
        $str .= '';
        $str .= '            <div class="modal-body">';
        $str .= '                <h4>Search Keywords</h4>';
        $str .= '';
        $str .= '                <p><span class=font-weight-bold>Barcode:</span>';
        $str .= '                    <br>The 12 or 13 digit barcode, normally located on the back, offers the best chance to find a specific album.</p>';
        $str .= '';
        $str .= '                <p><span class=font-weight-bold>Artist and Title:</span>';
        $str .= '                    <br>The full name of the album, including artist and title, will usually lead to a specific album.</p>';
        $str .= '';
        $str .= '                <p><span class=font-weight-bold>Just Artist or Title:</span>';
        $str .= '                    <br>Searches for artist or title alone will bring up random albums.</p>';
        $str .= '            </div>';
        $str .= '        </div>';
        $str .= '    </div>';
        $str .= '</div>';

        return ($str);
}

        function saveSearchResult() {
            global $handler;
            $_sess_db = $handler->getDBSessionId();

        $access = mysqli_real_escape_string($_sess_db, time());
        // BUGBUG
        //  country
        //  currency
        $zip = mysqli_real_escape_string($_sess_db, $_SESSION['buyer']['Zip']);
        $condNew = $_SESSION['filterCondition']['New'] ? 'Y' : 'N';
        $condUsed = $_SESSION['filterCondition']['Used'] ? 'Y' : 'N';
        $mediaCD = $_SESSION['filterMediaType']['CD'] ? 'Y' : 'N';
        $mediaRecord = $_SESSION['filterMediaType']['Record'] ? 'Y' : 'N';
        $mediaDigital = $_SESSION['filterMediaType']['Digital'] ? 'Y' : 'N';
        $data = mysqli_real_escape_string($_sess_db, $_SESSION['searchTerm']);
        $lowNew = floatval($_SESSION['lowestPrice']['New']);
        $lowUsed = floatval($_SESSION['lowestPrice']['Used']);
        $lowDigital = floatval($_SESSION['lowestPrice']['Digital']);
        $count = count($_SESSION['resultArr']);

        $sql = "INSERT
                INTO    searches
                (sessId, access, zip, condNew, condUsed, mediaCD, mediaRecord, mediaDigital, data, lowNew, lowUsed, lowDigital, count)
                VALUES  ('" . session_id() . "', '$access', '$zip', '$condNew', '$condUsed', '$mediaCD', '$mediaRecord', '$mediaDigital', '$data', $lowNew, $lowUsed, $lowDigital, $count)";

//        return mysqli_query($_sess_db, $sql);

        return (mysqli_query($_sess_db, $sql));
        }

// file_get_contents wrapper to retrieve compressed url data
function getUrl($url, $userAgent = null) {
    // Set request header with encoding, charset and optional user-agent
        $opts = array(
                'http' => array(
                'method' => "GET",
                        'header' => "Accept-Language: en-US,en;q=0.5\r\n" .
                                    "Accept-Encoding: gzip, deflate\r\n" .
                                                "Accept-Charset: UTF-8,*;q=0.5\r\n" .
                                                ($userAgent ? "User-Agent: " . $userAgent . "\r\n" : "")
                )
        );

        $context = stream_context_create($opts);
        try {
            $content = file_get_contents($url, false, $context);

        $status_line = $http_response_header[0];
        preg_match('{HTTP\/\S*\s(\d{3})}', $status_line, $match);
        $status = $match[1];

            if ($status != 200 || $content === false) {
//bugbug no return
            return "";
            }
        } catch (Exection $e) {
//bugbug unreachable
        return "";
        }

        // If http response header mentions that content is gzipped, then uncompress it
        foreach($http_response_header as $c => $h)
        {
                if(stristr($h, 'content-encoding') && stristr($h, 'gzip'))
                {
                        // Uncompress the data
                        $content = gzinflate(substr($content, 10, -8));
                }
        }

        return $content;
}

function getSearchHistory() {
    $str = "";
    $sql = "select data, max(access) from searches where sessId = '" . session_id () . "' group by data order by max(access) desc, data limit 0,30;";
    $conn = MySessionHandler::getDBSessionId();

    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) {
        while($row = mysqli_fetch_assoc($result)) {
            $str .= "<option>" . $row["data"] . "</option>";
        }
    }

    return $str;
}

// bugbug
// Delete left over progressbar files older than 2 days
function cleanupPbFiles() {
    $files = glob("../tmp/pb*.txt");
    $now   = time();
    foreach ($files as $file) {
        if (is_file($file)) {
            if ($now - filemtime($file) >= 60 * 60 * 24 * 2) { // 2 days and older
                unlink($file);
            }
         }
    }
}

// Update progressbar file for a session
function updatePbFile($total, $current) {
    global $handler;
    $filename = session_id()  . "_" . $handler->getSessionTab(); 
    $arr_content = array();

    $percent = intval($current / $total * 100);

    $arr_content['percent'] = $percent;
    $arr_content['message'] = $current . " search(es) processed.";

    file_put_contents("../tmp/pb_" . $filename . ".txt", json_encode($arr_content));
}