/**
 * Checks if an uploaded media item hits any configured limits.
 *
 * @param  string   The filename
 * @return boolean  TRUE when file is okay, FALSE when it is beyond limits
 *
 */
function serendipity_checkMediaSize($file)
{
    global $serendipity;
    if (!empty($serendipity['maxFileSize'])) {
        if (filesize($file) > $serendipity['maxFileSize']) {
            printf(MEDIA_UPLOAD_SIZEERROR . '<br />', (int) $serendipity['maxFileSize']);
            return false;
        }
    }
    if (!empty($serendipity['maxImgWidth']) || !empty($serendipity['maxImgHeight'])) {
        $dim = serendipity_getimagesize($file);
        if (!is_array($dim) || !isset($dim[0])) {
            return true;
        }
        if (!empty($serendipity['maxImgWidth'])) {
            if ($dim[0] > $serendipity['maxImgWidth']) {
                printf(MEDIA_UPLOAD_DIMERROR . '<br />', (int) $serendipity['maxImgWidth'], (int) $serendipity['maxImgHeight']);
                return false;
            }
        }
        if (!empty($serendipity['maxImgHeight'])) {
            if ($dim[1] > $serendipity['maxImgHeight']) {
                printf(MEDIA_UPLOAD_DIMERROR . '<br />', (int) $serendipity['maxImgWidth'], (int) $serendipity['maxImgHeight']);
                return false;
            }
        }
    }
    return true;
}
/**
 * Checks if an uploaded media item hits any configured limits.
 *
 * @param  string   The filename
 * @return boolean  TRUE when file is okay, FALSE when it is beyond limits
 *
 */
function serendipity_checkMediaSize($file)
{
    global $serendipity;
    if (!empty($serendipity['maxFileSize'])) {
        if (filesize($file) > $serendipity['maxFileSize']) {
            echo '<span class="msg_error"><span class="icon-attention-circled"></span> ';
            printf(MEDIA_UPLOAD_SIZEERROR . '<br />', (int) $serendipity['maxFileSize']);
            echo "</span>\n";
            return false;
        }
    }
    if (!empty($serendipity['maxImgWidth']) || !empty($serendipity['maxImgHeight'])) {
        $dim = serendipity_getimagesize($file);
        if (!is_array($dim) || !isset($dim[0])) {
            return true;
        }
        if (!empty($serendipity['maxImgWidth'])) {
            if ($dim[0] > $serendipity['maxImgWidth']) {
                echo '<span class="msg_error"><span class="icon-attention-circled"></span> ';
                printf(MEDIA_UPLOAD_DIMERROR . '<br />', (int) $serendipity['maxImgWidth'], (int) $serendipity['maxImgHeight']);
                echo "</span>\n";
                return false;
            }
        }
        if (!empty($serendipity['maxImgHeight'])) {
            if ($dim[1] > $serendipity['maxImgHeight']) {
                echo '<span class="msg_error"><span class="icon-attention-circled"></span> ';
                printf(MEDIA_UPLOAD_DIMERROR . '<br />', (int) $serendipity['maxImgWidth'], (int) $serendipity['maxImgHeight']);
                echo "</span>\n";
                return false;
            }
        }
    }
    return true;
}
 function resizeThumb($sizes, $target)
 {
     global $serendipity;
     // Thumbsize: 75
     // A: 100x300
     // B: 300x100
     // s9y A: 25x75
     // s9y B: 75x25
     // Max-Height: 0
     // Max-Width : 75
     // s9y A:
     // s9y B:
     // Max-Height: 0
     // Max-Height: 75
     // s9y A: 25x75
     // s9y B: 225x75
     $fdim = @serendipity_getimagesize($target, '', '');
     if (!isset($serendipity['thumbConstraint'])) {
         // Original code, for older versions of s9y
         $s9ysizes = serendipity_calculate_aspect_size($fdim[0], $fdim[1], $serendipity['thumbSize']);
         if ($fdim[0] >= $fdim[1]) {
             $orientation = 'Landscape';
         } else {
             $orientation = 'Portrait';
         }
         if ($sizes['width'] == 0) {
             if ($orientation == 'Landscape') {
                 $_newsizes = serendipity_calculate_aspect_size($fdim[0], $fdim[1], null, $sizes['height']);
             } else {
                 $_newsizes = serendipity_calculate_aspect_size($fdim[0], $fdim[1], $sizes['height'], null);
             }
             $newsizes = array('width' => $_newsizes[0], 'height' => $_newsizes[1]);
         } elseif ($sizes['height'] == 0) {
             if ($orientation == 'Landscape') {
                 $_newsizes = serendipity_calculate_aspect_size($fdim[0], $fdim[1], $sizes['width'], null);
             } else {
                 $_newsizes = serendipity_calculate_aspect_size($fdim[0], $fdim[1], null, $sizes['width']);
             }
             $newsizes = array('width' => $_newsizes[0], 'height' => $_newsizes[1]);
         } else {
             $newsizes = array(0 => $sizes['width'], 1 => $sizes['height']);
         }
     } else {
         // Newer s9y version that understands how to constrain images properly
         $s9ysizes = serendipity_calculate_aspect_size($fdim[0], $fdim[1], $serendipity['thumbSize'], $serendipity['thumbConstraint']);
         $orientation = 'size';
         if ($sizes['width'] == 0) {
             $_newsizes = serendipity_calculate_aspect_size($fdim[0], $fdim[1], $sizes['height'], 'height');
         } elseif ($sizes['height'] == 0) {
             $_newsizes = serendipity_calculate_aspect_size($fdim[0], $fdim[1], $sizes['width'], 'width');
         } else {
             $_newsizes = array(0 => $sizes['width'], 1 => $sizes['height']);
         }
         $newsizes = array('width' => $_newsizes[0], 'height' => $_newsizes[1]);
     }
     echo '<span class="msg_notice"><span class="icon-attention-circled"></span> Resizing thumb of ' . $orientation . ' ' . $fdim[0] . 'x' . $fdim[1] . ' to ' . $_newsizes[0] . 'x' . $_newsizes[1] . ' instead of ' . $s9ysizes[0] . 'x' . $s9ysizes[1] . "...</span>\n";
     $dirname = dirname($target) . '/';
     $dirname = str_replace($serendipity['serendipityPath'] . $serendipity['uploadPath'], '', $dirname);
     $serendipity['imagemagick_nobang'] = true;
     serendipity_makeThumbnail(basename($target), $dirname, $newsizes, $serendipity['thumbSuffix']);
     $serendipity['imagemagick_nobang'] = false;
 }
 /**
  * Sets $this->image_name to the name of a valid image, or to '0' to
  * indicate text-only rating bars should be used.
  */
 function set_valid_image_data()
 {
     $base_image = $this->get_config('base_image', false);
     if ($base_image !== false) {
         // Definitely configured
         if ($base_image == '0') {
             // Configured to text-only
             $this->image_name = $base_image;
         } else {
             $imagesize = serendipity_getimagesize(dirname(__FILE__) . "/img/" . $base_image);
             if ($imagesize['noimage']) {
                 // Leave as default
             } else {
                 // Set to valid image name
                 $this->image_name = $base_image;
             }
         }
     }
     // Is the (possibly default) image valid?
     if ($this->image_name) {
         $imagesize = serendipity_getimagesize(dirname(__FILE__) . "/img/" . $this->image_name);
         if ($imagesize['noimage']) {
             // No valid image; use text-only
             $this->image_name = '0';
         } else {
             // Valid graphical image; set the dimensions, too
             $this->image_width = $imagesize[0];
             $this->image_height = $imagesize[1];
         }
     }
 }
/**
 * Get the Serendipity dimensions for an image
 *
 * @access public
 * @param   array       Smarty parameter input array:
 *                      file: The image file to get image data for
 *                      assign: The variable to assign the image data array to
 * @param   object      Smarty object
 * @return  string      Empty
 */
function serendipity_smarty_getImageSize($params, &$smarty)
{
    global $serendipity;
    if (!isset($params['file'])) {
        trigger_error("Smarty Error: " . __FUNCTION__ . ": missing 'file' parameter", E_USER_WARNING);
        return;
    }
    if (!isset($params['assign'])) {
        trigger_error("Smarty Error: " . __FUNCTION__ . ": missing 'assign' parameter", E_USER_WARNING);
        return;
    }
    // Is it a correct filesystem absolute path?
    $file = $params['file'];
    // Most likely the user specified an HTTP path
    if (!file_exists($file)) {
        $file = $_SERVER['DOCUMENT_ROOT'] . $file;
    }
    // Maybe wants a template file (returns filesystem path)
    if (!file_exists($file)) {
        $file = serendipity_getTemplateFile($params['file']);
    }
    // If no file, trigger an error
    if (!file_exists($file)) {
        trigger_error("Smarty Error: " . __FUNCTION__ . ': file ' . $params['file'] . NOT_FOUND . ' ', E_USER_WARNING);
        return;
    }
    $smarty->assign($params['assign'], serendipity_getimagesize($file));
}
 function picasa_upload()
 {
     global $serendipity;
     if (!serendipity_userLoggedIn()) {
         $this->report_upload_result('You must be logged in to upload an album.');
     }
     if (!count($_FILES)) {
         $this->report_upload_result('Missing files');
         return;
     }
     if (!isset($_POST['albumName'])) {
         $this->report_upload_result('Missing album name');
         return;
     }
     if (!isset($_POST['parentDir'])) {
         $this->report_upload_result('Missing parent directory');
         return;
     }
     if (!isset($_SESSION['picasa_rss_parsed'])) {
         $this->report_upload_result('Missing parsed rss (needed for descriptions)');
         return;
     }
     $albumName = html_entity_decode($_POST['albumName'], ENT_QUOTES, LANG_CHARSET);
     $decodedParentDir = html_entity_decode($_POST['parentDir'], ENT_QUOTES, LANG_CHARSET);
     $albumDir = $decodedParentDir . $albumName;
     $dirname = $this->get_config('picasapath') . '/' . $albumDir;
     if (file_exists($dirname)) {
         $this->report_upload_result(PLUGIN_EVENT_PICASA_ERR_UPLOAD_DIR_ALREADY_EXISTS);
         return;
     }
     $this->mkdir_recursive($dirname, 0755);
     if (!is_dir($dirname)) {
         $this->report_upload_result(PLUGIN_EVENT_PICASA_ERR_DIR_CREATION_FAILED);
         return;
     }
     // first move all the files to their final destination and put their information
     // in a map.  Match up thumbs with their main image.
     foreach ($_FILES as $key => $file) {
         if (!empty($file)) {
             // obtain the original filename from Picasa
             $tmpfile = $file['tmp_name'];
             $fname = $file['name'];
             // If this is the thumbnail, change the path from name.ext to name.thumb.ext
             // The image and thumbnail keys look like:
             // http://localhost:3671/92c624539502989c5b1d84401a47f03d/image/1262eaef64f127c2_jpg?size=640
             // http://localhost:3671/92c624539502989c5b1d84401a47f03d/thumb/1262eaef64f127c2_jpg?size=90
             if (strpos($key, '/thumb/') != false) {
                 $periodPos = strrpos($fname, '.');
                 $destName = substr($fname, 0, $periodPos) . ".thumb" . substr($fname, $periodPos);
                 $imageType = 'thumb';
             } else {
                 $destName = $fname;
                 $imageType = 'image';
             }
             $destPath = "{$dirname}/{$destName}";
             if (move_uploaded_file($tmpfile, $destPath)) {
                 chmod($destPath, 0644);
             }
             $dims = serendipity_getimagesize($destPath);
             $entriesByName[$fname][$imageType] = $destName;
             $entriesByName[$fname][$imageType . 'width'] = $dims[0];
             $entriesByName[$fname][$imageType . 'height'] = $dims[1];
         }
     }
     // go through the captions and associate them with the correct image
     foreach ($_SESSION['picasa_rss_parsed'] as $e) {
         if (array_key_exists('description', $e) && isset($e['title']) && array_key_exists($e['title'], $entriesByName)) {
             $entriesByName[$e['title']]['caption'] = $e['description'];
         }
     }
     // put the map into an array
     $entries = array();
     foreach ($entriesByName as $key => $value) {
         $value['name'] = $key;
         $entries[] = $value;
     }
     $imageCount = count($entries);
     $albumDesc = html_entity_decode($_POST['albumDescription'], ENT_QUOTES, LANG_CHARSET);
     $xmlPath = "{$dirname}/index.xml";
     $xmlFile = fopen($xmlPath, 'w+');
     fputs($xmlFile, "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n");
     fputs($xmlFile, "<album>\n");
     $this->writeXMLTag($xmlFile, "albumName", $albumName);
     $this->writeXMLTag($xmlFile, "albumItemCount", $imageCount);
     $this->writeXMLTag($xmlFile, "albumCaption", $albumDesc);
     fputs($xmlFile, "<images>\n");
     $emptyEntry = array('name' => '', 'image' => '', 'thumb' => '', 'caption' => '');
     $firstImage = $entries[0];
     $lastImage = $entries[count($entries) - 1];
     foreach ($entries as $index => $data) {
         if (!array_key_exists('caption', $data)) {
             $data['caption'] = $data['image'];
         }
         $prev = array_key_exists($index - 1, $entries) ? $entries[$index - 1] : $emptyEntry;
         $next = array_key_exists($index + 1, $entries) ? $entries[$index + 1] : $emptyEntry;
         fputs($xmlFile, "<image>\n");
         $this->writeXMLTagBool($xmlFile, "isFirstImage", $index == 0);
         $this->writeXMLTagBool($xmlFile, "isPrevImage", $index != 0);
         $this->writeXMLTagBool($xmlFile, "isLastImage", $index == $imageCount - 1);
         $this->writeXMLTagBool($xmlFile, "isNextImage", $index != $imageCount - 1);
         $this->writeXMLTag($xmlFile, "firstImage", $firstImage['image']);
         $this->writeXMLTag($xmlFile, "itemLargeImage", $data['image']);
         $this->writeXMLTag($xmlFile, "nextImage", $next['image']);
         $this->writeXMLTag($xmlFile, "nextThumbnail", $next['thumb']);
         $this->writeXMLTag($xmlFile, "prevImage", $prev['image']);
         $this->writeXMLTag($xmlFile, "prevThumbnail", $prev['thumb']);
         $this->writeXMLTag($xmlFile, "lastImage", $lastImage['image']);
         $this->writeXMLTag($xmlFile, "lastThumbnail", $lastImage['thumb']);
         $this->writeXMLTag($xmlFile, "itemWidth", $data['imagewidth']);
         $this->writeXMLTag($xmlFile, "itemHeight", $data['imageheight']);
         $this->writeXMLTag($xmlFile, "itemThumbnailImage", $data['thumb']);
         $this->writeXMLTag($xmlFile, "itemThumbnailWidth", $data['thumbwidth']);
         $this->writeXMLTag($xmlFile, "itemThumbnailHeight", $data['thumbheight']);
         $this->writeXMLTag($xmlFile, "itemName", $data['image']);
         $this->writeXMLTag($xmlFile, "itemNumber", $index);
         $this->writeXMLTag($xmlFile, "itemOriginalPath", "");
         $this->writeXMLTag($xmlFile, "itemNameOnly", "");
         $this->writeXMLTag($xmlFile, "itemCaption", $data['caption']);
         $this->writeXMLTag($xmlFile, "itemSize", "");
         fputs($xmlFile, "</image>\n");
     }
     fputs($xmlFile, "</images>\n");
     fputs($xmlFile, "</album>\n");
     fclose($xmlFile);
     if ($this->get_config('create_entry_after_upload')) {
         // create a new entry using the newly uploaded album
         $entry = array();
         $entry['isdraft'] = 'true';
         $entry['title'] = $albumName;
         $entry['body'] = '<p>[picasa]' . $albumDir . '[/picasa]</p>';
         $entry['authorid'] = $serendipity['authorid'];
         $entry['exflag'] = false;
         $entry['allow_comments'] = 'true';
         $entry['moderate_comments'] = 'false';
         $id = serendipity_updertEntry($entry);
         $retUrl = $serendipity['baseURL'] . 'serendipity_admin.php?serendipity[action]=admin&serendipity[adminModule]=entries&serendipity[adminAction]=edit&serendipity[id]=' . $id;
         echo $retUrl;
     } else {
         $this->report_upload_result(PLUGIN_EVENT_PICASA_UPLOAD_SUCCESS);
     }
 }
 function g2image_scale($album, $photo, $extension, $method = 'thumb')
 {
     global $serendipity;
     $gallery_base = $this->get_config('gallery_base');
     $album_base = $this->get_config('album_base') . "/albums";
     $album_abs = $this->get_config('album_abs');
     $photo_ext = $extension ? "{$extension}" : "jpg";
     $infile = $album_abs . '/albums/' . $album . '/' . $photo . '.' . $photo_ext;
     if ($method == 'thumb') {
         $outfile = $album_abs . '/tmp/' . $photo . '.thumb.' . $photo_ext;
         $size = $this->get_config('thumb_max');
     } else {
         $outfile = $album_abs . '/tmp/' . $photo . '.sized.' . $photo_ext;
         $size = $this->get_config('popup_max');
     }
     $fdim = @serendipity_getimagesize($infile, '', $extension);
     if (isset($fdim['noimage'])) {
         $r = array(0, 0);
     } else {
         if ($serendipity['magick'] !== true) {
             $r = serendipity_resize_image_gd($infile, $outfile, $size);
         } else {
             $r = array($size, $size);
             $newSize = $size . 'x' . $size;
             if ($fdim['mime'] == 'application/pdf') {
                 $cmd = escapeshellcmd($serendipity['convert']) . ' -antialias -flatten -scale ' . serendipity_escapeshellarg($newSize) . ' ' . serendipity_escapeshellarg($infile) . ' ' . serendipity_escapeshellarg($outfile . '.png');
             } else {
                 $cmd = escapeshellcmd($serendipity['convert']) . ' -antialias -scale ' . serendipity_escapeshellarg($newSize) . ' ' . serendipity_escapeshellarg($infile) . ' ' . serendipity_escapeshellarg($outfile);
             }
             exec($cmd, $output, $result);
             if ($result != 0) {
                 echo '<div class="serendipityAdminMsgError"><img style="width: 22px; height: 22px; border: 0px; padding-right: 4px; vertical-align: middle" src="' . serendipity_getTemplateFile('admin/img/admin_msg_error.png') . '" alt="" />' . sprintf(IMAGICK_EXEC_ERROR, $cmd, $output[0], $result) . '</div>';
                 $r = false;
                 // return failure
             } else {
                 touch($outfile);
             }
             unset($output, $result);
         }
     }
 }
 function showRSS(&$eventData, $offset = 0)
 {
     global $serendipity;
     static $entries = array();
     if (!isset($_REQUEST['gallery'])) {
         return false;
     }
     $limit = !empty($_REQUEST['limit']) ? (int) $_REQUEST['limit'] : $serendipity['RSSfetchLimit'];
     if (empty($limit)) {
         $limit = 15;
     }
     $dir = !empty($_REQUEST['picdir']) ? $_REQUEST['picdir'] : '';
     $total = 0;
     $size = !empty($_REQUEST['feed_width']) ? (int) $_REQUEST['feed_width'] : $this->get_config('feed_width');
     $hide_title = !empty($_REQUEST['hide_title']) ? true : false;
     $basepath = $serendipity['serendipityPath'] . $serendipity['uploadPath'];
     $baseurl = $serendipity['baseURL'] . $serendipity['uploadHTTPPath'];
     $lo = serendipity_db_bool($this->get_config('feed_linked_only'));
     $feed_body = serendipity_db_bool($this->get_config('feed_body'));
     $images = serendipity_fetchImagesFromDatabase($offset, $limit, $total, 'i.date', 'DESC', $dir);
     // Let's push the $images array into the destination $entries format.
     foreach ($images as $idx => $image) {
         if (count($entries) > $limit) {
             continue;
         }
         $filename = $image['name'] . '.' . $image['extension'];
         $thumbname = $image['name'] . '.' . $image['thumbnail_name'] . '.' . $image['extension'];
         $sourcefile = $basepath . $image['path'] . $filename;
         $thumbfile = $basepath . $image['path'] . $thumbname;
         $sourcefile_http = $baseurl . $image['path'] . $filename;
         $thumbfile_http = $baseurl . $image['path'] . $thumbname;
         // Creating temporary thumbnails
         if ($serendipity['thumbSize'] != $size) {
             $thumbname = $image['name'] . '.serendipityGallery.' . $image['extension'];
             $thumbfile = $serendipity['serendipityPath'] . PATH_SMARTY_COMPILE . '/' . $thumbname;
             $thumbfile_http = $serendipity['baseURL'] . PATH_SMARTY_COMPILE . '/' . $thumbname;
             if (!file_exists($thumbfile)) {
                 serendipity_makeThumbnail($filename, $image['path'], $size, $thumbfile, true);
             }
         }
         $fdim = @serendipity_getimagesize($thumbfile, '', '');
         $e = $this->fetchLinkedEntries($image['id'], $image['path'] . $filename, $image['path'] . $thumbname, true, $feed_body);
         if (is_array($e)) {
             $link = serendipity_archiveURL($e[0]['id'], $e[0]['title'], 'serendipityHTTPPath', true, array('timestamp' => $e[0]['timestamp']));
             $lid = $e[0]['id'];
         } elseif ($lo) {
             // Images without links will be discarded
             continue;
         } else {
             $link = $sourcefile_http;
             $lid = $image['id'];
         }
         if ($feed_body && is_array($e)) {
             // Replace big image with thumbnail
             $body = preg_replace('@(["\'])[^"\']*' . preg_quote($image['path'] . $filename, '@') . '@imsU', '\\1' . $thumbfile_http, $e[0]['body']);
             // Kill possible width attributes of <img> tags to not screw up display
             $body = preg_replace('@(<img[^>]*)\\s*width\\s*=["\'][0-9]+["\']@imsU', '\\1', $body);
             $body = preg_replace('@(<img[^>]*)\\s*height\\s*=["\'][0-9]+["\']@imsU', '\\1', $body);
         }
         $body = '<a href="' . $link . '"><img src="' . $thumbfile_http . '" alt="" width="' . $fdim[0] . '" height="' . $fdim[1] . '" /></a>';
         $entries[] = array('title' => $hide_title ? '' : $filename, 'entryid' => $lid, 'timestamp' => $image['date'], 'author' => $image['authorname'], 'body' => $body, 'extended' => '', 'authorid' => $image['authorid'], 'email' => $image['authorname'], 'category_name' => $image['path'], 'last_modified' => $image['date']);
     }
     if (count($entries) < $limit && count($images) == $limit) {
         $this->showRSS($eventData, $offset + $limit);
     }
     if ($offset == 0) {
         // We are Borg. Resistance is futile. Sue us.
         $GLOBALS['entries'] =& $entries;
         $GLOBALS['comments'] = false;
         $_GET['type'] = 'content';
     }
     return true;
 }