/**
  * if a cached image is available, this could return a direct url
  * otherwise it can return a url which will generate the required
  * image 
  * @access public
  */
 function getImageUrl()
 {
     global $CONF;
     if ($this->type_or_user == -1 && $this->pixels_per_km > 4) {
         $this->type_or_user = 0;
         $real = -1;
     }
     //always given dynamic url, that way cached HTML can
     //always get an image
     $token = $this->getToken();
     $file = "http://{$CONF['TILE_HOST']}/tile.php?map={$token}";
     if (isset($CONF['curtail_level']) && $CONF['curtail_level'] > 2 && empty($GLOBALS['USER']->user_id)) {
         $file = cachize_url($file);
     }
     if (isset($real)) {
         $this->type_or_user = $real;
     }
     return $file;
 }
 function getImageTag($gridref = '')
 {
     global $CONF;
     $east = floor($this->nateastings / 1000) * 1000;
     $nort = floor($this->natnorthings / 1000) * 1000;
     $width = $this->width;
     if ($this->service == 'Google') {
         if (!empty($this->inline) || !empty($this->issubmit)) {
             return "<div id=\"map\" style=\"width:{$width}px; height:{$width}px\">Loading map... (JavaScript required)</div>";
         } else {
             $token = new Token();
             foreach ($this as $key => $value) {
                 if (is_scalar($value)) {
                     $token->setValue($key, $value);
                 }
             }
             $token = $token->getToken();
             return "<iframe src=\"/map_frame.php?t={$token}\" id=\"map\" width=\"{$width}\" height=\"{$width}\" scrolling=\"no\">Loading map... (JavaScript required)</iframe>";
         }
     } elseif ($this->service == 'OS50k-small') {
         static $idcounter = 1;
         if ($this->natgrlen == 4) {
             $this->nateastings = $east + 500;
             $this->natnorthings = $nort + 500;
         }
         $mapurl = "http://{$CONF['TILE_HOST']}/tile.php?r=" . $this->getToken();
         if (isset($CONF['curtail_level']) && $CONF['curtail_level'] > 3 && empty($GLOBALS['USER']->user_id)) {
             $mapurl = cachize_url($mapurl);
         }
         $gr = str_replace(' ', '+', !empty($this->square->grid_reference_full) ? $this->square->grid_reference_full : $this->square->grid_reference);
         $title = "1:50,000 Modern Day Landranger(TM) Map &copy; Crown Copyright";
         $this->displayMarker1 = $this->exactPosition;
         if ($this->displayMarker1 && !($this->natgrlen > 6)) {
             //nice central marker
             $padding = intval(($width - 29) / 2);
             $str .= "<a href=\"/gridref/{$gr}\" title=\"{$title}\" onmouseover=\"document.getElementById('marker{$idcounter}').src='http://{$CONF['STATIC_HOST']}/img/blank.gif'\" onmouseout=\"document.getElementById('marker{$idcounter}').src='http://{$CONF['STATIC_HOST']}/img/icons/circle.png'\"><img src=\"http://{$CONF['STATIC_HOST']}/img/icons/circle.png\" style=\"padding:{$padding}px;width:29px;height:29px;background-image:url({$mapurl});\" border=\"1\" alt=\"{$title}\" galleryimg=\"no\" id=\"marker{$idcounter}\"/></a>";
         } elseif ($this->displayMarker1) {
             //need to manipualte the marker position
             $top = $width / 2;
             $left = $width / 2;
             $widthby20 = $width / 20;
             //remove the automatic 50m centering
             $top += $widthby20;
             $left -= $widthby20;
             $widthby10 = $width / 10;
             //assubuing 1km width
             #100m = 1 unit
             $left += intval($this->nateastings % 100 / 100 * $widthby10);
             $top -= intval($this->natnorthings % 100 / 100 * $widthby10);
             //top,left contain center point
             $widthby2 = $width / 2;
             $movedown = intval($top - $widthby2);
             $movetoright = intval($left - $widthby2);
             $padding = intval(($width - 29) / 2);
             $ptop = $padding + $movedown;
             $pbottom = $padding - $movedown;
             $pleft = $padding + $movetoright;
             $pright = $padding - $movetoright;
             $padding = "padding:{$ptop}px {$pright}px {$pbottom}px {$pleft}px";
             $str .= "<a href=\"/gridref/{$gr}\" title=\"{$title}\" onmouseover=\"document.getElementById('marker{$idcounter}').src='http://{$CONF['STATIC_HOST']}/img/blank.gif'\" onmouseout=\"document.getElementById('marker{$idcounter}').src='http://{$CONF['STATIC_HOST']}/img/icons/circle.png'\"><img src=\"http://{$CONF['STATIC_HOST']}/img/icons/circle.png\" style=\"{$padding};width:29px;height:29px;background-image:url({$mapurl});\" border=\"0\" alt=\"{$title}\" galleryimg=\"no\" id=\"marker{$idcounter}\"/></a>";
         } else {
             //no marker
             $str .= "<a href=\"/gridref/{$gr}\" title=\"{$title}\"><img src=\"http://{$CONF['STATIC_HOST']}/img/blank.gif\" style=\"width:{$width}px;height:{$width}px;background-image:url({$mapurl});\" border=\"1\" alt=\"{$title}\" galleryimg=\"no\" id=\"marker{$idcounter}\"/></a>";
         }
         $idcounter++;
         return $str;
     } elseif ($this->service == 'OS50k') {
         if (!empty($CONF['fetch_on_demand'])) {
             $mapurl = "http://{$CONF['fetch_on_demand']}/tile.php?r=" . $this->getToken();
         } else {
             $mapurl = "http://{$CONF['TILE_HOST']}/tile.php?r=" . $this->getToken();
         }
         if (isset($CONF['curtail_level']) && $CONF['curtail_level'] > 3 && empty($GLOBALS['USER']->user_id)) {
             $mapurl = cachize_url($mapurl);
         }
         #$this->mapurl = $mapurl;
         $title = "1:50,000 Modern Day Landranger(TM) Map &copy; Crown Copyright";
     }
     if ($this->service == 'VoB' || $this->service2 == 'VoB') {
         $e1 = $east - 500;
         $e2 = $e1 + 2000;
         $n1 = $nort - 500;
         $n2 = $n1 + 2000;
         //Use of this URL is not permitted outside of geograph.org.uk
         $mapurl2 = "http://vision.edina.ac.uk/cgi-bin/wms-vision?version=1.1.0&request=getMap&layers=newpop%2Csmall_1920%2Cmed_1904&styles=&SRS=EPSG:27700&Format=image/png&width={$width}&height={$width}&bgcolor=cfd6e5&bbox={$e1},{$n1},{$e2},{$n2}&exception=application/vnd.ogc.se_inimage";
         $title2 = "1940s OS New Popular Edition Historical Map &copy; VisionOfBritain.org.uk";
         if ($this->service == 'VoB') {
             $title = $title2;
             $mapurl = $mapurl2;
         }
     }
     if (isset($title)) {
         $extra = $this->issubmit === true ? 44 : ($this->issubmit ? 22 : 0);
         //container
         $str = "<div style=\"position:relative;height:" . ($width + $extra) . "px;width:{$this->width}px;\" id=\"rastermap\">";
         //map image
         $str .= "<div style=\"top:0px;left:0px;width:{$width}px;height:{$width}px\"><img name=\"tile\" src=\"{$mapurl}\" style=\"width:{$width}px;height:{$width}px\" border=\"1\" alt=\"{$title}\"/></div>";
         //drag prompt
         if ($this->issubmit) {
             $str .= "<div style=\"position:absolute;top:" . $width . "px;left:0px; font-size:0.8em;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <small style=\"color:#0018F8\">&lt;- Drag to mark subject position.</small></div>";
         }
         if ($this->issubmit === true) {
             $str .= "<div style=\"position:absolute;top:" . ($width + 22) . "px;left:0px; font-size:0.8em;\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <small style=\"color:#002E73\">&lt;- Drag to mark photographer position.</small></div>";
         }
         $widthby2 = $width / 2;
         //calculate subject position
         if ($this->issubmit && !$this->exactPosition) {
             //ready to drag position
             $left = 13;
             $top = $width + 10;
         } else {
             $e = $this->nateastings;
             $n = $this->natnorthings;
             if ($this->natgrlen == '6' && $this->exactPosition) {
                 $e += 50;
                 $n += 50;
             }
             $left = $width / 4 + ($e - $east) * $widthby2 / 1000;
             $top = $width - ($width / 4 + ($n - $nort) * $widthby2 / 1000);
         }
         //choose photographer icon
         $prefix = $this->issubmit ? 'viewc' : 'camicon';
         if (isset($this->view_direction) && strlen($this->view_direction) && $this->view_direction != -1) {
             $iconfile = "{$prefix}-" . intval($this->view_direction) . ".png";
         } else {
             $iconfile = "{$prefix}--1.png";
         }
         if ($this->viewpoint_ri == $this->reference_index) {
             $viewpoint_eastings = $this->viewpoint_eastings;
             $viewpoint_northings = $this->viewpoint_northings;
         } else {
             $viewpoint_eastings = -1;
             $viewpoint_northings = -1;
             $latlong = $conv->national_to_wgs84($this->viewpoint_eastings, $this->viewpoint_northings, $this->viewpoint_ri);
             if (count($latlong)) {
                 $enr = $conv->wgs84_to_national($latlong[0], $latlong[1], true, $this->reference_index);
                 if (count($enr)) {
                     $viewpoint_eastings = $enr[0];
                     $viewpoint_northings = $enr[1];
                 }
             }
         }
         $different_square_true = intval($this->nateastings / 1000) != intval($viewpoint_eastings / 1000) || intval($this->natnorthings / 1000) != intval($viewpoint_northings / 1000);
         $show_viewpoint = intval($this->viewpoint_grlen) > 4 || $different_square_true && $this->viewpoint_grlen == '4';
         //calculate photographer position
         if (!$this->issubmit && $show_viewpoint) {
             $e = $viewpoint_eastings;
             $n = $viewpoint_northings;
             if ($this->viewpoint_grlen == '4') {
                 $e += 500;
                 $n += 500;
             }
             if ($this->viewpoint_grlen == '6') {
                 $e += 50;
                 $n += 50;
             }
             $vleft = $width / 4 + ($e - $east) * $widthby2 / 1000;
             $vtop = $width - ($width / 4 + ($n - $nort) * $widthby2 / 1000);
             if ($vleft < -8 || $vleft > $width + 8 || $vtop < -8 || $vtop > $width + 8 || $different_square_true && $this->viewpoint_grlen == '4') {
                 //if outside the map extents clamp to an edge
                 if (abs($left - $vleft) < abs($top - $vtop)) {
                     // top/bottom edge
                     $realangle = atan2($left - $vleft, $top - $vtop);
                     $vtop = $top < $vtop ? $width + 16 : -16;
                     $vleft = tan($realangle) * ($top - $vtop) * -1 + $left;
                 } else {
                     // left/right edge
                     $realangle = atan2($top - $vtop, $left - $vleft);
                     $vleft = $left < $vleft ? $width + 16 : -16;
                     $vtop = tan($realangle) * ($left - $vleft) * -1 + $top;
                 }
                 $iconfile = "camera.png";
             }
         } else {
             //ready to drag position
             $vleft = 13;
             $vtop = $width + 32;
         }
         $top = round($top);
         $left = round($left);
         $vtop = round($vtop);
         $vleft = round($vleft);
         $this->displayMarker1 = $this->issubmit || $this->exactPosition ? 1 : 0;
         $this->displayMarker2 = $this->issubmit === true || $show_viewpoint && ($vleft != $left || $vtop != $top) ? 1 : 0;
         if ((!$this->displayMarker2 || $iconfile == "camera.png") && !$this->issubmit) {
             $prefix = 'subc';
             if (isset($this->view_direction) && strlen($this->view_direction) && $this->view_direction != -1) {
                 $subfile = "{$prefix}-" . intval($this->view_direction) . ".png";
             } else {
                 $subfile = "{$prefix}--1.png";
             }
         } else {
             $subfile = 'circle.png';
         }
         //subject icon
         $str .= "<div style=\"position:absolute;top:" . ($top - 14) . "px;left:" . ($left - 14) . "px;" . ($this->displayMarker1 ? '' : 'display:none') . "\" id=\"marker1\"><img src=\"http://{$CONF['STATIC_HOST']}/img/icons/{$subfile}\" alt=\"+\" width=\"29\" height=\"29\" name=\"subicon\"/></div>";
         //photographer icon
         if ($this->issubmit) {
             $str .= "<div style=\"position:absolute;top:" . ($vtop - 14) . "px;left:" . ($vleft - 14) . "px;" . ($this->displayMarker2 ? '' : 'display:none') . "\" id=\"marker2\"><img src=\"http://{$CONF['STATIC_HOST']}/img/icons/{$iconfile}\" alt=\"+\" width=\"29\" height=\"29\" name=\"camicon\"/></div>";
         } else {
             $str .= "<div style=\"position:absolute;top:" . ($vtop - 20) . "px;left:" . ($vleft - 9) . "px;" . ($this->displayMarker2 ? '' : 'display:none') . "\" id=\"marker2\"><img src=\"http://{$CONF['STATIC_HOST']}/img/icons/{$iconfile}\" alt=\"+\" width=\"20\" height=\"31\" name=\"camicon\"/></div>";
         }
         //overlay (for dragging)
         $str .= "<div style=\"position:absolute;top:0px;left:0px;z-index:3\">";
         $imagestr = "<img src=\"http://{$CONF['STATIC_HOST']}/img/blank.gif\" class=\"mapmask\" style=\"width:{$width}px;height:" . ($width + $extra) . "px\" border=\"1\" alt=\"{$title}\" title=\"{$title}\" name=\"map\" galleryimg=\"no\"/>";
         if (!empty($gridref)) {
             $this->clickable = true;
             $str .= smarty_function_getamap(array('text' => $imagestr, 'gridref' => $gridref, 'title' => $title, 'icon' => 'no'));
         } else {
             $str .= $imagestr;
         }
         $str .= "</div>";
         $str .= "</div>";
         //map switcher
         if ($this->service2) {
             return "{$str}\n\t\t\t\t<br/>\n\t\t\t\t<div class=\"interestBox\" style=\"font-size:0.8em\">Switch to <a href=\"javascript:switchTo(2);\"  id=\"mapSwitcherOS50k\">Historic Map</a><a href=\"javascript:switchTo(1);\" id=\"mapSwitcherVoB\" style=\"display:none\">Modern Map</a>.</div>\n\t\t\t\t<script type=\"text/javascript\">\n\t\t\t\tfunction switchTo(too) {\n\t\t\t\t\tshowOS50k = (too == 1)?'':'none';\n\t\t\t\t\tshowVoB = (too == 2)?'':'none';\n\t\t\t\t\t\n\t\t\t\t\tdocument.getElementById('mapSwitcherOS50k').style.display = showOS50k;\n\t\t\t\t\tdocument.getElementById('mapTitleOS50k').style.display = showOS50k;\n\t\t\t\t\tdocument.getElementById('mapFootNoteOS50k').style.display = showOS50k;\n\t\t\t\t\t\n\t\t\t\t\tdocument.getElementById('mapSwitcherVoB').style.display = showVoB;\n\t\t\t\t\tdocument.getElementById('mapTitleVoB').style.display = showVoB;\n\t\t\t\t\tdocument.getElementById('mapFootNoteVoB').style.display = showVoB;\n\t\t\t\t\t\n\t\t\t\t\tif (too == 1) {\n\t\t\t\t\t\tdocument.images['tile'].src = '{$mapurl}';\n\t\t\t\t\t\tdocument.images['map'].title = '{$title}';\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdocument.images['tile'].src = 'http://{$CONF['STATIC_HOST']}/img/blank.gif';\n\t\t\t\t\t\tdocument.images['tile'].src = '{$mapurl2}';\n\t\t\t\t\t\tdocument.images['map'].title = '{$title2}';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t</script>";
         } else {
             return $str;
         }
         //end
     }
 }
/**
* smarty function to get revision number
*/
function smarty_modifier_revision($filename)
{
    global $REVISIONS, $CONF;
    if (isset($REVISIONS[$filename])) {
        $url = "http://{$CONF['STATIC_HOST']}" . preg_replace('/\\.(js|css)$/', ".v{$REVISIONS[$filename]}.\$1", $filename);
        if (isset($CONF['curtail_level']) && $CONF['curtail_level'] > 4 && strpos($filename, 'css') === FALSE && empty($GLOBALS['USER']->user_id)) {
            $url = cachize_url($url);
        }
        return $url;
    } else {
        #return "http://{$CONF['STATIC_HOST']}".preg_replace('/\.(js|css)$/',".v".time().".$1",$filename);
        return $filename;
    }
}
 /**
  * general purpose internal method for creating resized images - accepts
  * a variety of options. Use this to build specific methods for public
  * consumption
  * 
  * maxw : maximum width of image (default '100')
  * maxh : maximum height of image (default '100')
  * bestfit : show entire image inside max width/height. If false
  *           then the image is cropped to match the aspect ratio of
  *           of the target area first (default 'true')
  * attribname : attribute name of img tag which holds url (default 'src')
  * bevel : give image a raised edge (default true)
  * unsharp : do an unsharp mask on the image
  * pano : do not crop, even if w:h > 2:1 (default false)
  * 
  * returns an association array containing 'html' element, which contains
  * a fragment to load the image, and 'path' containg relative url to image
  */
 function _getResized($params)
 {
     global $memcache, $CONF, $MESSAGES;
     $mkey = "{$this->gridimage_id}:" . md5(serialize($params));
     //fails quickly if not using memcached!
     $result =& $memcache->name_get('ir', $mkey);
     if ($result && $result['url'] != '/photos/error.jpg') {
         return $result;
     }
     //unpack known params and set defaults
     $maxw = isset($params['maxw']) ? $params['maxw'] : 100;
     $maxh = isset($params['maxh']) ? $params['maxh'] : 100;
     $attribname = isset($params['attribname']) ? $params['attribname'] : 'src';
     $bestfit = isset($params['bestfit']) ? $params['bestfit'] : true;
     $bevel = isset($params['bevel']) ? $params['bevel'] : true;
     $unsharp = isset($params['unsharp']) ? $params['unsharp'] : true;
     $pano = isset($params['pano']) ? $params['pano'] : false;
     $source = isset($params['source']) ? $params['source'] : '';
     global $CONF;
     //establish whether we have a cached thumbnail
     $ab = sprintf("%02d", floor($this->gridimage_id % 1000000 / 10000));
     $cd = sprintf("%02d", floor($this->gridimage_id % 10000 / 100));
     $abcdef = sprintf("%06d", $this->gridimage_id);
     $hash = $this->_getAntiLeechHash();
     $base = $_SERVER['DOCUMENT_ROOT'] . '/photos';
     if ($this->gridimage_id < 1000000) {
         $thumbpath = "/photos/{$ab}/{$cd}/{$abcdef}_{$hash}_{$maxw}x{$maxh}.jpg";
     } else {
         $yz = sprintf("%02d", floor($this->gridimage_id / 1000000));
         $thumbpath = "/geophotos/{$yz}/{$ab}/{$cd}/{$abcdef}_{$hash}_{$maxw}x{$maxh}.jpg";
     }
     if (!empty($params['urlonly']) && $params['urlonly'] !== 2 && file_exists($_SERVER['DOCUMENT_ROOT'] . $thumbpath)) {
         $return = array();
         $return['url'] = $thumbpath;
         if (!empty($CONF['enable_cluster'])) {
             $return['server'] = str_replace('0', $this->gridimage_id % $CONF['enable_cluster'], "http://{$CONF['STATIC_HOST']}");
         } else {
             $return['server'] = "http://" . $CONF['CONTENT_HOST'];
         }
         return $return;
     }
     $mkey = "{$this->gridimage_id}:{$maxw}x{$maxh}";
     //fails quickly if not using memcached!
     $size =& $memcache->name_get('is', $mkey);
     if ($size) {
         $return = array();
         $return['url'] = $thumbpath;
         $by = $MESSAGES['class_gridimage']['by'];
         $title = $this->grid_reference . ' : ' . htmlentities2($this->title) . $by . htmlentities2($this->realname);
         if (!empty($CONF['enable_cluster'])) {
             $return['server'] = str_replace('0', $this->gridimage_id % $CONF['enable_cluster'], "http://{$CONF['STATIC_HOST']}");
         } else {
             $return['server'] = "http://" . $CONF['CONTENT_HOST'];
         }
         $thumbpath = $return['server'] . $thumbpath;
         if (isset($CONF['curtail_level']) && $CONF['curtail_level'] > 1 && empty($GLOBALS['USER']->user_id) && isset($GLOBALS['smarty'])) {
             $thumbpath = cachize_url($thumbpath);
         }
         $html = "<img alt=\"{$title}\" {$attribname}=\"{$thumbpath}\" {$size[3]} />";
         $return['html'] = $html;
         return $return;
     }
     if (!file_exists($_SERVER['DOCUMENT_ROOT'] . $thumbpath)) {
         if ($source == 'original') {
             $fullpath = $this->_getOriginalpath();
         } else {
             //get path to fullsize image (will try to fetch it from fetch_on_demand)
             $fullpath = $this->_getFullpath();
         }
         if ($pano && $fullpath != '/photos/error.jpg' && file_exists($_SERVER['DOCUMENT_ROOT'] . $fullpath)) {
             require_once "geograph/uploadmanager.class.php";
             $uploadmanager = new UploadManager();
             list($owidth, $oheight, $otype, $oattr) = getimagesize($_SERVER['DOCUMENT_ROOT'] . $fullpath);
             list($destwidth, $destheight, $destdim, $changedim) = $uploadmanager->_new_size($owidth, $oheight, $maxw);
             $maxw = $destdim;
             $maxh = $destdim;
             $bestfit = true;
         }
         if ($fullpath != '/photos/error.jpg' && file_exists($_SERVER['DOCUMENT_ROOT'] . $fullpath)) {
             if (strlen($CONF['imagemagick_path'])) {
                 if (($info = getimagesize($_SERVER['DOCUMENT_ROOT'] . $fullpath)) === FALSE) {
                     //couldn't read image!
                     $thumbpath = "/photos/error.jpg";
                 } else {
                     list($width, $height, $type, $attr) = $info;
                     if ($width > $maxw || $height > $maxh || !$bestfit) {
                         $unsharpen = $unsharp ? "-unsharp 0x1+0.8+0.1" : "";
                         $raised = $bevel ? "-raise 2x2" : "";
                         $operation = $maxw + $maxh < 400 ? 'thumbnail' : 'resize';
                         $aspect_src = $width / $height;
                         $aspect_dest = $maxw / $maxh;
                         if (!$pano && $bestfit && $aspect_src > 2 && $aspect_dest < 2) {
                             $bestfit = false;
                             $maxh = round($maxw / 2);
                             $aspect_dest = 2;
                         }
                         if ($bestfit) {
                             $cmd = sprintf("\"%sconvert\" -{$operation} %ldx%ld  {$unsharpen} {$raised} -quality 87 jpg:%s jpg:%s", $CONF['imagemagick_path'], $maxw, $maxh, $_SERVER['DOCUMENT_ROOT'] . $fullpath, $_SERVER['DOCUMENT_ROOT'] . $thumbpath);
                             passthru($cmd);
                         } else {
                             if ($aspect_src > $aspect_dest) {
                                 //src image is relatively wider - we'll trim the sides
                                 $optimum_width = round($height * $aspect_dest);
                                 $offset = round(($width - $optimum_width) / 2);
                                 $crop = "-crop {$optimum_width}x{$height}+{$offset}+0";
                             } else {
                                 //src image is relatively taller - we'll trim the top/bottom
                                 $optimum_height = round($width / $aspect_dest);
                                 $offset = round(($height - $optimum_height) / 2);
                                 $crop = "-crop {$width}x{$optimum_height}+0+{$offset}";
                             }
                             $cmd = sprintf("\"%sconvert\" {$crop} -quality 87 jpg:%s jpg:%s", $CONF['imagemagick_path'], $_SERVER['DOCUMENT_ROOT'] . $fullpath, $_SERVER['DOCUMENT_ROOT'] . $thumbpath);
                             passthru($cmd);
                             //now resize // FIXME: one step!
                             $cmd = sprintf("\"%smogrify\" -{$operation} %ldx%ld {$unsharpen} {$raised} -quality 87 jpg:%s", $CONF['imagemagick_path'], $maxw, $maxh, $_SERVER['DOCUMENT_ROOT'] . $thumbpath);
                             passthru($cmd);
                         }
                     } else {
                         //requested thumb is larger than original - stick with original
                         copy($_SERVER['DOCUMENT_ROOT'] . $fullpath, $_SERVER['DOCUMENT_ROOT'] . $thumbpath);
                     }
                 }
             } else {
                 // FIXME not the same as above
                 //generate resized image
                 $fullimg = @imagecreatefromjpeg($_SERVER['DOCUMENT_ROOT'] . $fullpath);
                 if ($fullimg) {
                     $srcw = imagesx($fullimg);
                     $srch = imagesy($fullimg);
                     if ($srcw > $maxw || $srch > $maxh) {
                         //figure out size of image we'll keep
                         if ($srcw > $srch) {
                             //landscape
                             $destw = $maxw;
                             $desth = round($destw * $srch / $srcw);
                         } else {
                             //portrait
                             $desth = $maxh;
                             $destw = round($desth * $srcw / $srch);
                         }
                         $resized = imagecreatetruecolor($destw, $desth);
                         imagecopyresampled($resized, $fullimg, 0, 0, 0, 0, $destw, $desth, $srcw, $srch);
                         if ($unsharp) {
                             require_once 'geograph/image.inc.php';
                             UnsharpMask($resized, 100, 0.5, 3);
                         }
                         imagedestroy($fullimg);
                         //save the thumbnail
                         imagejpeg($resized, $_SERVER['DOCUMENT_ROOT'] . $thumbpath, 85);
                         imagedestroy($resized);
                     } elseif ($srcw == 0 && $srch == 0) {
                         //couldn't read image!
                         $thumbpath = "/photos/error.jpg";
                         imagedestroy($fullimg);
                     } else {
                         //requested thumb is larger than original - stick with original
                         copy($_SERVER['DOCUMENT_ROOT'] . $fullpath, $_SERVER['DOCUMENT_ROOT'] . $thumbpath);
                     }
                 } else {
                     //couldn't load full jpeg
                     $thumbpath = "/photos/error.jpg";
                 }
             }
         } else {
             //no original image! - return link to error image
             $thumbpath = "/photos/error.jpg";
         }
     }
     $return = array();
     $return['url'] = $thumbpath;
     if ($thumbpath == '/photos/error.jpg') {
         $html = "<img {$attribname}=\"{$thumbpath}\" width=\"{$maxw}\" height=\"{$maxh}\" />";
     } else {
         $by = $MESSAGES['class_gridimage']['by'];
         $title = $this->grid_reference . ' : ' . htmlentities2($this->title) . $by . htmlentities2($this->realname);
         $size = getimagesize($_SERVER['DOCUMENT_ROOT'] . $thumbpath);
         if (!empty($CONF['enable_cluster'])) {
             $return['server'] = str_replace('0', $this->gridimage_id % $CONF['enable_cluster'], "http://{$CONF['STATIC_HOST']}");
         } else {
             $return['server'] = "http://" . $CONF['CONTENT_HOST'];
         }
         $thumbpath = $return['server'] . $thumbpath;
         if (isset($CONF['curtail_level']) && $CONF['curtail_level'] > 1 && empty($GLOBALS['USER']->user_id) && isset($GLOBALS['smarty'])) {
             $thumbpath = cachize_url($thumbpath);
         }
         $html = "<img alt=\"{$title}\" {$attribname}=\"{$thumbpath}\" {$size[3]} />";
         //fails quickly if not using memcached!
         $memcache->name_set('is', $mkey, $size, $memcache->compress, $memcache->period_med);
     }
     $return['html'] = $html;
     return $return;
 }