<?php

// Try to find a usable title for an image, checking multiple metadata
// sources (since different tools - GIMP, Lightroom, camera EXIF, etc -
// don't all write to the same tag). Falls back to a cleaned-up filename
// if nothing else is found, so alt text is never empty.
function get_image_title($image_path) {

    // strips 'special' characters, allows a-z, spaces, dashes and round brackets
    $clean = function($val) {
        return trim(preg_replace('/[^A-Za-z0-9\- ()]/', ' ', $val));
    };

    // 1) EXIF - IFD0 Title (what many cameras / some tools use)
    $exif = @exif_read_data($image_path, 0, true);
    if ($exif !== false) {
        foreach ($exif as $key => $section) {
            foreach ($section as $name => $val) {
                if ($key == 'IFD0' and $name == "Title" and trim($val) !== '') {
                    return $clean($val);
                }
            }
        }
    }

    // 2) IPTC - "Object Name" (2#005), commonly used as "Title" by
    // GIMP, Photoshop, and most DAM/photo tools
    $info = array();
    if (@getimagesize($image_path, $info) !== false && isset($info['APP13'])) {
        $iptc = @iptcparse($info['APP13']);
        if ($iptc !== false && isset($iptc['2#005'][0]) && trim($iptc['2#005'][0]) !== '') {
            return $clean($iptc['2#005'][0]);
        }
    }

    // 3) XMP - dc:title (used by GIMP's metadata editor, Lightroom, etc)
    // XMP isn't exposed by a built-in PHP function, so pull the raw XMP
    // packet out of the file and grab the title with a simple regex.
    $raw = @file_get_contents($image_path, false, null, 0, 65536);
    if ($raw !== false && preg_match('/<dc:title>.*?<rdf:li[^>]*>(.*?)<\/rdf:li>/s', $raw, $matches)) {
        $xmp_title = trim(html_entity_decode($matches[1]));
        if ($xmp_title !== '') {
            return $clean($xmp_title);
        }
    }

    // 4) Fallback - use the filename, swapping underscores/dashes for
    // spaces and title-casing it, so there's always sensible alt text
    $filename = pathinfo($image_path, PATHINFO_FILENAME);
    $filename = str_replace(array('_', '-'), ' ', $filename);
    return ucwords(trim($filename));

}

function make_gallery($folder_name) {

    $dirname = "images/$folder_name/";
        $images = glob($dirname."*.jpg");

        foreach($images as $images) {

            // checks EXIF, then IPTC, then XMP, then falls back to the
            // filename so every image gets sensible alt text
            $title = get_image_title($images);

            ?>

        <div class="responsive-gallery">

            <div class="gallery">

                <a href="<?php echo $images; ?>" class="big">
                <img class="responsive" src="<?php echo $images; ?>" alt="<?php echo $title; ?>" title="<?php echo $title; ?>" />
                </a>

            </div>

        </div>

        <?php

        } // end of each loop


} // end f gallery maker function

?>