Exemplo n.º 1
0
function wppa_get_thumbphotoxy($id, $key, $force = false)
{
    $result = wppa_get_photo_item($id, $key);
    if ($result && !$force) {
        return $result;
        // Value found
    }
    if ($key == 'thumbx' || $key == 'thumby') {
        $file = wppa_get_thumb_path($id);
    } else {
        $file = wppa_get_photo_path($id);
    }
    if (wppa_get_ext($file) == 'xxx') {
        //		if ( $key == 'photox' || $key == 'photoy' ) {
        $file = wppa_fix_poster_ext($file, $id);
        //		}
    }
    if (!is_file($file) && !$force) {
        return '0';
        // File not found
    }
    if (is_file($file)) {
        $size = getimagesize($file);
    } else {
        $size = array('0', '0');
    }
    if (is_array($size)) {
        if ($key == 'thumbx' || $key == 'thumby') {
            wppa_update_photo(array('id' => $id, 'thumbx' => $size[0], 'thumby' => $size[1]));
        } else {
            wppa_update_photo(array('id' => $id, 'photox' => $size[0], 'photoy' => $size[1]));
        }
        wppa_cache_photo('invalidate', $id);
    }
    if ($key == 'thumbx' || $key == 'photox') {
        return $size[0];
    } else {
        return $size[1];
    }
}
Exemplo n.º 2
0
function wppa_add_metatags()
{
    global $wpdb;
    global $thumb;
    // Share info for sm that uses og
    $id = wppa_get_get('photo');
    if ($id) {
        $imgurl = wppa_get_photo_url($id);
        if (wppa_is_video($id)) {
            $imgurl = wppa_fix_poster_ext($imgurl, $id);
        }
    } else {
        $imgurl = '';
    }
    if ($id) {
        if (wppa_switch('wppa_og_tags_on')) {
            wppa_cache_thumb($id);
            if ($thumb) {
                $title = wppa_get_photo_name($id);
                $desc = wppa_get_og_desc($id);
                $url = (is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                $site = get_bloginfo('name');
                echo '
<!-- WPPA+ Share data -->
<meta property="og:site_name" content="' . esc_attr(sanitize_text_field($site)) . '" />
<meta property="og:type" content="article" />
<meta property="og:url" content="' . esc_url(sanitize_text_field($url)) . '" />
<meta property="og:title" content="' . esc_attr(sanitize_text_field($title)) . '" />
<meta property="og:image" content="' . esc_url(sanitize_text_field($imgurl)) . '" />
<meta property="og:description" content="' . esc_attr(sanitize_text_field($desc)) . '" />
<!-- WPPA+ End Share data -->
';
            }
        }
    }
    // To make sure we are on a page that contains at least %%wppa%% we check for Get var 'wppa-album'.
    // This also narrows the selection of featured photos to those that exist in the current album.
    $done = array();
    if (wppa_get_get('album')) {
        if (wppa_switch('wppa_meta_page')) {
            $album = wppa_get_get('album');
            $photos = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s AND `status` = 'featured'", $album), ARRAY_A);
            wppa_dbg_q('Q-meta1');
            wppa_cache_photo('add', $photos);
            if ($photos) {
                echo "\n<!-- WPPA+ BEGIN Featured photos on this page -->";
                foreach ($photos as $photo) {
                    $thumb = $photo;
                    // Set to global to reduce queries when getting the name
                    $id = $photo['id'];
                    $content = esc_attr(sanitize_text_field(wppa_get_keywords($id)));
                    if ($content && !in_array($content, $done)) {
                        echo '
<meta name="keywords" content="' . $content . '" >';
                        $done[] = $content;
                    }
                }
                echo "\n<!-- WPPA+ END Featured photos on this page -->\n";
            }
        }
    } elseif (wppa_switch('wppa_meta_all')) {
        $photos = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `status` = 'featured'", ARRAY_A);
        wppa_dbg_q('Q-meta2');
        wppa_cache_photo('add', $photos);
        if ($photos) {
            echo "\n<!-- WPPA+ BEGIN Featured photos on this site -->";
            foreach ($photos as $photo) {
                $thumb = $photo;
                // Set to global to reduce queries when getting the name
                $id = $photo['id'];
                $content = esc_attr(sanitize_text_field(wppa_get_keywords($id)));
                if ($content && !in_array($content, $done)) {
                    echo '
<meta name="keywords" content="' . $content . '" >';
                    $done[] = $content;
                }
            }
            echo "\n<!-- WPPA+ END Featured photos on this site -->\n";
        }
    }
    // Facebook Admin and App
    if ((wppa_switch('wppa_share_on') || wppa_switch('wppa_share_on_widget')) && (wppa_switch('wppa_facebook_comments') || wppa_switch('wppa_facebook_like') || wppa_switch('wppa_share_facebook'))) {
        echo "\n<!-- WPPA+ BEGIN Facebook meta tags -->";
        if (wppa_opt('wppa_facebook_admin_id')) {
            echo "\n\t<meta property=\"fb:admins\" content=\"" . wppa_opt('wppa_facebook_admin_id') . "\" />";
        }
        if (wppa_opt('wppa_facebook_app_id')) {
            echo "\n\t<meta property=\"fb:app_id\" content=\"" . wppa_opt('wppa_facebook_app_id') . "\" />";
        }
        if ($imgurl) {
            echo '
<link rel="image_src" href="' . esc_url($imgurl) . '" />';
        }
        echo '
<!-- WPPA+ END Facebook meta tags -->
';
    }
}
Exemplo n.º 3
0
function wppa_get_potd()
{
    global $wpdb;
    $image = '';
    switch (wppa_opt('widget_method')) {
        case '1':
            // Fixed photo
            $id = wppa_opt('widget_photo');
            if ($id != '') {
                $image = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s LIMIT 0,1", $id), ARRAY_A);
                wppa_dbg_q('Q-Potd');
                wppa_cache_photo('add', $image);
            }
            break;
        case '2':
            // Random
            $album = wppa_opt('widget_album');
            if ($album == 'topten') {
                $images = wppa_get_widgetphotos($album);
                if (count($images) > 1) {
                    // Select a random first from the current selection
                    $idx = rand(0, count($images) - 1);
                    $image = $images[$idx];
                }
            } elseif ($album != '') {
                $images = wppa_get_widgetphotos($album, "ORDER BY RAND() LIMIT 0,1");
                $image = $images[0];
            }
            break;
        case '3':
            // Last upload
            $album = wppa_opt('widget_album');
            if ($album == 'topten') {
                $images = wppa_get_widgetphotos($album);
                if ($images) {
                    // fid last uploaded image in the $images pool
                    $temp = 0;
                    foreach ($images as $img) {
                        if ($img['timestamp'] > $temp) {
                            $temp = $img['timestamp'];
                            $image = $img;
                        }
                    }
                }
            } elseif ($album != '') {
                $images = wppa_get_widgetphotos($album, "ORDER BY timestamp DESC LIMIT 0,1");
                $image = $images[0];
            }
            break;
        case '4':
            // Change every
            $album = wppa_opt('widget_album');
            if ($album != '') {
                $per = wppa_opt('widget_period');
                $photos = wppa_get_widgetphotos($album);
                if ($per == '0') {
                    if ($photos) {
                        $image = $photos[rand(0, count($photos) - 1)];
                    } else {
                        $image = '';
                    }
                } elseif ($per == 'day-of-week') {
                    $image = '';
                    if ($photos) {
                        $d = date_i18n("w");
                        $d -= get_option('wppa_potd_offset', '0');
                        while ($d < '1') {
                            $d += '7';
                        }
                        foreach ($photos as $img) {
                            if ($img['p_order'] == $d) {
                                $image = $img;
                            }
                        }
                    }
                } elseif ($per == 'day-of-month') {
                    $image = '';
                    if ($photos) {
                        $d = strval(intval(date_i18n("d")));
                        $d -= get_option('wppa_potd_offset', '0');
                        while ($d < '1') {
                            $d += '31';
                        }
                        foreach ($photos as $img) {
                            if ($img['p_order'] == $d) {
                                $image = $img;
                            }
                        }
                    }
                } elseif ($per == 'day-of-year') {
                    $image = '';
                    if ($photos) {
                        $d = strval(intval(date_i18n("z")));
                        $d -= get_option('wppa_potd_offset', '0');
                        while ($d < '0') {
                            $d += '366';
                        }
                        foreach ($photos as $img) {
                            if ($img['p_order'] == $d) {
                                $image = $img;
                            }
                        }
                    }
                } else {
                    $u = date_i18n("U");
                    // Seconds since 1-1-1970, local
                    $u /= 3600;
                    //  hours since
                    $u = floor($u);
                    $u /= $per;
                    $u = floor($u);
                    // Find the right photo out of the photos found by wppa_get_widgetphotos(),
                    // based on the Change every { any timeperiod } algorithm.
                    if ($photos) {
                        $p = count($photos);
                        $idn = fmod($u, $p);
                        // If from topten,...
                        if ($album == 'topten') {
                            // Do a re-read of the same to order by rand, reproduceable
                            // This can not be done by wppa_get_widgetphotos(),
                            // it does already ORDER BY for the top selection criterium.
                            // So we save the ids, and do a SELECT WHERE id IN ( array of found ids ) ORDER BY RAND( seed )
                            $ids = array();
                            foreach ($photos as $photo) {
                                $ids[] = $photo['id'];
                            }
                            $photos = $wpdb->get_results("SELECT `id`, `p_order` " . "FROM `" . WPPA_PHOTOS . "` " . "WHERE `id` IN (" . implode(',', $ids) . ") " . "ORDER BY RAND(" . $idn . ")", ARRAY_A);
                        } else {
                            $photos = wppa_get_widgetphotos($album, " ORDER BY RAND(" . $idn . ")");
                        }
                        // Image found
                        $image = $photos[$idn];
                    } else {
                        $image = '';
                    }
                }
            } else {
                $image = '';
            }
            break;
        default:
            $image = '';
    }
    if ($image) {
        $image = wppa_cache_photo($image['id']);
    }
    return $image;
}
function wppa_add_metatags()
{
    global $wpdb;
    // Share info for sm that uses og
    $id = wppa_get_get('photo');
    if (!wppa_photo_exists($id)) {
        $id = false;
    }
    if ($id) {
        // SM may not accept images from the cloud.
        wppa('for_sm', true);
        $imgurl = wppa_get_photo_url($id);
        wppa('for_sm', false);
        if (wppa_is_video($id)) {
            $imgurl = wppa_fix_poster_ext($imgurl, $id);
        }
    } else {
        $imgurl = '';
    }
    if ($id) {
        if (wppa_switch('og_tags_on')) {
            $thumb = wppa_cache_thumb($id);
            if ($thumb) {
                $title = wppa_get_photo_name($id);
                $desc = wppa_get_og_desc($id);
                $url = (is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                $site = get_bloginfo('name');
                $mime = wppa_get_mime_type($id);
                echo '
<!-- WPPA+ Og Share data -->
<meta property="og:site_name" content="' . esc_attr(sanitize_text_field($site)) . '" />
<meta property="og:type" content="article" />
<meta property="og:url" content="' . $url . '" />
<meta property="og:title" content="' . esc_attr(sanitize_text_field($title)) . '" />';
                if ($mime) {
                    echo '
<meta property="og:image" content="' . esc_url(sanitize_text_field($imgurl)) . '" />
<meta property="og:image:type" content="' . $mime . '" />
<meta property="og:image:width" content="' . wppa_get_photox($id) . '" />
<meta property="og:image:height" content="' . wppa_get_photoy($id) . '" />';
                }
                if ($desc) {
                    echo '
<meta property="og:description" content="' . esc_attr(sanitize_text_field($desc)) . '" />';
                }
                echo '
<!-- WPPA+ End Og Share data -->
';
            }
        }
        if (wppa_switch('share_twitter') && wppa_opt('twitter_account')) {
            $thumb = wppa_cache_thumb($id);
            // Twitter wants at least 280px in width, and at least 150px in height
            if ($thumb) {
                $x = wppa_get_photo_item($id, 'photox');
                $y = wppa_get_photo_item($id, 'photoy');
            }
            if ($thumb && $x >= 280 && $y >= 150) {
                $title = wppa_get_photo_name($id);
                $desc = wppa_get_og_desc($id);
                $url = (is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                $site = get_bloginfo('name');
                echo '
<!-- WPPA+ Twitter Share data -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="' . wppa_opt('twitter_account') . '">
<meta name="twitter:creator" content="' . wppa_opt('twitter_account') . '">
<meta name="twitter:title" content="' . esc_attr(sanitize_text_field($title)) . '">
<meta name="twitter:description" content="' . esc_attr(sanitize_text_field($desc)) . '">
<meta name="twitter:image" content="' . esc_url(sanitize_text_field($imgurl)) . '">
<!-- WPPA+ End Twitter Share data -->
';
            } elseif ($thumb && $x >= 120 && $y >= 120) {
                $title = wppa_get_photo_name($id);
                $desc = wppa_get_og_desc($id);
                $url = (is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                $site = get_bloginfo('name');
                echo '
<!-- WPPA+ Twitter Share data -->
<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="' . wppa_opt('twitter_account') . '">
<meta name="twitter:title" content="' . esc_attr(sanitize_text_field($title)) . '">
<meta name="twitter:description" content="' . esc_attr(sanitize_text_field($desc)) . '">
<meta name="twitter:image" content="' . esc_url(sanitize_text_field($imgurl)) . '">
<!-- WPPA+ End Twitter Share data -->
';
            }
        }
    }
    // To make sure we are on a page that contains at least [wppa] we check for Get var 'wppa-album'.
    // This also narrows the selection of featured photos to those that exist in the current album.
    $done = array();
    $album = '';
    if (isset($_REQUEST['album'])) {
        $album = $_REQUEST['album'];
    } elseif (isset($_REQUEST['wppa-album'])) {
        $album = $_REQUEST['wppa-album'];
    }
    $album = strip_tags($album);
    if (strlen($album == 12)) {
        $album = wppa_get_get('album');
    }
    if ($album) {
        if (wppa_switch('meta_page')) {
            $photos = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s AND `status` = 'featured'", $album), ARRAY_A);
            wppa_cache_photo('add', $photos);
            if ($photos) {
                echo "\n<!-- WPPA+ BEGIN Featured photos on this page -->";
                foreach ($photos as $photo) {
                    $id = $photo['id'];
                    $content = esc_attr(sanitize_text_field(wppa_get_keywords($id)));
                    if ($content && !in_array($content, $done)) {
                        echo '
<meta name="keywords" content="' . $content . '" >';
                        $done[] = $content;
                    }
                }
                echo "\n<!-- WPPA+ END Featured photos on this page -->\n";
            }
        }
    } elseif (wppa_switch('meta_all')) {
        $photos = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `status` = 'featured'", ARRAY_A);
        wppa_cache_photo('add', $photos);
        if ($photos) {
            echo "\n<!-- WPPA+ BEGIN Featured photos on this site -->";
            foreach ($photos as $photo) {
                $thumb = $photo;
                // Set to global to reduce queries when getting the name
                $id = $photo['id'];
                $content = esc_attr(sanitize_text_field(wppa_get_keywords($id)));
                if ($content && !in_array($content, $done)) {
                    echo '
<meta name="keywords" content="' . $content . '" >';
                    $done[] = $content;
                }
            }
            echo "\n<!-- WPPA+ END Featured photos on this site -->\n";
        }
    }
    // Facebook Admin and App
    if ((wppa_switch('share_on') || wppa_switch('share_on_widget')) && (wppa_switch('facebook_comments') || wppa_switch('facebook_like') || wppa_switch('share_facebook'))) {
        echo "\n<!-- WPPA+ BEGIN Facebook meta tags -->";
        if (wppa_opt('facebook_admin_id')) {
            echo "\n\t<meta property=\"fb:admins\" content=\"" . wppa_opt('facebook_admin_id') . "\" />";
        }
        if (wppa_opt('facebook_app_id')) {
            echo "\n\t<meta property=\"fb:app_id\" content=\"" . wppa_opt('facebook_app_id') . "\" />";
        }
        if ($imgurl) {
            echo '
<link rel="image_src" href="' . esc_url($imgurl) . '" />';
        }
        echo '
<!-- WPPA+ END Facebook meta tags -->
';
    }
}
Exemplo n.º 5
0
function wppa_rate_photo($id)
{
    global $wpdb;
    // Likes only?
    if (wppa_opt('rating_display_type') == 'likes') {
        // Get rating(like)count
        $count = $wpdb->get_var("SELECT COUNT(*) FROM `" . WPPA_RATING . "` WHERE `photo` = {$id}");
        // Update photo
        $wpdb->query("UPDATE `" . WPPA_PHOTOS . "` SET `rating_count` = '{$count}', `mean_rating` = '0' WHERE `id` = {$id}");
        // Invalidate cache
        wppa_cache_photo('invalidate', $id);
    } else {
        // Get all ratings for this photo
        $ratings = $wpdb->get_results($wpdb->prepare("SELECT `value` FROM `" . WPPA_RATING . "` WHERE `photo` = %s AND `status` = %s", $id, 'publish'), ARRAY_A);
        // Init
        $the_value = '0';
        $the_count = '0';
        // Compute mean value and count
        if ($ratings) {
            foreach ($ratings as $rating) {
                if ($rating['value'] == '-1') {
                    $the_value += wppa_opt('dislike_value');
                } else {
                    $the_value += $rating['value'];
                }
                $the_count++;
            }
        }
        if ($the_count) {
            $the_value /= $the_count;
        }
        if (wppa_opt('rating_max') == '1') {
            $the_value = '0';
        }
        if ($the_value == '10') {
            $the_value = '9.9999999';
        }
        // mean_rating is a text field. for sort order reasons we make 10 into 9.99999
        // Update photo
        $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `mean_rating` = %s, `rating_count` = %s WHERE `id` = {$id}", $the_value, $the_count));
        // Invalidate cache
        wppa_cache_photo('invalidate', $id);
        // Set status to a medaltype if appiliccable
        wppa_test_for_medal($id);
    }
}
function wppa_dbg_q($id)
{
    global $wppa;
    if (!$wppa['debug']) {
        return;
    }
    // Nothing to do here
    switch ($id) {
        case 'init':
            break;
        case 'print':
            if (!isset($wppa['queries'])) {
                return;
            }
            if (!is_array($wppa['queries'])) {
                return;
            }
            // Did nothing
            $qtot = 0;
            $gtot = 0;
            $keys = array_keys($wppa['queries']);
            sort($keys);
            $line = 'Cumulative query stats: Q=query, G=cache<br />';
            foreach ($keys as $k) {
                if (substr($k, 0, 1) == 'Q') {
                    $line .= $k . '=>' . $wppa['queries'][$k] . ', ';
                    $qtot += $wppa['queries'][$k];
                }
            }
            $line .= '<br />';
            foreach ($keys as $k) {
                if (substr($k, 0, 1) == 'G') {
                    $line .= $k . '=>' . $wppa['queries'][$k] . ', ';
                    $gtot += $wppa['queries'][$k];
                }
            }
            $line .= '<br />';
            $line .= sprintf('Total queries attempted: %d, Cash hits: %d, equals %4.2f%%, misses: %d.', $qtot + $gtot, $gtot, $gtot * 100 / ($qtot + $gtot), $qtot);
            $line .= ' 2nd level cache entries: albums: ' . wppa_cache_album('count') . ', photos: ' . wppa_cache_photo('count') . ' NQ=' . get_num_queries();
            wppa_dbg_msg($line);
            //			ob_start();
            //			print_r( $wppa['queries'] );
            //			wppa_dbg_msg( ob_get_clean() );
            break;
        default:
            if ($wppa['debug']) {
                if (!isset($wppa['queries'][$id])) {
                    $wppa['queries'][$id] = 1;
                } else {
                    $wppa['queries'][$id]++;
                }
            }
            break;
    }
}
function wppa_get_potd()
{
    global $wpdb;
    global $thumb;
    $image = '';
    switch (wppa_opt('wppa_widget_method')) {
        case '1':
            // Fixed photo
            $id = wppa_opt('wppa_widget_photo');
            if ($id != '') {
                $image = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s LIMIT 0,1", $id), ARRAY_A);
                wppa_dbg_q('Q-Potd');
                wppa_cache_photo('add', $image);
            }
            break;
        case '2':
            // Random
            $album = wppa_opt('wppa_widget_album');
            if ($album == 'topten') {
                $images = wppa_get_widgetphotos($album);
                if (count($images) > 1) {
                    // Select a random first from the current selection
                    $idx = rand(0, count($images) - 1);
                    $image = $images[$idx];
                }
            } elseif ($album != '') {
                $images = wppa_get_widgetphotos($album, "ORDER BY RAND() LIMIT 0,1");
                $image = $images[0];
            }
            break;
        case '3':
            // Last upload
            $album = wppa_opt('wppa_widget_album');
            if ($album == 'topten') {
                $images = wppa_get_widgetphotos($album);
                if ($images) {
                    // fid last uploaded image in the $images pool
                    $temp = 0;
                    foreach ($images as $img) {
                        if ($img['timestamp'] > $temp) {
                            $temp = $img['timestamp'];
                            $image = $img;
                        }
                    }
                }
            } elseif ($album != '') {
                $images = wppa_get_widgetphotos($album, "ORDER BY timestamp DESC LIMIT 0,1");
                $image = $images[0];
            }
            break;
        case '4':
            // Change every
            $album = wppa_opt('wppa_widget_album');
            if ($album != '') {
                $per = wppa_opt('wppa_widget_period');
                $photos = wppa_get_widgetphotos($album);
                if ($per == '0') {
                    if ($photos) {
                        $image = $photos[rand(0, count($photos) - 1)];
                    } else {
                        $image = '';
                    }
                } elseif ($per == 'day-of-week') {
                    $image = '';
                    if ($photos) {
                        $d = wppa_local_date('w');
                        if (!$d) {
                            $d = '7';
                        }
                        foreach ($photos as $img) {
                            if ($img['p_order'] == $d) {
                                $image = $img;
                            }
                        }
                    }
                } elseif ($per == 'day-of-month') {
                    $image = '';
                    if ($photos) {
                        $d = wppa_local_date('d');
                        if (substr($d, '0', '1') == '0') {
                            $d = substr($d, '1');
                        }
                        foreach ($photos as $img) {
                            if ($img['p_order'] == $d) {
                                $image = $img;
                            }
                        }
                    }
                } else {
                    $u = date("U");
                    // Seconds since 1-1-1970
                    $u /= 3600;
                    //  hours since
                    $u = floor($u);
                    $u /= $per;
                    $u = floor($u);
                    if ($photos) {
                        $p = count($photos);
                        $idn = fmod($u, $p);
                        $image = $photos[$idn];
                    } else {
                        $image = '';
                    }
                }
            } else {
                $image = '';
            }
            break;
        default:
            $image = '';
    }
    $thumb = $image;
    return $image;
}
function wppa_do_get_thumbs_query($query, $count_first = true)
{
    global $wpdb;
    // Anything to do here?
    if (!$query) {
        wppa('thumb_count', '0');
        wppa('any', false);
        wppa_dbg_msg('Empty query photos', 'red');
        return false;
    }
    // Init
    $time = -microtime(true);
    // Inverse requested?
    $invers = false;
    if (wppa('is_inverse')) {
        $invers = true;
    }
    // Do we need to get the count first to dicede if we get the full data and probably cache it ?
    if ($count_first || $invers) {
        // First get the count of the result
        $count = $wpdb->get_var(str_replace('SELECT *', 'SELECT COUNT(*)', $query));
        // If less than 2500, get them and cache them
        if ($count <= 2500 && !$invers) {
            $thumbs = $wpdb->get_results($query, ARRAY_A);
            $caching = true;
        } else {
            $query = str_replace('SELECT *', 'SELECT `id`', $query);
            $thumbs = $wpdb->get_results($query, ARRAY_A);
            $caching = false;
        }
    } else {
        $thumbs = $wpdb->get_results($query, ARRAY_A);
        $caching = true;
        $count = empty($thumbs) ? '0' : count($thumbs);
    }
    // Inverse selection requested?
    if ($invers) {
        $all = $wpdb->get_results("SELECT `id`, `album` FROM `" . WPPA_PHOTOS . "` " . wppa_get_photo_order('0'), ARRAY_A);
        if (is_array($thumbs)) {
            foreach (array_keys($thumbs) as $thumbs_key) {
                foreach (array_keys($all) as $all_key) {
                    if ($thumbs[$thumbs_key]['id'] == $all[$all_key]['id']) {
                        unset($all[$all_key]);
                    }
                }
            }
        }
        // Exclude separate albums?
        if (wppa_switch('excl_sep')) {
            foreach (array_keys($all) as $all_key) {
                if (wppa_is_separate($all[$all_key]['album'])) {
                    unset($all[$all_key]);
                }
            }
        }
        // Resequence for slideshow pagination
        $thumbs = array();
        if (!empty($all)) {
            foreach ($all as $item) {
                $thumbs[] = $item;
            }
        }
    }
    // Log query
    wppa_dbg_q('Q-TG');
    wppa_dbg_msg($query);
    wppa('thumb_count', $count);
    $time += microtime(true);
    wppa_dbg_msg('Get thumbs query took ' . $time . ' seconds. ' . 'Found: ' . $count . ' items. ' . 'Mem used=' . ceil(memory_get_peak_usage(true) / (1024 * 1024)) . ' Mb.');
    if ($caching) {
        wppa_cache_photo('add', $thumbs);
    }
    wppa('any', !empty($thumbs));
    return $thumbs;
}
function wppa_dbg_cachecounts($what)
{
    static $counters;
    // Init
    $indexes = array('albumhit', 'albummis', 'photohit', 'photomis');
    foreach ($indexes as $i) {
        if (!isset($counters[$i])) {
            $counters[$i] = 0;
        }
    }
    if (wppa('debug')) {
        switch ($what) {
            case 'albumhit':
            case 'albummis':
            case 'photohit':
            case 'photomis':
                $counters[$what]++;
                break;
            case 'print':
                if ($counters['albumhit'] + $counters['albummis'] && $counters['photohit'] + $counters['photomis']) {
                    wppa_dbg_msg('Cache usage: ' . 'Album hits: ' . $counters['albumhit'] . ', ' . 'Album misses: ' . $counters['albummis'] . ' = ' . sprintf('%6.2f', 100 * $counters['albummis'] / ($counters['albumhit'] + $counters['albummis'])) . '%; ' . 'Photo hits: ' . $counters['photohit'] . ', ' . 'Photo misses: ' . $counters['photomis'] . ' = ' . sprintf('%6.2f', 100 * $counters['photomis'] / ($counters['photohit'] + $counters['photomis'])) . '%; ');
                    wppa_dbg_msg('2nd level cache entries: ' . 'albums: ' . wppa_cache_album('count') . ', ' . 'photos: ' . wppa_cache_photo('count') . '. ' . 'NQ=' . get_num_queries());
                } else {
                    wppa_dbg_msg('Cache usage: ' . 'Album hits: ' . $counters['albumhit'] . ', ' . 'Album misses: ' . $counters['albummis'] . ', ' . 'Photo hits: ' . $counters['photohit'] . ', ' . 'Photo misses: ' . $counters['photomis'] . '.');
                }
                break;
            default:
                wppa_log('err', 'Illegal $what in wppa_dbg_cachecounts(): ' . $what);
        }
    }
}
Exemplo n.º 10
0
function wppa_get_thumbs()
{
    global $wpdb;
    global $wppa;
    global $thumbs;
    global $wppa_session;
    if ($wppa['is_owner'] && !$wppa['start_album']) {
        return false;
    }
    // No owner album( s ) -> no photos
    wppa_dbg_msg('get_thumbs entered: ' . $wppa['mocc'] . ' Start_album=' . $wppa['start_album'] . ', Cover=' . $wppa['is_cover']);
    if ($wppa['is_cover']) {
        wppa_dbg_msg('its cover, leave get_thumbs');
        return;
    }
    if ($wppa['albums_only']) {
        return false;
    }
    if (is_array($thumbs)) {
        // Done already?
        wppa_dbg_msg('cached thumbs used');
        return $thumbs;
    }
    $time = -microtime(true);
    // See if album is an enumeration or range
    $fullalb = $wppa['start_album'];
    // Assume not
    if (strpos($fullalb, '.') !== false) {
        $ids = wppa_series_to_array($fullalb);
        $fullalb = implode(' OR `album` = ', $ids);
    }
    // Single image slideshow?
    if ($wppa['start_photo'] && $wppa['is_single']) {
        $thumbs = $wpdb->get_results($wpdb->prepare('SELECT * FROM `' . WPPA_PHOTOS . '` WHERE `id` = %s', $wppa['start_photo']), ARRAY_A);
        wppa_dbg_q('Q-SIS');
    } elseif ($wppa['is_upldr']) {
        $max = '1000000';
        $alb = $fullalb;
        $status = "`status` <> 'pending' AND `status` <> 'scheduled'";
        if (!is_user_logged_in()) {
            $status .= " AND `status` <> 'private'";
        }
        if ($alb) {
            $query = $wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE ( `album` = " . $alb . " ) AND `owner` = %s AND ( ( " . $status . " ) OR `owner` = %s ) ORDER BY `timestamp` DESC LIMIT %d", $wppa['is_upldr'], wppa_get_user(), $max);
            //, ARRAY_A );
        } else {
            $query = $wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `owner` = %s AND ( ( " . $status . " ) OR `owner` = %s ) ORDER BY `timestamp` DESC LIMIT %d", $wppa['is_upldr'], wppa_get_user(), $max);
            //, ARRAY_A );
        }
        $thumbs = $wpdb->get_results($query, ARRAY_A);
        wppa_dbg_q('Q-UPL');
    } elseif ($wppa['is_topten']) {
        $max = $wppa['topten_count'];
        $alb = $fullalb;
        switch (wppa_opt('topten_sortby')) {
            case 'mean_rating':
                $sortby = '`mean_rating` DESC, `rating_count` DESC, `views` DESC';
                break;
            case 'rating_count':
                $sortby = '`rating_count` DESC, `mean_rating` DESC, `views` DESC';
                break;
            case 'views':
                $sortby = '`views` DESC, `mean_rating` DESC, `rating_count` DESC';
                break;
            default:
                wppa_error_message('Unimplemented sorting method');
                $sortby = '';
                break;
        }
        $status = "`status` <> 'pending' AND `status` <> 'scheduled'";
        if (!is_user_logged_in()) {
            $status .= " AND `status` <> 'private'";
        }
        if ($alb) {
            $thumbs = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE ( `album` = " . $alb . " AND " . $status . " ) ORDER BY " . $sortby . " LIMIT " . $max, ARRAY_A);
        } else {
            $thumbs = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE ( " . $status . " ) ORDER BY " . $sortby . " LIMIT " . $max, ARRAY_A);
        }
        wppa_dbg_q('Q-TT');
    } elseif ($wppa['is_featen']) {
        $max = $wppa['featen_count'];
        $alb = $fullalb;
        if ($alb) {
            $thumbs = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `status` = 'featured' AND ( `album` = " . $alb . " ) ORDER BY RAND( " . wppa_get_randseed() . " ) DESC LIMIT " . $max, ARRAY_A);
        } else {
            $thumbs = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `status` = 'featured' ORDER BY RAND( " . wppa_get_randseed() . " ) DESC LIMIT " . $max, ARRAY_A);
        }
        wppa_dbg_q('Q-FT');
    } elseif ($wppa['is_lasten']) {
        $max = $wppa['lasten_count'];
        $alb = $fullalb;
        $status = "`status` <> 'pending' AND `status` <> 'scheduled'";
        if (!is_user_logged_in()) {
            $status .= " AND `status` <> 'private'";
        }
        // If you want only 'New' photos in the selection, the period must be <> 0;
        if (wppa_switch('wppa_lasten_limit_new') && wppa_opt('max_photo_newtime')) {
            $newtime = " `timestamp` >= " . (time() - wppa_opt('max_photo_newtime'));
            if (current_user_can('wppa_moderate')) {
                if ($alb) {
                    $q = "SELECT * FROM `" . WPPA_PHOTOS . "` WHERE ( `album` = " . $alb . " ) AND (" . $newtime . ") ORDER BY `timestamp` DESC LIMIT " . $max;
                } else {
                    $q = "SELECT * FROM `" . WPPA_PHOTOS . "` WHERE " . $newtime . " ORDER BY `timestamp` DESC LIMIT " . $max;
                }
            } else {
                if ($alb) {
                    $q = "SELECT * FROM `" . WPPA_PHOTOS . "` WHERE ( `album` = " . $alb . " ) AND ( " . $status . " ) AND ( " . $newtime . " ) ORDER BY `timestamp` DESC LIMIT " . $max;
                } else {
                    $q = "SELECT * FROM `" . WPPA_PHOTOS . "` WHERE ( " . $status . " ) AND (" . $newtime . ") ORDER BY `timestamp` DESC LIMIT " . $max;
                }
            }
        } else {
            if (current_user_can('wppa_moderate')) {
                if ($alb) {
                    $q = "SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `album` = " . $alb . " ORDER BY `timestamp` DESC LIMIT " . $max;
                } else {
                    $q = "SELECT * FROM `" . WPPA_PHOTOS . "` ORDER BY `timestamp` DESC LIMIT " . $max;
                }
            } else {
                if ($alb) {
                    $q = "SELECT * FROM `" . WPPA_PHOTOS . "` WHERE ( `album` = " . $alb . " ) AND ( " . $status . " ) ORDER BY `timestamp` DESC LIMIT " . $max;
                } else {
                    $q = "SELECT * FROM `" . WPPA_PHOTOS . "` WHERE " . $status . " ORDER BY `timestamp` DESC LIMIT " . $max;
                }
            }
        }
        // echo $q;
        $thumbs = $wpdb->get_results($q, ARRAY_A);
        wppa_dbg_q('Q-LT');
    } elseif ($wppa['is_comten']) {
        $alb_ids = $wppa['start_album'];
        if (strpos($alb_ids, '.') !== false) {
            $alb_ids = wppa_series_to_array($alb_ids);
        }
        $photo_ids = wppa_get_comten_ids($wppa['comten_count'], (array) $alb_ids);
        $status = "`status` <> 'pending' AND `status` <> 'scheduled'";
        if (!is_user_logged_in()) {
            $status .= " AND `status` <> 'private'";
        }
        $thumbs = array();
        if (is_array($photo_ids)) {
            foreach ($photo_ids as $id) {
                $temp = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE " . $status . " AND `id` = %s", $id), ARRAY_A);
                if ($temp) {
                    $thumbs[] = $temp;
                }
            }
        }
    } elseif ($wppa['is_tag']) {
        $status = "`status` <> 'pending' AND `status` <> 'scheduled'";
        if (!is_user_logged_in()) {
            $status .= " AND `status` <> 'private'";
        }
        if (current_user_can('wppa_moderate')) {
            $temp = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `tags` <> '' " . wppa_get_photo_order('0'), ARRAY_A);
        } else {
            $temp = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE " . $status . " AND `tags` <> '' " . wppa_get_photo_order('0'), ARRAY_A);
        }
        wppa_dbg_q('Q-TG');
        $tags = wppa_get_taglist();
        $thumbs = false;
        $andor = 'and';
        if (strpos($wppa['is_tag'], ';')) {
            $andor = 'or';
        }
        foreach (array_keys($temp) as $index) {
            if ($andor == 'and') {
                // and
                $seltags = explode(',', $wppa['is_tag']);
                $in = true;
                if ($seltags) {
                    foreach ($seltags as $seltag) {
                        if ($seltag && !@in_array($temp[$index]['id'], $tags[$seltag]['ids'])) {
                            $in = false;
                        }
                    }
                }
            } else {
                // or
                $seltags = explode(';', $wppa['is_tag']);
                $in = false;
                if ($seltags) {
                    foreach ($seltags as $seltag) {
                        if ($seltag && @in_array($temp[$index]['id'], $tags[$seltag]['ids'])) {
                            $in = true;
                        }
                    }
                }
            }
            if ($in) {
                if ($wppa['is_related'] != 'tags' || count($thumbs) < $wppa['related_count']) {
                    $thumbs[] = $temp[$index];
                }
            }
        }
        wppa_dbg_msg('Found:' . count($thumbs) . ' thumbs');
    } elseif ($wppa['supersearch']) {
        $ss_data = explode(',', $wppa['supersearch']);
        $data = $ss_data['3'];
        $status = "`status` <> 'pending' AND `status` <> 'scheduled'";
        if (!is_user_logged_in()) {
            $status .= " AND `status` <> 'private'";
        }
        switch ($ss_data['1']) {
            // Name
            case 'n':
                $is = '=';
                if (substr($data, -3) == '...') {
                    $data = substr($data, 0, strlen($data) - 3) . '%';
                    $is = 'LIKE';
                }
                if (current_user_can('wppa_moderate')) {
                    $thumbs = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `name` " . $is . " %s " . wppa_get_photo_order('0'), $data), ARRAY_A);
                } else {
                    $thumbs = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `name` " . $is . " %s AND " . $status . " " . wppa_get_photo_order('0'), $data), ARRAY_A);
                }
                wppa_dbg_q('Q-SS');
                break;
                // Owner
            // Owner
            case 'o':
                if (current_user_can('wppa_moderate')) {
                    $thumbs = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `owner` = %s " . wppa_get_photo_order('0'), $data), ARRAY_A);
                } else {
                    $thumbs = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `owner` = %s AND " . $status . " " . wppa_get_photo_order('0'), $data), ARRAY_A);
                }
                wppa_dbg_q('Q-SS');
                break;
                // Tag
            // Tag
            case 'g':
                $taglist = wppa_get_taglist();
                if (strpos($data, '.')) {
                    $qtags = explode('.', $data);
                    $tagids = $taglist[$qtags['0']]['ids'];
                    $i = '0';
                    while ($i < count($qtags)) {
                        $tagids = array_intersect($tagids, $taglist[$qtags[$i]]['ids']);
                        $i++;
                    }
                } else {
                    $tagids = $taglist[$data]['ids'];
                }
                if (count($tagids) > '0') {
                    $query = "SELECT * FROM `" . WPPA_PHOTOS . "` WHERE " . $status . " AND `id` IN (" . implode(',', $tagids) . ")";
                    $thumbs = $wpdb->get_results($query, ARRAY_A);
                    wppa_dbg_q('Q-SS');
                }
                break;
                // Text
            // Text
            case 't':
                // To distinguish items with ellipses, we temporary replace them with ***
                $data = str_replace('...', '***', $data);
                if (strpos($data, '.')) {
                    $temp = explode('.', $data);
                    $is = '=';
                    if (wppa_opt('ss_text_max')) {
                        if (substr($temp['0'], -3) == '***') {
                            $temp['0'] = substr($temp['0'], 0, strlen($temp['0']) - 3) . '%';
                            $is = 'LIKE';
                        }
                    }
                    $query = $wpdb->prepare("SELECT * FROM `" . WPPA_INDEX . "` WHERE `slug` " . $is . " %s", $temp['0']);
                    $indexes = $wpdb->get_results($query, ARRAY_A);
                    $ids = array();
                    foreach ($indexes as $item) {
                        $ids = array_merge($ids, explode('.', wppa_expand_enum($item['photos'])));
                    }
                    $i = '1';
                    while ($i < count($temp)) {
                        $is = '=';
                        if (wppa_opt('ss_text_max')) {
                            if (substr($temp[$i], -3) == '***') {
                                $temp[$i] = substr($temp[$i], 0, strlen($temp[$i]) - 3) . '%';
                                $is = 'LIKE';
                            }
                        }
                        $query = $wpdb->prepare("SELECT * FROM `" . WPPA_INDEX . "` WHERE `slug` " . $is . " %s", $temp[$i]);
                        $indexes = $wpdb->get_results($query, ARRAY_A);
                        $deltaids = array();
                        foreach ($indexes as $item) {
                            $deltaids = array_merge($deltaids, explode('.', wppa_expand_enum($item['photos'])));
                        }
                        $ids = array_intersect($ids, $deltaids);
                        $i++;
                    }
                } else {
                    $is = '=';
                    if (wppa_opt('ss_text_max')) {
                        if (substr($data, -3) == '***') {
                            $data = substr($data, 0, strlen($data) - 3) . '%';
                            $is = 'LIKE';
                        }
                    }
                    $query = $wpdb->prepare("SELECT * FROM `" . WPPA_INDEX . "` WHERE `slug` " . $is . " %s", $data);
                    $indexes = $wpdb->get_results($query, ARRAY_A);
                    $ids = array();
                    foreach ($indexes as $item) {
                        $ids = array_merge($ids, explode('.', wppa_expand_enum($item['photos'])));
                    }
                }
                if (empty($ids)) {
                    $ids = array('0');
                    // Dummy
                }
                $query = "SELECT * FROM `" . WPPA_PHOTOS . "` WHERE " . $status . " AND `id` IN (" . implode(',', $ids) . ")";
                $thumbs = $wpdb->get_results($query, ARRAY_A);
                wppa_dbg_q('Q_SS');
                break;
                // Iptc
            // Iptc
            case 'i':
                $itag = str_replace('H', '#', $ss_data['2']);
                $desc = $ss_data['3'];
                $query = $wpdb->prepare("SELECT * FROM `" . WPPA_IPTC . "` WHERE `tag` = %s AND `description` = %s", $itag, $desc);
                $iptclines = $wpdb->get_results($query, ARRAY_A);
                $ids = '0';
                if (is_array($iptclines)) {
                    foreach ($iptclines as $item) {
                        $ids .= ',' . $item['photo'];
                    }
                }
                $query = "SELECT * FROM `" . WPPA_PHOTOS . "` WHERE " . $status . " AND `id` IN (" . $ids . ")";
                $thumbs = $wpdb->get_results($query, ARRAY_A);
                wppa_dbg_q('Q_SS');
                break;
                // Exif
            // Exif
            case 'e':
                $etag = str_replace('H', '#', $ss_data['2']);
                $desc = $ss_data['3'];
                $query = $wpdb->prepare("SELECT * FROM `" . WPPA_EXIF . "` WHERE `tag` = %s AND `description` = %s", $etag, $desc);
                $exiflines = $wpdb->get_results($query, ARRAY_A);
                $ids = '0';
                if (is_array($exiflines)) {
                    foreach ($exiflines as $item) {
                        $ids .= ',' . $item['photo'];
                    }
                }
                $query = "SELECT * FROM `" . WPPA_PHOTOS . "` WHERE " . $status . " AND `id` IN (" . $ids . ")";
                $thumbs = $wpdb->get_results($query, ARRAY_A);
                wppa_dbg_q('Q_SS');
                break;
        }
    } elseif ($wppa['src']) {
        // Searching
        $status = "`status` <> 'pending' AND `status` <> 'scheduled'";
        if (!is_user_logged_in()) {
            $status .= " AND `status` <> 'private'";
        }
        $searchstring = $wppa['searchstring'];
        if (isset($wppa_session['use_searchstring']) && !empty($wppa_session['use_searchstring'])) {
            $searchstring = $wppa_session['use_searchstring'];
        }
        // Indexed search??
        //		if ( wppa_switch( 'indexed_search' ) ) {
        $final_array = array();
        $chunks = explode(',', stripslashes(strtolower($searchstring)));
        // all chunks
        foreach ($chunks as $chunk) {
            if (strlen(trim($chunk))) {
                $words = wppa_index_raw_to_words($chunk);
                $photo_array = array();
                // all words in the searchstring
                foreach ($words as $word) {
                    $word = trim($word);
                    if (strlen($word) > 1) {
                        if (strlen($word) > 20) {
                            $word = substr($word, 0, 20);
                        }
                        if (wppa_switch('wild_front')) {
                            $pidxs = $wpdb->get_results("SELECT `slug`, `photos` FROM `" . WPPA_INDEX . "` WHERE `slug` LIKE '%" . $word . "%'", ARRAY_A);
                        } else {
                            $pidxs = $wpdb->get_results("SELECT `slug`, `photos` FROM `" . WPPA_INDEX . "` WHERE `slug` LIKE '" . $word . "%'", ARRAY_A);
                        }
                        wppa_dbg_q('Q-IX');
                        $photos = '';
                        if ($pidxs) {
                            foreach ($pidxs as $pi) {
                                $photos .= $pi['photos'] . ',';
                            }
                        }
                        $photo_array[] = wppa_index_string_to_array(trim($photos, ','));
                    }
                }
                // Must meet all words: intersect photo sets
                foreach (array_keys($photo_array) as $idx) {
                    if ($idx > '0') {
                        $photo_array['0'] = array_intersect($photo_array['0'], $photo_array[$idx]);
                    }
                }
                // Save partial result
                if (isset($photo_array['0'])) {
                    $final_array = array_merge($final_array, $photo_array['0']);
                }
            }
        }
        // Compose WHERE clause
        $selection = " `id` = '0' ";
        $count = '0';
        foreach (array_keys($final_array) as $p) {
            if (wppa_opt('max_search_photos')) {
                $selection .= "OR `id` = '" . $final_array[$p] . "' ";
                $count++;
            }
        }
        // Get them, depending of 'pending' criteria
        if (current_user_can('wppa_moderate')) {
            $thumbs = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE " . $selection . wppa_get_photo_order('0'), ARRAY_A);
        } else {
            $thumbs = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE " . $status . " AND ( " . $selection . " ) " . wppa_get_photo_order('0'), ARRAY_A);
        }
        wppa_dbg_q('Q-SR');
        // Check on seperate albums?
        if (wppa_switch('excl_sep')) {
            $broken = false;
            foreach (array_keys($thumbs) as $idx) {
                $alb = $thumbs[$idx]['album'];
                if (wppa_is_separate($alb)) {
                    unset($thumbs[$idx]);
                    $broken = true;
                }
            }
            // Sequence broken?, create new indexes for thumbs array
            if ($broken) {
                $temp = $thumbs;
                $thumbs = array();
                foreach ($temp as $item) {
                    $thumbs[] = $item;
                }
            }
        }
        //		}
        /*
        		else { // Conventional search
        
        			if ( current_user_can( 'wppa_moderate' ) ) {
        				$q = "SELECT * FROM `" . WPPA_PHOTOS . "` " . wppa_get_photo_order( '0' );
        			}
        			else {
        				$q = "SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `status` <> 'pending' AND `status` <> 'scheduled' " . wppa_get_photo_order( '0' );
        			}
        			$tmbs = $wpdb->get_results( $q, ARRAY_A );
        			wppa_dbg_q( 'Q-SR' );
        			
        			$thumbs = array();
        			foreach ( $tmbs as $thumb ) {
        				if ( ! wppa_switch( 'excl_sep' ) || ! wppa_is_separate( $thumb['album'] ) ) {	// Not exclude sepreate or not seperate
        					$haystack = __( $thumb['name'] ).' '.wppa_filter_exif( wppa_filter_iptc( __( stripslashes( $thumb['description'] ) ),$thumb['id'] ),$thumb['id'] );
        					if ( wppa_switch( 'search_tags' ) ) {
        						$haystack .= ' '.str_replace( ',', ' ', $thumb['tags'] );
        					}
        					if ( wppa_switch( 'search_comments' ) ) {
        						$comms = $wpdb->get_results( $wpdb->prepare( " SELECT * FROM `".WPPA_COMMENTS."` WHERE `photo` = %s", $thumb['id'] ), ARRAY_A );
        						wppa_dbg_q( 'Q-CM' );
        						if ( $comms ) foreach ( $comms as $comm ) {
        							$haystack .= $comm['comment'];
        						}
        					}
        					if ( wppa_deep_stristr( strtolower( $haystack ), $searchstring ) ) {
        						$thumbs[] = $thumb;
        					}
        				}
        			}
        		} // end conventional search
        */
        // Rootsearch?
        if ($wppa['is_rootsearch'] && isset($wppa_session['search_root'])) {
            // Find all albums below root
            $root = $wppa_session['search_root'];
            $albs = array($root);
            $albs = array_merge($albs, wppa_get_all_children($root));
            // Now remove the thumbs that are not in any of these albums
            $c1 = count($thumbs);
            $broken = false;
            foreach (array_keys($thumbs) as $idx) {
                if (!in_array($thumbs[$idx]['album'], $albs)) {
                    unset($thumbs[$idx]);
                    $broken = true;
                }
            }
            $c2 = count($thumbs);
            wppa_dbg_msg('Rootsearch thumbs:' . $c1 . ' -> ' . $c2);
            // Sequence broken?, create new indexes for thumbs array. required for filmstrip to be able to use the cached thumbs. It relies on uninterrupted sequence
            if ($broken) {
                $temp = $thumbs;
                $thumbs = array();
                foreach ($temp as $item) {
                    $thumbs[] = $item;
                }
            }
        }
        // Check maximum
        if (is_array($thumbs) && count($thumbs) > wppa_opt('max_search_photos') && wppa_opt('max_search_photos') != '0') {
            $alert_text = sprintf(__a('There are %s photos found. Only the first %s will be shown. Please refine your search criteria.'), count($thumbs), wppa_opt('max_search_photos'));
            wppa_alert($alert_text);
            foreach (array_keys($thumbs) as $idx) {
                if ($idx >= wppa_opt('max_search_photos')) {
                    unset($thumbs[$idx]);
                }
            }
        }
        $wppa['any'] = !empty($thumbs);
    } else {
        // Not search, normal
        // Init $thumbs
        $thumbs = array();
        // Status
        $status = "`status` <> 'pending' AND `status` <> 'scheduled'";
        if (!is_user_logged_in()) {
            $status .= " AND `status` <> 'private'";
        }
        // On which album( s )?
        if (strpos($wppa['start_album'], '.') !== false) {
            $allalb = wppa_series_to_array($wppa['start_album']);
        } else {
            $allalb = false;
        }
        wppa_dbg_msg('Startalbum = ' . $wppa['start_album'], 'red');
        /* Nieuwe versie */
        // All albums ?
        if ($wppa['start_album'] == -2) {
            if (current_user_can('wppa_moderate')) {
                $q = "SELECT * FROM `" . WPPA_PHOTOS . "` " . wppa_get_photo_order('0');
            } else {
                $q = $wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE ( ( " . $status . " ) OR `owner` = %s ) " . wppa_get_photo_order('0'), wppa_get_user());
            }
            wppa_dbg_msg('Q-PH1 ' . $q);
            wppa_dbg_q('Q-PH1');
            $thumbs = $wpdb->get_results($q, ARRAY_A);
        } elseif (wppa_is_int($wppa['start_album'])) {
            if (current_user_can('wppa_moderate')) {
                $q = "SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `album` = " . $wppa['start_album'] . " " . wppa_get_photo_order($wppa['start_album']);
            } else {
                $q = $wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE ( ( " . $status . " ) OR `owner` = %s ) AND `album` = " . $wppa['start_album'] . " " . wppa_get_photo_order($wppa['start_album']), wppa_get_user());
            }
            wppa_dbg_msg('Q-PH2 ' . $q);
            wppa_dbg_q('Q-PH2');
            $thumbs = $wpdb->get_results($q, ARRAY_A);
        } elseif (is_array($allalb)) {
            $wherealbum = ' `album` IN (' . implode(',', $allalb) . ') ';
            if (current_user_can('wppa_moderate')) {
                $q = "SELECT * FROM `" . WPPA_PHOTOS . "` WHERE " . $wherealbum . " " . wppa_get_photo_order('0');
            } else {
                $q = $wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE ( ( " . $status . " ) OR `owner` = %s ) AND " . $wherealbum . " " . wppa_get_photo_order('0'), wppa_get_user());
            }
            wppa_dbg_msg('Q-PH3 ' . $q);
            wppa_dbg_q('Q-PH3');
            $thumbs = $wpdb->get_results($q, ARRAY_A);
        } else {
            $thumbs = array();
        }
    }
    $wppa['thumb_count'] = empty($thumbs) ? '0' : count($thumbs);
    $time += microtime(true);
    wppa_dbg_msg('Get thumbs took ' . $time . ' seconds, found: ' . $wppa['thumb_count'] . ' items.');
    wppa_cache_photo('add', $thumbs);
    return $thumbs;
}
function wppa_get_coverphoto_ids($alb, $count)
{
    global $wpdb;
    if (!$alb) {
        return false;
    }
    // no album, no coverphoto
    // Find cover photo id
    $id = wppa_get_album_item($alb, 'main_photo');
    // main_photo is a positive integer ( photo id )?
    if ($id > '0') {
        // 1 coverphoto explicitly given
        $photo = wppa_cache_photo($id);
        if (!$photo) {
            // Photo gone, set id to 0
            $id = '0';
        } elseif ($photo['album'] != $alb) {
            // Photo moved to other album, set id to 0
            $id = '0';
        } else {
            $temp['0'] = $photo;
            // Found!
        }
    }
    // main_photo is 0? Random
    if ('0' == $id) {
        if (current_user_can('wppa_moderate')) {
            $temp = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s ORDER BY RAND( " . wppa_get_randseed('page') . " ) LIMIT %d", $alb, $count), ARRAY_A);
        } else {
            $temp = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s AND ( ( `status` <> 'pending' AND `status` <> 'scheduled' ) OR `owner` = %s ) ORDER BY RAND( " . wppa_get_randseed('page') . " ) LIMIT %d", $alb, wppa_get_user(), $count), ARRAY_A);
        }
    }
    // main_photo is -2? Last upload
    if ('-2' == $id) {
        if (current_user_can('wppa_moderate')) {
            $temp = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s ORDER BY `timestamp` DESC LIMIT %d", $alb, $count), ARRAY_A);
        } else {
            $temp = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s AND ( ( `status` <> 'pending' AND `status` <> 'scheduled' ) OR `owner` = %s ) ORDER BY `timestamp` DESC LIMIT %d", $alb, wppa_get_user(), $count), ARRAY_A);
        }
    }
    // main_phtot is -1? Random featured
    if ('-1' == $id) {
        $temp = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s AND `status` = 'featured' ORDER BY RAND( " . wppa_get_randseed('page') . " ) LIMIT %d", $alb, $count), ARRAY_A);
    }
    // Random from children
    if ('-3' == $id) {
        $allalb = wppa_expand_enum(wppa_alb_to_enum_children($alb));
        $temp = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` " . "WHERE `album` IN ( " . str_replace('.', ',', $allalb) . " ) " . "AND ( ( `status` <> 'pending' AND `status` <> 'scheduled' ) OR `owner` = %s ) " . "ORDER BY RAND( " . wppa_get_randseed('page') . " ) LIMIT %d", wppa_get_user(), $count), ARRAY_A);
    }
    // Most recent from children
    if ('-4' == $id) {
        $allalb = wppa_expand_enum(wppa_alb_to_enum_children($alb));
        $temp = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` " . "WHERE `album` IN ( " . str_replace('.', ',', $allalb) . " ) " . "AND ( ( `status` <> 'pending' AND `status` <> 'scheduled' ) OR `owner` = %s ) " . "ORDER BY `timestamp` DESC LIMIT %d", wppa_get_user(), $count), ARRAY_A);
    }
    // Report query
    wppa_dbg_q('Q-gcovp');
    // Add to 2nd level cache
    wppa_cache_photo('add', $temp);
    // Extract the ids only
    $ids = array();
    if (is_array($temp)) {
        foreach ($temp as $item) {
            $ids[] = $item['id'];
        }
    }
    return $ids;
}
function wppa_update_photo($args)
{
    global $wpdb;
    if (!is_array($args)) {
        return false;
    }
    if (!$args['id']) {
        return false;
    }
    $thumb = wppa_cache_thumb($args['id']);
    if (!$thumb) {
        return false;
    }
    $id = $args['id'];
    // If Timestamp update, make sure modified is updated to now
    if (isset($args['timestamp'])) {
        $args['modified'] = time();
    }
    foreach (array_keys($args) as $itemname) {
        $itemvalue = $args[$itemname];
        $doit = false;
        // Sanitize input
        switch ($itemname) {
            case 'id':
                break;
            case 'name':
                $itemvalue = wppa_strip_tags($itemvalue, 'all');
                $doit = true;
                break;
            case 'description':
                $itemvalue = balanceTags($itemvalue, true);
                $itemvalue = wppa_strip_tags($itemvalue, 'script&style');
                $doit = true;
                break;
            case 'timestamp':
            case 'modified':
                if (!$itemvalue) {
                    $itemvalue = time();
                }
                $doit = true;
                break;
            case 'scheduledtm':
            case 'exifdtm':
            case 'page_id':
                $doit = true;
                break;
            case 'status':
                $doit = true;
                break;
            case 'tags':
                $itemvalue = wppa_sanitize_tags($itemvalue);
                $doit = true;
                break;
            case 'thumbx':
            case 'thumby':
            case 'photox':
            case 'photoy':
            case 'videox':
            case 'videoy':
                $itemvalue = intval($itemvalue);
                $doit = true;
                break;
            case 'ext':
                $doit = true;
                break;
            case 'filename':
                $itemvalue = wppa_sanitize_file_name($itemvalue);
                $doit = true;
                break;
            case 'custom':
            case 'stereo':
                $doit = true;
                break;
            default:
                wppa_log('Error', 'Not implemented in wppa_update_photo(): ' . $itemname);
                return false;
        }
        if ($doit) {
            if ($wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `" . $itemname . "` = %s WHERE `id` = %s LIMIT 1", $itemvalue, $id))) {
                wppa_cache_photo('invalidate', $id);
            }
        }
    }
    return true;
}
function wppa_bump_clickcount($id)
{
    global $wpdb;
    global $wppa_session;
    // Feature enabled?
    if (!wppa_switch('track_clickcounts')) {
        return;
    }
    // Sanitize input
    if (!wppa_is_int($id) || $id < '1') {
        return;
    }
    // Init clicks in session?
    if (!isset($wppa_session['click'])) {
        $wppa_session['click'] = array();
    }
    // Remember click and update photodata, only if first time
    if (!isset($wppa_session['click'][$id])) {
        $wppa_session['click'][$id] = true;
        $count = $wpdb->get_var("SELECT `clicks` FROM `" . WPPA_PHOTOS . "` WHERE `id` = {$id}");
        $count++;
        $wpdb->query("UPDATE `" . WPPA_PHOTOS . "` SET `clicks` = {$count} WHERE `id` = {$id}");
        // Invalidate cache
        wppa_cache_photo('invalidate', $id);
    }
}