function getOptionsSupported()
 {
     global $_zp_gallery, $_zp_images_classes, $mysetoptions;
     $dir = opendir($albumdir = $_zp_gallery->getAlbumDir());
     $albums = array();
     while ($dirname = readdir($dir)) {
         if (is_dir($albumdir . $dirname) && substr($dirname, 0, 1) != '.' || hasDynamicAlbumSuffix($dirname)) {
             $albums[] = filesystemToInternal($dirname);
         }
     }
     closedir($dir);
     $albums = array_unique($albums);
     natcasesort($albums);
     $lista = array();
     foreach ($albums as $album) {
         $lista[$album] = 'filter_file_searches_albums_' . $album;
     }
     $list = array_keys($_zp_images_classes);
     natcasesort($list);
     $listi = array();
     foreach ($list as $suffix) {
         $listi[$suffix] = 'filter_file_searches_images_' . $suffix;
     }
     return array(gettext('Albums') => array('key' => 'filter_file_searches_albums', 'type' => OPTION_TYPE_CHECKBOX_UL, 'checkboxes' => $lista, 'desc' => gettext("Check album names to be ignored.")), gettext('Images') => array('key' => 'filter_file_searches_images', 'type' => OPTION_TYPE_CHECKBOX_UL, 'checkboxes' => $listi, 'desc' => gettext('Check image suffixes to be ignored.')));
 }
function getSubalbumImages($folder)
{
    global $imagelist, $gallery;
    if (hasDynamicAlbumSuffix($folder)) {
        return;
    }
    $album = new Album($gallery, $folder);
    $images = $album->getImages();
    foreach ($images as $image) {
        $imagelist[] = '/' . $folder . '/' . $image;
    }
    $albums = $album->getAlbums();
    foreach ($albums as $folder) {
        getSubalbumImages($folder);
    }
}
 /**
  * Load all of the filenames that are found in this Albums directory on disk.
  * Returns an array with all the names.
  *
  * @param  $dirs Whether or not to return directories ONLY with the file array.
  * @return array
  */
 protected function loadFileNames($dirs = false)
 {
     clearstatcache();
     $albumdir = $this->localpath;
     $dir = @opendir($albumdir);
     if (!$dir) {
         if (is_dir($albumdir)) {
             $msg = sprintf(gettext("Error: The album %s is not readable."), html_encode($this->name));
         } else {
             $msg = sprintf(gettext("Error: The album named %s cannot be found."), html_encode($this->name));
         }
         trigger_error($msg, E_USER_NOTICE);
         return array();
     }
     $files = array();
     $others = array();
     while (false !== ($file = readdir($dir))) {
         $file8 = filesystemToInternal($file);
         if (@$file8[0] != '.') {
             if ($dirs && (is_dir($albumdir . $file) || hasDynamicAlbumSuffix($file))) {
                 $files[] = $file8;
             } else {
                 if (!$dirs && is_file($albumdir . $file)) {
                     if (Gallery::validImageAlt($file)) {
                         $files[] = $file8;
                         $others[] = $file8;
                     } else {
                         if (Gallery::validImage($file)) {
                             $files[] = $file8;
                         }
                     }
                 }
             }
         }
     }
     closedir($dir);
     if (count($others) > 0) {
         $others_thumbs = array();
         foreach ($others as $other) {
             $others_root = substr($other, 0, strrpos($other, "."));
             foreach ($files as $image) {
                 if ($image != $other) {
                     $image_root = substr($image, 0, strrpos($image, "."));
                     if ($image_root == $others_root && Gallery::validImage($image)) {
                         $others_thumbs[] = $image;
                     }
                 }
             }
         }
         $files = array_diff($files, $others_thumbs);
     }
     if ($dirs) {
         return zp_apply_filter('album_filter', $files);
     } else {
         return zp_apply_filter('image_filter', $files);
     }
 }
/**
 * Handles an album for printAlbumMenuList
 *
 * @param array $albums albums array
 * @param string $folder
 * @param string $option see printAlbumMenuList
 * @param string $showcount see printAlbumMenuList
 * @param int $showsubs see printAlbumMenuList
 * @param string $css_class see printAlbumMenuList
 * @param string $css_class_topactive see printAlbumMenuList
 * @param string $css_class_active see printAlbumMenuList
 * @param bool $firstimagelink If set to TRUE and if the album has images the link will point to page of the first image instead the album thumbnail page
 * @param bool $keeptopactive If set to TRUE the toplevel album entry will stay marked as active if within its subalbums ("list" only)
 * @param int $limit truncation of display text
 */
function printAlbumMenuListAlbum($albums, $folder, $option, $showcount, $showsubs, $css_class, $css_class_topactive, $css_class_active, $firstimagelink, $keeptopactive, $limit = NULL)
{
    global $_zp_gallery, $_zp_current_album, $_zp_current_search, $_recursion_limiter;
    if (is_null($limit)) {
        $limit = MENU_TRUNCATE_STRING;
    }
    if (is_null($showcount)) {
        $showcount = ALBUM_MENU_COUNT;
    }
    if (is_null($showsubs)) {
        $showsubs = ALBUM_MENU_SHOWSUBS;
    }
    if ($showsubs && !is_numeric($showsubs)) {
        $showsubs = 9999999999.0;
    }
    $pagelevel = count(explode('/', $folder));
    $currenturalbumname = "";
    foreach ($albums as $album) {
        $level = count(explode('/', $album));
        $process = $level < $showsubs && $option == "list" || $option != 'list-top' && strpos($folder, $album) === 0 && $level <= $pagelevel;
        if ($process && hasDynamicAlbumSuffix($album) && !is_dir(ALBUM_FOLDER_SERVERPATH . $album)) {
            if (in_array($album, $_recursion_limiter)) {
                $process = false;
            }
            // skip already seen dynamic albums
        }
        $topalbum = newAlbum($album, true);
        if ($level > 1 || $option != 'omit-top') {
            // listing current level album
            if ($level == 1) {
                $css_class_t = $css_class_topactive;
            } else {
                $css_class_t = $css_class_active;
            }
            if ($keeptopactive) {
                if (isset($_zp_current_album) && is_object($_zp_current_album)) {
                    $currenturalbum = getUrAlbum($_zp_current_album);
                    $currenturalbumname = $currenturalbum->name;
                }
            }
            $count = "";
            if ($showcount) {
                $toplevelsubalbums = $topalbum->getAlbums();
                $toplevelsubalbums = count($toplevelsubalbums);
                $topalbumnumimages = $topalbum->getNumImages();
                if ($topalbumnumimages + $toplevelsubalbums > 0) {
                    $count = ' <span style="white-space:nowrap;"><small>(';
                    if ($toplevelsubalbums > 0) {
                        $count .= sprintf(ngettext('%u album', '%u albums', $toplevelsubalbums), $toplevelsubalbums);
                    }
                    if ($topalbumnumimages > 0) {
                        if ($toplevelsubalbums) {
                            $count .= ' ';
                        }
                        $count .= sprintf(ngettext('%u image', '%u images', $topalbumnumimages), $topalbumnumimages);
                    }
                    $count .= ')</small></span>';
                }
            }
            if (in_context(ZP_ALBUM) && !in_context(ZP_SEARCH_LINKED) && (@$_zp_current_album->getID() == $topalbum->getID() || $topalbum->name == $currenturalbumname) || in_context(ZP_SEARCH_LINKED) && ($a = $_zp_current_search->getDynamicAlbum()) && $a->name == $topalbum->name) {
                $current = $css_class_t . ' ';
            } else {
                $current = "";
            }
            $title = $topalbum->getTitle();
            if ($limit) {
                $display = shortenContent($title, $limit, MENU_TRUNCATE_INDICATOR);
            } else {
                $display = $title;
            }
            if ($firstimagelink && $topalbum->getNumImages() != 0) {
                $link = "<li><a " . $current . "href='" . html_encode($topalbum->getImage(0)->getLink()) . "' title='" . html_encode($title) . "'>" . html_encode($display) . "</a>" . $count;
            } else {
                $link = "<li><a " . $current . "href='" . html_encode($topalbum->getLink(1)) . "' title='" . html_encode($title) . "'>" . html_encode($display) . "</a>" . $count;
            }
            echo $link;
        }
        if ($process) {
            // listing subalbums
            $subalbums = $topalbum->getAlbums();
            if (!empty($subalbums)) {
                echo "\n<ul" . $css_class . ">\n";
                array_push($_recursion_limiter, $album);
                printAlbumMenuListAlbum($subalbums, $folder, $option, $showcount, $showsubs, $css_class, $css_class_topactive, $css_class_active, $firstimagelink, false, $limit);
                array_pop($_recursion_limiter);
                echo "\n</ul>\n";
            }
        }
        if ($option == 'list' || $option == 'list-top' || $level > 1) {
            // close the LI
            echo "\n</li>\n";
        }
    }
}
Exemple #5
0
/**
 * recovers search parameters from stored cookie, clears the cookie
 *
 * @param string $what the page type
 * @param string $album Name of the album
 * @param string $image Name of the image
 */
function handleSearchParms($what, $album = NULL, $image = NULL)
{
    global $_zp_current_search, $zp_request, $_zp_last_album, $_zp_current_album, $_zp_current_zenpage_news, $_zp_current_zenpage_page, $_zp_gallery, $_zp_loggedin;
    $_zp_last_album = zp_getCookie('zenphoto_last_album');
    if (is_object($zp_request) && get_class($zp_request) == 'SearchEngine') {
        //	we are are on a search
        return $zp_request->getAlbumList();
    }
    $params = zp_getCookie('zenphoto_search_params');
    if (!empty($params)) {
        $context = get_context();
        $_zp_current_search = new SearchEngine();
        $_zp_current_search->setSearchParams($params);
        // check to see if we are still "in the search context"
        if (!is_null($image)) {
            $dynamic_album = $_zp_current_search->getDynamicAlbum();
            if ($_zp_current_search->getImageIndex($album->name, $image->filename) !== false) {
                if ($dynamic_album) {
                    $_zp_current_album = $dynamic_album;
                }
                $context = $context | ZP_SEARCH_LINKED | ZP_IMAGE_LINKED;
            }
        }
        if (!is_null($album)) {
            $albumname = $album->name;
            zp_setCookie('zenphoto_last_album', $albumname);
            if (hasDynamicAlbumSuffix($albumname) && !is_dir(ALBUM_FOLDER_SERVERPATH . $albumname)) {
                $albumname = stripSuffix($albumname);
                // strip off the suffix as it will not be reflected in the search path
            }
            //	see if the album is within the search context. NB for these purposes we need to look at all albums!
            $save_logon = $_zp_loggedin;
            $_zp_loggedin = $_zp_loggedin | VIEW_ALL_RIGHTS;
            $search_album_list = $_zp_current_search->getAlbums(0);
            $_zp_loggedin = $save_logon;
            foreach ($search_album_list as $searchalbum) {
                if (strpos($albumname, $searchalbum) !== false) {
                    $context = $context | ZP_SEARCH_LINKED | ZP_ALBUM_LINKED;
                    break;
                }
            }
        } else {
            zp_clearCookie('zenphoto_last_album');
        }
        if (!is_null($_zp_current_zenpage_page)) {
            $pages = $_zp_current_search->getPages();
            if (!empty($pages)) {
                $tltlelink = $_zp_current_zenpage_page->getTitlelink();
                foreach ($pages as $apage) {
                    if ($apage == $tltlelink) {
                        $context = $context | ZP_SEARCH_LINKED;
                        break;
                    }
                }
            }
        }
        if (!is_null($_zp_current_zenpage_news)) {
            $news = $_zp_current_search->getArticles(0, NULL, true);
            if (!empty($news)) {
                $tltlelink = $_zp_current_zenpage_news->getTitlelink();
                foreach ($news as $anews) {
                    if ($anews['titlelink'] == $tltlelink) {
                        $context = $context | ZP_SEARCH_LINKED;
                        break;
                    }
                }
            }
        }
        if ($context & ZP_SEARCH_LINKED) {
            set_context($context);
        } else {
            // not an object in the current search path
            $_zp_current_search = null;
            rem_context(ZP_SEARCH);
            if (!isset($_REQUEST['preserve_serch_params'])) {
                zp_clearCookie("zenphoto_search_params");
            }
        }
    }
}
/**
 * Creates the managed album table for Admin
 *
 * @param string $type the kind of list
 * @param array $objlist list of objects
 * @param string $alterrights are the items changable
 * @param object $userobj the user
 * @param int $prefix the admin row
 * @param string $kind user, group, or template
 * @param array $flat items to be flagged with an asterix
 */
function printManagedObjects($type, $objlist, $alterrights, $userobj, $prefix_id, $kind, $flag)
{
    $rest = $extra = $extra2 = array();
    $rights = $userobj->getRights();
    $full = $userobj->getObjects();
    $legend = '';
    $icon_edit = '<img src="' . WEBPATH . '/' . ZENFOLDER . '/images/options.png" class="icon-position-top3" alt="" title="' . gettext('edit rights') . '" />';
    $icon_view = '<img src="' . WEBPATH . '/' . ZENFOLDER . '/images/action.png" class="icon-position-top3" alt="" title="' . gettext('view unpublished items') . '" />';
    $icon_upload = '<img src="' . WEBPATH . '/' . ZENFOLDER . '/images/arrow_up.png" class="icon-position-top3"  alt="" title="' . gettext('upload rights') . '"/>';
    $icon_upload_disabled = '<img src="' . WEBPATH . '/' . ZENFOLDER . '/images/arrow_up.png" class="icon-position-top3"  alt="" title="' . gettext('the album is dynamic') . '"/>';
    switch ($type) {
        case 'albums':
            if ($rights & (MANAGE_ALL_ALBUM_RIGHTS | ADMIN_RIGHTS)) {
                $cv = $objlist;
                $alterrights = ' disabled="disabled"';
            } else {
                $cv = $extra = $extra2 = array();
                if (!empty($flag)) {
                    $legend .= '* ' . gettext('Primary album') . ' ';
                }
                $legend .= $icon_edit . ' ' . gettext('edit') . ' ';
                if ($rights & UPLOAD_RIGHTS) {
                    $legend .= $icon_upload . ' ' . gettext('upload') . ' ';
                }
                if (!($rights & VIEW_UNPUBLISHED_RIGHTS)) {
                    $legend .= $icon_view . ' ' . gettext('view unpublished');
                }
                foreach ($full as $item) {
                    if ($item['type'] == 'album') {
                        if (in_array($item['data'], $flag)) {
                            $note = '*';
                        } else {
                            $note = '';
                        }
                        $cv[$item['name'] . $note] = $item['data'];
                        $extra[$item['data']][] = array('name' => 'name', 'value' => $item['name'], 'display' => '', 'checked' => 0);
                        $extra[$item['data']][] = array('name' => 'edit', 'value' => MANAGED_OBJECT_RIGHTS_EDIT, 'display' => $icon_edit, 'checked' => $item['edit'] & MANAGED_OBJECT_RIGHTS_EDIT);
                        if ($rights & UPLOAD_RIGHTS) {
                            if (hasDynamicAlbumSuffix($item['data']) && !is_dir(ALBUM_FOLDER_SERVERPATH . $item['data'])) {
                                $extra[$item['data']][] = array('name' => 'upload', 'value' => MANAGED_OBJECT_RIGHTS_UPLOAD, 'display' => $icon_upload_disabled, 'checked' => 0, 'disable' => true);
                            } else {
                                $extra[$item['data']][] = array('name' => 'upload', 'value' => MANAGED_OBJECT_RIGHTS_UPLOAD, 'display' => $icon_upload, 'checked' => $item['edit'] & MANAGED_OBJECT_RIGHTS_UPLOAD);
                            }
                        }
                        if (!($rights & VIEW_UNPUBLISHED_RIGHTS)) {
                            $extra[$item['data']][] = array('name' => 'view', 'value' => MANAGED_OBJECT_RIGHTS_VIEW, 'display' => $icon_view, 'checked' => $item['edit'] & MANAGED_OBJECT_RIGHTS_VIEW);
                        }
                    }
                }
                $rest = array_diff($objlist, $cv);
                foreach ($rest as $unmanaged) {
                    $extra2[$unmanaged][] = array('name' => 'name', 'value' => $unmanaged, 'display' => '', 'checked' => 0);
                    $extra2[$unmanaged][] = array('name' => 'edit', 'value' => MANAGED_OBJECT_RIGHTS_EDIT, 'display' => $icon_edit, 'checked' => 1);
                    if ($rights & UPLOAD_RIGHTS) {
                        if (hasDynamicAlbumSuffix($unmanaged) && !is_dir(ALBUM_FOLDER_SERVERPATH . $unmanaged)) {
                            $extra2[$unmanaged][] = array('name' => 'upload', 'value' => MANAGED_OBJECT_RIGHTS_UPLOAD, 'display' => $icon_upload_disabled, 'checked' => 0, 'disable' => true);
                        } else {
                            $extra2[$unmanaged][] = array('name' => 'upload', 'value' => MANAGED_OBJECT_RIGHTS_UPLOAD, 'display' => $icon_upload, 'checked' => 1);
                        }
                    }
                    if (!($rights & VIEW_UNPUBLISHED_RIGHTS)) {
                        $extra2[$unmanaged][] = array('name' => 'view', 'value' => MANAGED_OBJECT_RIGHTS_VIEW, 'display' => $icon_view, 'checked' => 1);
                    }
                }
            }
            $text = gettext("Managed albums:");
            $simplename = $objectname = gettext('Albums');
            $prefix = 'managed_albums_list_' . $prefix_id . '_';
            break;
        case 'news':
            if ($rights & (MANAGE_ALL_NEWS_RIGHTS | ADMIN_RIGHTS)) {
                $cv = $objlist;
                $rest = array();
                $alterrights = ' disabled="disabled"';
            } else {
                $cv = $extra = $extra2 = array();
                $rest = array_diff($objlist, $cv);
                $legend = $icon_edit . ' ' . gettext('edit') . ' ' . $icon_view . ' ' . gettext('view unpublished');
                foreach ($full as $item) {
                    if ($item['type'] == 'news') {
                        $cv[$item['name']] = $item['data'];
                        $extra[$item['data']][] = array('name' => 'name', 'value' => $item['name'], 'display' => '', 'checked' => 0);
                        $extra[$item['data']][] = array('name' => 'edit', 'value' => MANAGED_OBJECT_RIGHTS_EDIT, 'display' => $icon_edit, 'checked' => $item['edit'] & MANAGED_OBJECT_RIGHTS_EDIT);
                        $extra[$item['data']][] = array('name' => 'view', 'value' => MANAGED_OBJECT_RIGHTS_VIEW, 'display' => $icon_view, 'checked' => $item['edit'] & MANAGED_OBJECT_RIGHTS_VIEW);
                    }
                }
                $rest = array_diff($objlist, $cv);
                foreach ($rest as $unmanaged) {
                    $extra2[$unmanaged][] = array('name' => 'name', 'value' => $unmanaged, 'display' => '', 'checked' => 0);
                    $extra2[$unmanaged][] = array('name' => 'edit', 'value' => MANAGED_OBJECT_RIGHTS_EDIT, 'display' => $icon_edit, 'checked' => 1);
                    $extra2[$unmanaged][] = array('name' => 'view', 'value' => MANAGED_OBJECT_RIGHTS_VIEW, 'display' => $icon_view, 'checked' => 1);
                }
            }
            $text = gettext("Managed news categories:");
            $simplename = gettext('News');
            $objectname = gettext('News categories');
            $prefix = 'managed_news_list_' . $prefix_id . '_';
            break;
        case 'pages':
            if ($rights & (MANAGE_ALL_PAGES_RIGHTS | ADMIN_RIGHTS)) {
                $cv = $objlist;
                $rest = array();
                $alterrights = ' disabled="disabled"';
            } else {
                $cv = $extra = $extra2 = array();
                $rest = array_diff($objlist, $cv);
                $legend = $icon_edit . ' ' . gettext('edit') . ' ' . $icon_view . ' ' . gettext('view unpublished');
                foreach ($full as $item) {
                    if ($item['type'] == 'pages') {
                        $cv[$item['name']] = $item['data'];
                        $extra[$item['data']][] = array('name' => 'name', 'value' => $item['name'], 'display' => '', 'checked' => 0);
                        $extra[$item['data']][] = array('name' => 'edit', 'value' => MANAGED_OBJECT_RIGHTS_EDIT, 'display' => $icon_edit, 'checked' => $item['edit'] & MANAGED_OBJECT_RIGHTS_EDIT);
                        $extra[$item['data']][] = array('name' => 'view', 'value' => MANAGED_OBJECT_RIGHTS_VIEW, 'display' => $icon_view, 'checked' => $item['edit'] & MANAGED_OBJECT_RIGHTS_VIEW);
                    }
                }
                $rest = array_diff($objlist, $cv);
                foreach ($rest as $unmanaged) {
                    $extra2[$unmanaged][] = array('name' => 'name', 'value' => $unmanaged, 'display' => '', 'checked' => 0);
                    $extra2[$unmanaged][] = array('name' => 'edit', 'value' => MANAGED_OBJECT_RIGHTS_EDIT, 'display' => $icon_edit, 'checked' => 1);
                    $extra2[$unmanaged][] = array('name' => 'view', 'value' => MANAGED_OBJECT_RIGHTS_VIEW, 'display' => $icon_view, 'checked' => 1);
                }
            }
            $text = gettext("Managed pages:");
            $simplename = $objectname = gettext('Pages');
            $prefix = 'managed_pages_list_' . $prefix_id . '_';
            break;
    }
    if (empty($alterrights)) {
        $hint = sprintf(gettext('Select one or more %1$s for the %2$s to manage.'), $simplename, $kind) . ' ';
        if ($kind == gettext('user')) {
            $hint .= sprintf(gettext('Users with "Admin" or "Manage all %1$s" rights can manage all %2$s. All others may manage only those that are selected.'), $type, $objectname);
        }
    } else {
        $hint = sprintf(gettext('You may manage these %s subject to the above rights.'), $simplename);
    }
    if (count($cv) > 0) {
        $itemcount = ' (' . count($cv) . ')';
    } else {
        $itemcount = '';
    }
    ?>
	<div class="box-albums-unpadded">
		<h2 class="h2_bordered_albums">
			<a onclick="toggle('<?php 
    echo $prefix;
    ?>
');" title="<?php 
    echo html_encode($hint);
    ?>
" ><?php 
    echo $text . $itemcount;
    ?>
</a>
		</h2>
		<div id="<?php 
    echo $prefix;
    ?>
" style="display:none;">
			<ul class="albumchecklist">
				<?php 
    generateUnorderedListFromArray($cv, $cv, $prefix, $alterrights, true, true, 'user-' . $prefix_id, $extra);
    generateUnorderedListFromArray(array(), $rest, $prefix, $alterrights, true, true, 'user-' . $prefix_id, $extra2);
    ?>
			</ul>
			<span class="floatright"><?php 
    echo $legend;
    ?>
&nbsp;&nbsp;&nbsp;&nbsp;</span>
			<br class="clearall" />
		</div>
	</div>
	<?php 
}
        $albums[] = sanitize($album);
    }
} else {
    $count = 0;
    $albumcount = 0;
    $albums = $gallery->getAlbums();
}
?>
<script type="text/javascript">
<!--
	var albumcount = 0;
	var imagecount = 0;
	var albumspending = [<?php 
$c = 0;
foreach ($albums as $key => $album) {
    if (hasDynamicAlbumSuffix($album)) {
        unset($albums[$key]);
    } else {
        if ($c) {
            echo ',';
        }
        echo "'" . $album . "'";
        $c++;
    }
}
?>
];
	function reStart() {
		var datum = '?imagecount='+imagecount+'&albumcount='+albumcount+'&todo='+albumspending.join(',')+'&XSRFToken=<?php 
echo getXSRFToken('seo_cleanup');
?>
/**
 * Gets the title, url and name of a menu item
 *
 * @return array
 */
function getItemTitleAndURL($item)
{
    global $_zp_gallery;
    $themename = $_zp_gallery->getCurrentTheme();
    $array = array();
    $valid = true;
    $title = get_language_string($item['title']);
    switch ($item['type']) {
        case "galleryindex":
            $array = array("title" => get_language_string($item['title']), "url" => WEBPATH, "name" => WEBPATH, 'protected' => false, 'theme' => $themename);
            break;
        case "album":
            $folderFS = internalToFilesystem($item['link']);
            $localpath = ALBUM_FOLDER_SERVERPATH . $folderFS;
            $dynamic = hasDynamicAlbumSuffix($folderFS) && !is_dir($folderFS);
            $valid = file_exists($localpath) && ($dynamic || is_dir($localpath));
            if (!$valid || strpos($localpath, '..') !== false) {
                $valid = false;
                $url = '';
                $protected = 0;
            } else {
                $obj = newAlbum($item['link']);
                $url = $obj->getLink(0);
                $protected = $obj->isProtected();
                $title = $obj->getTitle();
            }
            $array = array("title" => $title, "url" => $url, "name" => $item['link'], 'protected' => $protected, 'theme' => $themename);
            break;
        case "page":
            $sql = 'SELECT * FROM ' . prefix('pages') . ' WHERE `titlelink`="' . $item['link'] . '"';
            $result = query_single_row($sql);
            if (is_array($result) && extensionEnabled('zenpage')) {
                $obj = newPage($item['link']);
                $url = $obj->getLink(0);
                $protected = $obj->isProtected();
                $title = $obj->getTitle();
            } else {
                $valid = false;
                $url = '';
                $protected = 0;
            }
            $array = array("title" => $title, "url" => $url, "name" => $item['link'], 'protected' => $protected);
            break;
        case "newsindex":
            if ($valid = extensionEnabled('zenpage')) {
                $url = getNewsIndexURL();
            } else {
                $url = '';
            }
            $array = array("title" => get_language_string($item['title']), "url" => $url, "name" => $url, 'protected' => false);
            break;
        case "category":
            $valid = extensionEnabled('zenpage');
            $sql = "SELECT title FROM " . prefix('news_categories') . " WHERE titlelink = '" . $item['link'] . "'";
            $obj = query_single_row($sql, false);
            if ($obj && $valid) {
                $obj = newCategory($item['link']);
                $title = $obj->getTitle();
                $protected = $obj->isProtected();
                $url = $obj->getLink(0);
            } else {
                $valid = false;
                $url = '';
                $protected = 0;
            }
            $array = array("title" => $title, "url" => $url, "name" => $item['link'], 'protected' => $protected);
            break;
        case "custompage":
            $root = SERVERPATH . '/' . THEMEFOLDER . '/' . $themename . '/';
            if (file_exists($root . $item['link'] . '.php')) {
                $url = zp_apply_filter('getLink', rewrite_path(_PAGE_ . '/' . $item['link'], "/index.php?p=" . $item['link']), $item['link'] . '.php', NULL);
            } else {
                $valid = false;
                $url = '';
            }
            $array = array("title" => $title, "url" => $url, "name" => $item['link'], 'protected' => false, 'theme' => $themename);
            break;
        case "customlink":
            $array = array("title" => get_language_string($item['title']), "url" => $item['link'], "name" => $item['link'], 'protected' => false, 'theme' => $themename);
            break;
        case 'menulabel':
            $array = array("title" => get_language_string($item['title']), "url" => NULL, 'name' => $item['title'], 'protected' => false, 'theme' => $themename);
            break;
        default:
            $array = array("title" => get_language_string($item['title']), "url" => $item['link'], "name" => $item['link'], 'protected' => false, 'theme' => $themename);
            break;
    }
    $limit = MENU_TRUNCATE_STRING;
    $array['valid'] = $valid;
    if ($limit) {
        $array['title'] = shortenContent($array['title'], $limit, MENU_TRUNCATE_INDICATOR);
    }
    return $array;
}
printLogoAndLinks();
?>
<div id="main">
	<?php 
printTabs();
?>
	<div id="content">
		<?php 
if (!empty($zenphoto_tabs['upload']['subtabs'])) {
    printSubtabs();
}
$albumlist = array();
genAlbumList($albumlist);
//	remove dynamic albums--can't upload to them
foreach ($albumlist as $key => $albumname) {
    if (hasDynamicAlbumSuffix($key) && !is_dir(ALBUM_FOLDER_SERVERPATH . $key)) {
        unset($albumlist[$key]);
    }
}
?>
		<script type="text/javascript">
			// <!-- <![CDATA[
			// Array of album names for javascript functions.
			var albumArray = new Array(
<?php 
$separator = '';
foreach ($albumlist as $key => $value) {
    echo $separator . "'" . addslashes($key) . "'";
    $separator = ", ";
}
?>
/**
 * Returns table row(s) for edit of an admin user's custom data
 *
 * @param string $html always empty
 * @param $userobj Admin user object
 * @param string $i prefix for the admin
 * @param string $background background color for the admin row
 * @param bool $current true if this admin row is the logged in admin
 * @return string
 */
function user_groups_edit_admin($html, $userobj, $i, $background, $current)
{
    global $gallery, $_zp_authority, $_zp_zenpage;
    $group = $userobj->getGroup();
    $admins = $_zp_authority->getAdministrators('all');
    $ordered = array();
    $groups = array();
    $hisgroup = NULL;
    $adminordered = array();
    foreach ($admins as $key => $admin) {
        $ordered[$key] = $admin['user'];
        if ($group == $admin['user']) {
            $hisgroup = $admin;
        }
    }
    asort($ordered);
    foreach ($ordered as $key => $user) {
        $adminordered[] = $admins[$key];
        if (!$admins[$key]['valid']) {
            $groups[] = $admins[$key];
        }
    }
    if (empty($groups)) {
        return '';
    }
    // no groups setup yet
    if (zp_loggedin(ADMIN_RIGHTS)) {
        $albumlist = array();
        $allalb = array();
        foreach ($gallery->getAlbums() as $folder) {
            if (hasDynamicAlbumSuffix($folder)) {
                $name = substr($folder, 0, -4);
                // Strip the .'.alb' suffix
            } else {
                $name = $folder;
            }
            $albumlist[$name] = $folder;
            $allalb[] = "'#managed_albums_" . $i . '_' . postIndexEncode($folder) . "'";
        }
        if (getOption('zp_plugin_zenpage')) {
            $pagelist = array();
            $allpag = array();
            $pages = $_zp_zenpage->getPages(false);
            foreach ($pages as $page) {
                if (!$page['parentid']) {
                    $pagelist[get_language_string($page['title'])] = $page['titlelink'];
                    $allpag[] = "'#managed_pages_" . $i . '_' . postIndexEncode($page['titlelink']) . "'";
                }
            }
            $newslist = array();
            $allnew = array();
            $categories = $_zp_zenpage->getAllCategories(false);
            foreach ($categories as $category) {
                $newslist[get_language_string($category['titlelink'])] = $category['title'];
                $allnew[] = "'#managed_news_" . $i . '_' . postIndexEncode($category['titlelink']) . "'";
            }
        }
        $rights = array();
        foreach ($_zp_authority->getRights() as $rightselement => $right) {
            if ($right['display']) {
                $rights[] = "'#" . $rightselement . '-' . $i . "'";
            }
        }
        $grouppart = '
			<script type="text/javascript">
				// <!-- <![CDATA[
				function groupchange' . $i . '(obj) {
					var disable = obj.value != \'\';
					var albdisable = false;
					var checkedalbums = [];
					var checked = 0;
					var uncheckedalbums = [];
					var unchecked = 0;
					var allalbums = [' . implode(',', $allalb) . '];
					var allalbumsc = ' . count($allalb) . ';';
        if (getOption('zp_plugin_zenpage')) {
            $grouppart .= '
						var allpages = [' . implode(',', $allpag) . '];
						var allpagesc = ' . count($allpag) . ';
						var allnews = [' . implode(',', $allnew) . '];
						var allnewsc = ' . count($allnew) . ';';
        }
        $grouppart .= '
					var rights = [' . implode(',', $rights) . '];
					var rightsc = ' . count($rights) . ';
					for (i=0;i<rightsc;i++) {
						$(rights[i]).attr(\'disabled\',disable);
					}
					for (i=0;i<allalbumsc;i++) {
						$(allalbums[i]).attr(\'disabled\',disable);
					}';
        if (getOption('zp_plugin_zenpage')) {
            $grouppart .= '
					for (i=0;i<allpagesc;i++) {
						$(allpages[i]).attr(\'disabled\',disable);
					}
					for (i=0;i<allnewsc;i++) {
						$(allnews[i]).attr(\'disabled\',disable);
					}';
        }
        $grouppart .= '
					$(\'#hint' . $i . '\').html(obj.options[obj.selectedIndex].title);
					if (disable) {
						switch (obj.value) {';
        foreach ($groups as $user) {
            $grouppart .= '
							case \'' . $user['user'] . '\':
								target = ' . $user['rights'] . ';';
            if (getOption('zp_plugin_zenpage')) {
                $codelist = array('album', 'pages', 'news');
            } else {
                $codelist = array('album');
            }
            foreach ($codelist as $mo) {
                $cv = populateManagedObjectsList($mo, $user['id']);
                switch ($mo) {
                    case 'album':
                        $xv = array_diff($albumlist, $cv);
                        break;
                    case 'pages':
                        $xv = array_diff($pagelist, $cv);
                        break;
                    case 'news':
                        $xv = array_diff($newslist, $cv);
                        break;
                }
                $cvo = array();
                foreach ($cv as $moid) {
                    $cvo[] = "'#managed_" . $mo . "_" . $i . '_' . postIndexEncode($moid) . "'";
                }
                $xvo = array();
                foreach ($xv as $moid) {
                    $xvo[] = "'#managed_" . $mo . "_" . $i . '_' . postIndexEncode($moid) . "'";
                }
                $grouppart .= '
									checked' . $mo . ' = [' . implode(',', $cvo) . '];
									checked' . $mo . 'c = ' . count($cvo) . ';
									unchecked' . $mo . ' = [' . implode(',', $xvo) . '];
									unchecked' . $mo . 'c = ' . count($xvo) . ';';
            }
            if ($user['name'] == 'template') {
                $albdisable = 'false';
            } else {
                $albdisable = 'true';
            }
            $grouppart .= '
								break;';
        }
        $grouppart .= '
							}
						for (i=0;i<checkedalbumc;i++) {
							$(checkedalbum[i]).attr(\'checked\',\'checked\');
						}
						for (i=0;i<uncheckedalbumc;i++) {
							$(uncheckedalbum[i]).attr(\'checked\',\'\');
						}';
        foreach ($groups as $user) {
            $grouppart .= '
						for (i=0;i<checkedpagesc;i++) {
							$(checkedpages[i]).attr(\'checked\',\'checked\');
						}
						for (i=0;i<uncheckedpagesc;i++) {
							$(uncheckedpages[i]).attr(\'checked\',\'\');
						}
						for (i=0;i<checkednewsc;i++) {
							$(checkednews[i]).attr(\'checked\',\'checked\');
						}
						for (i=0;i<uncheckednewsc;i++) {
							$(uncheckednews[i]).attr(\'checked\',\'\');
						}';
        }
        $grouppart .= '
						for (i=0;i<rightsc;i++) {
							if ($(rights[i]).val()&target) {
								$(rights[i]).attr(\'checked\',\'checked\');
							} else {
								$(rights[i]).attr(\'checked\',\'\');
							}
						}
					}
				}';
        if (is_array($hisgroup)) {
            $grouppart .= '
				window.onload = function() {';
            foreach ($codelist as $mo) {
                $cv = populateManagedObjectsList($mo, $user['id']);
                switch ($mo) {
                    case 'album':
                        $list = $albumlist;
                        break;
                    case 'pages':
                        $list = $pagelist;
                        break;
                    case 'news':
                        $list = $newslist;
                        break;
                }
                foreach ($list as $moid) {
                    if (in_array($moid, $cv)) {
                        $grouppart .= '
						$(\'#managed_' . $mo . '_' . $i . '_' . postIndexEncode($moid) . '\').attr(\'checked\',\'checked\');';
                    } else {
                        $grouppart .= '
						$(\'#managed_' . $mo . '_' . $i . '_' . postIndexEncode($moid) . '\').attr(\'checked\',\'\');';
                    }
                }
            }
            $grouppart .= '
				}';
        }
        $grouppart .= '
				//]]> -->
			</script>';
        $grouppart .= '<select name="' . $i . 'group" onchange="javascript:groupchange' . $i . '(this);"' . '>' . "\n";
        $grouppart .= '<option value="" title="' . gettext('*no group affiliation') . '">' . gettext('*no group selected') . '</option>' . "\n";
        $selected_hint = gettext('no group affiliation');
        foreach ($groups as $user) {
            if ($user['name'] == 'template') {
                $type = '<strong>' . gettext('Template:') . '</strong> ';
            } else {
                $type = '';
            }
            $hint = $type . '<em>' . html_encode($user['custom_data']) . '</em>';
            if ($group == $user['user']) {
                $selected = ' selected="selected"';
                $selected_hint = $hint;
            } else {
                $selected = '';
            }
            $grouppart .= '<option' . $selected . ' value="' . $user['user'] . '" title="' . sanitize($hint, 3) . '">' . $user['user'] . '</option>' . "\n";
        }
        $grouppart .= '</select>' . "\n";
        $grouppart .= '<span class="hint' . $i . '" id="hint' . $i . '" style="width:15em;">' . $selected_hint . "</span>\n";
    } else {
        if ($group) {
            $grouppart = $group;
        } else {
            $grouppart = gettext('no group affiliation');
        }
        $grouppart = ' <em>' . $grouppart . '</em><input type="hidden" name="' . $i . 'group" value="' . $group . '" />' . "\n";
    }
    $result = '<tr' . (!$current ? ' style="display:none;"' : '') . ' class="userextrainfo">
			<td colspan="2" width="20%"' . (!empty($background) ? ' style="' . $background . '"' : '') . ' valign="top">' . gettext('User group membership') . $grouppart . '<br />' . gettext('<strong>Note:</strong> When a group is assigned <em>rights</em> and <em>managed albums</em> are determined by the group!') . '</td>
			<td' . (!empty($background) ? ' style="' . $background . '"' : '') . ' valign="top" width="345">' . '</td>
			</tr>' . "\n";
    return $html . $result;
}
 /**
  * Load all of the filenames that are found in this Albums directory on disk.
  * Returns an array with all the names.
  *
  * @param  $dirs Whether or not to return directories ONLY with the file array.
  * @return array
  */
 function loadFileNames($dirs = false)
 {
     if ($this->isDynamic()) {
         // there are no 'real' files
         return array();
     }
     $albumdir = $this->localpath;
     if (!is_dir($albumdir) || !is_readable($albumdir)) {
         if (!is_dir($albumdir)) {
             $msg = sprintf(gettext("Error: The album named %s cannot be found."), $this->name);
         } else {
             $msg = sprintf(gettext("Error: The album %s is not readable."), $this->name);
         }
         zp_error($msg, false);
         return array();
     }
     $dir = opendir($albumdir);
     $files = array();
     $others = array();
     while (false !== ($file = readdir($dir))) {
         $file8 = filesystemToInternal($file);
         if ($dirs && (is_dir($albumdir . $file) && substr($file, 0, 1) != '.' || hasDynamicAlbumSuffix($file))) {
             $files[] = $file8;
         } else {
             if (!$dirs && is_file($albumdir . $file)) {
                 if (is_valid_other_type($file)) {
                     $files[] = $file8;
                     $others[] = $file8;
                 } else {
                     if (is_valid_image($file)) {
                         $files[] = $file8;
                     }
                 }
             }
         }
     }
     closedir($dir);
     if (count($others) > 0) {
         $others_thumbs = array();
         foreach ($others as $other) {
             $others_root = substr($other, 0, strrpos($other, "."));
             foreach ($files as $image) {
                 $image_root = substr($image, 0, strrpos($image, "."));
                 if ($image_root == $others_root && $image != $other && is_valid_image($image)) {
                     $others_thumbs[] = $image;
                 }
             }
         }
         $files = array_diff($files, $others_thumbs);
     }
     if ($dirs) {
         return zp_apply_filter('album_filter', $files);
     } else {
         return zp_apply_filter('image_filter', $files);
     }
 }
 /** For every album in the gallery, look for its file. Delete from the database
  * if the file does not exist. Do the same for images. Clean up comments that have
  * been left orphaned.
  *
  * Returns true if the operation was interrupted because it was taking too long
  *
  * @param bool $cascade garbage collect every image and album in the gallery.
  * @param bool $complete garbage collect every image and album in the *database* - completely cleans the database.
  * @param  int $restart Image ID to restart scan from
  * @return bool
  */
 function garbageCollect($cascade = true, $complete = false, $restart = '')
 {
     global $_zp_gallery, $_zp_authority;
     if (empty($restart)) {
         setOption('last_garbage_collect', time());
         /* purge old search cache items */
         $sql = 'DELETE FROM ' . prefix('search_cache');
         if (!$complete) {
             $sql .= ' WHERE `date`<' . db_quote(date('Y-m-d H:m:s', time() - SEARCH_CACHE_DURATION * 60));
         }
         $result = query($sql);
         /* clean the comments table */
         $this->commentClean('images');
         $this->commentClean('albums');
         $this->commentClean('news');
         $this->commentClean('pages');
         // clean up obj_to_tag
         $dead = array();
         $result = query("SELECT * FROM " . prefix('obj_to_tag'));
         if ($result) {
             while ($row = db_fetch_assoc($result)) {
                 $tbl = $row['type'];
                 $dbtag = query_single_row("SELECT `id` FROM " . prefix('tags') . " WHERE `id`='" . $row['tagid'] . "'", false);
                 if (!$dbtag) {
                     $dead[] = $row['id'];
                 }
                 $dbtag = query_single_row("SELECT `id` FROM " . prefix($tbl) . " WHERE `id`='" . $row['objectid'] . "'", false);
                 if (!$dbtag) {
                     $dead[] = $row['id'];
                 }
             }
             db_free_result($result);
         }
         if (!empty($dead)) {
             $dead = array_unique($dead);
             query('DELETE FROM ' . prefix('obj_to_tag') . ' WHERE `id`=' . implode(' OR `id`=', $dead));
         }
         // clean up admin_to_object
         $dead = array();
         $result = query("SELECT * FROM " . prefix('admin_to_object'));
         if ($result) {
             while ($row = db_fetch_assoc($result)) {
                 if (!$_zp_authority->validID($row['adminid'])) {
                     $dead[] = $row['id'];
                 }
                 $tbl = $row['type'];
                 $dbtag = query_single_row("SELECT `id` FROM " . prefix($tbl) . " WHERE `id`='" . $row['objectid'] . "'", false);
                 if (!$dbtag) {
                     $dead[] = $row['id'];
                 }
             }
             db_free_result($result);
         }
         if (!empty($dead)) {
             $dead = array_unique($dead);
             query('DELETE FROM ' . prefix('admin_to_object') . ' WHERE `id`=' . implode(' OR `id`=', $dead));
         }
         // clean up news2cat
         $dead = array();
         $result = query("SELECT * FROM " . prefix('news2cat'));
         if ($result) {
             while ($row = db_fetch_assoc($result)) {
                 $dbtag = query_single_row("SELECT `id` FROM " . prefix('news') . " WHERE `id`='" . $row['news_id'] . "'", false);
                 if (!$dbtag) {
                     $dead[] = $row['id'];
                 }
                 $dbtag = query_single_row("SELECT `id` FROM " . prefix('news_categories') . " WHERE `id`='" . $row['cat_id'] . "'", false);
                 if (!$dbtag) {
                     $dead[] = $row['id'];
                 }
             }
             db_free_result($result);
         }
         if (!empty($dead)) {
             $dead = array_unique($dead);
             query('DELETE FROM ' . prefix('news2cat') . ' WHERE `id`=' . implode(' OR `id`=', $dead));
         }
         // Check for the existence albums
         $dead = array();
         $live = array('');
         // purge the root album if it exists
         $deadalbumthemes = array();
         // Load the albums from disk
         $result = query("SELECT * FROM " . prefix('albums'));
         while ($row = db_fetch_assoc($result)) {
             $albumpath = internalToFilesystem($row['folder']);
             $albumpath_valid = preg_replace('~/\\.*/~', '/', $albumpath);
             $albumpath_valid = ltrim(trim($albumpath_valid, '/'), './');
             $illegal = $albumpath != $albumpath_valid;
             $valid = file_exists(ALBUM_FOLDER_SERVERPATH . $albumpath_valid) && (hasDynamicAlbumSuffix($albumpath_valid) || is_dir(ALBUM_FOLDER_SERVERPATH . $albumpath_valid));
             if ($valid && $illegal) {
                 // maybe there is only one record so we can fix it.
                 $valid = query('UPDATE ' . prefix('albums') . ' SET `folder`=' . db_quote($albumpath_valid) . ' WHERE `id`=' . $row['id'], false);
                 debugLog(sprintf(gettext('Invalid album folder: %1$s %2$s'), $albumpath, $valid ? gettext('fixed') : gettext('discarded')));
             }
             if (!$valid || in_array($row['folder'], $live)) {
                 $dead[] = $row['id'];
                 if ($row['album_theme'] !== '') {
                     // orphaned album theme options table
                     $deadalbumthemes[$row['id']] = $row['folder'];
                 }
             } else {
                 $live[] = $row['folder'];
             }
         }
         db_free_result($result);
         if (count($dead) > 0) {
             /* delete the dead albums from the DB */
             asort($dead);
             $criteria = '(' . implode(',', $dead) . ')';
             $first = array_pop($dead);
             $sql1 = "DELETE FROM " . prefix('albums') . " WHERE `id` IN {$criteria}";
             $n = query($sql1);
             if (!$complete && $n && $cascade) {
                 $sql2 = "DELETE FROM " . prefix('images') . " WHERE `albumid` IN {$criteria}";
                 query($sql2);
                 $sql3 = "DELETE FROM " . prefix('comments') . " WHERE `type`='albums' AND `ownerid` IN {$criteria}";
                 query($sql3);
                 $sql4 = "DELETE FROM " . prefix('obj_to_tag') . " WHERE `type`='albums' AND `objectid` IN {$criteria}";
                 query($sql4);
             }
         }
         if (count($deadalbumthemes) > 0) {
             // delete the album theme options tables for dead albums
             foreach ($deadalbumthemes as $id => $deadtable) {
                 $sql = 'DELETE FROM ' . prefix('options') . ' WHERE `ownerid`=' . $id;
                 query($sql, false);
             }
         }
     }
     if ($complete) {
         if (empty($restart)) {
             /* check album parent linkage */
             $albums = $_zp_gallery->getAlbums();
             foreach ($albums as $album) {
                 checkAlbumParentid($album, NULL, 'debuglog');
             }
             /* refresh 'metadata' albums */
             $albumids = query("SELECT `id`, `mtime`, `folder`, `dynamic` FROM " . prefix('albums'));
             if ($albumids) {
                 while ($analbum = db_fetch_assoc($albumids)) {
                     if (($mtime = filemtime(ALBUM_FOLDER_SERVERPATH . internalToFilesystem($analbum['folder']))) > $analbum['mtime']) {
                         // refresh
                         $album = newAlbum($analbum['folder']);
                         $album->set('mtime', $mtime);
                         if ($this->getAlbumUseImagedate()) {
                             $album->setDateTime(NULL);
                         }
                         if ($album->isDynamic()) {
                             $data = file_get_contents($album->localpath);
                             $thumb = getOption('AlbumThumbSelect');
                             $words = $fields = '';
                             while (!empty($data)) {
                                 $data1 = trim(substr($data, 0, $i = strpos($data, "\n")));
                                 if ($i === false) {
                                     $data1 = $data;
                                     $data = '';
                                 } else {
                                     $data = substr($data, $i + 1);
                                 }
                                 if (strpos($data1, 'WORDS=') !== false) {
                                     $words = "words=" . urlencode(substr($data1, 6));
                                 }
                                 if (strpos($data1, 'THUMB=') !== false) {
                                     $thumb = trim(substr($data1, 6));
                                 }
                                 if (strpos($data1, 'FIELDS=') !== false) {
                                     $fields = "&searchfields=" . trim(substr($data1, 7));
                                 }
                             }
                             if (!empty($words)) {
                                 if (empty($fields)) {
                                     $fields = '&searchfields=tags';
                                 }
                             }
                             $album->set('search_params', $words . $fields);
                             $album->set('thumb', $thumb);
                         }
                         $album->save();
                         zp_apply_filter('album_refresh', $album);
                     }
                 }
                 db_free_result($albumids);
             }
             /* Delete all image entries that don't belong to an album at all. */
             $albumids = query("SELECT `id` FROM " . prefix('albums'));
             /* all the album IDs */
             $idsofalbums = array();
             if ($albumids) {
                 while ($row = db_fetch_assoc($albumids)) {
                     $idsofalbums[] = $row['id'];
                 }
                 db_free_result($albumids);
             }
             $imageAlbums = query("SELECT DISTINCT `albumid` FROM " . prefix('images'));
             /* albumids of all the images */
             $albumidsofimages = array();
             if ($imageAlbums) {
                 while ($row = db_fetch_assoc($imageAlbums)) {
                     $albumidsofimages[] = $row['albumid'];
                 }
                 db_free_result($imageAlbums);
             }
             $orphans = array_diff($albumidsofimages, $idsofalbums);
             /* albumids of images with no album */
             if (count($orphans) > 0) {
                 /* delete dead images from the DB */
                 $sql = "DELETE FROM " . prefix('images') . " WHERE ";
                 foreach ($orphans as $id) {
                     if (is_null($id)) {
                         $sql .= "`albumid` is NULL OR ";
                     } else {
                         $sql .= " `albumid`='" . $id . "' OR ";
                     }
                 }
                 $sql = substr($sql, 0, -4);
                 query($sql);
                 // Then go into existing albums recursively to clean them... very invasive.
                 foreach ($this->getAlbums(0) as $folder) {
                     $album = newAlbum($folder);
                     if (!$album->isDynamic()) {
                         if (is_null($album->getDateTime())) {
                             // see if we can get one from an image
                             $images = $album->getImages(0, 0);
                             if (count($images) > 0) {
                                 $image = newImage($album, array_shift($images));
                                 $album->setDateTime($image->getDateTime());
                                 $album->save();
                             }
                         }
                         $album->garbageCollect(true);
                     }
                     zp_apply_filter('album_refresh', $album);
                 }
             }
         }
         /* Look for image records where the file no longer exists. While at it, check for images with IPTC data to update the DB */
         $start = array_sum(explode(" ", microtime()));
         // protect against too much processing.
         if (!empty($restart)) {
             $restartwhere = ' WHERE `id`>' . $restart . ' AND `mtime`=0';
         } else {
             $restartwhere = ' WHERE `mtime`=0';
         }
         define('RECORD_LIMIT', 5);
         $sql = 'SELECT * FROM ' . prefix('images') . $restartwhere . ' ORDER BY `id` LIMIT ' . (RECORD_LIMIT + 2);
         $images = query($sql);
         if ($images) {
             $c = 0;
             while ($image = db_fetch_assoc($images)) {
                 $albumobj = getItemByID('albums', $image['albumid']);
                 if ($albumobj->exists && file_exists($imageName = internalToFilesystem(ALBUM_FOLDER_SERVERPATH . $albumobj->name . '/' . $image['filename']))) {
                     if ($image['mtime'] != ($mtime = filemtime($imageName))) {
                         // file has changed since we last saw it
                         $imageobj = newImage($albumobj, $image['filename']);
                         $imageobj->set('mtime', $mtime);
                         $imageobj->updateMetaData();
                         // prime the EXIF/IPTC fields
                         $imageobj->updateDimensions();
                         // update the width/height & account for rotation
                         $imageobj->save();
                         zp_apply_filter('image_refresh', $imageobj);
                     }
                 } else {
                     $sql = 'DELETE FROM ' . prefix('images') . ' WHERE `id`="' . $image['id'] . '";';
                     $result = query($sql);
                     $sql = 'DELETE FROM ' . prefix('comments') . ' WHERE `type` IN (' . zp_image_types('"') . ') AND `ownerid` ="' . $image['id'] . '";';
                     $result = query($sql);
                 }
                 if (++$c >= RECORD_LIMIT) {
                     return $image['id'];
                     // avoide excessive processing
                 }
             }
             db_free_result($images);
         }
         // cleanup the tables
         $resource = db_show('tables');
         if ($resource) {
             while ($row = db_fetch_assoc($resource)) {
                 $tbl = array_shift($row);
                 query('OPTIMIZE TABLE `' . $tbl . '`');
             }
             db_free_result($resource);
         }
     }
     return false;
 }
switch ($subtab) {
    case 'groups':
        $adminlist = $adminordered;
        $users = array();
        $groups = array();
        foreach ($adminlist as $user) {
            if ($user['valid']) {
                $users[] = $user['user'];
            } else {
                $groups[] = $user;
            }
        }
        $gallery = new Gallery();
        $albumlist = array();
        foreach ($gallery->getAlbums() as $folder) {
            if (hasDynamicAlbumSuffix($folder)) {
                $name = substr($folder, 0, -4);
                // Strip the .'.alb' suffix
            } else {
                $name = $folder;
            }
            $albumlist[$name] = $folder;
        }
        ?>
						<p>
							<?php 
        echo gettext("Set group rights and select one or more albums for the users in the group to manage. Users with <em>User admin</em> or <em>Manage all albums</em> rights can manage all albums. All others may manage only those that are selected.");
        ?>
						</p>
						<form action="?action=savegroups&amp;tab=groups" method="post" autocomplete="off" onsubmit="return checkSubmit()" >
							<?php 
/**
 * rewrite_get_album_image - Fix special characters in the album and image names if mod_rewrite is on:
 * This is redundant and hacky; we need to either make the rewriting completely internal,
 * or fix the bugs in mod_rewrite. The former is probably a good idea.
 *
 *  Old explanation:
 *    rewrite_get_album_image() parses the album and image from the requested URL
 *    if mod_rewrite is on, and replaces the query variables with corrected ones.
 *    This is because of bugs in mod_rewrite that disallow certain characters.
 *
 * @param string $albumvar "$_GET" parameter for the album
 * @param string $imagevar "$_GET" parameter for the image
 */
function rewrite_get_album_image($albumvar, $imagevar)
{
    //	initialize these. If not mod_rewrite, then they are fine. If so, they may be overwritten
    $ralbum = isset($_GET[$albumvar]) ? sanitize_path($_GET[$albumvar]) : null;
    $rimage = isset($_GET[$imagevar]) ? sanitize_path($_GET[$imagevar]) : null;
    if (MOD_REWRITE) {
        $uri = urldecode(sanitize($_SERVER['REQUEST_URI'], 0));
        $path = substr($uri, strlen(WEBPATH) + 1);
        $scripturi = sanitize($_SERVER['PHP_SELF'], 0);
        $script = substr($scripturi, strpos($scripturi, WEBPATH . '/') + strlen(WEBPATH) + 1);
        // Only extract the path when the request doesn't include the running php file (query request).
        if (strlen($path) > 0 && strpos($uri, $script) === false && isset($_GET[$albumvar])) {
            // remove query string if present
            $qspos = strpos($path, '?');
            if ($qspos !== false) {
                $path = substr($path, 0, $qspos);
            }
            // Strip off the image suffix (could interfere with the rest, needs to go anyway).
            $im_suffix = getOption('mod_rewrite_image_suffix');
            $suf_len = strlen($im_suffix);
            if ($suf_len > 0 && substr($path, -$suf_len) == $im_suffix) {
                $path = substr($path, 0, -$suf_len);
            } else {
                $im_suffix = false;
            }
            //	remove trailing slash
            if (substr($path, -1, 1) == '/') {
                $path = substr($path, 0, -1);
            }
            $ralbum = $path;
            //strip off things discarded by the rewrite rules
            $pagepos = strpos($path, '/page/');
            $slashpos = strrpos($path, '/');
            $imagepos = strpos($path, '/image/');
            $albumpos = strpos($path, '/album/');
            if ($imagepos !== false) {
                $ralbum = substr($path, 0, $imagepos);
                $rimage = substr($path, $slashpos + 1);
            } else {
                if ($albumpos !== false) {
                    $ralbum = substr($path, 0, $albumpos);
                    $rimage = substr($path, $slashpos + 1);
                } else {
                    if ($pagepos !== false) {
                        $ralbum = substr($path, 0, $pagepos);
                        $rimage = null;
                    } else {
                        if ($slashpos !== false) {
                            $ralbum = substr($path, 0, $slashpos);
                            $rimage = substr($path, $slashpos + 1);
                            //	check if it might be an album, not an album/image form
                            if (!$im_suffix && (hasDynamicAlbumSuffix($rimage) || is_dir(ALBUM_FOLDER_SERVERPATH . internalToFilesystem($ralbum . '/' . $rimage)))) {
                                $ralbum = $ralbum . '/' . $rimage;
                                $rimage = null;
                            }
                        } else {
                            $ralbum = $path;
                            $rimage = null;
                        }
                    }
                }
            }
            if (empty($ralbum)) {
                if (isset($_GET[$albumvar])) {
                    unset($_GET[$albumvar]);
                }
            } else {
                $_GET[$albumvar] = $ralbum;
            }
            if (empty($rimage)) {
                if (isset($_GET[$imagevar])) {
                    unset($_GET[$imagevar]);
                }
            } else {
                $_GET[$imagevar] = $rimage;
            }
            return array($ralbum, $rimage);
        }
    }
    return array($ralbum, $rimage);
}
function processManagedObjects($i, &$rights)
{
    $objects = array();
    $albums = array();
    $pages = array();
    $news = array();
    $l_a = strlen($prefix_a = 'managed_albums_list_' . $i . '_');
    $l_p = strlen($prefix_p = 'managed_pages_list_' . $i . '_');
    $l_n = strlen($prefix_n = 'managed_news_list_' . $i . '_');
    foreach ($_POST as $key => $value) {
        $key = postIndexDecode($key);
        if (substr($key, 0, $l_a) == $prefix_a) {
            $key = substr($key, $l_a);
            if (strpos($key, '_default')) {
                $key = substr($key, 0, -8);
                if (isset($albums[$key])) {
                    // album still part of the list
                    $albums[$key]['edit'] = sanitize_numeric($value);
                }
            } else {
                if (strpos($key, '_view')) {
                    $key = substr($key, 0, -5);
                    if (isset($albums[$key])) {
                        // album still part of the list
                        $albums[$key]['edit'] = $albums[$key]['edit'] | MANAGED_OBJECT_RIGHTS_VIEW_IMAGE;
                    }
                } else {
                    if (strpos($key, '_edit')) {
                        $key = substr($key, 0, -5);
                        if (isset($albums[$key])) {
                            // album still part of the list
                            $albums[$key]['edit'] = $albums[$key]['edit'] | MANAGED_OBJECT_RIGHTS_EDIT;
                        }
                    } else {
                        if (strpos($key, '_upload')) {
                            $key = substr($key, 0, -7);
                            if (isset($albums[$key])) {
                                // album still part of the list
                                $albums[$key]['edit'] = $albums[$key]['edit'] | MANAGED_OBJECT_RIGHTS_UPLOAD;
                            }
                        } else {
                            if ($value) {
                                if (hasDynamicAlbumSuffix($key)) {
                                    $name = substr($key, 0, -4);
                                    // Strip the .'.alb' suffix
                                } else {
                                    $name = $key;
                                }
                                $albums[$key] = array('data' => $key, 'name' => $name, 'type' => 'album');
                            }
                        }
                    }
                }
            }
        }
        if (substr($key, 0, $l_p) == $prefix_p) {
            if ($value) {
                $pages[] = array('data' => substr($key, $l_p), 'type' => 'pages');
            }
        }
        if (substr($key, 0, $l_n) == $prefix_n) {
            if ($value) {
                $news[] = array('data' => substr($key, $l_n), 'type' => 'news');
            }
        }
    }
    foreach ($albums as $key => $analbum) {
        unset($albums[$key]);
        $albums[] = $analbum;
    }
    if (empty($albums)) {
        if (!($rights & MANAGE_ALL_ALBUM_RIGHTS)) {
            $rights = $rights & ~ALBUM_RIGHTS;
        }
    } else {
        $rights = $rights | ALBUM_RIGHTS;
        if ($rights & (MANAGE_ALL_ALBUM_RIGHTS | ADMIN_RIGHTS)) {
            $albums = array();
        }
    }
    if (empty($pages)) {
        if (!($rights & MANAGE_ALL_PAGES_RIGHTS)) {
            $rights = $rights & ~ZENPAGE_PAGES_RIGHTS;
        }
    } else {
        $rights = $rights | ZENPAGE_PAGES_RIGHTS;
        if ($rights & (MANAGE_ALL_PAGES_RIGHTS | ADMIN_RIGHTS)) {
            $pages = array();
        }
    }
    if (empty($news)) {
        if (!($rights & MANAGE_ALL_NEWS_RIGHTS)) {
            $rights = $rights & ~ZENPAGE_NEWS_RIGHTS;
        }
    } else {
        $rights = $rights | ZENPAGE_NEWS_RIGHTS;
        if ($rights & (MANAGE_ALL_NEWS_RIGHTS | ADMIN_RIGHTS)) {
            $news = array();
        }
    }
    $objects = array_merge($albums, $pages, $news);
    return $objects;
}
 /** For every album in the gallery, look for its file. Delete from the database
  * if the file does not exist. Do the same for images. Clean up comments that have
  * been left orphaned.
  *
  * Returns true if the operation was interrupted because it was taking too long
  *
  * @param bool $cascade garbage collect every image and album in the gallery.
  * @param bool $complete garbage collect every image and album in the *database* - completely cleans the database.
  * @param  int $restart Image ID to restart scan from
  * @return bool
  */
 function garbageCollect($cascade = true, $complete = false, $restart = '')
 {
     if (empty($restart)) {
         setOption('last_garbage_collect', time());
         /* clean the comments table */
         $this->commentClean('images');
         $this->commentClean('albums');
         $this->commentClean('news');
         $this->commentClean('pages');
         // clean up obj_to_tag
         $dead = array();
         $result = query_full_array("SELECT * FROM " . prefix('obj_to_tag'));
         if (is_array($result)) {
             foreach ($result as $row) {
                 $dbtag = query_single_row("SELECT * FROM " . prefix('tags') . " WHERE `id`='" . $row['tagid'] . "'");
                 if (!$dbtag) {
                     $dead['id'] = $row['id'];
                 }
                 switch ($row['type']) {
                     case 'album':
                         $tbl = 'albums';
                         break;
                     default:
                         $tbl = $row['type'];
                         break;
                 }
                 $dbtag = query_single_row("SELECT * FROM " . prefix($tbl) . " WHERE `id`='" . $row['objectid'] . "'");
                 if (!$dbtag) {
                     $dead['id'] = $row['id'];
                 }
             }
         }
         if (!empty($dead)) {
             query('DELETE FROM ' . prefix('obj_to_tag') . ' WHERE `id`=' . implode(' OR `id`=', $dead));
         }
         // clean up admin_to_object
         $dead = array();
         $result = query_full_array("SELECT * FROM " . prefix('admin_to_object'));
         if (is_array($result)) {
             foreach ($result as $row) {
                 $dbtag = query_single_row("SELECT * FROM " . prefix('administrators') . " WHERE `id`='" . $row['adminid'] . "'");
                 if (!$dbtag) {
                     $dead['id'] = $row['id'];
                 }
                 switch ($row['type']) {
                     case 'album':
                         $tbl = 'albums';
                         break;
                     default:
                         $tbl = $row['type'];
                         break;
                 }
                 $dbtag = query_single_row("SELECT * FROM " . prefix($tbl) . " WHERE `id`='" . $row['objectid'] . "'");
                 if (!$dbtag) {
                     $dead['id'] = $row['id'];
                 }
             }
         }
         if (!empty($dead)) {
             query('DELETE FROM ' . prefix('admin_to_object') . ' WHERE `id`=' . implode(' OR `id`=', $dead));
         }
         // clean up news2cat
         $dead = array();
         $result = query_full_array("SELECT * FROM " . prefix('news2cat'));
         if (is_array($result)) {
             foreach ($result as $row) {
                 $dbtag = query_single_row("SELECT * FROM " . prefix('news') . " WHERE `id`='" . $row['news_id'] . "'");
                 if (!$dbtag) {
                     $dead['id'] = $row['id'];
                 }
                 $dbtag = query_single_row("SELECT * FROM " . prefix('news_categories') . " WHERE `id`='" . $row['cat_id'] . "'");
                 if (!$dbtag) {
                     $dead['id'] = $row['id'];
                 }
             }
         }
         if (!empty($dead)) {
             query('DELETE FROM ' . prefix('news2cat') . ' WHERE `id`=' . implode(' OR `id`=', $dead));
         }
         // Check for the existence of top-level albums (subalbums handled recursively).
         $sql = "SELECT * FROM " . prefix('albums');
         $result = query($sql);
         $dead = array();
         $live = array('');
         // purge the root album if it exists
         $deadalbumthemes = array();
         // Load the albums from disk
         while ($row = db_fetch_assoc($result)) {
             $valid = file_exists($albumpath = ALBUM_FOLDER_SERVERPATH . internalToFilesystem($row['folder'])) && (hasDynamicAlbumSuffix($albumpath) || is_dir($albumpath) && strpos($albumpath, '/./') === false && strpos($albumpath, '/../') === false);
             if (!$valid || in_array($row['folder'], $live)) {
                 $dead[] = $row['id'];
                 if ($row['album_theme'] !== '') {
                     // orphaned album theme options table
                     $deadalbumthemes[$row['id']] = $row['folder'];
                 }
             } else {
                 $live[] = $row['folder'];
             }
         }
         if (count($dead) > 0) {
             /* delete the dead albums from the DB */
             $first = array_pop($dead);
             $sql1 = "DELETE FROM " . prefix('albums') . " WHERE `id`='{$first}'";
             $sql2 = "DELETE FROM " . prefix('images') . " WHERE `albumid`='{$first}'";
             $sql3 = "DELETE FROM " . prefix('comments') . " WHERE `type`='albums' AND `ownerid`='{$first}'";
             $sql4 = "DELETE FROM " . prefix('obj_to_tag') . " WHERE `type`='albums' AND `objectid`='{$first}'";
             foreach ($dead as $albumid) {
                 $sql1 .= " OR `id` = '{$albumid}'";
                 $sql2 .= " OR `albumid` = '{$albumid}'";
                 $sql3 .= " OR `ownerid` = '{$albumid}'";
                 $sql4 .= " OR `objectid` = '{$albumid}'";
             }
             $n = query($sql1);
             if (!$complete && $n && $cascade) {
                 query($sql2);
                 query($sql3);
                 query($sql4);
             }
         }
         if (count($deadalbumthemes) > 0) {
             // delete the album theme options tables for dead albums
             foreach ($deadalbumthemes as $id => $deadtable) {
                 $sql = 'DELETE FROM ' . prefix('options') . ' WHERE `ownerid`=' . $id;
                 query($sql, false);
             }
         }
     }
     if ($complete) {
         if (empty($restart)) {
             /* refresh 'metadata' albums */
             $albumids = query_full_array("SELECT `id`, `mtime`, `folder`, `dynamic` FROM " . prefix('albums'));
             foreach ($albumids as $analbum) {
                 if (($mtime = filemtime(ALBUM_FOLDER_SERVERPATH . internalToFilesystem($analbum['folder']))) > $analbum['mtime']) {
                     // refresh
                     $album = new Album($this, $analbum['folder']);
                     $album->set('mtime', $mtime);
                     if ($album->isDynamic()) {
                         $data = file_get_contents($album->localpath);
                         while (!empty($data)) {
                             $data1 = trim(substr($data, 0, $i = strpos($data, "\n")));
                             if ($i === false) {
                                 $data1 = $data;
                                 $data = '';
                             } else {
                                 $data = substr($data, $i + 1);
                             }
                             if (strpos($data1, 'WORDS=') !== false) {
                                 $words = "words=" . urlencode(substr($data1, 6));
                             }
                             if (strpos($data1, 'THUMB=') !== false) {
                                 $thumb = trim(substr($data1, 6));
                             }
                             if (strpos($data1, 'FIELDS=') !== false) {
                                 $fields = "&searchfields=" . trim(substr($data1, 7));
                             }
                         }
                         if (!empty($words)) {
                             if (empty($fields)) {
                                 $fields = '&searchfields=tags';
                             }
                         }
                         $album->set('search_params', $words . $fields);
                         $album->set('thumb', $thumb);
                     }
                     $album->save();
                     zp_apply_filter('album_refresh', $album);
                 }
             }
             /* Delete all image entries that don't belong to an album at all. */
             $albumids = query_full_array("SELECT `id` FROM " . prefix('albums'));
             /* all the album IDs */
             $idsofalbums = array();
             foreach ($albumids as $row) {
                 $idsofalbums[] = $row['id'];
             }
             $imageAlbums = query_full_array("SELECT DISTINCT `albumid` FROM " . prefix('images'));
             /* albumids of all the images */
             $albumidsofimages = array();
             foreach ($imageAlbums as $row) {
                 $albumidsofimages[] = $row['albumid'];
             }
             $orphans = array_diff($albumidsofimages, $idsofalbums);
             /* albumids of images with no album */
             if (count($orphans) > 0) {
                 /* delete dead images from the DB */
                 $firstrow = array_pop($orphans);
                 $sql = "DELETE FROM " . prefix('images') . " WHERE `albumid`='" . $firstrow . "'";
                 foreach ($orphans as $id) {
                     $sql .= " OR `albumid`='" . $id . "'";
                 }
                 query($sql);
                 // Then go into existing albums recursively to clean them... very invasive.
                 foreach ($this->getAlbums(0) as $folder) {
                     $album = new Album($this, $folder);
                     if (!$album->isDynamic()) {
                         if (is_null($album->getDateTime())) {
                             // see if we can get one from an image
                             $images = $album->getImages(0, 0, 'date', 'DESC');
                             if (count($images) > 0) {
                                 $image = newImage($album, array_shift($images));
                                 $album->setDateTime($image->getDateTime());
                             }
                         }
                         $album->garbageCollect(true);
                         $album->preLoad();
                     }
                     $album->save();
                     zp_apply_filter('album_refresh', $album);
                 }
             }
         }
         /* Look for image records where the file no longer exists. While at it, check for images with IPTC data to update the DB */
         $start = array_sum(explode(" ", microtime()));
         // protect against too much processing.
         if (!empty($restart)) {
             $restartwhere = ' WHERE `id`>' . $restart . ' AND `mtime`=0';
         } else {
             $restartwhere = ' WHERE `mtime`=0';
         }
         define('RECORD_LIMIT', 5);
         $sql = 'SELECT * FROM ' . prefix('images') . $restartwhere . ' ORDER BY `id` LIMIT ' . (RECORD_LIMIT + 2);
         $images = query_full_array($sql);
         if (count($images) > 0) {
             $c = 0;
             foreach ($images as $image) {
                 $sql = 'SELECT `folder` FROM ' . prefix('albums') . ' WHERE `id`="' . $image['albumid'] . '";';
                 $row = query_single_row($sql);
                 $imageName = internalToFilesystem(ALBUM_FOLDER_SERVERPATH . $row['folder'] . '/' . $image['filename']);
                 if (file_exists($imageName)) {
                     $mtime = filemtime($imageName);
                     if ($image['mtime'] != $mtime) {
                         // file has changed since we last saw it
                         $imageobj = newImage(new Album($this, $row['folder']), $image['filename']);
                         $imageobj->set('mtime', $mtime);
                         $imageobj->updateMetaData();
                         // prime the EXIF/IPTC fields
                         $imageobj->updateDimensions();
                         // update the width/height & account for rotation
                         $imageobj->save();
                         zp_apply_filter('image_refresh', $imageobj);
                     }
                 } else {
                     $sql = 'DELETE FROM ' . prefix('images') . ' WHERE `id`="' . $image['id'] . '";';
                     $result = query($sql);
                     $sql = 'DELETE FROM ' . prefix('comments') . ' WHERE `type` IN (' . zp_image_types('"') . ') AND `ownerid` ="' . $image['id'] . '";';
                     $result = query($sql);
                 }
                 if (++$c >= RECORD_LIMIT) {
                     return $image['id'];
                     // avoide excessive processing
                 }
             }
         }
     }
     return false;
 }