/**
 * Gets news articles and images of a gallery to show them together on the news section
 *
 * NOTE: This function does not exclude articles that are password protected via a category
 *
 * @param int $articles_per_page The number of articles to get
 * @param string $mode 	"latestimages-thumbnail"
 *											"latestimages-thumbnail-customcrop"
 *											"latestimages-sizedimage"
 *											"latestalbums-thumbnail"
 *		 									"latestalbums-thumbnail-customcrop"
 *		 									"latestalbums-sizedimage"
 *		 									"latestimagesbyalbum-thumbnail"
 *		 									"latestimagesbyalbum-thumbnail-customcrop"
 *		 									"latestimagesbyalbum-sizedimage"
 *		 									"latestupdatedalbums-thumbnail" (for RSS and getLatestNews() used only)
 *		 									"latestupdatedalbums-thumbnail-customcrop" (for RSS and getLatestNews() used only)
 *		 									"latestupdatedalbums-sizedimage" (for RSS and getLatestNews() used only)
 *	NOTE: The "latestupdatedalbums" variants do NOT support pagination as required on the news loop!
 *
 * @param string $published "published" for published articles,
 * 													"unpublished" for un-published articles,
 * 													"all" for all articles
 * @param string $sortorder 	id, date or mtime, only for latestimages-... modes
 * @param bool $sticky set to true to place "sticky" articles at the front of the list.
 * @return array
 */
function getCombiNews($articles_per_page = '', $mode = '', $published = NULL, $sortorder = '', $sticky = true)
{
    deprecated_function_notify(gettext('Use the Zenpage class method instead.'));
    global $_zp_gallery, $_zp_flash_player;
    processExpired('news');
    if (is_null($published)) {
        if (zp_loggedin(ZENPAGE_NEWS_RIGHTS)) {
            $published = "all";
        } else {
            $published = "published";
        }
    }
    if (empty($mode)) {
        $mode = getOption("zenpage_combinews_mode");
    }
    if ($published == "published") {
        $show = " WHERE `show` = 1 AND date <= '" . date('Y-m-d H:i:s') . "'";
        $imagesshow = " AND images.show = 1 ";
    } else {
        $show = "";
        $imagesshow = "";
    }
    $passwordcheck = "";
    if (zp_loggedin(ZENPAGE_NEWS_RIGHTS)) {
        $albumWhere = "";
        $passwordcheck = "";
    } else {
        $albumscheck = query_full_array("SELECT * FROM " . prefix('albums') . " ORDER BY title");
        foreach ($albumscheck as $albumcheck) {
            if (!checkAlbumPassword($albumcheck['folder'])) {
                $albumpasswordcheck = " AND albums.id != " . $albumcheck['id'];
                $passwordcheck = $passwordcheck . $albumpasswordcheck;
            }
        }
        $albumWhere = "AND albums.show=1" . $passwordcheck;
    }
    $limit = getLimitAndOffset($articles_per_page);
    if (empty($sortorder)) {
        $combinews_sortorder = getOption("zenpage_combinews_sortorder");
    } else {
        $combinews_sortorder = $sortorder;
    }
    $stickyorder = '';
    if ($sticky) {
        $stickyorder = 'sticky DESC,';
    }
    $type3 = query("SET @type3:='0'");
    switch ($mode) {
        case "latestimages-thumbnail":
        case "latestimages-thumbnail-customcrop":
        case "latestimages-sizedimage":
            $sortorder = "images." . $combinews_sortorder;
            $type1 = query("SET @type1:='news'");
            $type2 = query("SET @type2:='images'");
            switch ($combinews_sortorder) {
                case 'id':
                case 'date':
                    $imagequery = "(SELECT albums.folder, images.filename, images.date, @type2, @type3 as sticky FROM " . prefix('images') . " AS images, " . prefix('albums') . " AS albums\n\t\t\t\t\t\t\tWHERE albums.id = images.albumid " . $imagesshow . $albumWhere . ")";
                    break;
                case 'mtime':
                    $imagequery = "(SELECT albums.folder, images.filename, FROM_UNIXTIME(images.mtime), @type2, @type3 as sticky FROM " . prefix('images') . " AS images, " . prefix('albums') . " AS albums\n\t\t\t\t\t\t\tWHERE albums.id = images.albumid " . $imagesshow . $albumWhere . ")";
                    break;
            }
            $result = query_full_array("(SELECT title as albumname, titlelink, date, @type1 as type, sticky FROM " . prefix('news') . " " . $show . ")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUNION\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" . $imagequery . "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tORDER BY {$stickyorder} date DESC {$limit}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t");
            break;
        case "latestalbums-thumbnail":
        case "latestalbums-thumbnail-customcrop":
        case "latestalbums-sizedimage":
            $sortorder = $combinews_sortorder;
            $type1 = query("SET @type1:='news'");
            $type2 = query("SET @type2:='albums'");
            switch ($combinews_sortorder) {
                case 'id':
                case 'date':
                    $albumquery = "(SELECT albums.folder, albums.title, albums.date, @type2, @type3 as sticky FROM " . prefix('albums') . " AS albums\n\t\t\t\t\t\t\t" . $show . $albumWhere . ")";
                    break;
                case 'mtime':
                    $albumquery = "(SELECT albums.folder, albums.title, FROM_UNIXTIME(albums.mtime), @type2, @type3 as sticky FROM " . prefix('albums') . " AS albums\n\t\t\t\t\t\t\t" . $show . $albumWhere . ")";
                    break;
            }
            $result = query_full_array("(SELECT title as albumname, titlelink, date, @type1 as type, sticky FROM " . prefix('news') . " " . $show . ")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUNION\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" . $albumquery . "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tORDER BY {$stickyorder} date DESC {$limit}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t");
            break;
        case "latestimagesbyalbum-thumbnail":
        case "latestimagesbyalbum-thumbnail-customcrop":
        case "latestimagesbyalbum-sizedimage":
            $type1 = query("SET @type1:='news'");
            $type2 = query("SET @type2:='albums'");
            if (empty($combinews_sortorder) || $combinews_sortorder != "date" || $combinews_sortorder != "mtime") {
                $combinews_sortorder = "date";
            }
            $combinews_sortorder = "date";
            $sortorder = "images." . $combinews_sortorder;
            switch ($combinews_sortorder) {
                case "date":
                    $imagequery = "(SELECT DISTINCT DATE_FORMAT(" . $sortorder . ",'%Y-%m-%d'), albums.folder, DATE_FORMAT(images.`date`,'%Y-%m-%d'), @type2 FROM " . prefix('images') . " AS images, " . prefix('albums') . " AS albums\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE albums.id = images.albumid " . $imagesshow . $albumWhere . ")";
                    break;
                case "mtime":
                    $imagequery = "(SELECT DISTINCT FROM_UNIXTIME(" . $sortorder . ",'%Y-%m-%d'), albums.folder, DATE_FORMAT(images.`mtime`,'%Y-%m-%d'), @type2 FROM " . prefix('images') . " AS images, " . prefix('albums') . " AS albums\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE albums.id = images.albumid " . $imagesshow . $albumWhere . ")";
                    break;
            }
            $result = query_full_array("(SELECT title as albumname, titlelink, date, @type1 as type FROM " . prefix('news') . " " . $show . ")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUNION\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" . $imagequery . "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tORDER By date DESC {$limit}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t");
            //echo "<pre>"; print_r($result); echo "</pre>";
            //$result = "";
            break;
        case "latestupdatedalbums-thumbnail":
        case "latestupdatedalbums-thumbnail-customcrop":
        case "latestupdatedalbums-sizedimage":
            $latest = getNewsArticles($articles_per_page, '', NULL, true);
            $counter = '';
            foreach ($latest as $news) {
                $article = new ZenpageNews($news['titlelink']);
                if ($article->checkAccess($hint, $show)) {
                    $counter++;
                    $latestnews[$counter] = array("albumname" => $article->getTitle(), "titlelink" => $article->getTitlelink(), "date" => $article->getDateTime(), "type" => "news");
                }
            }
            $albums = getAlbumStatistic($articles_per_page, "latestupdated");
            $latestalbums = array();
            $counter = "";
            foreach ($albums as $album) {
                $counter++;
                $tempalbum = new Album($_zp_gallery, $album['folder']);
                $tempalbumthumb = $tempalbum->getAlbumThumbImage();
                $timestamp = $tempalbum->get('mtime');
                if ($timestamp == 0) {
                    $albumdate = $tempalbum->getDateTime();
                } else {
                    $albumdate = strftime('%Y-%m-%d %H:%M:%S', $timestamp);
                }
                $latestalbums[$counter] = array("albumname" => $tempalbum->getFolder(), "titlelink" => $tempalbum->getTitle(), "date" => $albumdate, "type" => 'albums');
            }
            //$latestalbums = array_merge($latestalbums, $item);
            $latest = array_merge($latestnews, $latestalbums);
            $result = sortMultiArray($latest, "date", true);
            if (count($result) > $articles_per_page) {
                $result = array_slice($result, 0, 10);
            }
            break;
    }
    //$result = "";
    return $result;
}
    printTabs('edit');
    ?>


<div id="content">

<h1>Sort Album: <?php 
    echo $album->getTitle();
    ?>
</h1>
<p><?php 
    printAlbumEditLinks('', "&laquo; " . gettext("back to the album list"), gettext("Back to the list of albums"));
    ?>
 
| <?php 
    printAlbumEditLinks("&album=" . urlencode($album->getFolder()), gettext("edit album"), gettext("Edit Album"));
    ?>
 
| <?php 
    printViewLink($album, gettext("view album"), gettext("View Album"));
    ?>
</p>
	<?php 
    if (isset($_GET['saved'])) {
        echo '<div class="messagebox" id="fade-message">';
        echo "<h2>" . gettext("Image order saved");
        echo '</h2></div>';
    }
    ?>

<div class="box" style="padding: 15px;">
/**
 * Returns  a randomly selected image from the album or its subalbums. (May be NULL if none exists)
 *
 * @param mixed $rootAlbum optional album object/folder from which to get the image.
 * @param bool $daily set to true to change picture only once a day.
 * @param bool $showunpublished set true to consider all images
 *
 * @return object
 */
function getRandomImagesAlbum($rootAlbum = NULL, $daily = false, $showunpublished = false)
{
    global $_zp_current_album, $_zp_gallery, $_zp_current_search;
    if (empty($rootAlbum)) {
        $album = $_zp_current_album;
    } else {
        if (is_object($rootAlbum)) {
            $album = $rootAlbum;
        } else {
            $album = new Album($_zp_gallery, $rootAlbum);
        }
    }
    if ($daily && ($potd = getOption('picture_of_the_day:' . $album->name))) {
        $potd = unserialize($potd);
        if (date('Y-m-d', $potd['day']) == date('Y-m-d')) {
            $rndalbum = new Album($_zp_gallery, $potd['folder']);
            $image = newImage($rndalbum, $potd['filename']);
            if ($image->exists) {
                return $image;
            }
        }
    }
    $image = NULL;
    if ($album->isDynamic()) {
        $images = $album->getImages(0);
        shuffle($images);
        while (count($images) > 0) {
            $result = array_pop($images);
            if (is_valid_image($result['filename'])) {
                $image = newImage(new Album(new Gallery(), $result['folder']), $result['filename']);
            }
        }
    } else {
        $albumfolder = $album->getFolder();
        if ($album->isMyItem(LIST_RIGHTS) || $showunpublished) {
            $imageWhere = '';
            $albumNotWhere = '';
            $albumInWhere = '';
        } else {
            $imageWhere = " AND " . prefix('images') . ".show=1";
            $albumNotWhere = getProtectedAlbumsWhere();
            $albumInWhere = prefix('albums') . ".show=1";
        }
        $query = "SELECT id FROM " . prefix('albums') . " WHERE ";
        if ($albumInWhere) {
            $query .= $albumInWhere . ' AND ';
        }
        $query .= "folder LIKE " . db_quote($albumfolder . '%');
        $result = query_full_array($query);
        if (is_array($result) && count($result) > 0) {
            $albumInWhere = prefix('albums') . ".id in (";
            foreach ($result as $row) {
                $albumInWhere = $albumInWhere . $row['id'] . ", ";
            }
            $albumInWhere = ' AND ' . substr($albumInWhere, 0, -2) . ')';
            $c = 0;
            while (is_null($image) && $c < 10) {
                $result = query_single_row('SELECT COUNT(*) AS row_count ' . ' FROM ' . prefix('images') . ', ' . prefix('albums') . ' WHERE ' . prefix('albums') . '.folder!="" AND ' . prefix('images') . '.albumid = ' . prefix('albums') . '.id ' . $albumInWhere . $albumNotWhere . $imageWhere);
                $rand_row = rand(0, $result['row_count'] - 1);
                $result = query_single_row('SELECT ' . prefix('images') . '.filename, ' . prefix('albums') . '.folder ' . ' FROM ' . prefix('images') . ', ' . prefix('albums') . ' WHERE ' . prefix('images') . '.albumid = ' . prefix('albums') . '.id  ' . $albumInWhere . $albumNotWhere . $imageWhere . ' LIMIT ' . $rand_row . ', 1');
                $imageName = $result['filename'];
                if (is_valid_image($imageName)) {
                    $image = newImage(new Album(new Gallery(), $result['folder']), $imageName);
                }
                $c++;
            }
        }
    }
    if ($daily && is_object($image)) {
        $potd = array('day' => time(), 'folder' => $result['folder'], 'filename' => $result['filename']);
        setThemeOption('picture_of_the_day:' . $album->name, serialize($potd));
    }
    return $image;
}
function genAlbumUploadList(&$list, $curAlbum = NULL)
{
    $gallery = new Gallery();
    $albums = array();
    if (is_null($curAlbum)) {
        $albumsprime = $gallery->getAlbums(0);
        foreach ($albumsprime as $album) {
            // check for rights
            $albumobj = new Album($gallery, $album);
            if ($albumobj->isMyItem(UPLOAD_RIGHTS)) {
                $albums[] = $album;
            }
        }
    } else {
        $albums = $curAlbum->getAlbums(0);
    }
    if (is_array($albums)) {
        foreach ($albums as $folder) {
            $album = new Album($gallery, $folder);
            if (!$album->isDynamic()) {
                $list[$album->getFolder()] = $album->getTitle();
                genAlbumUploadList($list, $album);
                /* generate for subalbums */
            }
        }
    }
}
/**
 * Returns  a randomly selected image from the album or its subalbums. (May be NULL if none exists)
 *
 * @param string $rootAlbum optional album folder from which to get the image.
 *
 * @return object
 */
function getRandomImagesAlbum($rootAlbum = null)
{
    global $_zp_current_album, $_zp_gallery, $_zp_current_search;
    if (empty($rootAlbum)) {
        $album = $_zp_current_album;
    } else {
        $album = new Album($_zp_gallery, $rootAlbum);
    }
    if ($album->isDynamic()) {
        $search = $album->getSearchEngine();
        $images = $search->getImages(0);
        $image = NULL;
        shuffle($images);
        while (count($images) > 0) {
            $randomImage = array_pop($images);
            if (is_valid_image($randomImage['filename'])) {
                $image = newImage(new Album(new Gallery(), $randomImage['folder']), $randomImage['filename']);
                return $image;
            }
        }
    } else {
        if (zp_loggedin()) {
            $imageWhere = '';
            $albumNotWhere = '';
        } else {
            $imageWhere = " AND " . prefix('images') . ".show=1";
            $albumNotWhere = getProtectedAlbumsWhere();
        }
        $albumInWhere = '';
        $albumfolder = $album->getFolder();
        $query = "SELECT id FROM " . prefix('albums') . " WHERE " . prefix('albums') . ".show = 1 AND folder LIKE '" . mysql_real_escape_string($albumfolder) . "%'";
        $result = query_full_array($query);
        $albumInWhere = prefix('albums') . ".id in (";
        foreach ($result as $row) {
            $albumInWhere = $albumInWhere . $row['id'] . ", ";
        }
        $albumInWhere = ' AND ' . substr($albumInWhere, 0, -2) . ')';
        $c = 0;
        while ($c < 10) {
            $result = query_single_row('SELECT COUNT(*) AS row_count ' . ' FROM ' . prefix('images') . ', ' . prefix('albums') . ' WHERE ' . prefix('albums') . '.folder!="" AND ' . prefix('images') . '.albumid = ' . prefix('albums') . '.id ' . $albumInWhere . $albumNotWhere . $imageWhere);
            $rand_row = rand(1, $result['row_count']);
            $result = query_single_row('SELECT ' . prefix('images') . '.filename, ' . prefix('albums') . '.folder ' . ' FROM ' . prefix('images') . ', ' . prefix('albums') . ' WHERE ' . prefix('images') . '.albumid = ' . prefix('albums') . '.id  ' . $albumInWhere . $albumNotWhere . $imageWhere . ' LIMIT ' . $rand_row . ', 1');
            $imageName = $result['filename'];
            if (is_valid_image($imageName)) {
                $image = newImage(new Album(new Gallery(), $result['folder']), $imageName);
                return $image;
            }
            $c++;
        }
    }
    return null;
}