Location: PHPKode > scripts > Impleo Music Collection Script > impleo/years.php
<?php
/* ----------------------------------------------------------------------------
 * "THE BEER-WARE LICENSE" (Revision 42):
 * <hide@address.com> wrote this file. As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return Christoffer Kjeldgaard Petersen
 * ----------------------------------------------------------------------------
 */

require_once(dirname(__FILE__) . '/classes/Factory.class.php');

$factory = Factory::getInstance();
$arrItems = $factory->getAttributeListCount('year');

$arrYears = yearSort($arrItems);

$IMAGE_WIDTH = 20 * count($arrYears);
$IMAGE_HEIGHT = 400;

$itemKeys = array_keys($arrItems);

outputImage($arrYears, $IMAGE_WIDTH, $IMAGE_HEIGHT, $arrItems[$itemKeys[0]]);

/**
 * Sorts year array and fills non-present years with zeroes.
 * @param array $arrYears Raw year array
 * @return array Sorted year array
 */
function yearSort($arrYears)
{
    ksort($arrYears);
    $keys = array_keys($arrYears);
    $first = $keys[0];
    $last = $keys[count($arrYears)-1];

    $arrYearSorted = array();
    for ($year = $first; $year <= $last; $year++)
    {
        if (array_key_exists($year, $arrYears))
            $arrYearSorted[] = array($year, $arrYears[$year]);
        else
            $arrYearSorted[] = array($year, 0);
    }

    return $arrYearSorted;
}

/**
 * Ouputs the year graph.
 * 
 * @param array $arrYears Data array with release years
 * @param int $width Width of the image to output
 * @param int $height Height of the image to output
 * @param int $largestY Amount of years most present in the collection.
 */
function outputImage($arrYears, $width, $height, $largestY)
{
    if (count($arrYears) > 0)
    {
        $img = imagecreate($width, $height);
        
        $bg = imagecolorallocate($img, 204, 204, 204);
        $barColor = imagecolorallocate($img, 0x00, 0x00, 0x00);
        $black = imagecolorallocate($img, 0x00, 0x00, 0x00);

        imagefilledrectangle($img, 0, 0, $width, $height, $bg);

        $deltaX = $width / count($arrYears);

        for ($i = 0; $i < count($arrYears); $i++)
        {
            $items = $arrYears[$i][1];
            $maxHeight = $height - 60;
            $y = $height - ($items / $largestY * $maxHeight);

            imagefilledrectangle($img, $i*$deltaX, $y, ($i*$deltaX)+$deltaX, $height, $barColor);

            $txt = $arrYears[$i][0] . " (" . $arrYears[$i][1] . ")";
            imagestringup($img, 3, ($i*$deltaX)+3, $y-5, $txt, $black);
        }

        header("Content-Type: image/png");
        imagepng($img);
    }
}

?>
Return current item: Impleo Music Collection Script