function wppa_orientate_image_file($file, $ori)
{
    // Validate args
    if (!is_file($file)) {
        wppa_log('Err', 'File not found (wppa_orientate_image_file())');
        return false;
    }
    if (!wppa_is_int($ori) || $ori < '2' || $ori > '8') {
        wppa_log('Err', 'Bad arg $ori:' . $ori . ' (wppa_orientate_image_file())');
        return false;
    }
    // Load image
    $source = wppa_imagecreatefromjpeg($file);
    if (!$source) {
        wppa_log('Err', 'Could not create memoryimage from jpg file ' . $file);
        return false;
    }
    // Perform operation
    switch ($ori) {
        case '2':
            $orientate = $source;
            imageflip($orientate, IMG_FLIP_HORIZONTAL);
            break;
        case '3':
            $orientate = imagerotate($source, 180, 0);
            break;
        case '4':
            $orientate = $source;
            imageflip($orientate, IMG_FLIP_VERTICAL);
            break;
        case '5':
            $orientate = imagerotate($source, 270, 0);
            imageflip($orientate, IMG_FLIP_HORIZONTAL);
            break;
        case '6':
            $orientate = imagerotate($source, 270, 0);
            break;
        case '7':
            $orientate = imagerotate($source, 90, 0);
            imageflip($orientate, IMG_FLIP_HORIZONTAL);
            break;
        case '8':
            $orientate = imagerotate($source, 90, 0);
            break;
    }
    // Output
    imagejpeg($orientate, $file, wppa_opt('jpeg_quality'));
    // Accessable
    wppa_chmod($file);
    // Optimized
    wppa_optimize_image_file($file);
    // Free the memory
    imagedestroy($source);
    @imagedestroy($orientate);
    // Done
    return true;
}
function wppa_encrypt_album($album)
{
    // Feature enabled?
    if (!wppa_switch('use_encrypted_links')) {
        return $album;
    }
    // Encrypted album enumeration must always be expanded
    $album = wppa_expand_enum($album);
    // Decompose possible album enumeration
    $album_ids = strpos($album, '.') === false ? array($album) : explode('.', $album);
    $album_crypts = array();
    $i = 0;
    // Process all tokens
    while ($i < count($album_ids)) {
        $id = $album_ids[$i];
        // Check for existance of album, otherwise return dummy
        if (wppa_is_int($id) && $id > '0' && !wppa_album_exists($id)) {
            $id = '999999';
        }
        switch ($id) {
            case '-3':
                $crypt = get_option('wppa_album_crypt_3', false);
                break;
            case '-2':
                $crypt = get_option('wppa_album_crypt_2', false);
                break;
            case '-1':
                $crypt = get_option('wppa_album_crypt_1', false);
                break;
            case '':
            case '0':
                $crypt = get_option('wppa_album_crypt_0', false);
                break;
            case '999999':
                $crypt = get_option('wppa_album_crypt_9', false);
                break;
            default:
                if (strlen($id) < 12) {
                    $crypt = wppa_get_album_item($id, 'crypt');
                } else {
                    $crypt = $id;
                    // Already encrypted
                }
        }
        $album_crypts[$i] = $crypt;
        $i++;
    }
    // Compose result
    $result = implode('.', $album_crypts);
    return $result;
}
function wppa_album_number_to_name_in_uri($uri)
{
    if (wppa_switch('use_album_names_in_urls')) {
        $apos = strpos($uri, 'album=');
        if ($apos === false) {
            return $uri;
        } else {
            $start = $apos + '6';
            $end = strpos($uri, '&', $start);
        }
        $before = substr($uri, 0, $start);
        if ($end) {
            $albnum = substr($uri, $start, $end - $start);
            if (wppa_is_int($albnum) && $albnum > '0') {
                // Can convert single positive integer album ids only
                $after = substr($uri, $end);
                $albnam = stripslashes(wppa_get_album_item($albnum, 'name'));
                $albnam = wppa_encode_uri_component($albnam);
                $uri = $before . $albnam . $after;
            }
        } else {
            $albnum = substr($uri, $start);
            if (wppa_is_int($albnum) && $albnum > '0') {
                // Can convert single positive integer album ids only
                $albnam = stripslashes(wppa_get_album_item($albnum, 'name'));
                $albnam = wppa_encode_uri_component($albnam);
                $uri = $before . $albnam;
            }
        }
    }
    return $uri;
}
Beispiel #4
0
function wppa_slide_custom($opt = '')
{
    if ($opt == 'optional' && !wppa_switch('custom_on')) {
        return;
    }
    if (wppa('is_slideonly')) {
        return;
    }
    /* Not when slideonly */
    if (is_feed()) {
        return;
    }
    $content = __(stripslashes(wppa_opt('custom_content')));
    // w#albdesc
    if (wppa_is_int(wppa('start_album')) && wppa('start_album') > '0') {
        $content = str_replace('w#albdesc', wppa_get_album_desc(wppa('start_album')), $content);
    } else {
        $content = str_replace('w#albdesc', '', $content);
    }
    // w#fotomoto
    if (wppa_switch('fotomoto_on')) {
        $fontsize = wppa_opt('fotomoto_fontsize');
        if ($fontsize) {
            $s = '<style>.FotomotoToolbarClass{font-size:' . wppa_opt('fotomoto_fontsize') . 'px !important;}</style>';
        } else {
            $s = '';
        }
        $content = str_replace('w#fotomoto', $s . '<div' . ' id="wppa-fotomoto-container-' . wppa('mocc') . '"' . ' class="wppa-fotomoto-container"' . ' >' . '</div>' . '<div' . ' id="wppa-fotomoto-checkout-' . wppa('mocc') . '"' . ' class="wppa-fotomoto-checkout FotomotoToolbarClass"' . ' style="float:right; clear:none;"' . ' >' . '<ul' . ' class="FotomotoBar"' . ' style="list-style:none outside none;"' . ' >' . '<li>' . '<a' . ' onclick="FOTOMOTO.API.checkout(); return false;"' . ' >' . __('Checkout', 'wp-photo-album-plus') . '</a>' . '</li>' . '</ul>' . '</div>' . '<div' . ' style="clear:both;"' . ' >' . '</div>', $content);
    } else {
        $content = str_replace('w#fotomoto', '', $content);
    }
    $content = wppa_html($content);
    wppa_out('<div' . ' id="wppa-custom-' . wppa('mocc') . '"' . ' class="wppa-box wppa-custom"' . ' style="' . __wcs('wppa-box') . __wcs('wppa-custom') . '"' . ' >' . $content . '</div>');
}
Beispiel #5
0
function wppa_get_thumb_masonry($id)
{
    global $wpdb;
    // Init
    if (!$id) {
        wppa_dbg_msg('Please check file wppa-theme.php or any other php file that calls wppa_thumb_masonry(). Argument 1: photo id is missing!', 'red', 'force');
        die('Please check your configuration');
    }
    $result = '';
    $cont_width = wppa_get_container_width();
    $count_cols = ceil($cont_width / wppa_opt('thumbsize'));
    // Get the photo info
    $thumb = wppa_cache_thumb($id);
    // Get the album info
    $album = wppa_cache_album($thumb['album']);
    // Get photo info
    $is_video = wppa_is_video($id);
    $has_audio = wppa_has_audio($id);
    $imgsrc = wppa_fix_poster_ext(wppa_get_thumb_path($id), $id);
    if (!wppa_is_video($id) && !is_file($imgsrc)) {
        $result .= '<div' . ' class=""' . ' style="' . 'font-size:10px;' . 'color:red;' . 'width:' . wppa_opt('thumbsize') . 'px;' . 'position:static;' . 'float:left;' . '"' . ' >' . sprintf(__('Missing thumbnail image #%s', 'wp-photo-album-plus'), $id) . '</div>';
        return $result;
    }
    $alt = $album['alt_thumbsize'] == 'yes' ? '_alt' : '';
    $imgattr_a = wppa_get_imgstyle_a($id, $imgsrc, wppa_opt('thumbsize' . $alt), 'optional', 'thumb');
    // Verical style ?
    if (wppa_opt('thumbtype') == 'masonry-v') {
        $imgwidth = wppa_opt('thumbsize');
        $imgheight = $imgwidth * wppa_get_thumbratioyx($id);
        $imgstyle = 'width:100%; height:auto; margin:0; position:relative; box-sizing:border-box;';
        $frame_h = '';
    } else {
        $imgheight = wppa_opt('thumbsize');
        $imgwidth = $imgheight * wppa_get_thumbratioxy($id);
        $imgstyle = 'height:100%;' . 'width:auto;' . 'margin:0;' . 'position:relative;' . 'box-sizing:border-box;' . '';
        $frame_h = 'height:100%; ';
    }
    // Mouseover effect?
    if (wppa_switch('use_thumb_opacity')) {
        $opac = wppa_opt('thumb_opacity');
        $imgstyle .= ' opacity:' . $opac / 100 . '; filter:alpha( opacity=' . $opac . ' );';
    }
    // Padding
    if (wppa_is_int(wppa_opt('tn_margin') / 2)) {
        $imgstyle .= ' padding:' . wppa_opt('tn_margin') / 2 . 'px;';
    } else {
        $p1 = floor(wppa_opt('tn_margin') / 2);
        $p2 = ceil(wppa_opt('tn_margin') / 2);
        $imgstyle .= ' padding:' . $p1 . 'px ' . $p2 . 'px ' . $p2 . 'px ' . $p1 . 'px;';
    }
    // Cursor
    $cursor = $imgattr_a['cursor'];
    // Popup ?
    if (wppa_switch('use_thumb_popup')) {
        // Landscape?
        if ($imgwidth > $imgheight) {
            $popwidth = wppa_opt('popupsize');
            $popheight = round($popwidth * $imgheight / $imgwidth);
        } else {
            $popheight = wppa_opt('popupsize');
            $popwidth = round($popheight * $imgwidth / $imgheight);
        }
    } else {
        $popwidth = $imgwidth;
        $popheight = $imgheight;
    }
    $imgurl = wppa_fix_poster_ext(wppa_get_thumb_url($id, '', $popwidth, $popheight), $id);
    $events = wppa_get_imgevents('thumb', $id);
    $imgalt = wppa_get_imgalt($id);
    // returns something like ' alt="Any text" '
    $title = esc_attr(wppa_get_masonry_title($id));
    // esc_attr( wppa_get_photo_name( $id ) );
    // Feed ?
    if (is_feed()) {
        $imgattr_a = wppa_get_imgstyle_a($id, $imgsrc, '100', '4', 'thumb');
        $style = $imgattr_a['style'];
        $result .= '<a href="' . get_permalink() . '">' . '<img' . ' src="' . $imgurl . '"' . ' ' . $imgalt . ($title ? ' title="' . $title . '"' : '') . ' style="' . $style . '"' . ' />' . '</a>';
        return;
    }
    // Get the image link
    if (wppa('is_topten')) {
        $no_album = !wppa('start_album');
        if ($no_album) {
            $tit = __('View the top rated photos', 'wp-photo-album-plus');
        } else {
            $tit = esc_attr(__(stripslashes($thumb['description'])));
        }
        $link = wppa_get_imglnk_a('thumb', $id, '', $tit, '', $no_album);
    } else {
        $link = wppa_get_imglnk_a('thumb', $id);
    }
    // voor parent uplr
    // Open the thumbframe
    // Add class wppa-mas-h-{mocc} for ie if horizontal
    $is_ie_or_chrome = strpos($_SERVER["HTTP_USER_AGENT"], 'Trident') || strpos($_SERVER["HTTP_USER_AGENT"], 'Chrome');
    $result .= '
				<div' . ' id="thumbnail_frame_masonry_' . $id . '_' . wppa('mocc') . '"' . ($is_ie_or_chrome && wppa_opt('thumbtype') == 'masonry-h' ? ' class="wppa-mas-h-' . wppa('mocc') . '"' : '') . ' style="' . $frame_h . 'position:static;' . 'float:left;' . 'font-size:12px;' . 'line-height:8px;' . 'overflow:hidden;' . 'box-sizing:content-box;' . '" >';
    // The medals
    $result .= wppa_get_medal_html_a(array('id' => $id, 'size' => 'M', 'where' => 'top'));
    // See if ajax possible
    if ($link) {
        if ($link['is_url']) {
            // is url
            if (wppa_switch('allow_ajax') && wppa_opt('thumb_linktype') == 'photo' && wppa_opt('thumb_linkpage') == '0' && !wppa_switch('thumb_blank') && !(wppa_switch('thumb_overrule') && $thumb['linkurl']) && !wppa('is_topten') && !wppa('is_lasten') && !wppa('is_comten') && !wppa('is_featen') && !wppa('is_tag') && !wppa('is_upldr') && !wppa('src') && !wppa('supersearch') && (wppa_is_int(wppa('start_album')) || wppa('start_album') == '')) {
                // Ajax	possible
                // The a img ajax
                $p = wppa('calendar') ? '' : '&amp;wppa-photo=' . $id;
                $onclick = 'wppaDoAjaxRender( ' . wppa('mocc') . ', \'' . wppa_get_slideshow_url_ajax(wppa('start_album'), '0') . '&amp;wppa-photo=' . $id . '\', \'' . wppa_convert_to_pretty(wppa_get_slideshow_url(wppa('start_album'), '0') . $p) . '\' )';
                // old			$onclick = "wppaDoAjaxRender( ".wppa( 'mocc' ).", '".wppa_get_slideshow_url_ajax( wppa( 'start_album' ), '0' ).'&amp;wppa-photo='.$id."', '".wppa_convert_to_pretty( wppa_get_slideshow_url( wppa( 'start_album' ), '0' )."&amp;wppa-photo=".$id )."' )";
                $result .= '<a style="position:static;" class="thumb-img" id="x-' . $id . '-' . wppa('mocc') . '">';
                if ($is_video) {
                    //					$result .= '<video preload="metadata" onclick="'.$onclick.'" id="i-'.$id.'-'.wppa( 'mocc' ).'" '.$imgalt.' title="'.$title.'" style="'.$imgstyle.' cursor:pointer;" '.$events.' >'.wppa_get_video_body( $id ).'</video>';
                    $result .= wppa_get_video_html(array('id' => $id, 'controls' => false, 'margin_top' => '0', 'margin_bottom' => '0', 'tagid' => 'i-' . $id . '-' . wppa('mocc'), 'cursor' => 'cursor:pointer;', 'events' => $events, 'title' => $title, 'preload' => 'metadata', 'onclick' => $onclick, 'lb' => false, 'class' => '', 'style' => $imgstyle, 'use_thumb' => true));
                } else {
                    $result .= '<img' . ' onclick="' . $onclick . '"' . ' id="i-' . $id . '-' . wppa('mocc') . '"' . ' src="' . $imgurl . '"' . ' ' . $imgalt . ($title ? ' title="' . $title . '"' : '') . ' style="' . $imgstyle . ' cursor:pointer;"' . ' ' . $events . ' />';
                }
                $result .= '</a>';
            } else {
                // non ajax
                // The a img non ajax
                $result .= '<a style="position:static;" href="' . $link['url'] . '" target="' . $link['target'] . '" class="thumb-img" id="x-' . $id . '-' . wppa('mocc') . '">';
                if ($is_video) {
                    //					$result .= '<video preload="metadata" id="i-'.$id.'-'.wppa( 'mocc' ).'" '.$imgalt.' title="'.$title.'" width="'.$imgwidth.'" height="'.$imgheight.'" style="'.$imgstyle.' cursor:pointer;" '.$events.' >'.wppa_get_video_body( $id ).'</video>';
                    $result .= wppa_get_video_html(array('id' => $id, 'controls' => false, 'margin_top' => '0', 'margin_bottom' => '0', 'tagid' => 'i-' . $id . '-' . wppa('mocc'), 'cursor' => 'cursor:pointer;', 'events' => $events, 'title' => $title, 'preload' => 'metadata', 'onclick' => '', 'lb' => false, 'class' => '', 'style' => $imgstyle, 'use_thumb' => true));
                } else {
                    $result .= '<img' . ' id="i-' . $id . '-' . wppa('mocc') . '"' . ' src="' . $imgurl . '"' . ' ' . $imgalt . ($title ? ' title="' . $title . '"' : '') . ' style="' . $imgstyle . 'cursor:pointer;"' . ' ' . $events . ' />';
                }
                $result .= '</a>';
            }
        } elseif ($link['is_lightbox']) {
            // The a img
            $title = wppa_get_lbtitle('thumb', $id);
            $result .= '<a href="' . $link['url'] . '"' . ' target="' . $link['target'] . '"' . ($is_video ? ' data-videohtml="' . esc_attr(wppa_get_video_body($id)) . '"' . ' data-videonatwidth="' . wppa_get_videox($id) . '"' . ' data-videonatheight="' . wppa_get_videoy($id) . '"' : '') . ($has_audio ? ' data-audiohtml="' . esc_attr(wppa_get_audio_body($id)) . '"' : '') . ' ' . wppa('rel') . '="' . wppa_opt('lightbox_name') . '[occ' . wppa('mocc') . ']"' . ($title ? ' ' . wppa('lbtitle') . '="' . $title . '"' : '') . ' class="thumb-img"' . ' id="x-' . $id . '-' . wppa('mocc') . '">';
            // The image
            $title = wppa_zoom_in($id);
            // Video?
            if ($is_video) {
                $result .= wppa_get_video_html(array('id' => $id, 'controls' => false, 'margin_top' => '0', 'margin_bottom' => '0', 'tagid' => 'i-' . $id . '-' . wppa('mocc'), 'cursor' => $cursor, 'events' => $events, 'title' => $title, 'preload' => 'metadata', 'onclick' => '', 'lb' => false, 'class' => '', 'style' => $imgstyle, 'use_thumb' => true));
            } else {
                $result .= '<img' . ' id="i-' . $id . '-' . wppa('mocc') . '"' . ' src="' . $imgurl . '"' . ' ' . $imgalt . ($title ? ' title="' . $title . '"' : '') . ' style="' . $imgstyle . $cursor . '"' . ' ' . $events . ' />';
            }
            $result .= '</a>';
        } else {
            // The div img
            $result .= '<div onclick="' . $link['url'] . '" class="thumb-img" id="x-' . $id . '-' . wppa('mocc') . '" style="height:100%;" >';
            // Video?
            if ($is_video) {
                $result .= wppa_get_video_html(array('id' => $id, 'controls' => false, 'margin_top' => '0', 'margin_bottom' => '0', 'tagid' => 'i-' . $id . '-' . wppa('mocc'), 'cursor' => 'cursor:pointer;', 'events' => $events, 'title' => $title, 'preload' => 'metadata', 'onclick' => '', 'lb' => false, 'class' => '', 'style' => $imgstyle, 'use_thumb' => true));
            } else {
                $result .= '<img' . ' id="i-' . $id . '-' . wppa('mocc') . '"' . ' src="' . $imgurl . '"' . ' ' . $imgalt . ($title ? ' title="' . $title . '"' : '') . ' style="' . $imgstyle . 'cursor:pointer;"' . ' ' . $events . ' />';
            }
            $result .= '</div>';
            $result .= '<script type="text/javascript">';
            $result .= '/* <![CDATA[ */';
            $result .= 'wppaPopupOnclick[' . $id . '] = "' . $link['url'] . '";';
            $result .= '/* ]]> */';
            $result .= '</script>';
        }
    } else {
        // no link
        if (wppa_switch('use_thumb_popup')) {
            $result .= '<div id="x-' . $id . '-' . wppa('mocc') . '" style="height:100%" >';
            if ($is_video) {
                $result .= wppa_get_video_html(array('id' => $id, 'controls' => false, 'margin_top' => '0', 'margin_bottom' => '0', 'tagid' => 'i-' . $id . '-' . wppa('mocc'), 'cursor' => '', 'events' => $events, 'title' => $title, 'preload' => 'metadata', 'onclick' => '', 'lb' => false, 'class' => '', 'style' => $imgstyle, 'use_thumb' => true));
            } else {
                $result .= '<img' . ' id="i-' . $id . '-' . wppa('mocc') . '"' . ' src="' . $imgurl . '"' . ' ' . $imgalt . ($title ? ' title="' . $title . '"' : '') . ' width="' . $imgwidth . '"' . ' height="' . $imgheight . '"' . ' style="' . $imgstyle . '"' . ' ' . $events . ' />';
            }
            $result .= '</div>';
        } else {
            if ($is_video) {
                //				$result .= '<video preload="metadata" '.$imgalt.' title="'.$title.'" width="'.$imgwidth.'" height="'.$imgheight.'" style="'.$imgstyle.'" '.$events.' >'.wppa_get_video_body( $id ).'</video>';
                $result .= wppa_get_video_html(array('id' => $id, 'controls' => false, 'margin_top' => '0', 'margin_bottom' => '0', 'tagid' => 'i-' . $id . '-' . wppa('mocc'), 'cursor' => '', 'events' => $events, 'title' => $title, 'preload' => 'metadata', 'onclick' => '', 'lb' => false, 'class' => '', 'style' => $imgstyle, 'use_thumb' => true));
            } else {
                $result .= '<img' . ' id="i-' . $id . '-' . wppa('mocc') . '"' . ' src="' . $imgurl . '"' . ' ' . $imgalt . ($title ? ' title="' . $title . '"' : '') . ' width="' . $imgwidth . '"' . ' height="' . $imgheight . '"' . ' style="' . $imgstyle . '" ' . $events . ' />';
            }
        }
    }
    // The audio when no popup
    if (wppa_switch('thumb_audio') && wppa_has_audio($id)) {
        $result .= '<div style="position:relative;z-index:11;">';
        //	$is_safari 	= strpos( $_SERVER["HTTP_USER_AGENT"], 'Safari' );
        //	$cont_h 	= $is_safari ? 16 : 28;
        //	$audiotop 	= $imgattr_a['height'] + $imgattr_a['margin-top'] - $cont_h;
        //			if ( ! is_file( $imgsrc ) ) { // Audio without image
        //				$audiotop 	= wppa_get_audio_control_height();
        //				$imgwidth 	= wppa_opt( 'tf_width' );
        //				$imgheight 	= wppa_get_audio_control_height();
        //			}
        $result .= wppa_get_audio_html(array('id' => $id, 'tagid' => 'a-' . $id . '-' . wppa('mocc'), 'style' => 'width:100%;position:absolute;bottom:0;margin:0;padding:' . wppa_opt('tn_margin') / 2 . 'px;left:0;border:none;z-index:10;'));
        $result .= '</div>';
    }
    // The medals
    $result .= wppa_get_medal_html_a(array('id' => $id, 'size' => 'M', 'where' => 'bot'));
    // Close the thumbframe
    $result .= '</div>';
    return $result;
}
Beispiel #6
0
function wppa_convert_to_pretty($xuri)
{
    // Make local copy
    $uri = $xuri;
    // Only when permalink structure is not default
    if (!get_option('permalink_structure')) {
        return $uri;
    }
    // Not on front page, the redirection will fail...
    //	if ( is_front_page() ) {
    //		return $uri;
    //	}
    // Any querystring?
    if (strpos($uri, '?') === false) {
        return $uri;
    }
    // Not during search. Otherwise wppa_test_for_search('at_session_start') returns '';
    // and this will destroy use and display searchstrings in wppa_session_start()
    // Fix in 6.3.9
    if (strpos($uri, 'searchstring')) {
        return $uri;
    }
    // Re-order
    if (strpos($uri, '&amp;') !== false) {
        $amps = true;
        $uri = str_replace('&amp;', '&', $uri);
    } else {
        $amps = false;
    }
    $parts = explode('?', $uri);
    // If is_front_page(), redirection will fail
    // During ajax, is_front_page() returns always false
    // So we test on the existence of a page id ( a single / ) instead
    // If no slash found, its http://mysite.com/wppaspec/.... this will fail: return xuri
    $temp = $parts[0];
    // Befor the ?
    $temp = rtrim($temp, '/');
    // remove potential trailing slash
    $temp = str_replace('//', '', $temp);
    // Remove //
    if (strpos($temp, '/') === false) {
        return $xuri;
        // return original
    }
    $args = explode('&', $parts[1]);
    $order = array('occur', 'woccur', 'searchstring', 'supersearch', 'topten', 'lasten', 'comten', 'featen', 'lang', 'single', 'tag', 'photos-only', 'albums-only', 'rel', 'relcount', 'upldr', 'owner', 'rootsearch', 'slide', 'cover', 'page', 'album', 'photo', 'hilite', 'calendar', 'caldate', 'debug', 'inv');
    $uri = $parts[0] . '?';
    $first = true;
    foreach ($order as $item) {
        foreach (array_keys($args) as $argidx) {
            if (strpos($args[$argidx], $item) === 0 || strpos($args[$argidx], 'wppa-' . $item) === 0) {
                if (!$first) {
                    $uri .= '&';
                }
                $uri .= $args[$argidx];
                unset($args[$argidx]);
                $first = false;
            }
        }
    }
    foreach ($args as $arg) {
        // append unprocessed items
        $uri .= '&' . $arg;
    }
    if ($amps) {
        $uri = str_replace('&', '&amp;', $uri);
    }
    // First filter for short query args
    $uri = wppa_trim_wppa_($uri);
    /*	if ( wppa_switch( 'use_short_qargs' ) ) {
    		$uri = str_replace( '?wppa-', '?', $uri );
    		$uri = str_replace( '&amp;wppa-', '&amp;', $uri );
    		$uri = str_replace( '&wppa-', '&', $uri );
    	}
    */
    // Now filter for album names in urls
    if (wppa_switch('use_album_names_in_urls')) {
        $apos = strpos($uri, 'album=');
        if ($apos !== false) {
            $start = $apos + '6';
            $end = strpos($uri, '&', $start);
        }
        $before = substr($uri, 0, $start);
        if ($end) {
            $albnum = substr($uri, $start, $end - $start);
            if (wppa_is_int($albnum) && $albnum > '0') {
                // Can convert single positive integer album ids only
                $after = substr($uri, $end);
                $albnam = stripslashes(wppa_get_album_item($albnum, 'name'));
                $albnam = wppa_encode_uri_component($albnam);
                $uri = $before . $albnam . $after;
            }
        } else {
            $albnum = substr($uri, $start);
            if (wppa_is_int($albnum) && $albnum > '0') {
                // Can convert single positive integer album ids only
                $albnam = stripslashes(wppa_get_album_item($albnum, 'name'));
                $albnam = wppa_encode_uri_component($albnam);
                $uri = $before . $albnam;
            }
        }
    }
    // Now filter for photo names in urls
    if (wppa_switch('use_photo_names_in_urls')) {
        $start = 0;
        $end = 0;
        $ppos = strpos($uri, 'photo=');
        if ($ppos !== false) {
            $start = $ppos + '6';
            $end = strpos($uri, '&', $start);
        }
        $before = substr($uri, 0, $start);
        if ($end) {
            $id = substr($uri, $start, $end - $start);
            if (wppa_is_int($id)) {
                // Can convert single integer photo ids only
                $after = substr($uri, $end);
                $pname = stripslashes(wppa_get_photo_item($id, 'name'));
                $pname = wppa_encode_uri_component($pname);
                $uri = $before . $pname . $after;
            }
        } else {
            $id = substr($uri, $start);
            if (wppa_is_int($id)) {
                // Can convert single integer photo ids only
                $pname = stripslashes(wppa_get_photo_item($id, 'name'));
                $pname = wppa_encode_uri_component($pname);
                $uri = $before . $pname;
            }
        }
    }
    // Now urlencode for funny chars
    $uri = str_replace(array(' ', '[', ']'), array('%20', '%5B', '%5D'), $uri);
    // Now the actual conversion to pretty links
    if (!wppa_switch('wppa_use_pretty_links')) {
        return $uri;
    }
    if (!get_option('permalink_structure')) {
        return $uri;
    }
    // Leaving the next line out gives 404 on pretty links under certain circumstances.
    // Can not reproduce and also do not understand why, and do not remember why i have put it in.
    //
    // nov 5 2014: changed add_action to test on redirection form init to pplugins_loaded.
    // also skipped if ( ! isset($_ENV["SCRIPT_URI"]) ) return; in redirect test. See wpp-non-admin.php. Seems to work now
    //	if ( ! isset($_ENV["SCRIPT_URI"]) ) return $uri;
    // Do some preprocessing
    $uri = str_replace('&amp;', '&', $uri);
    $uri = str_replace('?wppa-', '?', $uri);
    $uri = str_replace('&wppa-', '&', $uri);
    // Test if querystring exists
    $qpos = stripos($uri, '?');
    if (!$qpos) {
        return $uri;
    }
    // Make sure we end without '/'
    $newuri = trim(substr($uri, 0, $qpos), '/');
    $newuri .= '/wppaspec';
    // explode querystring
    $args = explode('&', substr($uri, $qpos + 1));
    $support = array('album', 'photo', 'slide', 'cover', 'occur', 'woccur', 'page', 'searchstring', 'supersearch', 'topten', 'lasten', 'comten', 'featen', 'lang', 'single', 'tag', 'photos-only', 'albums-only', 'debug', 'rel', 'relcount', 'upldr', 'owner', 'rootsearch', 'hilite', 'calendar', 'caldate', 'inv');
    if (count($args) > 0) {
        foreach ($args as $arg) {
            $t = explode('=', $arg);
            $code = $t['0'];
            if (isset($t['1'])) {
                $val = $t['1'];
            } else {
                $val = false;
            }
            if (in_array($code, $support)) {
                $newuri .= '/';
                switch ($code) {
                    case 'album':
                        $newuri .= 'ab';
                        break;
                    case 'photo':
                        $newuri .= 'pt';
                        break;
                    case 'slide':
                        $newuri .= 'sd';
                        break;
                    case 'cover':
                        $newuri .= 'cv';
                        break;
                    case 'occur':
                        $newuri .= 'oc';
                        break;
                    case 'woccur':
                        $newuri .= 'wo';
                        break;
                    case 'page':
                        $newuri .= 'pg';
                        break;
                    case 'searchstring':
                        $newuri .= 'ss';
                        break;
                    case 'supersearch':
                        $newuri .= 'su';
                        break;
                    case 'topten':
                        $newuri .= 'tt';
                        break;
                    case 'lasten':
                        $newuri .= 'lt';
                        break;
                    case 'comten':
                        $newuri .= 'ct';
                        break;
                    case 'featen':
                        $newuri .= 'ft';
                        break;
                    case 'lang':
                        $newuri .= 'ln';
                        break;
                    case 'single':
                        $newuri .= 'si';
                        break;
                    case 'tag':
                        $newuri .= 'tg';
                        break;
                    case 'photos-only':
                        $newuri .= 'po';
                        break;
                    case 'albums-only':
                        $newuri .= 'ao';
                        break;
                    case 'debug':
                        $newuri .= 'db';
                        break;
                    case 'rel':
                        $newuri .= 'rl';
                        break;
                    case 'relcount':
                        $newuri .= 'rc';
                        break;
                    case 'upldr':
                        $newuri .= 'ul';
                        break;
                    case 'owner':
                        $newuri .= 'ow';
                        break;
                    case 'rootsearch':
                        $newuri .= 'rt';
                        break;
                    case 'hilite':
                        $newuri .= 'hl';
                        break;
                    case 'calendar':
                        $newuri .= 'ca';
                        break;
                    case 'caldate':
                        $newuri .= 'cd';
                        break;
                    case 'inv':
                        $newuri .= 'in';
                        break;
                }
                if ($val !== false) {
                    if ($code == 'searchstring') {
                        $newuri .= str_replace(' ', '_', $val);
                    } else {
                        $newuri .= $val;
                    }
                }
            }
        }
    }
    return $newuri;
}
function wppa_get_get($index)
{
    static $wppa_get_get_cache;
    // Found this already?
    if (isset($wppa_get_get_cache[$index])) {
        return $wppa_get_get_cache[$index];
    }
    // See if set
    if (isset($_GET['wppa-' . $index])) {
        // New syntax first
        $result = $_GET['wppa-' . $index];
    } elseif (isset($_GET[$index])) {
        // Old syntax
        $result = $_GET[$index];
    } else {
        return false;
    }
    // Not set
    if ($result == 'nil') {
        return false;
    }
    // Nil simulates not set
    if (!strlen($result)) {
        $result = '1';
    }
    // Set but no value
    // Sanitize
    $result = strip_tags($result);
    if (strpos($result, '<?') !== false) {
        die('Security check failure #191');
    }
    if (strpos($result, '?>') !== false) {
        die('Security check failure #192');
    }
    // Post processing needed?
    if ($index == 'photo' && !wppa_is_int($result)) {
        // Encrypted?
        $result = wppa_decrypt_photo($result);
        // By name?
        $result = wppa_get_photo_id_by_name($result, wppa_get_album_id_by_name(wppa_get_get('album')));
        if (!$result) {
            return false;
        }
        // Non existing photo, treat as not set
    }
    if ($index == 'album') {
        // Encrypted?
        $result = wppa_decrypt_album($result);
        if (!wppa_is_int($result)) {
            $temp = wppa_get_album_id_by_name($result);
            if (wppa_is_int($temp) && $temp > '0') {
                $result = $temp;
            } elseif (!wppa_series_to_array($result)) {
                $result = false;
            }
        }
    }
    // Save in cache
    $wppa_get_get_cache[$index] = $result;
    return $result;
}
function wppa_get_album_id_by_name($xname, $report_dups = false)
{
    global $wpdb;
    global $allalbums;
    if (wppa_is_int($xname)) {
        return $xname;
        // Already numeric
    }
    if (wppa_is_enum($xname)) {
        return $xname;
        // Is enumeration
    }
    $name = wppa_decode_uri_component($xname);
    $name = str_replace('\'', '%', $name);
    // A trick for single quotes
    $name = str_replace('"', '%', $name);
    // A trick for double quotes
    $name = stripslashes($name);
    $albs = $wpdb->get_results("SELECT `id` FROM `" . WPPA_ALBUMS . "` WHERE `name` LIKE '%" . $name . "%'", ARRAY_A);
    if ($albs) {
        if (count($albs == 1)) {
            wppa_dbg_msg('Alb ' . $albs[0]['id'], ' found for ' . $xname);
            $aid = $albs[0]['id'];
        } else {
            wppa_dbg_msg('Dups found for ' . $xname);
            if ($report_dups) {
                $aid = false;
            } else {
                $aid = $albs[0]['id'];
            }
        }
    } else {
        $aid = false;
    }
    if ($aid) {
        wppa_dbg_msg('Aid ' . $aid . ' found for ' . $name);
    } else {
        wppa_dbg_msg('No aid found for ' . $name);
    }
    return $aid;
}
function wppa_do_maintenance_proc($slug)
{
    global $wpdb;
    global $thumb;
    global $wppa_opt;
    global $wppa_session;
    global $wppa_supported_video_extensions;
    global $wppa_supported_audio_extensions;
    // Check for multiple maintenance procs
    if (!wppa_switch('wppa_maint_ignore_concurrency_error')) {
        $all_slugs = array('wppa_remake_index_albums', 'wppa_remove_empty_albums', 'wppa_remake_index_photos', 'wppa_apply_new_photodesc_all', 'wppa_append_to_photodesc', 'wppa_remove_from_photodesc', 'wppa_remove_file_extensions', 'wppa_readd_file_extensions', 'wppa_regen_thumbs', 'wppa_rerate', 'wppa_recup', 'wppa_file_system', 'wppa_cleanup', 'wppa_remake', 'wppa_list_index', 'wppa_blacklist_user', 'wppa_un_blacklist_user', 'wppa_rating_clear', 'wppa_viewcount_clear', 'wppa_iptc_clear', 'wppa_exif_clear', 'wppa_watermark_all', 'wppa_create_all_autopages', 'wppa_leading_zeros', 'wppa_add_gpx_tag', 'wppa_optimize_ewww', 'wppa_comp_sizes', 'wppa_edit_tag');
        foreach (array_keys($all_slugs) as $key) {
            if ($all_slugs[$key] != $slug) {
                if (get_option($all_slugs[$key] . '_togo', '0')) {
                    // Process running
                    return __('You can run only one maintenance procedure at a time', 'wppa') . '||' . $slug . '||' . __('Error', 'wppa') . '||' . '' . '||' . '';
                }
            }
        }
    }
    // Lock this proc
    update_option($slug . '_user', wppa_get_user());
    // Initialize
    $endtime = time() + '5';
    // Allow for 5 seconds
    $chunksize = '1000';
    $lastid = strval(intval(get_option($slug . '_last', '0')));
    $errtxt = '';
    $id = '0';
    $topid = '0';
    $reload = '';
    if (!isset($wppa_session)) {
        $wppa_session = array();
    }
    if (!isset($wppa_session[$slug . '_fixed'])) {
        $wppa_session[$slug . '_fixed'] = '0';
    }
    if (!isset($wppa_session[$slug . '_deleted'])) {
        $wppa_session[$slug . '_deleted'] = '0';
    }
    if (!isset($wppa_session[$slug . '_skipped'])) {
        $wppa_session[$slug . '_skipped'] = '0';
    }
    if ($lastid == '0') {
        $wppa_session[$slug . '_fixed'] = '0';
        $wppa_session[$slug . '_deleted'] = '0';
        $wppa_session[$slug . '_skipped'] = '0';
    }
    // Pre-processing needed?
    if ($lastid == '0') {
        switch ($slug) {
            case 'wppa_remake_index_albums':
                $wpdb->query("UPDATE `" . WPPA_INDEX . "` SET `albums` = ''");
                break;
            case 'wppa_remake_index_photos':
                $wpdb->query("UPDATE `" . WPPA_INDEX . "` SET `photos` = ''");
                wppa_index_compute_skips();
                break;
            case 'wppa_recup':
                $wpdb->query("DELETE FROM `" . WPPA_IPTC . "` WHERE `photo` <> '0'");
                $wpdb->query("DELETE FROM `" . WPPA_EXIF . "` WHERE `photo` <> '0'");
                break;
            case 'wppa_file_system':
                if (get_option('wppa_file_system') == 'flat') {
                    update_option('wppa_file_system', 'to-tree');
                }
                if (get_option('wppa_file_system') == 'tree') {
                    update_option('wppa_file_system', 'to-flat');
                }
                break;
            case 'wppa_cleanup':
                $orphan_album = get_option('wppa_orphan_album', '0');
                $album_exists = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM`" . WPPA_ALBUMS . "` WHERE `id` = %s", $orphan_album));
                if (!$album_exists) {
                    $orphan_album = false;
                }
                if (!$orphan_album) {
                    $orphan_album = wppa_create_album_entry(array('name' => __('Orphan photos', 'wppa'), 'a_parent' => '-1', 'description' => __('This album contains refound lost photos', 'wppa')));
                    update_option('wppa_orphan_album', $orphan_album);
                }
                break;
        }
    }
    // Dispatch on albums / photos / single actions
    switch ($slug) {
        case 'wppa_remake_index_albums':
        case 'wppa_remove_empty_albums':
            // Process albums
            $table = WPPA_ALBUMS;
            $topid = $wpdb->get_var("SELECT `id` FROM `" . WPPA_ALBUMS . "` ORDER BY `id` DESC LIMIT 1");
            $albums = $wpdb->get_results("SELECT * FROM `" . WPPA_ALBUMS . "` WHERE `id` > " . $lastid . " ORDER BY `id` LIMIT 100", ARRAY_A);
            wppa_cache_album('add', $albums);
            if ($albums) {
                foreach ($albums as $album) {
                    $id = $album['id'];
                    switch ($slug) {
                        case 'wppa_remake_index_albums':
                            wppa_index_add('album', $id);
                            break;
                        case 'wppa_remove_empty_albums':
                            $p = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s", $id));
                            $a = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_ALBUMS . "` WHERE `a_parent` = %s", $id));
                            if (!$a && !$p) {
                                $wpdb->query($wpdb->prepare("DELETE FROM `" . WPPA_ALBUMS . "` WHERE `id` = %s", $id));
                                wppa_delete_album_source($id);
                                wppa_flush_treecounts($id);
                                wppa_index_remove('album', $id);
                            }
                            break;
                    }
                    // Test for timeout / ready
                    $lastid = $id;
                    update_option($slug . '_last', $lastid);
                    if (time() > $endtime) {
                        break;
                    }
                    // Time out
                }
            } else {
                // Nothing to do, Done anyway
                $lastid = $topid;
            }
            break;
            // End process albums
        // End process albums
        case 'wppa_remake_index_photos':
            $chunksize = '100';
        case 'wppa_apply_new_photodesc_all':
        case 'wppa_append_to_photodesc':
        case 'wppa_remove_from_photodesc':
        case 'wppa_remove_file_extensions':
        case 'wppa_readd_file_extensions':
        case 'wppa_regen_thumbs':
        case 'wppa_rerate':
        case 'wppa_recup':
        case 'wppa_file_system':
        case 'wppa_cleanup':
        case 'wppa_remake':
        case 'wppa_watermark_all':
        case 'wppa_create_all_autopages':
        case 'wppa_leading_zeros':
        case 'wppa_add_gpx_tag':
        case 'wppa_optimize_ewww':
        case 'wppa_comp_sizes':
        case 'wppa_edit_tag':
            // Process photos
            $table = WPPA_PHOTOS;
            if ($slug == 'wppa_cleanup') {
                $topid = get_option('wppa_' . WPPA_PHOTOS . '_lastkey', '1') * 10;
                $photos = array();
                for ($i = $lastid + '1'; $i <= $topid; $i++) {
                    $photos[]['id'] = $i;
                }
            } else {
                $topid = $wpdb->get_var("SELECT `id` FROM `" . WPPA_PHOTOS . "` ORDER BY `id` DESC LIMIT 1");
                $photos = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `id` > " . $lastid . " ORDER BY `id` LIMIT " . $chunksize, ARRAY_A);
            }
            if ($slug == 'wppa_edit_tag') {
                $edit_tag = get_option('wppa_tag_to_edit');
                $new_tag = get_option('wppa_new_tag_value');
            }
            if (!$photos && $slug == 'wppa_file_system') {
                $fs = get_option('wppa_file_system');
                if ($fs == 'to-tree') {
                    $to = 'tree';
                } elseif ($fs == 'to-flat') {
                    $to = 'flat';
                } else {
                    $to = $fs;
                }
            }
            if ($photos) {
                foreach ($photos as $photo) {
                    $thumb = $photo;
                    // Make globally known
                    $id = $photo['id'];
                    switch ($slug) {
                        case 'wppa_remake_index_photos':
                            wppa_index_add('photo', $id);
                            break;
                        case 'wppa_apply_new_photodesc_all':
                            $value = $wppa_opt['wppa_newphoto_description'];
                            $description = trim($value);
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_append_to_photodesc':
                            $value = trim($wppa_opt['wppa_append_text']);
                            if (!$value) {
                                return 'Unexpected error: missing text to append||' . $slug . '||Error||0';
                            }
                            $description = rtrim($photo['description'] . ' ' . $value);
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_remove_from_photodesc':
                            $value = trim($wppa_opt['wppa_remove_text']);
                            if (!$value) {
                                return 'Unexpected error: missing text to remove||' . $slug . '||Error||0';
                            }
                            $description = rtrim(str_replace($value, '', $photo['description']));
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_remove_file_extensions':
                            if (!wppa_is_video($id)) {
                                $name = str_replace(array('.jpg', '.png', '.gif', '.JPG', '.PNG', '.GIF'), '', $photo['name']);
                                if ($name != $photo['name']) {
                                    // Modified photo name
                                    $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name, $id));
                                }
                            }
                            break;
                        case 'wppa_readd_file_extensions':
                            if (!wppa_is_video($id)) {
                                $name = str_replace(array('.jpg', '.png', 'gif', '.JPG', '.PNG', '.GIF'), '', $photo['name']);
                                if ($name == $photo['name']) {
                                    // Name had no fileextension
                                    $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name . '.' . $photo['ext'], $id));
                                }
                            }
                            break;
                        case 'wppa_regen_thumbs':
                            if (!wppa_is_video($id) || file_exists(str_replace('xxx', 'jpg', wppa_get_photo_path($id)))) {
                                wppa_create_thumbnail($id);
                            }
                            break;
                        case 'wppa_rerate':
                            wppa_rate_photo($id);
                            break;
                        case 'wppa_recup':
                            $a_ret = wppa_recuperate($id);
                            if ($a_ret['iptcfix']) {
                                $wppa_session[$slug . '_fixed']++;
                            }
                            if ($a_ret['exiffix']) {
                                $wppa_session[$slug . '_fixed']++;
                            }
                            break;
                        case 'wppa_file_system':
                            $fs = get_option('wppa_file_system');
                            if ($fs == 'to-tree' || $fs == 'to-flat') {
                                if ($fs == 'to-tree') {
                                    $from = 'flat';
                                    $to = 'tree';
                                } else {
                                    $from = 'tree';
                                    $to = 'flat';
                                }
                                // Media files
                                if (wppa_is_multi($id)) {
                                    // Can NOT use wppa_has_audio() or wppa_is_video(), they use wppa_get_photo_path() without fs switch!!
                                    $exts = array_merge($wppa_supported_video_extensions, $wppa_supported_audio_extensions);
                                    $pathfrom = wppa_get_photo_path($id, $from);
                                    $pathto = wppa_get_photo_path($id, $to);
                                    //	wppa_log( 'dbg', 'Trying: '.$pathfrom );
                                    foreach ($exts as $ext) {
                                        if (is_file(str_replace('.xxx', '.' . $ext, $pathfrom))) {
                                            //	wppa_log( 'dbg',  str_replace( '.xxx', '.'.$ext, $pathfrom ).' -> '.str_replace( '.xxx', '.'.$ext, $pathto ));
                                            @rename(str_replace('.xxx', '.' . $ext, $pathfrom), str_replace('.xxx', '.' . $ext, $pathto));
                                        }
                                    }
                                }
                                // Poster / photo
                                if (file_exists(wppa_fix_poster_ext(wppa_get_photo_path($id, $from), $id))) {
                                    @rename(wppa_fix_poster_ext(wppa_get_photo_path($id, $from), $id), wppa_fix_poster_ext(wppa_get_photo_path($id, $to), $id));
                                }
                                // Thumbnail
                                if (file_exists(wppa_fix_poster_ext(wppa_get_thumb_path($id, $from), $id))) {
                                    @rename(wppa_fix_poster_ext(wppa_get_thumb_path($id, $from), $id), wppa_fix_poster_ext(wppa_get_thumb_path($id, $to), $id));
                                }
                            }
                            break;
                        case 'wppa_cleanup':
                            $photo_files = glob(WPPA_UPLOAD_PATH . '/' . $id . '.*');
                            // Remove dirs
                            if ($photo_files) {
                                foreach (array_keys($photo_files) as $key) {
                                    if (is_dir($photo_files[$key])) {
                                        unset($photo_files[$key]);
                                    }
                                }
                            }
                            // files left? process
                            if ($photo_files) {
                                foreach ($photo_files as $photo_file) {
                                    $basename = basename($photo_file);
                                    $ext = substr($basename, strpos($basename, '.') + '1');
                                    if (!$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $id))) {
                                        // no db entry for this photo
                                        if (wppa_is_id_free(WPPA_PHOTOS, $id)) {
                                            if (wppa_create_photo_entry(array('id' => $id, 'album' => $orphan_album, 'ext' => $ext, 'filename' => $basename))) {
                                                // Can create entry
                                                $wppa_session[$slug . '_fixed']++;
                                                // Bump counter
                                                wppa_log('Debug', 'Lost photo file ' . $photo_file . ' recovered');
                                            } else {
                                                wppa_log('Debug', 'Unable to recover lost photo file ' . $photo_file . ' Create photo entry failed');
                                            }
                                        } else {
                                            wppa_log('Debug', 'Could not recover lost photo file ' . $photo_file . ' The id is not free');
                                        }
                                    }
                                }
                            }
                            break;
                        case 'wppa_remake':
                            if (wppa_remake_files('', $id)) {
                                $wppa_session[$slug . '_fixed']++;
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_watermark_all':
                            if (!wppa_is_video($id)) {
                                if (wppa_add_watermark($id)) {
                                    wppa_create_thumbnail($id);
                                    // create new thumb
                                    $wppa_session[$slug . '_fixed']++;
                                } else {
                                    $wppa_session[$slug . '_skipped']++;
                                }
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_create_all_autopages':
                            wppa_get_the_auto_page($id);
                            break;
                        case 'wppa_leading_zeros':
                            $name = $photo['name'];
                            if (wppa_is_int($name)) {
                                $target_len = wppa_opt('wppa_zero_numbers');
                                $name = strval(intval($name));
                                while (strlen($name) < $target_len) {
                                    $name = '0' . $name;
                                }
                            }
                            if ($name !== $photo['name']) {
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name, $id));
                            }
                            break;
                        case 'wppa_add_gpx_tag':
                            $tags = $photo['tags'];
                            $temp = explode('/', $photo['location']);
                            if (!isset($temp['2'])) {
                                $temp['2'] = false;
                            }
                            if (!isset($temp['3'])) {
                                $temp['3'] = false;
                            }
                            $lat = $temp['2'];
                            $lon = $temp['3'];
                            if ($lat < 0.01 && $lat > -0.01 && $lon < 0.01 && $lon > -0.01) {
                                $lat = false;
                                $lon = false;
                            }
                            if ($photo['location'] && strpos($tags, 'Gpx') === false && $lat && $lon) {
                                // Add it
                                $tags = wppa_sanitize_tags($tags . ',Gpx');
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                wppa_index_update('photo', $photo['id']);
                                wppa_clear_taglist();
                            } elseif (strpos($tags, 'Gpx') !== false && !$lat && !$lon) {
                                // Remove it
                                $tags = wppa_sanitize_tags(str_replace('Gpx', '', $tags));
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                wppa_index_update('photo', $photo['id']);
                                wppa_clear_taglist();
                            }
                            break;
                        case 'wppa_optimize_ewww':
                            $file = wppa_get_photo_path($photo['id']);
                            if (is_file($file)) {
                                ewww_image_optimizer($file, 4, false, false, false);
                            }
                            $file = wppa_get_thumb_path($photo['id']);
                            if (is_file($file)) {
                                ewww_image_optimizer($file, 4, false, false, false);
                            }
                            break;
                        case 'wppa_comp_sizes':
                            $tx = 0;
                            $ty = 0;
                            $px = 0;
                            $py = 0;
                            $file = wppa_get_photo_path($photo['id']);
                            if (is_file($file)) {
                                $temp = getimagesize($file);
                                if (is_array($temp)) {
                                    $px = $temp[0];
                                    $py = $temp[1];
                                }
                            }
                            $file = wppa_get_thumb_path($photo['id']);
                            if (is_file($file)) {
                                $temp = getimagesize($file);
                                if (is_array($temp)) {
                                    $tx = $temp[0];
                                    $ty = $temp[1];
                                }
                            }
                            wppa_update_photo(array('id' => $photo['id'], 'thumbx' => $tx, 'thumby' => $ty, 'photox' => $px, 'photoy' => $py));
                            break;
                        case 'wppa_edit_tag':
                            $phototags = explode(',', wppa_get_photo_item($photo['id'], 'tags'));
                            if (in_array($edit_tag, $phototags)) {
                                foreach (array_keys($phototags) as $key) {
                                    if ($phototags[$key] == $edit_tag) {
                                        $phototags[$key] = $new_tag;
                                    }
                                }
                                $tags = wppa_sanitize_tags(implode(',', $phototags));
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                $wppa_session[$slug . '_fixed']++;
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                    }
                    // Test for timeout / ready
                    $lastid = $id;
                    update_option($slug . '_last', $lastid);
                    if (time() > $endtime) {
                        break;
                    }
                    // Time out
                }
            } else {
                // Nothing to do, Done anyway
                $lastid = $topid;
                wppa_log('Debug', 'Maintenance proc ' . $slug . ': Done!');
            }
            break;
            // End process photos
            // Single action maintenance modules
            //		case 'wppa_list_index':
            //			break;
            //		case 'wppa_blacklist_user':
            //			break;
            //		case 'wppa_un_blacklist_user':
            //			break;
            //		case 'wppa_rating_clear':
            //			break;
            //		case 'wppa_viewcount_clear':
            //			break;
            //		case 'wppa_iptc_clear':
            //			break;
            //		case 'wppa_exif_clear':
            //			break;
        // End process photos
        // Single action maintenance modules
        //		case 'wppa_list_index':
        //			break;
        //		case 'wppa_blacklist_user':
        //			break;
        //		case 'wppa_un_blacklist_user':
        //			break;
        //		case 'wppa_rating_clear':
        //			break;
        //		case 'wppa_viewcount_clear':
        //			break;
        //		case 'wppa_iptc_clear':
        //			break;
        //		case 'wppa_exif_clear':
        //			break;
        default:
            $errtxt = 'Unimplemented maintenance slug: ' . strip_tags($slug);
    }
    // either $albums / $photos has been exhousted ( for this try ) or time is up
    if ($slug == 'wppa_cleanup') {
        $togo = $topid - $lastid;
    } else {
        $togo = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . $table . "` WHERE `id` > %s ", $lastid));
    }
    $status = $togo ? 'Pending' : 'Ready';
    if ($togo) {
        update_option($slug . '_togo', $togo);
        update_option($slug . '_status', $status);
    } else {
        // Really done
        // Report fixed/skipped/deleted
        if ($wppa_session[$slug . '_fixed']) {
            $status .= ' fixed:' . $wppa_session[$slug . '_fixed'];
            unset($wppa_session[$slug . '_fixed']);
        }
        if ($wppa_session[$slug . '_skipped']) {
            $status .= ' skipped:' . $wppa_session[$slug . '_skipped'];
            unset($wppa_session[$slug . '_skipped']);
        }
        if ($wppa_session[$slug . '_deleted']) {
            $status .= ' deleted:' . $wppa_session[$slug . '_deleted'];
            unset($wppa_session[$slug . '_deleted']);
        }
        // Re-Init options
        delete_option($slug . '_togo', '');
        delete_option($slug . '_status', '');
        delete_option($slug . '_last', '0');
        delete_option($slug . '_user', '');
        // Post-processing needed?
        switch ($slug) {
            case 'wppa_remake_index_albums':
            case 'wppa_remake_index_photos':
                $wpdb->query("DELETE FROM `" . WPPA_INDEX . "` WHERE `albums` = '' AND `photos` = ''");
                // Remove empty entries
                delete_option('wppa_index_need_remake');
                break;
            case 'wppa_apply_new_photodesc_all':
            case 'wppa_append_to_photodesc':
            case 'wppa_remove_from_photodesc':
                update_option('wppa_remake_index_photos_status', __('Required', 'wppa'));
                break;
            case 'wppa_regen_thumbs':
                wppa_bump_thumb_rev();
                break;
            case 'wppa_file_system':
                wppa_update_option('wppa_file_system', $to);
                $reload = 'reload';
                break;
            case 'wppa_remake':
                wppa_bump_photo_rev();
                wppa_bump_thumb_rev();
                break;
            case 'wppa_edit_tag':
                wppa_clear_taglist();
                $reload = 'reload';
                break;
        }
    }
    return $errtxt . '||' . $slug . '||' . $status . '||' . $togo . '||' . $reload;
}
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;
            case 'crypt':
                $doit = true;
                break;
            case 'owner':
                $doit = true;
                break;
            case 'album':
                if (wppa_is_int($itemvalue) && $itemvalue > 0) {
                    $doit = true;
                } else {
                    wppa_log('err', 'Invalid album id found in wppa_update_album(): ' . $itemvalue);
                }
                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_fe_edit_new_style($photo)
{
    $items = array('name', 'description', 'tags', 'custom_0', 'custom_1', 'custom_2', 'custom_3', 'custom_4', 'custom_5', 'custom_6', 'custom_7', 'custom_8', 'custom_9');
    $titles = array(__('Name', 'wp-photo-album-plus'), __('Description', 'wp-photo-album-plus'), __('Tags', 'wp-photo-album-plus'), apply_filters('translate_text', wppa_opt('custom_caption_0')), apply_filters('translate_text', wppa_opt('custom_caption_1')), apply_filters('translate_text', wppa_opt('custom_caption_2')), apply_filters('translate_text', wppa_opt('custom_caption_3')), apply_filters('translate_text', wppa_opt('custom_caption_4')), apply_filters('translate_text', wppa_opt('custom_caption_5')), apply_filters('translate_text', wppa_opt('custom_caption_6')), apply_filters('translate_text', wppa_opt('custom_caption_7')), apply_filters('translate_text', wppa_opt('custom_caption_8')), apply_filters('translate_text', wppa_opt('custom_caption_9')));
    $types = array('text', 'textarea', 'text', 'text', 'text', 'text', 'text', 'text', 'text', 'text', 'text', 'text', 'text');
    $doit = array(wppa_switch('fe_edit_name'), wppa_switch('fe_edit_desc'), wppa_switch('fe_edit_tags'), wppa_switch('custom_edit_0'), wppa_switch('custom_edit_1'), wppa_switch('custom_edit_2'), wppa_switch('custom_edit_3'), wppa_switch('custom_edit_4'), wppa_switch('custom_edit_5'), wppa_switch('custom_edit_6'), wppa_switch('custom_edit_7'), wppa_switch('custom_edit_8'), wppa_switch('custom_edit_9'));
    // Open page
    echo '<div' . ' style="width:100%;margin-top:8px;padding:8px;display:block;box-sizing:border-box;background-color:#fff;"' . ' >' . '<h3>' . '<img' . ' style="height:50px;"' . ' src="' . wppa_get_thumb_url($photo) . '"' . ' alt="' . $photo . '"' . ' />' . '&nbsp;&nbsp;' . wppa_opt('fe_edit_caption') . '</h3>';
    // Open form
    echo '<form' . ' >' . '<input' . ' type="hidden"' . ' id="wppa-nonce-' . $photo . '"' . ' name="wppa-nonce"' . ' value="' . wp_create_nonce('wppa-nonce-' . $photo) . '"' . ' />';
    // Get custom data
    $custom = wppa_get_photo_item($photo, 'custom');
    if ($custom) {
        $custom_data = unserialize($custom);
    } else {
        $custom_data = array('', '', '', '', '', '', '', '', '', '');
    }
    // Items
    foreach (array_keys($items) as $idx) {
        if ($titles[$idx] && $doit[$idx]) {
            echo '<h6>' . $titles[$idx] . '</h6>';
            if (wppa_is_int(substr($items[$idx], -1))) {
                $value = stripslashes($custom_data[substr($items[$idx], -1)]);
            } else {
                $value = wppa_get_photo_item($photo, $items[$idx]);
                if ($items[$idx] == 'tags') {
                    $value = trim($value, ',');
                }
            }
            if ($types[$idx] == 'text') {
                echo '<input' . ' type="text"' . ' style="width:100%;"' . ' id="' . $items[$idx] . '"' . ' name="' . $items[$idx] . '"' . ' value="' . esc_attr($value) . '"' . ' />';
            }
            if ($types[$idx] == 'textarea') {
                echo '<textarea' . ' style="width:100%;min-width:100%;max-width:100%;"' . ' id="' . $items[$idx] . '"' . ' name="' . $items[$idx] . '"' . ' >' . esc_textarea(stripslashes($value)) . '</textarea>';
            }
        }
    }
    // Submit
    echo '<input' . ' type="button"' . ' style="margin-top:8px;margin-right:8px;"' . ' value="' . esc_attr(__('Send', 'wp-photo-album-plus')) . '"' . ' onclick="wppaUpdatePhotoNew(' . $photo . ');document.location.reload(true);"' . ' />';
    // Cancel
    echo '<input' . ' type="button"' . ' style="margin-top:8px;"' . ' value="' . esc_attr(__('Cancel', 'wp-photo-album-plus')) . '"' . ' onclick="jQuery( \'.ui-button\' ).trigger(\'click\')"' . ' />';
    // Close form
    echo '</form>';
    // Close page
    echo '</div>';
}
function wppa_bump_viewcount($type, $id)
{
    global $wpdb;
    global $wppa_session;
    if (!wppa_switch('track_viewcounts')) {
        return;
    }
    if ($type != 'album' && $type != 'photo') {
        die('Illegal $type in wppa_bump_viewcount: ' . $type);
    }
    if ($type == 'album') {
        if (strlen($id) == 12) {
            $id = wppa_decrypt_album($id);
        }
    } else {
        if (strlen($id) == 12) {
            $id = wppa_decrypt_photo($id);
        }
    }
    if ($id < '1') {
        return;
    }
    // Not a wppa image
    if (!wppa_is_int($id)) {
        return;
    }
    // Not an integer
    if (!isset($wppa_session[$type])) {
        $wppa_session[$type] = array();
    }
    if (!isset($wppa_session[$type][$id])) {
        // This one not done yest
        $wppa_session[$type][$id] = true;
        // Mark as viewed
        if ($type == 'album') {
            $table = WPPA_ALBUMS;
        } else {
            $table = WPPA_PHOTOS;
        }
        $count = $wpdb->get_var("SELECT `views` FROM `" . $table . "` WHERE `id` = " . $id);
        $count++;
        $wpdb->query("UPDATE `" . $table . "` SET `views` = " . $count . " WHERE `id` = " . $id);
        wppa_dbg_msg('Bumped viewcount for ' . $type . ' ' . $id . ' to ' . $count, 'red');
        // If 'wppa_owner_to_name'
        if ($type == 'photo') {
            wppa_set_owner_to_name($id);
        }
    }
    wppa_save_session();
}
function wppa_do_maintenance_proc($slug)
{
    global $wpdb;
    global $wppa_session;
    global $wppa_supported_video_extensions;
    global $wppa_supported_audio_extensions;
    // Check for multiple maintenance procs
    if (!wppa_switch('maint_ignore_concurrency_error') && !wppa_is_cron()) {
        $all_slugs = array('wppa_remake_index_albums', 'wppa_remove_empty_albums', 'wppa_remake_index_photos', 'wppa_apply_new_photodesc_all', 'wppa_append_to_photodesc', 'wppa_remove_from_photodesc', 'wppa_remove_file_extensions', 'wppa_readd_file_extensions', 'wppa_all_ext_to_lower', 'wppa_regen_thumbs', 'wppa_rerate', 'wppa_recup', 'wppa_file_system', 'wppa_cleanup', 'wppa_remake', 'wppa_list_index', 'wppa_blacklist_user', 'wppa_un_blacklist_user', 'wppa_rating_clear', 'wppa_viewcount_clear', 'wppa_iptc_clear', 'wppa_exif_clear', 'wppa_watermark_all', 'wppa_create_all_autopages', 'wppa_delete_all_autopages', 'wppa_leading_zeros', 'wppa_add_gpx_tag', 'wppa_optimize_ewww', 'wppa_comp_sizes', 'wppa_edit_tag', 'wppa_sync_cloud', 'wppa_sanitize_tags', 'wppa_sanitize_cats', 'wppa_test_proc', 'wppa_crypt_photos', 'wppa_crypt_albums', 'wppa_create_o1_files', 'wppa_owner_to_name_proc', 'wppa_move_all_photos');
        foreach (array_keys($all_slugs) as $key) {
            if ($all_slugs[$key] != $slug) {
                if (get_option($all_slugs[$key] . '_togo', '0')) {
                    // Process running
                    return __('You can run only one maintenance procedure at a time', 'wp-photo-album-plus') . '||' . $slug . '||' . __('Error', 'wp-photo-album-plus') . '||' . '' . '||' . '';
                }
            }
        }
    }
    // Lock this proc
    if (wppa_is_cron()) {
        update_option($slug . '_user', 'cron-job');
        update_option($slug . '_lasttimestamp', time());
    } else {
        update_option($slug . '_user', wppa_get_user());
    }
    // Extend session
    wppa_extend_session();
    // Initialize
    // Cron job: 30 sec, realtime: 5 sec
    $endtime = wppa_is_cron() ? time() + '30' : time() + '5';
    $chunksize = '1000';
    $lastid = strval(intval(get_option($slug . '_last', '0')));
    $errtxt = '';
    $id = '0';
    $topid = '0';
    $reload = '';
    $to_delete_from_cloudinary = array();
    if (!isset($wppa_session)) {
        $wppa_session = array();
    }
    if (!isset($wppa_session[$slug . '_fixed'])) {
        $wppa_session[$slug . '_fixed'] = '0';
    }
    if (!isset($wppa_session[$slug . '_added'])) {
        $wppa_session[$slug . '_added'] = '0';
    }
    if (!isset($wppa_session[$slug . '_deleted'])) {
        $wppa_session[$slug . '_deleted'] = '0';
    }
    if (!isset($wppa_session[$slug . '_skipped'])) {
        $wppa_session[$slug . '_skipped'] = '0';
    }
    if ($lastid == '0') {
        $wppa_session[$slug . '_fixed'] = '0';
        $wppa_session[$slug . '_deleted'] = '0';
        $wppa_session[$slug . '_skipped'] = '0';
    }
    wppa_save_session();
    // Pre-processing needed?
    if ($lastid == '0') {
        if (wppa_is_cron()) {
            wppa_log('Obs', 'Cron job ' . $slug . ' started.');
        } else {
            wppa_log('Obs', 'Maintenance proc ' . $slug . ' started.');
        }
        switch ($slug) {
            case 'wppa_remake_index_albums':
                // Pre-Clear album index only if not cron
                if (!wppa_is_cron()) {
                    $wpdb->query("UPDATE `" . WPPA_INDEX . "` SET `albums` = ''");
                }
                break;
            case 'wppa_remake_index_photos':
                // Pre-Clear photo index only if not cron
                if (!wppa_is_cron()) {
                    $wpdb->query("UPDATE `" . WPPA_INDEX . "` SET `photos` = ''");
                }
                wppa_index_compute_skips();
                break;
            case 'wppa_recup':
                // Pre-Clear exif and iptc tables only if not cron
                if (!wppa_is_cron()) {
                    $wpdb->query("DELETE FROM `" . WPPA_IPTC . "` WHERE `photo` <> '0'");
                    $wpdb->query("DELETE FROM `" . WPPA_EXIF . "` WHERE `photo` <> '0'");
                }
                break;
            case 'wppa_file_system':
                if (get_option('wppa_file_system') == 'flat') {
                    update_option('wppa_file_system', 'to-tree');
                }
                if (get_option('wppa_file_system') == 'tree') {
                    update_option('wppa_file_system', 'to-flat');
                }
                break;
            case 'wppa_cleanup':
                $orphan_album = get_option('wppa_orphan_album', '0');
                $album_exists = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM`" . WPPA_ALBUMS . "` WHERE `id` = %s", $orphan_album));
                if (!$album_exists) {
                    $orphan_album = false;
                }
                if (!$orphan_album) {
                    $orphan_album = wppa_create_album_entry(array('name' => __('Orphan photos', 'wp-photo-album-plus'), 'a_parent' => '-1', 'description' => __('This album contains refound lost photos', 'wp-photo-album-plus')));
                    update_option('wppa_orphan_album', $orphan_album);
                }
                break;
            case 'wppa_sync_cloud':
                if (!wppa_get_present_at_cloudinary_a()) {
                    // Still Initializing
                    $status = 'Initializing';
                    if (!isset($wppa_session['fun-count'])) {
                        $wppa_session['fun-count'] = 0;
                    }
                    $wppa_session['fun-count'] = ($wppa_session['fun-count'] + 1) % 3;
                    for ($i = 0; $i < $wppa_session['fun-count']; $i++) {
                        $status .= '.';
                    }
                    $togo = 'all';
                    $reload = false;
                    echo '||' . $slug . '||' . $status . '||' . $togo . '||' . $reload;
                    wppa_exit();
                }
                break;
            case 'wppa_crypt_albums':
                update_option('wppa_album_crypt_0', wppa_get_unique_album_crypt());
                update_option('wppa_album_crypt_1', wppa_get_unique_album_crypt());
                update_option('wppa_album_crypt_2', wppa_get_unique_album_crypt());
                update_option('wppa_album_crypt_3', wppa_get_unique_album_crypt());
                update_option('wppa_album_crypt_9', wppa_get_unique_album_crypt());
                break;
            case 'wppa_owner_to_name_proc':
                if (!wppa_switch('owner_to_name')) {
                    echo __('Feature must be enabled in Table IV-A28 first', 'wp-photo-album-plus') . '||' . $slug . '||||||';
                    wppa_exit();
                }
                break;
            case 'wppa_move_all_photos':
                $fromalb = get_option('wppa_move_all_photos_from');
                if (!wppa_album_exists($fromalb)) {
                    echo sprintf(__('From album %d does not exist', 'wp-photo-album-plus'), $fromalb);
                    wppa_exit();
                }
                $toalb = get_option('wppa_move_all_photos_to');
                if (!wppa_album_exists($toalb)) {
                    echo sprintf(__('To album %d does not exist', 'wp-photo-album-plus'), $toalb);
                    wppa_exit();
                }
                if ($fromalb == $toalb) {
                    echo __('From and To albums are identical', 'wp-photo-album-plus');
                    wppa_exit();
                }
                break;
        }
        wppa_save_session();
    }
    // Dispatch on albums / photos / single actions
    switch ($slug) {
        case 'wppa_remake_index_albums':
        case 'wppa_remove_empty_albums':
        case 'wppa_sanitize_cats':
        case 'wppa_crypt_albums':
            // Process albums
            $table = WPPA_ALBUMS;
            $topid = $wpdb->get_var("SELECT `id` FROM `" . WPPA_ALBUMS . "` ORDER BY `id` DESC LIMIT 1");
            $albums = $wpdb->get_results("SELECT * FROM `" . WPPA_ALBUMS . "` WHERE `id` > " . $lastid . " ORDER BY `id` LIMIT 100", ARRAY_A);
            wppa_cache_album('add', $albums);
            if ($albums) {
                foreach ($albums as $album) {
                    $id = $album['id'];
                    switch ($slug) {
                        case 'wppa_remake_index_albums':
                            // If done as cron job, no initial clear has been done
                            if (wppa_is_cron()) {
                                wppa_index_remove('album', $id);
                            }
                            wppa_index_add('album', $id);
                            break;
                        case 'wppa_remove_empty_albums':
                            $p = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s", $id));
                            $a = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_ALBUMS . "` WHERE `a_parent` = %s", $id));
                            if (!$a && !$p) {
                                $wpdb->query($wpdb->prepare("DELETE FROM `" . WPPA_ALBUMS . "` WHERE `id` = %s", $id));
                                wppa_delete_album_source($id);
                                wppa_flush_treecounts($id);
                                wppa_index_remove('album', $id);
                            }
                            break;
                        case 'wppa_sanitize_cats':
                            $cats = $album['cats'];
                            if ($cats) {
                                wppa_update_album(array('id' => $album['id'], 'cats' => wppa_sanitize_tags($cats)));
                            }
                            break;
                        case 'wppa_crypt_albums':
                            wppa_update_album(array('id' => $album['id'], 'crypt' => wppa_get_unique_album_crypt()));
                            break;
                    }
                    // Test for timeout / ready
                    $lastid = $id;
                    update_option($slug . '_last', $lastid);
                    if (time() > $endtime) {
                        break;
                    }
                    // Time out
                }
            } else {
                // Nothing to do, Done anyway
                $lastid = $topid;
            }
            break;
            // End process albums
        // End process albums
        case 'wppa_remake_index_photos':
        case 'wppa_apply_new_photodesc_all':
        case 'wppa_append_to_photodesc':
        case 'wppa_remove_from_photodesc':
        case 'wppa_remove_file_extensions':
        case 'wppa_readd_file_extensions':
        case 'wppa_all_ext_to_lower':
        case 'wppa_regen_thumbs':
        case 'wppa_rerate':
        case 'wppa_recup':
        case 'wppa_file_system':
        case 'wppa_cleanup':
        case 'wppa_remake':
        case 'wppa_watermark_all':
        case 'wppa_create_all_autopages':
        case 'wppa_delete_all_autopages':
        case 'wppa_leading_zeros':
        case 'wppa_add_gpx_tag':
        case 'wppa_optimize_ewww':
        case 'wppa_comp_sizes':
        case 'wppa_edit_tag':
        case 'wppa_sync_cloud':
        case 'wppa_sanitize_tags':
        case 'wppa_crypt_photos':
        case 'wppa_test_proc':
        case 'wppa_create_o1_files':
        case 'wppa_owner_to_name_proc':
        case 'wppa_move_all_photos':
            // Process photos
            $table = WPPA_PHOTOS;
            if ($slug == 'wppa_cleanup') {
                $topid = get_option('wppa_' . WPPA_PHOTOS . '_lastkey', '1') * 10;
                $photos = array();
                for ($i = $lastid + '1'; $i <= $topid; $i++) {
                    $photos[]['id'] = $i;
                }
            } else {
                $topid = $wpdb->get_var("SELECT `id` FROM `" . WPPA_PHOTOS . "` ORDER BY `id` DESC LIMIT 1");
                $photos = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `id` > " . $lastid . " ORDER BY `id` LIMIT " . $chunksize, ARRAY_A);
            }
            if ($slug == 'wppa_edit_tag') {
                $edit_tag = get_option('wppa_tag_to_edit');
                $new_tag = get_option('wppa_new_tag_value');
            }
            if (!$photos && $slug == 'wppa_file_system') {
                $fs = get_option('wppa_file_system');
                if ($fs == 'to-tree') {
                    $to = 'tree';
                } elseif ($fs == 'to-flat') {
                    $to = 'flat';
                } else {
                    $to = $fs;
                }
            }
            if ($photos) {
                foreach ($photos as $photo) {
                    $thumb = $photo;
                    // Make globally known
                    $id = $photo['id'];
                    switch ($slug) {
                        case 'wppa_remake_index_photos':
                            // If done as cron job, no initial clear has been done
                            if (wppa_is_cron()) {
                                wppa_index_remove('photo', $id);
                            }
                            wppa_index_add('photo', $id);
                            break;
                        case 'wppa_apply_new_photodesc_all':
                            $value = wppa_opt('newphoto_description');
                            $description = trim($value);
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_append_to_photodesc':
                            $value = trim(wppa_opt('append_text'));
                            if (!$value) {
                                return 'Unexpected error: missing text to append||' . $slug . '||Error||0';
                            }
                            $description = rtrim($photo['description'] . ' ' . $value);
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_remove_from_photodesc':
                            $value = trim(wppa_opt('remove_text'));
                            if (!$value) {
                                return 'Unexpected error: missing text to remove||' . $slug . '||Error||0';
                            }
                            $description = rtrim(str_replace($value, '', $photo['description']));
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_remove_file_extensions':
                            if (!wppa_is_video($id)) {
                                $name = str_replace(array('.jpg', '.png', '.gif', '.JPG', '.PNG', '.GIF'), '', $photo['name']);
                                if ($name != $photo['name']) {
                                    // Modified photo name
                                    $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name, $id));
                                }
                            }
                            break;
                        case 'wppa_readd_file_extensions':
                            if (!wppa_is_video($id)) {
                                $name = str_replace(array('.jpg', '.png', 'gif', '.JPG', '.PNG', '.GIF'), '', $photo['name']);
                                if ($name == $photo['name']) {
                                    // Name had no fileextension
                                    $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name . '.' . $photo['ext'], $id));
                                }
                            }
                            break;
                        case 'wppa_all_ext_to_lower':
                            $EXT = wppa_get_photo_item($id, 'ext');
                            $ext = strtolower($EXT);
                            if ($EXT != $ext) {
                                wppa_update_photo(array('id' => $id, 'ext' => $ext));
                                $fixed_this = true;
                            }
                            $EXT = strtoupper($ext);
                            $rawpath = wppa_strip_ext(wppa_get_photo_path($id));
                            $rawthumb = wppa_strip_ext(wppa_get_thumb_path($id));
                            $fixed_this = false;
                            if (wppa_is_multi($id)) {
                            } else {
                                if (is_file($rawpath . '.' . $EXT)) {
                                    if (is_file($rawpath . '.' . $ext)) {
                                        unlink($rawpath . '.' . $EXT);
                                    } else {
                                        rename($rawpath . '.' . $EXT, $rawpath . '.' . $ext);
                                    }
                                    $fixed_this = true;
                                }
                                if (is_file($rawthumb . '.' . $EXT)) {
                                    if (is_file($rawthumb . '.' . $ext)) {
                                        unlink($rawthumb . '.' . $EXT);
                                    } else {
                                        rename($rawthumb . '.' . $EXT, $rawthumb . '.' . $ext);
                                    }
                                    $fixed_this = true;
                                }
                            }
                            if ($fixed_this) {
                                $wppa_session[$slug . '_fixed']++;
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_regen_thumbs':
                            if (!wppa_is_video($id) || file_exists(str_replace('xxx', 'jpg', wppa_get_photo_path($id)))) {
                                wppa_create_thumbnail($id);
                            }
                            break;
                        case 'wppa_rerate':
                            wppa_rate_photo($id);
                            break;
                        case 'wppa_recup':
                            $a_ret = wppa_recuperate($id);
                            if ($a_ret['iptcfix']) {
                                $wppa_session[$slug . '_fixed']++;
                            }
                            if ($a_ret['exiffix']) {
                                $wppa_session[$slug . '_fixed']++;
                            }
                            break;
                        case 'wppa_file_system':
                            $fs = get_option('wppa_file_system');
                            if ($fs == 'to-tree' || $fs == 'to-flat') {
                                if ($fs == 'to-tree') {
                                    $from = 'flat';
                                    $to = 'tree';
                                } else {
                                    $from = 'tree';
                                    $to = 'flat';
                                }
                                // Media files
                                if (wppa_is_multi($id)) {
                                    // Can NOT use wppa_has_audio() or wppa_is_video(), they use wppa_get_photo_path() without fs switch!!
                                    $exts = array_merge($wppa_supported_video_extensions, $wppa_supported_audio_extensions);
                                    $pathfrom = wppa_get_photo_path($id, $from);
                                    $pathto = wppa_get_photo_path($id, $to);
                                    //	wppa_log( 'dbg', 'Trying: '.$pathfrom );
                                    foreach ($exts as $ext) {
                                        if (is_file(str_replace('.xxx', '.' . $ext, $pathfrom))) {
                                            //	wppa_log( 'dbg',  str_replace( '.xxx', '.'.$ext, $pathfrom ).' -> '.str_replace( '.xxx', '.'.$ext, $pathto ));
                                            @rename(str_replace('.xxx', '.' . $ext, $pathfrom), str_replace('.xxx', '.' . $ext, $pathto));
                                        }
                                    }
                                }
                                // Poster / photo
                                if (file_exists(wppa_fix_poster_ext(wppa_get_photo_path($id, $from), $id))) {
                                    @rename(wppa_fix_poster_ext(wppa_get_photo_path($id, $from), $id), wppa_fix_poster_ext(wppa_get_photo_path($id, $to), $id));
                                }
                                // Thumbnail
                                if (file_exists(wppa_fix_poster_ext(wppa_get_thumb_path($id, $from), $id))) {
                                    @rename(wppa_fix_poster_ext(wppa_get_thumb_path($id, $from), $id), wppa_fix_poster_ext(wppa_get_thumb_path($id, $to), $id));
                                }
                            }
                            break;
                        case 'wppa_cleanup':
                            $photo_files = glob(WPPA_UPLOAD_PATH . '/' . $id . '.*');
                            // Remove dirs
                            if ($photo_files) {
                                foreach (array_keys($photo_files) as $key) {
                                    if (is_dir($photo_files[$key])) {
                                        unset($photo_files[$key]);
                                    }
                                }
                            }
                            // files left? process
                            if ($photo_files) {
                                foreach ($photo_files as $photo_file) {
                                    $basename = basename($photo_file);
                                    $ext = substr($basename, strpos($basename, '.') + '1');
                                    if (!$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $id))) {
                                        // no db entry for this photo
                                        if (wppa_is_id_free(WPPA_PHOTOS, $id)) {
                                            if (wppa_create_photo_entry(array('id' => $id, 'album' => $orphan_album, 'ext' => $ext, 'filename' => $basename))) {
                                                // Can create entry
                                                $wppa_session[$slug . '_fixed']++;
                                                // Bump counter
                                                wppa_log('Debug', 'Lost photo file ' . $photo_file . ' recovered');
                                            } else {
                                                wppa_log('Debug', 'Unable to recover lost photo file ' . $photo_file . ' Create photo entry failed');
                                            }
                                        } else {
                                            wppa_log('Debug', 'Could not recover lost photo file ' . $photo_file . ' The id is not free');
                                        }
                                    }
                                }
                            }
                            break;
                        case 'wppa_remake':
                            $doit = true;
                            if (wppa_switch('remake_orientation_only')) {
                                $ori = wppa_get_exif_orientation(wppa_get_source_path($id));
                                if ($ori < '2') {
                                    $doit = false;
                                }
                            }
                            if (wppa_switch('remake_missing_only')) {
                                if (is_file(wppa_get_thumb_path($id)) && is_file(wppa_get_photo_path($id))) {
                                    $doit = false;
                                }
                            }
                            if ($doit && wppa_remake_files('', $id)) {
                                $wppa_session[$slug . '_fixed']++;
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_watermark_all':
                            if (!wppa_is_video($id)) {
                                if (wppa_add_watermark($id)) {
                                    wppa_create_thumbnail($id);
                                    // create new thumb
                                    $wppa_session[$slug . '_fixed']++;
                                } else {
                                    $wppa_session[$slug . '_skipped']++;
                                }
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_create_all_autopages':
                            wppa_get_the_auto_page($id);
                            break;
                        case 'wppa_delete_all_autopages':
                            wppa_remove_the_auto_page($id);
                            break;
                        case 'wppa_leading_zeros':
                            $name = $photo['name'];
                            if (wppa_is_int($name)) {
                                $target_len = wppa_opt('zero_numbers');
                                $name = strval(intval($name));
                                while (strlen($name) < $target_len) {
                                    $name = '0' . $name;
                                }
                            }
                            if ($name !== $photo['name']) {
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name, $id));
                            }
                            break;
                        case 'wppa_add_gpx_tag':
                            $tags = $photo['tags'];
                            $temp = explode('/', $photo['location']);
                            if (!isset($temp['2'])) {
                                $temp['2'] = false;
                            }
                            if (!isset($temp['3'])) {
                                $temp['3'] = false;
                            }
                            $lat = $temp['2'];
                            $lon = $temp['3'];
                            if ($lat < 0.01 && $lat > -0.01 && $lon < 0.01 && $lon > -0.01) {
                                $lat = false;
                                $lon = false;
                            }
                            if ($photo['location'] && strpos($tags, 'Gpx') === false && $lat && $lon) {
                                // Add it
                                $tags = wppa_sanitize_tags($tags . ',Gpx');
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                wppa_index_update('photo', $photo['id']);
                                wppa_clear_taglist();
                            } elseif (strpos($tags, 'Gpx') !== false && !$lat && !$lon) {
                                // Remove it
                                $tags = wppa_sanitize_tags(str_replace('Gpx', '', $tags));
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                wppa_index_update('photo', $photo['id']);
                                wppa_clear_taglist();
                            }
                            break;
                        case 'wppa_optimize_ewww':
                            $file = wppa_get_photo_path($photo['id']);
                            if (is_file($file)) {
                                ewww_image_optimizer($file, 4, false, false, false);
                            }
                            $file = wppa_get_thumb_path($photo['id']);
                            if (is_file($file)) {
                                ewww_image_optimizer($file, 4, false, false, false);
                            }
                            break;
                        case 'wppa_comp_sizes':
                            $tx = 0;
                            $ty = 0;
                            $px = 0;
                            $py = 0;
                            $file = wppa_get_photo_path($photo['id']);
                            if (is_file($file)) {
                                $temp = getimagesize($file);
                                if (is_array($temp)) {
                                    $px = $temp[0];
                                    $py = $temp[1];
                                }
                            }
                            $file = wppa_get_thumb_path($photo['id']);
                            if (is_file($file)) {
                                $temp = getimagesize($file);
                                if (is_array($temp)) {
                                    $tx = $temp[0];
                                    $ty = $temp[1];
                                }
                            }
                            wppa_update_photo(array('id' => $photo['id'], 'thumbx' => $tx, 'thumby' => $ty, 'photox' => $px, 'photoy' => $py));
                            break;
                        case 'wppa_edit_tag':
                            $phototags = explode(',', wppa_get_photo_item($photo['id'], 'tags'));
                            if (in_array($edit_tag, $phototags)) {
                                foreach (array_keys($phototags) as $key) {
                                    if ($phototags[$key] == $edit_tag) {
                                        $phototags[$key] = $new_tag;
                                    }
                                }
                                $tags = wppa_sanitize_tags(implode(',', $phototags));
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                $wppa_session[$slug . '_fixed']++;
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_sync_cloud':
                            $is_old = wppa_opt('max_cloud_life') && time() > $photo['timestamp'] + wppa_opt('max_cloud_life');
                            //	$is_in_cloud = @ getimagesize( wppa_get_cloudinary_url( $photo['id'], 'test_only' ) );
                            $is_in_cloud = isset($wppa_session['cloudinary_ids'][$photo['id']]);
                            //	wppa_log('Obs', 'Id='.$photo['id'].', is old='.$is_old.', in cloud='.$is_in_cloud);
                            if ($is_old && $is_in_cloud) {
                                $to_delete_from_cloudinary[] = strval($photo['id']);
                                if (count($to_delete_from_cloudinary) == 10) {
                                    wppa_delete_from_cloudinary($to_delete_from_cloudinary);
                                    $to_delete_from_cloudinary = array();
                                }
                                $wppa_session[$slug . '_deleted']++;
                            }
                            if (!$is_old && !$is_in_cloud) {
                                wppa_upload_to_cloudinary($photo['id']);
                                $wppa_session[$slug . '_added']++;
                            }
                            if ($is_old && !$is_in_cloud) {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            if (!$is_old && $is_in_cloud) {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_sanitize_tags':
                            $tags = $photo['tags'];
                            if ($tags) {
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => wppa_sanitize_tags($tags)));
                            }
                            break;
                        case 'wppa_crypt_photos':
                            wppa_update_photo(array('id' => $photo['id'], 'crypt' => wppa_get_unique_photo_crypt()));
                            break;
                        case 'wppa_create_o1_files':
                            wppa_make_o1_source($photo['id']);
                            break;
                        case 'wppa_owner_to_name_proc':
                            $iret = wppa_set_owner_to_name($id);
                            if ($iret === true) {
                                $wppa_session[$slug . '_fixed']++;
                            }
                            if ($iret === '0') {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_move_all_photos':
                            $fromalb = get_option('wppa_move_all_photos_from');
                            $toalb = get_option('wppa_move_all_photos_to');
                            $alb = wppa_get_photo_item($id, 'album');
                            if ($alb == $fromalb) {
                                wppa_update_photo(array('id' => $id, 'album' => $toalb));
                                wppa_move_source(wppa_get_photo_item($id, 'filename'), $fromalb, $toalb);
                                wppa_flush_treecounts($fromalb);
                                wppa_flush_treecounts($toalb);
                                $wppa_session[$slug . '_fixed']++;
                            }
                            break;
                        case 'wppa_test_proc':
                            $tags = '';
                            $albid = $photo['album'];
                            $albnam = wppa_get_album_item($albid, 'name');
                            $tags .= $albnam;
                            while ($albid > '0') {
                                $albid = wppa_get_album_item($albid, 'a_parent');
                                if ($albid > '0') {
                                    $tags .= ',' . wppa_get_album_item($albid, 'name');
                                }
                            }
                            wppa_update_photo(array('id' => $photo['id'], 'tags' => wppa_sanitize_tags($tags)));
                            break;
                    }
                    // Test for timeout / ready
                    $lastid = $id;
                    update_option($slug . '_last', $lastid);
                    if (time() > $endtime) {
                        break;
                    }
                    // Time out
                }
            } else {
                // Nothing to do, Done anyway
                $lastid = $topid;
                wppa_log('Debug', 'Maintenance proc ' . $slug . ': Done!');
            }
            break;
            // End process photos
            // Single action maintenance modules
            //		case 'wppa_list_index':
            //			break;
            //		case 'wppa_blacklist_user':
            //			break;
            //		case 'wppa_un_blacklist_user':
            //			break;
            //		case 'wppa_rating_clear':
            //			break;
            //		case 'wppa_viewcount_clear':
            //			break;
            //		case 'wppa_iptc_clear':
            //			break;
            //		case 'wppa_exif_clear':
            //			break;
        // End process photos
        // Single action maintenance modules
        //		case 'wppa_list_index':
        //			break;
        //		case 'wppa_blacklist_user':
        //			break;
        //		case 'wppa_un_blacklist_user':
        //			break;
        //		case 'wppa_rating_clear':
        //			break;
        //		case 'wppa_viewcount_clear':
        //			break;
        //		case 'wppa_iptc_clear':
        //			break;
        //		case 'wppa_exif_clear':
        //			break;
        default:
            $errtxt = 'Unimplemented maintenance slug: ' . strip_tags($slug);
    }
    // either $albums / $photos has been exhousted ( for this try ) or time is up
    // Post proc this try:
    switch ($slug) {
        case 'wppa_sync_cloud':
            if (count($to_delete_from_cloudinary) > 0) {
                wppa_delete_from_cloudinary($to_delete_from_cloudinary);
            }
            break;
    }
    // Find togo
    if ($slug == 'wppa_cleanup') {
        $togo = $topid - $lastid;
    } else {
        $togo = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . $table . "` WHERE `id` > %s ", $lastid));
    }
    // Find status
    if (!$errtxt) {
        $status = $togo ? 'Working' : 'Ready';
    } else {
        $status = 'Error';
    }
    // Not done yet?
    if ($togo) {
        // If a cron job, reschedule next chunk
        if (wppa_is_cron()) {
            update_option($slug . '_togo', $togo);
            update_option($slug . '_status', 'Running cron');
            wppa_schedule_maintenance_proc($slug);
        } else {
            update_option($slug . '_togo', $togo);
            update_option($slug . '_status', 'Pending');
        }
    } else {
        // Report fixed/skipped/deleted
        if ($wppa_session[$slug . '_fixed']) {
            $status .= ' fixed:' . $wppa_session[$slug . '_fixed'];
            unset($wppa_session[$slug . '_fixed']);
        }
        if ($wppa_session[$slug . '_added']) {
            $status .= ' added:' . $wppa_session[$slug . '_added'];
            unset($wppa_session[$slug . '_added']);
        }
        if ($wppa_session[$slug . '_deleted']) {
            $status .= ' deleted:' . $wppa_session[$slug . '_deleted'];
            unset($wppa_session[$slug . '_deleted']);
        }
        if ($wppa_session[$slug . '_skipped']) {
            $status .= ' skipped:' . $wppa_session[$slug . '_skipped'];
            unset($wppa_session[$slug . '_skipped']);
        }
        // Re-Init options
        update_option($slug . '_togo', '');
        update_option($slug . '_status', '');
        update_option($slug . '_last', '0');
        update_option($slug . '_user', '');
        update_option($slug . '_lasttimestamp', '0');
        // Post-processing needed?
        switch ($slug) {
            case 'wppa_remake_index_albums':
            case 'wppa_remake_index_photos':
                $wpdb->query("DELETE FROM `" . WPPA_INDEX . "` WHERE `albums` = '' AND `photos` = ''");
                // Remove empty entries
                delete_option('wppa_index_need_remake');
                break;
            case 'wppa_apply_new_photodesc_all':
            case 'wppa_append_to_photodesc':
            case 'wppa_remove_from_photodesc':
                update_option('wppa_remake_index_photos_status', __('Required', 'wp-photo-album-plus'));
                break;
            case 'wppa_regen_thumbs':
                wppa_bump_thumb_rev();
                break;
            case 'wppa_file_system':
                wppa_update_option('wppa_file_system', $to);
                $reload = 'reload';
                break;
            case 'wppa_remake':
                wppa_bump_photo_rev();
                wppa_bump_thumb_rev();
                break;
            case 'wppa_edit_tag':
                wppa_clear_taglist();
                if (wppa_switch('search_tags')) {
                    update_option('wppa_remake_index_photos_status', __('Required', 'wp-photo-album-plus'));
                }
                $reload = 'reload';
                break;
            case 'wppa_sanitize_tags':
                wppa_clear_taglist();
                break;
            case 'wppa_sanitize_cats':
                wppa_clear_catlist();
                break;
            case 'wppa_test_proc':
                wppa_clear_taglist();
                break;
            case 'wppa_sync_cloud':
                unset($wppa_session['cloudinary_ids']);
                break;
        }
        wppa_log('Obs', 'Maintenance proc ' . $slug . ' completed');
    }
    wppa_save_session();
    if (wppa_is_cron()) {
        wppa_log('obs', $errtxt . '||' . $slug . '||' . $status . '||' . $togo . '||' . $reload);
    }
    return $errtxt . '||' . $slug . '||' . $status . '||' . $togo . '||' . $reload;
}
function wppa_cache_thumb($id, $data = '')
{
    global $wpdb;
    static $thumb;
    static $thumb_cache_2;
    // $id?
    if (!$id) {
        return false;
    }
    // Invalidate ?
    if ($id == 'invalidate') {
        if (isset($thumb_cache_2[$data])) {
            unset($thumb_cache_2[$data]);
        }
        $thumb = false;
        return false;
    }
    // Add ?
    if ($id == 'add') {
        if (!$data) {
            // Nothing to add
            return false;
        } elseif (isset($data['id'])) {
            // Add a single thumb to 2nd level cache
            if (count($data) < 31) {
                wppa_log('Err', 'Attempt to cache add incomplete photo item ' . $data['id'] . '. Only ' . count($data) . ' items supplied.');
                return false;
            }
            $thumb_cache_2[$data['id']] = $data;
            // Looks valid
        } elseif (count($data) > 10000) {
            return false;
            // Too many, may cause out of memory error
        } else {
            foreach ($data as $thumb) {
                // Add multiple
                if (isset($thumb['id'])) {
                    // Looks valid
                    if (count($thumb) < 31) {
                        wppa_log('Err', 'Attempt to cache add incomplete photo item ' . $thumb['id'] . '. Only ' . count($thumb) . ' items supplied.');
                        return false;
                    }
                    $thumb_cache_2[$thumb['id']] = $thumb;
                }
            }
        }
        return false;
    }
    // Count ?
    if ($id == 'count') {
        if (is_array($thumb_cache_2)) {
            return count($thumb_cache_2);
        } else {
            return false;
        }
    }
    // Error in arg?
    if (!wppa_is_int($id) || $id < '1') {
        wppa_dbg_msg('Invalid arg wppa_cache_thumb(' . $id . ')', 'red');
        $thumb = false;
        wppa('current_photo', false);
        return false;
    }
    // In first level cache?
    if (isset($thumb['id']) && $thumb['id'] == $id) {
        wppa_dbg_cachecounts('photohit');
        wppa('current_photo', $thumb);
        return $thumb;
    }
    // In  second level cache?
    if (!empty($thumb_cache_2)) {
        if (in_array($id, array_keys($thumb_cache_2))) {
            $thumb = $thumb_cache_2[$id];
            wppa('current_photo', $thumb);
            wppa_dbg_cachecounts('photohit');
            return $thumb;
        }
    }
    // Not in cache, do query
    $thumb = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $id), ARRAY_A);
    wppa_dbg_cachecounts('photomis');
    // Found one?
    if ($thumb) {
        // Store in second level cache
        $thumb_cache_2[$id] = $thumb;
        wppa('current_photo', $thumb);
        return $thumb;
    } else {
        wppa_dbg_msg('Photo ' . $id . ' does not exist', 'red');
        wppa('current_photo', false);
        return false;
    }
}
function _wppa_sidebar_page_options()
{
    global $wpdb;
    global $wppa_defaults;
    wppa_set_defaults();
    $onch = 'myReload()';
    // Handle spinner js and declare functions
    echo '<script type="text/javascript" >' . 'var didsome=false;' . 'jQuery(document).ready(function() {' . 'jQuery(\'#wppa-spinner\').css(\'display\', \'none\');' . '});' . 'function myReload() {' . 'jQuery(\'#wppa-spinner\').css(\'display\', \'block\');' . '_wppaRefreshAfter = true;' . '};' . 'function wppaSetFixed(id) {' . 'if (jQuery(\'#wppa-widget-photo-\' + id).attr(\'checked\') == \'checked\' ) {' . '_wppaRefreshAfter = true;' . 'wppaAjaxUpdateOptionValue(\'potd_photo\', id);' . '}' . '};' . '</script>';
    // The spinner
    echo '<img' . ' id="wppa-spinner"' . ' style="position:fixed;top:50%;left:50%;z-index:1000;margin-top:-33px;margin-left:-33px;display:block;"' . ' src="' . wppa_get_imgdir('loader.gif') . '"' . '/>';
    // Open wrapper
    echo '<div class="wrap">';
    // The settings icon
    echo '<img src="' . wppa_get_imgdir('settings32.png') . '" />';
    // The Page title
    echo '<h1 style="display:inline;" >' . __('Photo of the Day (Widget) Settings', 'wp-photo-album-plus') . '</h1>' . __('Changes are updated immediately. The page will reload if required.', 'wp-photo-album-plus') . '<br />&nbsp;';
    // The nonce
    wp_nonce_field('wppa-nonce', 'wppa-nonce');
    // The settings table
    echo '<table class="widefat wppa-table wppa-setting-table">';
    // The header
    echo '<thead style="font-weight: bold; " class="wppa_table_1">' . '<tr>' . '<td>' . __('#', 'wp-photo-album-plus') . '</td>' . '<td>' . __('Name', 'wp-photo-album-plus') . '</td>' . '<td>' . __('Description', 'wp-photo-album-plus') . '</td>' . '<td>' . __('Setting', 'wp-photo-album-plus') . '</td>' . '<td>' . __('Help', 'wp-photo-album-plus') . '</td>' . '</tr>' . '</thead>';
    // Open the table body
    echo '<tbody class="wppa_table" >';
    $name = __('Widget Title:', 'wp-photo-album-plus');
    $desc = __('The title of the widget.', 'wp-photo-album-plus');
    $help = esc_js(__('Enter/modify the title for the widget. This is a default and can be overriden at widget activation.', 'wp-photo-album-plus'));
    $slug = 'wppa_potd_title';
    $html = wppa_input($slug, '85%');
    wppa_setting($slug, '1', $name, $desc, $html, $help);
    $name = __('Widget Photo Width:', 'wp-photo-album-plus');
    $desc = __('Enter the desired display width of the photo in the sidebar.', 'wp-photo-album-plus');
    $help = '';
    $slug = 'wppa_potd_widget_width';
    $html = wppa_input($slug, '40px', '', __('pixels wide', 'wp-photo-album-plus'));
    wppa_setting($slug, '2', $name, $desc, $html, $help);
    $name = __('Horizontal alignment:', 'wp-photo-album-plus');
    $desc = __('Enter the desired display alignment of the photo in the sidebar.', 'wp-photo-album-plus');
    $help = '';
    $slug = 'wppa_potd_align';
    $opts = array(__('--- none ---', 'wp-photo-album-plus'), __('left', 'wp-photo-album-plus'), __('center', 'wp-photo-album-plus'), __('right', 'wp-photo-album-plus'));
    $vals = array('none', 'left', 'center', 'right');
    $html = wppa_select($slug, $opts, $vals);
    wppa_setting($slug, '3', $name, $desc, $html, $help);
    $linktype = wppa_opt('potd_linktype');
    if ($linktype == 'custom') {
        $name = __('Link to:', 'wp-photo-album-plus');
        $desc = __('Enter the url. Do\'nt forget the HTTP://', 'wp-photo-album-plus');
        $help = '';
        $slug = 'wppa_potd_linkurl';
        $html = wppa_input($slug, '85%');
        wppa_setting($slug, '4', $name, $desc, $html, $help);
        $name = __('Link Title:', 'wp-photo-album-plus');
        $desc = __('The balloon text when hovering over the photo.', 'wp-photo-album-plus');
        $help = '';
        $slug = 'wppa_potd_linktitle';
        $html = wppa_input($slug, '85%');
        wppa_setting($slug, '4a', $name, $desc, $html, $help);
    } else {
        $name = __('Link to:', 'wp-photo-album-plus');
        $desc = __('Links are set on the <b>Photo Albums -> Settings</b> screen.', 'wp-photo-album-plus');
        $help = '';
        $slug = 'wppa_potd_linkurl';
        $html = '';
        wppa_setting($slug, '4', $name, $desc, $html, $help);
    }
    $name = __('Subtitle:', 'wp-photo-album-plus');
    $desc = __('Select the content of the subtitle.', 'wp-photo-album-plus');
    $help = '';
    $slug = 'wppa_potd_subtitle';
    $opts = array(__('--- none ---', 'wp-photo-album-plus'), __('Photo Name', 'wp-photo-album-plus'), __('Description', 'wp-photo-album-plus'), __('Owner', 'wp-photo-album-plus'));
    $vals = array('none', 'name', 'desc', 'owner');
    $html = wppa_select($slug, $opts, $vals);
    wppa_setting($slug, '5', $name, $desc, $html, $help);
    $name = __('Counter:', 'wp-photo-album-plus');
    $desc = __('Display a counter of other photos in the album.', 'wp-photo-album-plus');
    $help = '';
    $slug = 'wppa_potd_counter';
    $html = wppa_checkbox($slug);
    wppa_setting($slug, '6', $name, $desc, $html, $help);
    $name = __('Link to:', 'wp-photo-album-plus');
    $desc = __('The counter links to.', 'wp-photo-album-plus');
    $help = '';
    $slug = 'wppa_potd_counter_link';
    $opts = array(__('thumbnails', 'wp-photo-album-plus'), __('slideshow', 'wp-photo-album-plus'), __('single image', 'wp-photo-album-plus'));
    $vals = array('thumbs', 'slide', 'single');
    $html = wppa_select($slug, $opts, $vals);
    wppa_setting($slug, '7', $name, $desc, $html, $help);
    $name = __('Type of album(s) to use:', 'wp-photo-album-plus');
    $desc = __('Select physical or virtual.', 'wp-photo-album-plus');
    $help = '';
    $slug = 'wppa_potd_album_type';
    $opts = array(__('physical albums', 'wp-photo-album-plus'), __('virtual albums', 'wp-photo-album-plus'));
    $vals = array('physical', 'virtual');
    $html = wppa_select($slug, $opts, $vals, $onch);
    wppa_setting($slug, '8', $name, $desc, $html, $help);
    $name = __('Albums to use:', 'wp-photo-album-plus');
    $desc = __('Select the albums to use for the photo of the day.', 'wp-photo-album-plus');
    $help = '';
    $slug = 'wppa_potd_album';
    if (get_option('wppa_potd_album_type') == 'physical') {
        $html = '<select' . ' id="wppa_potd_album"' . ' name="wppa_potd_album"' . ' style="float:left; max-width: 100%;"' . ' multiple="multiple"' . ' onchange="didsome=true;wppaAjaxUpdateOptionValue(\'potd_album\', this, true)"' . ' onmouseout="if(didsome)document.location.reload(true);"' . ' size="10"' . ' >' . wppa_album_select_a(array('path' => true, 'optionclass' => 'potd_album', 'selected' => get_option('wppa_potd_album'))) . '</select>' . '<img id="img_potd_album" class="" src="' . wppa_get_imgdir() . 'star.ico" title="' . __('Setting unmodified', 'wp-photo-album-plus') . '" style="padding:0 4px; float:left; height:16px; width:16px;" />';
        wppa_setting($slug, '9', $name, $desc, $html, $help);
    } else {
        $desc = __('Select the albums to use for the photo of the day.', 'wp-photo-album-plus');
        $opts = array(__('- all albums -', 'wp-photo-album-plus'), __('- all -separate- albums -', 'wp-photo-album-plus'), __('- all albums except -separate-', 'wp-photo-album-plus'), __('- top rated photos -', 'wp-photo-album-plus'));
        $vals = array('all', 'sep', 'all-sep', 'topten');
        $html = wppa_select($slug, $opts, $vals);
        wppa_setting($slug, '9', $name, $desc, $html, $help);
    }
    if (get_option('wppa_potd_album_type') == 'physical') {
        $name = __('Include (grand)children:', 'wp-photo-album-plus');
        $desc = __('Include the photos of all sub albums?', 'wp-photo-album-plus');
        $help = '';
        $slug = 'wppa_potd_include_subs';
        $html = wppa_checkbox($slug, $onch);
        wppa_setting($slug, '9a', $name, $desc, $html, $help);
        $name = __('Inverse selection:', 'wp-photo-album-plus');
        $desc = __('Use any album, except the selection made above.', 'wp-photo-album-plus');
        $help = '';
        $slug = 'wppa_potd_inverse';
        $html = wppa_checkbox($slug, $onch);
        wppa_setting($slug, '9b', $name, $desc, $html, $help);
    }
    $name = __('Status filter:', 'wp-photo-album-plus');
    $desc = __('Use only photos with a certain status.', 'wp-photo-album-plus');
    $help = esc_js(__('Select - none - if you want no filtering on status.', 'wp-photo-album-plus'));
    $slug = 'wppa_potd_status_filter';
    $opts = array(__('- none -', 'wp-photo-album-plus'), __('Publish', 'wp-photo-album-plus'), __('Featured', 'wp-photo-album-plus'), __('Gold', 'wp-photo-album-plus'), __('Silver', 'wp-photo-album-plus'), __('Bronze', 'wp-photo-album-plus'), __('Any medal', 'wp-photo-album-plus'));
    $vals = array('none', 'publish', 'featured', 'gold', 'silver', 'bronze', 'anymedal');
    $html = wppa_select($slug, $opts, $vals);
    wppa_setting($slug, '10', $name, $desc, $html, $help);
    $name = __('Display method:', 'wp-photo-album-plus');
    $desc = __('Select the way a photo will be selected.', 'wp-photo-album-plus');
    $help = '';
    $slug = 'wppa_potd_method';
    $opts = array(__('Fixed photo', 'wp-photo-album-plus'), __('Random', 'wp-photo-album-plus'), __('Last upload', 'wp-photo-album-plus'), __('Change every', 'wp-photo-album-plus'));
    $vals = array('1', '2', '3', '4');
    $html = wppa_select($slug, $opts, $vals, $onch);
    wppa_setting($slug, '11', $name, $desc, $html, $help);
    if (get_option('wppa_potd_method') == '4') {
        // Change every
        $name = __('Change every period:', 'wp-photo-album-plus');
        $desc = __('The time period a certain photo is used.', 'wp-photo-album-plus');
        $help = '';
        $slug = 'wppa_potd_period';
        $opts = array(__('pageview.', 'wp-photo-album-plus'), __('hour.', 'wp-photo-album-plus'), __('day.', 'wp-photo-album-plus'), __('week.', 'wp-photo-album-plus'), __('month.', 'wp-photo-album-plus'), __('day of week is order#', 'wp-photo-album-plus'), __('day of month is order#', 'wp-photo-album-plus'), __('day of year is order#', 'wp-photo-album-plus'));
        $vals = array('0', '1', '24', '168', '736', 'day-of-week', 'day-of-month', 'day-of-year');
        $html = wppa_select($slug, $opts, $vals, $onch);
        wppa_setting($slug, '11a', $name, $desc, $html, $help);
        $wppa_widget_period = get_option('wppa_potd_period');
        if (substr($wppa_widget_period, 0, 7) == 'day-of-') {
            switch (substr($wppa_widget_period, 7)) {
                case 'week':
                    $n_days = '7';
                    $date_key = 'w';
                    break;
                case 'month':
                    $n_days = '31';
                    $date_key = 'd';
                    break;
                case 'year':
                    $n_days = '366';
                    $date_key = 'z';
                    break;
            }
            while (get_option('wppa_potd_offset', '0') > $n_days) {
                update_option('wppa_potd_offset', get_option('wppa_potd_offset') - $n_days);
            }
            while (get_option('wppa_potd_offset', '0') < '0') {
                update_option('wppa_potd_offset', get_option('wppa_potd_offset') + $n_days);
            }
            $name = __('Day offset:', 'wp-photo-album-plus');
            $desc = __('The difference between daynumber and photo order number.', 'wp-photo-album-plus');
            $help = '';
            $slug = 'wppa_potd_offset';
            $opts = array();
            $day = '0';
            while ($day < $n_days) {
                $opts[] = $day;
                $day++;
            }
            $vals = $opts;
            $html = '<span style="float:left;" >' . sprintf(__('Current day# = %s, offset =', 'wp-photo-album-plus'), wppa_local_date($date_key)) . '</span> ' . wppa_select($slug, $opts, $vals, $onch);
            $photo_order = wppa_local_date($date_key) - get_option('wppa_potd_offset', '0');
            while ($photo_order < '0') {
                $photo_order += $n_days;
            }
            $html .= sprintf(__('Todays photo order# = %s.', 'wp-photo-album-plus'), $photo_order);
            wppa_setting($slug, '11b', $name, $desc, $html, $help);
        }
    }
    $name = __('Preview', 'wp-photo-album-plus');
    $desc = __('Current "photo of the day":', 'wp-photo-album-plus');
    $help = '';
    $slug = 'wppa_potd_photo';
    $photo = wppa_get_potd();
    if ($photo) {
        $html = '<div style="display:inline-block;width:25%;text-align:center;vertical-align:middle;">' . '<img src="' . wppa_fix_poster_ext(wppa_get_thumb_url($photo['id']), $photo['id']) . '" />' . '</div>' . '<div style="display:inline-block;width:75%;text-align:center;vertical-align:middle;" >' . __('Album', 'wp-photo-album-plus') . ': ' . wppa_get_album_name($photo['album']) . '<br />' . __('Uploader', 'wp-photo-album-plus') . ': ' . $photo['owner'] . '</div>';
    } else {
        $html = __('Not found.', 'wp-photo-album-plus');
    }
    wppa_setting($slug, '12', $name, $desc, $html, $help);
    $name = __('Show selection', 'wp-photo-album-plus');
    $desc = __('Show the photos in the current selection.', 'wp-photo-album-plus');
    $help = '';
    $slug = 'wppa_potd_preview';
    $html = wppa_checkbox($slug, $onch);
    wppa_setting($slug, '13', $name, $desc, $html, $help);
    // Cose table body
    echo '</tbody>';
    // Table footer
    echo '<tfoot style="font-weight: bold;" >' . '<tr>' . '<td>' . __('#', 'wp-photo-album-plus') . '</td>' . '<td>' . __('Name', 'wp-photo-album-plus') . '</td>' . '<td>' . __('Description', 'wp-photo-album-plus') . '</td>' . '<td>' . __('Setting', 'wp-photo-album-plus') . '</td>' . '<td>' . __('Help', 'wp-photo-album-plus') . '</td>' . '</tr>' . '</tfoot>' . '</table>';
    // Diagnostic
    //		echo
    //		'Diagnostic: wppa_potd_album = ' . get_option( 'wppa_potd_album' ) . ' wppa_potd_photo = ' . get_option( 'wppa_potd_photo' );
    // Status star must be here for js
    echo '<img' . ' id="img_potd_photo"' . ' src="' . wppa_get_imgdir('star.ico') . '" style="height:12px;display:none;"' . ' />';
    // The potd photo pool
    echo '<table class="widefat wppa-table wppa-setting-table" >';
    // Table header
    echo '<thead>' . '<tr>' . '<td>' . __('Photos in the current selection', 'wp-photo-album-plus') . '</td>' . '</tr>' . '</thead>';
    // Table body
    if (wppa_switch('potd_preview')) {
        echo '<tbody>' . '<tr>' . '<td>';
        // Get the photos
        $alb = wppa_opt('potd_album');
        $opt = wppa_is_int($alb) ? ' ' . wppa_get_photo_order($alb) . ' ' : '';
        $photos = wppa_get_widgetphotos($alb, $opt);
        // Count them
        $cnt = count($photos);
        // Find current
        $curid = wppa_opt('potd_photo');
        // See if we do this
        if (empty($photos)) {
            _e('No photos in the selection', 'wp-photo-album-plus');
        } elseif ($cnt > '5000') {
            echo sprintf(__('There are too many photos in the selection to show a preview ( %d )', 'wp-photo-album-plus'), $cnt);
        } else {
            // Yes, display the pool
            foreach ($photos as $photo) {
                $id = $photo['id'];
                // Open container div
                echo '<div' . ' class="photoselect"' . ' style="' . 'width:180px;' . 'height:300px;' . '" >';
                // Open image container div
                echo '<div' . ' style="' . 'width:180px;' . 'height:135px;' . 'overflow:hidden;' . 'text-align:center;' . '" >';
                // The image if a video
                if (wppa_is_video($id)) {
                    echo wppa_get_video_html(array('id' => $id, 'style' => 'width:180px;'));
                } else {
                    echo '<img' . ' src=" ' . wppa_fix_poster_ext(wppa_get_thumb_url($id), $id) . '"' . ' style="' . 'max-width:180px;' . 'max-height:135px;' . 'margin:auto;' . '"' . ' alt="' . esc_attr(wppa_get_photo_name($id)) . '" />';
                    // Audio ?
                    if (wppa_has_audio($id)) {
                        echo wppa_get_audio_html(array('id' => $id, 'style' => 'width:180px;' . 'position:relative;' . 'bottom:' . (wppa_get_audio_control_height() + 4) . 'px;'));
                    }
                }
                // Close image container div
                echo '</div>';
                // The order# and select radio box
                echo '<div style="clear:both;width:100%;margin:3px 0;position:relative;top:5px;" >' . '<div style="font-size:9px; line-height:10px;float:left;">(#' . $photo['p_order'] . ')</div>';
                if (get_option('wppa_potd_method') == '1') {
                    // Only if fixed photo
                    echo '<input' . ' style="float:right;"' . ' type="radio"' . ' name="wppa-widget-photo"' . ' id="wppa-widget-photo-' . $id . '"' . ' value="' . $id . '"' . ($id == $curid ? 'checked="checked"' : '') . ' onchange="wppaSetFixed(' . $id . ');"' . ' />';
                }
                echo '</div>';
                // The name/desc boxecho
                echo '<div style="clear:both;overflow:hidden;height:150px;position:relative;top:10px;" >' . '<div style="font-size:11px; overflow:hidden;">' . wppa_get_photo_name($id) . '</div>' . '<div style="font-size:9px; line-height:10px;">' . wppa_get_photo_desc($id) . '</div>' . '</div>';
                // Close container
                echo '</div>';
            }
            echo '<div class="clear"></div>';
        }
        // Close the table
        echo '</td>' . '</tr>' . '</tbody>';
    }
    echo '</table>';
    // Close wrap
    echo '</div>';
}
function wppa_get_album_id_by_name($xname, $report_dups = false)
{
    global $wpdb;
    global $allalbums;
    if (wppa_is_int($xname)) {
        return $xname;
        // Already numeric
    }
    if (wppa_is_enum($xname)) {
        return $xname;
        // Is enumeration
    }
    $name = wppa_decode_uri_component($xname);
    $name = str_replace('\'', '%', $name);
    // A trick for single quotes
    $name = str_replace('"', '%', $name);
    // A trick for double quotes
    $name = stripslashes($name);
    $query = "SELECT * FROM `" . WPPA_ALBUMS . "` WHERE `name` LIKE '%" . $name . "%'";
    $albs = $wpdb->get_results($query, ARRAY_A);
    if ($albs) {
        if (count($albs) == 1) {
            wppa_dbg_msg('Alb ' . $albs[0]['id'], ' found for ' . $xname);
            $aid = $albs[0]['id'];
        } else {
            wppa_dbg_msg('Dups found for ' . $xname);
            if ($report_dups == 'report_dups') {
                $aid = false;
            } elseif ($report_dups == 'return_dups') {
                $aid = '';
                foreach ($albs as $alb) {
                    $aid .= $alb['id'] . '.';
                }
                $aid = rtrim($aid, '.');
            } else {
                // Find the best match
                foreach ($albs as $alb) {
                    $aname = __($alb['name']);
                    // Possibly qTranslate translated
                    $aname = str_replace('\'', '%', $aname);
                    // A trick for single quotes
                    $aname = str_replace('"', '%', $aname);
                    // A trick for double quotes
                    $aname = stripslashes($aname);
                    wppa_dbg_msg('Testing ' . $aname . ' for ' . $name . ' (get_album_id_by_name)');
                    if (strcasecmp($aname, $name) == 0) {
                        $aid = $alb['id'];
                    }
                }
                // No perfect match, take the first 'like' option
                if (!$aid) {
                    $aid = $albs[0]['id'];
                }
            }
        }
    } else {
        $aid = false;
    }
    if ($aid) {
        wppa_dbg_msg('Aid ' . $aid . ' found for ' . $name);
    } else {
        wppa_dbg_msg('No aid found for ' . $name);
    }
    return $aid;
}
function wppa_get_youngest_photo_ids($n = '3')
{
    global $wpdb;
    if (!wppa_is_int($n)) {
        $n = '3';
    }
    $result = $wpdb->get_col("SELECT `id` FROM `" . WPPA_PHOTOS . "` WHERE `status` <> 'pending' AND `status` <> 'scheduled' ORDER BY `timestamp` DESC LIMIT " . $n);
    wppa_dbg_q('Q-gypin');
    return $result;
}
function wppa_update_album($args)
{
    global $wpdb;
    if (!is_array($args)) {
        return false;
    }
    if (!$args['id']) {
        return false;
    }
    if (!wppa_cache_album($args['id'])) {
        return false;
    }
    $id = $args['id'];
    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 'modified':
                if (!$itemvalue) {
                    $itemvalue = time();
                }
                $doit = true;
                break;
            case 'cats':
                $itemvalue = wppa_sanitize_tags($itemvalue);
                $doit = true;
                break;
            case 'scheduledtm':
                $doit = true;
                break;
            case 'main_photo':
                if (wppa_is_int($itemvalue)) {
                    $doit = true;
                }
                break;
            default:
                wppa_log('Error', 'Not implemented in wppa_update_album(): ' . $itemname);
                return false;
        }
        if ($doit) {
            if ($wpdb->query($wpdb->prepare("UPDATE `" . WPPA_ALBUMS . "` SET `" . $itemname . "` = %s WHERE `id` = %s LIMIT 1", $itemvalue, $id))) {
                wppa_cache_album('invalidate');
            }
        }
    }
    return true;
    /*
    		`a_order`,
    		`main_photo`,
    		`a_parent`,
    		`p_order_by`,
    		`cover_linktype`,
    		`cover_linkpage`,
    		`owner`,
    		`upload_limit`,
    		`alt_thumbsize`,
    		`default_tags`,
    		`cover_type`,
    		`suba_order_by`,
    		`views`,
    		`cats`
    */
}
Beispiel #19
0
function wppa_breadcrumb($opt = '')
{
    global $wpdb;
    global $wppa_session;
    // See if they need us
    // Check Table II-A1 a and b
    if ($opt == 'optional') {
        $pid = wppa_get_the_page_id();
        $type = $wpdb->get_var($wpdb->prepare("SELECT `post_type` FROM `" . $wpdb->posts . "` WHERE `ID` = %s", $pid));
        wppa_dbg_q('Q-bc1');
        if ($type == 'post' && !wppa_switch('show_bread_posts')) {
            return;
            // Nothing to do here
        }
        if ($type != 'post' && !wppa_switch('show_bread_pages')) {
            return;
            // Nothing to do here
        }
    }
    // Check special cases
    if (wppa('is_single')) {
        return;
    }
    // A single image slideshow needs no navigation
    if (wppa_page('oneofone')) {
        return;
    }
    // Never at a single image page
    if (wppa('is_slideonly')) {
        return;
    }
    // Not when slideonly
    if (wppa_in_widget()) {
        return;
    }
    // Not in a widget
    if (is_feed()) {
        return;
    }
    // Not in a feed
    $thumbhref = '';
    // Any special selection has its own switch
    if (wppa('is_topten') && !wppa_switch('bc_on_topten')) {
        return;
    }
    if (wppa('is_lasten') && !wppa_switch('bc_on_lasten')) {
        return;
    }
    if (wppa('is_comten') && !wppa_switch('bc_on_comten')) {
        return;
    }
    if (wppa('is_featen') && !wppa_switch('bc_on_featen')) {
        return;
    }
    if (wppa('is_related') && !wppa_switch('bc_on_related')) {
        return;
    }
    if (wppa('is_tag') && !wppa_switch('bc_on_tag')) {
        return;
    }
    if (wppa('src') && !wppa_switch('bc_on_search')) {
        return;
    }
    // Get the album number
    $alb = wppa_is_int(wppa('start_album')) ? wppa('start_album') : '0';
    // A single album or all ( all = 0 here )
    $is_albenum = strlen(wppa('start_album')) > '0' && !wppa_is_int(wppa('start_album'));
    wppa_dbg_msg('alb=' . $alb . ', albenum=' . $is_albenum, 'green');
    $virtual = wppa_is_virtual() || wppa('last_albums');
    if (wppa('last_albums')) {
        $alb = wppa('last_albums_parent');
    }
    wppa_dbg_msg('alb=' . $alb . ', albenum=' . $is_albenum . ', l_a=' . wppa('last_albums') . ', l_a_p=' . wppa('last_albums_parent'), 'green');
    // See if the album is a 'stand alone' album
    $separate = wppa_is_separate($alb);
    // See if the album links to slides in stead of thumbnails
    $slide = wppa_get_album_title_linktype($alb) == 'slide' ? '&amp;wppa-slide' : '';
    // See if we link to covers or to contents
    $to_cover = wppa_opt('thumbtype') == 'none' ? '1' : '0';
    // Photo number?
    $photo = wppa('start_photo');
    wppa_dbg_msg('pid=' . $pid . ', type=' . $type . ', alb=' . $alb . ', sep=' . $separate . ', slide=' . $slide . ', t_c=0, ph=' . $photo, 'green');
    // Open the breadcrumb box
    wppa_out('<div' . ' id="wppa-bc-' . wppa('mocc') . '"' . ' class="wppa-nav wppa-box wppa-nav-text" ' . 'style="' . __wcs('wppa-nav') . __wcs('wppa-box') . __wcs('wppa-nav-text') . '" >');
    // Do we need Home?
    if (wppa_switch('show_home')) {
        $value = __(wppa_opt('home_text'));
        $href = wppa_dbg_url(get_bloginfo('url'));
        $title = get_bloginfo('title');
        wppa_bcitem($value, $href, $title, 'b1');
    }
    // Page ( grand )parents ?
    if ($type == 'page' && wppa_switch('show_page')) {
        wppa_crumb_page_ancestors($pid);
    }
    // Do the post/page
    if (wppa_switch('show_page')) {
        $value = __(stripslashes($wpdb->get_var($wpdb->prepare("SELECT `post_title` FROM `" . $wpdb->posts . "` WHERE `post_status` = 'publish' AND `ID` = %s LIMIT 0,1", $pid))));
        wppa_dbg_q('Q-bc2');
        $href = $alb || $virtual || $is_albenum ? wppa_get_permalink($pid, true) : '';
        $title = $type == 'post' ? __('Post:', 'wp-photo-album-plus') . ' ' . $value : __('Page:', 'wp-photo-album-plus') . ' ' . $value;
        wppa_bcitem($value, $href, $title, 'b3');
    }
    // The album ( grand ) parents if not separate
    //		if ( ! $separate ) {
    wppa_crumb_ancestors($alb, $to_cover);
    //		}
    // The album and optional placeholder for photo
    // Supersearch ?
    if (wppa('supersearch')) {
        $value = ' ';
        $ss_data = explode(',', wppa('supersearch'));
        switch ($ss_data['0']) {
            case 'a':
                $value .= ' ' . __('Albums', 'wp-photo-album-plus');
                switch ($ss_data['1']) {
                    case 'c':
                        $value .= ' ' . __('with category:', 'wp-photo-album-plus');
                        break;
                    case 'n':
                        $value .= ' ' . __('with name:', 'wp-photo-album-plus');
                        break;
                    case 't':
                        $value .= ' ' . __('with words:', 'wp-photo-album-plus');
                        break;
                }
                $value .= ' <b>' . str_replace('.', '</b> ' . __('and', 'wp-photo-album-plus') . ' <b>', $ss_data['3']) . '</b>';
                break;
            case 'p':
                $value .= ' ' . __('Photos', 'wp-photo-album-plus');
                switch ($ss_data['1']) {
                    case 'g':
                        $value .= ' ' . __('with tag:', 'wp-photo-album-plus') . ' <b>' . str_replace('.', '</b> ' . __('and', 'wp-photo-album-plus') . ' <b>', $ss_data['3']) . '</b>';
                        break;
                    case 'n':
                        $value .= ' ' . __('with name:', 'wp-photo-album-plus') . ' <b>' . $ss_data['3'] . '</b>';
                        break;
                    case 't':
                        $ss_data['3'] = str_replace('...', '***', $ss_data['3']);
                        $value .= ' ' . __('with words:', 'wp-photo-album-plus') . ' <b>' . str_replace('.', '</b> ' . __('and', 'wp-photo-album-plus') . ' <b>', $ss_data['3']) . '</b>';
                        $value = str_replace('***', '...', $value);
                        break;
                    case 'o':
                        $value .= ' ' . __('of owner:', 'wp-photo-album-plus') . ' <b>' . $ss_data['3'] . '</b>';
                        break;
                    case 'i':
                        $label = $wpdb->get_var($wpdb->prepare("SELECT `description` FROM `" . WPPA_IPTC . "` WHERE `tag` = %s AND `photo` = '0'", str_replace('H', '#', $ss_data['2'])));
                        $label = trim($label, ':');
                        $value .= ' ' . __('with iptc tag:', 'wp-photo-album-plus') . ' <b>' . __($label, 'wp-photo-album-plus') . '</b> ' . __('with content:', 'wp-photo-album-plus') . ' <b>' . $ss_data['3'] . '</b>';
                        break;
                    case 'e':
                        $label = $wpdb->get_var($wpdb->prepare("SELECT `description` FROM `" . WPPA_EXIF . "` WHERE `tag` = %s AND `photo` = '0'", str_replace('H', '#', $ss_data['2'])));
                        $label = trim($label, ':');
                        $value .= ' ' . __('with exif tag:', 'wp-photo-album-plus') . ' <b>' . __($label, 'wp-photo-album-plus') . '</b> ' . __('with content:', 'wp-photo-album-plus') . ' <b>' . $ss_data['3'] . '</b>';
                        break;
                }
                break;
        }
        if (wppa('is_slide')) {
            $thumbhref = wppa_get_permalink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-supersearch=' . stripslashes(wppa('supersearch'));
            $thumbajax = wppa_get_ajaxlink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-supersearch=' . stripslashes(wppa('supersearch'));
            $title = __('View the thumbnails', 'wp-photo-album-plus');
            wppa_bcitem($value, $thumbhref, $title, 'b8', $thumbajax);
        }
        $href = '';
        $title = '';
        wppa_bcitem($value, $href, $title, 'b9');
    } elseif (wppa('src') && !wppa('is_related')) {
        $searchroot = $wppa_session['search_root'];
        if (!$searchroot) {
            $searchroot = '-2';
            // To get 'All albums'
        }
        $albtxt = wppa('is_rootsearch') ? ' <span style="cursor:pointer;" title="' . esc_attr(sprintf(__('Searchresults from album %s and its subalbums', 'wp-photo-album-plus'), wppa_display_root($searchroot))) . '">*</span> ' : '';
        if (wppa('is_slide')) {
            $value = __('Searchstring:', 'wp-photo-album-plus') . ' ' . (isset($wppa_session['display_searchstring']) ? $wppa_session['display_searchstring'] : stripslashes(wppa('searchstring'))) . $albtxt;
            $thumbhref = wppa_get_permalink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-searchstring=' . stripslashes(str_replace(' ', '+', $wppa_session['use_searchstring']));
            $thumbajax = wppa_get_ajaxlink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-searchstring=' . stripslashes(str_replace(' ', '+', $wppa_session['use_searchstring']));
            $title = __('View the thumbnails', 'wp-photo-album-plus');
            wppa_bcitem($value, $thumbhref, $title, 'b8', $thumbajax);
        }
        $value = __('Searchstring:', 'wp-photo-album-plus') . ' ' . (isset($wppa_session['display_searchstring']) ? $wppa_session['display_searchstring'] : stripslashes(wppa('searchstring'))) . $albtxt;
        $href = '';
        $title = isset($wppa_session['display_searchstring']) ? wppa_dss_to_title($wppa_session['display_searchstring']) : '';
        wppa_bcitem($value, $href, $title, 'b9');
    } elseif (wppa('calendar')) {
        if (wppa('is_slide')) {
            switch (wppa('calendar')) {
                case 'exifdtm':
                    $value = __('Photos by EXIF date', 'wp-photo-album-plus') . ': ' . wppa('caldate');
                    break;
                case 'timestamp':
                    $value = __('Photos by date of upload', 'wp-photo-album-plus') . ': ' . date('M d D Y', wppa('caldate') * 24 * 60 * 60);
                    break;
                case 'modified':
                    $value = __('Photos by date last modified', 'wp-photo-album-plus') . ': ' . date('M d D Y', wppa('caldate') * 24 * 60 * 60);
                    break;
            }
            $thumbhref = '#';
            $title = 'T8';
            wppa_bcitem($value, $thumbhref, $title, 'b8');
        }
        switch (wppa('calendar')) {
            case 'exifdtm':
                $value = __('Photos by EXIF date', 'wp-photo-album-plus') . ': ' . wppa('caldate');
                break;
            case 'timestamp':
                $value = __('Photos by date of upload', 'wp-photo-album-plus') . ': ' . date('M d D Y', wppa('caldate') * 24 * 60 * 60);
                break;
            case 'modified':
                $value = __('Photos by date last modified', 'wp-photo-album-plus') . ': ' . date('M d D Y', wppa('caldate') * 24 * 60 * 60);
                break;
        }
        $href = '';
        $title = '';
        wppa_bcitem($value, $href, $title, 'b9');
    } elseif (wppa('is_upldr')) {
        $usr = get_user_by('login', wppa('is_upldr'));
        if ($usr) {
            $user = $usr->display_name;
        } else {
            $user = wppa('is_upldr');
        }
        if (wppa('is_slide')) {
            $value = sprintf(__('Photos by %s', 'wp-photo-album-plus'), $user);
            if (wppa('start_album')) {
                $thumbhref = wppa_get_permalink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-upldr=' . wppa('is_upldr') . '&amp;wppa-album=' . wppa('start_album');
                $thumbajax = wppa_get_ajaxlink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-upldr=' . wppa('is_upldr') . '&amp;wppa-album=' . wppa('start_album');
            } else {
                $thumbhref = wppa_get_permalink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-upldr=' . wppa('is_upldr');
                $thumbajax = wppa_get_ajaxlink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-upldr=' . wppa('is_upldr');
            }
            $title = __('View the thumbnails', 'wp-photo-album-plus');
            wppa_bcitem($value, $thumbhref, $title, 'b8', $thumbajax);
        }
        $value = sprintf(__('Photos by %s', 'wp-photo-album-plus'), $user);
        $href = '';
        $title = '';
        wppa_bcitem($value, $href, $title, 'b9');
    } elseif (wppa('is_topten')) {
        // TopTen
        if (wppa('start_album')) {
            $value = $is_albenum ? __('Various albums', 'wp-photo-album-plus') : wppa_get_album_name($alb);
            $href = wppa_get_permalink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-album=' . wppa('start_album');
            $ajax = wppa_get_ajaxlink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-album=' . wppa('start_album');
            $title = $is_albenum ? __('Albums:', 'wp-photo-album-plus') . ' ' . wppa('start_album') : __('Album:', 'wp-photo-album-plus') . ' ' . $value;
            wppa_bcitem($value, $href, $title, 'b7', $ajax);
        }
        if (wppa('is_slide')) {
            $value = __('Top rated photos', 'wp-photo-album-plus');
            $thumbhref = wppa_get_permalink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-topten=' . wppa('topten_count') . '&amp;wppa-album=' . wppa('start_album');
            $thumbajax = wppa_get_ajaxlink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-topten=' . wppa('topten_count') . '&amp;wppa-album=' . wppa('start_album');
            $title = __('View the thumbnails', 'wp-photo-album-plus');
            wppa_bcitem($value, $thumbhref, $title, 'b8', $thumbajax);
        }
        $value = __('Top rated photos', 'wp-photo-album-plus');
        $href = '';
        $title = '';
        wppa_bcitem($value, $href, $title, 'b9');
    } elseif (wppa('is_lasten')) {
        // Lasten
        if (wppa('start_album')) {
            $value = $is_albenum ? __('Various albums', 'wp-photo-album-plus') : wppa_get_album_name($alb);
            $href = wppa_get_permalink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-album=' . wppa('start_album');
            $ajax = wppa_get_ajaxlink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-album=' . wppa('start_album');
            $title = $is_albenum ? __('Albums:', 'wp-photo-album-plus') . ' ' . wppa('start_album') : __('Album:', 'wp-photo-album-plus') . ' ' . $value;
            wppa_bcitem($value, $href, $title, 'b7', $ajax);
        }
        if (wppa('is_slide')) {
            if (wppa_switch('lasten_use_modified')) {
                $value = __('Recently modified photos', 'wp-photo-album-plus');
            } else {
                $value = __('Recently uploaded photos', 'wp-photo-album-plus');
            }
            $thumbhref = wppa_get_permalink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-lasten=' . wppa('lasten_count') . '&amp;wppa-album=' . wppa('start_album');
            $thumbajax = wppa_get_ajaxlink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-lasten=' . wppa('lasten_count') . '&amp;wppa-album=' . wppa('start_album');
            $title = __('View the thumbnails', 'wp-photo-album-plus');
            wppa_bcitem($value, $thumbhref, $title, 'b8', $thumbajax);
        }
        if (wppa_switch('lasten_use_modified')) {
            $value = __('Recently modified photos', 'wp-photo-album-plus');
        } else {
            $value = __('Recently uploaded photos', 'wp-photo-album-plus');
        }
        $href = '';
        $title = '';
        wppa_bcitem($value, $href, $title, 'b9');
    } elseif (wppa('is_comten')) {
        // Comten
        if (wppa('start_album')) {
            $value = $is_albenum ? __('Various albums', 'wp-photo-album-plus') : wppa_get_album_name($alb);
            $href = wppa_get_permalink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-album=' . wppa('start_album');
            $ajax = wppa_get_ajaxlink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-album=' . wppa('start_album');
            $title = $is_albenum ? __('Albums:', 'wp-photo-album-plus') . ' ' . wppa('start_album') : __('Album:', 'wp-photo-album-plus') . ' ' . $value;
            wppa_bcitem($value, $href, $title, 'b7', $ajax);
        }
        if (wppa('is_slide')) {
            $value = __('Recently commented photos', 'wp-photo-album-plus');
            $thumbhref = wppa_get_permalink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-comten=' . wppa('comten_count') . '&amp;wppa-album=' . wppa('start_album');
            $thumbajax = wppa_get_ajaxlink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-comten=' . wppa('comten_count') . '&amp;wppa-album=' . wppa('start_album');
            $title = __('View the thumbnails', 'wp-photo-album-plus');
            wppa_bcitem($value, $thumbhref, $title, 'b8', $thumbajax);
        }
        $value = __('Recently commented photos', 'wp-photo-album-plus');
        $href = '';
        $title = '';
        wppa_bcitem($value, $href, $title, 'b9');
    } elseif (wppa('is_featen')) {
        // Featen
        if (wppa('start_album')) {
            $value = $is_albenum ? __('Various albums', 'wp-photo-album-plus') : wppa_get_album_name($alb);
            $href = wppa_get_permalink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-album=' . wppa('start_album');
            $ajax = wppa_get_ajaxlink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-album=' . wppa('start_album');
            $title = $is_albenum ? __('Albums:', 'wp-photo-album-plus') . ' ' . wppa('start_album') : __('Album:', 'wp-photo-album-plus') . ' ' . $value;
            wppa_bcitem($value, $href, $title, 'b7', $ajax);
        }
        if (wppa('is_slide')) {
            $value = __('Featured photos', 'wp-photo-album-plus');
            $thumbhref = wppa_get_permalink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-featen=' . wppa('featen_count') . '&amp;wppa-album=' . wppa('start_album');
            $thumbajax = wppa_get_ajaxlink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-featen=' . wppa('featen_count') . '&amp;wppa-album=' . wppa('start_album');
            $title = __('View the thumbnails', 'wp-photo-album-plus');
            wppa_bcitem($value, $thumbhref, $title, 'b8', $thumbajax);
        }
        $value = __('Featured photos', 'wp-photo-album-plus');
        $href = '';
        $title = '';
        wppa_bcitem($value, $href, $title, 'b9');
    } elseif (wppa('is_related')) {
        // Related photos
        if (wppa('is_slide')) {
            $value = __('Related photos', 'wp-photo-album-plus');
            $href = wppa_get_permalink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-tag=' . wppa('is_tag') . '&amp;wppa-album=' . wppa('start_album');
            $ajax = wppa_get_ajaxlink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-tag=' . wppa('is_tag') . '&amp;wppa-album=' . wppa('start_album');
            $title = __('View the thumbnails', 'wp-photo-album-plus');
            wppa_bcitem($value, $href, $title, 'b8', $ajax);
        }
        $value = __('Related photos', 'wp-photo-album-plus');
        $href = '';
        $title = '';
        wppa_bcitem($value, $href, $title, 'b9');
    } elseif (wppa('is_tag')) {
        // Tagged photos
        if (wppa('is_slide')) {
            $value = __('Tagged photos:', 'wp-photo-album-plus') . '&nbsp;' . str_replace(';', ' ' . __('or', 'wp-photo-album-plus') . ' ', str_replace(',', ' ' . __('and', 'wp-photo-album-plus') . ' ', trim(wppa('is_tag'), ',;')));
            if (wppa_get_get('inv')) {
                $value .= ' (' . __('Inverted', 'wp-photo-album-plus') . ')';
            }
            $thumbhref = wppa_get_permalink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-tag=' . wppa('is_tag') . '&amp;wppa-album=' . wppa('start_album');
            $thumbajax = wppa_get_ajaxlink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-tag=' . wppa('is_tag') . '&amp;wppa-album=' . wppa('start_album');
            if (wppa('is_inverse')) {
                $thumbhref .= '&amp;wppa-inv=1';
                $thumbajax .= '&amp;wppa-inv=1';
            }
            $title = __('View the thumbnails', 'wp-photo-album-plus');
            wppa_bcitem($value, $thumbhref, $title, 'b8', $thumbajax);
        }
        $value = __('Tagged photos:', 'wp-photo-album-plus') . '&nbsp;' . str_replace(';', ' ' . __('or', 'wp-photo-album-plus') . ' ', str_replace(',', ' ' . __('and', 'wp-photo-album-plus') . ' ', trim(wppa('is_tag'), ',;')));
        if (wppa_get_get('inv')) {
            $value .= ' (' . __('Inverted', 'wp-photo-album-plus') . ')';
        }
        $href = '';
        $title = '';
        wppa_bcitem($value, $href, $title, 'b9');
    } elseif (wppa('is_cat')) {
        // Categorized albums
        if (wppa('is_slide')) {
            $value = __('Category:', 'wp-photo-album-plus') . '&nbsp;' . wppa('is_cat');
            //str_replace( ';', ' '.__( 'or' ).' ', str_replace( ',', ' '.__( 'and' ).' ', trim( wppa( 'is_tag' ), ',;' ) ) );
            $thumbhref = wppa_get_permalink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-cat=' . wppa('is_cat') . '&amp;wppa-album=' . wppa('start_album');
            $thumbajax = wppa_get_ajaxlink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-cat=' . wppa('is_cat') . '&amp;wppa-album=' . wppa('start_album');
            $title = __('View the thumbnails', 'wp-photo-album-plus');
            wppa_bcitem($value, $thumbhref, $title, 'b8', $thumbajax);
        }
        $value = __('Category:', 'wp-photo-album-plus') . '&nbsp;' . wppa('is_cat');
        //str_replace( ';', ' '.__( 'or' ).' ', str_replace( ',', ' '.__( 'and' ).' ', trim( wppa( 'is_tag' ), ',;' ) ) );
        $href = '';
        $title = '';
        wppa_bcitem($value, $href, $title, 'b9');
    } elseif (wppa('last_albums')) {
        // Recently modified albums( s )
        if (wppa('last_albums_parent')) {
            $value = wppa_get_album_name($alb);
            $href = wppa_get_permalink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-album=' . wppa('start_album');
            $ajax = wppa_get_ajaxlink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-album=' . wppa('start_album');
            $title = __('Album:', 'wp-photo-album-plus') . ' ' . $value;
            wppa_bcitem($value, $href, $title, 'b7', $ajax);
        }
        if (wppa('is_slide')) {
            $value = __('Recently updated albums', 'wp-photo-album-plus');
            $thumbhref = wppa_get_permalink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-album=' . wppa('start_album');
            $thumbajax = wppa_get_ajaxlink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-album=' . wppa('start_album');
            $title = __('View the thumbnails', 'wp-photo-album-plus');
            wppa_bcitem($value, $thumbhref, $title, 'b8', $thumbajax);
        }
        $value = __('Recently updated albums', 'wp-photo-album-plus');
        $href = '';
        $title = '';
        wppa_bcitem($value, $href, $title, 'b9');
    } else {
        // Maybe a simple normal standard album???
        if (wppa('is_owner')) {
            $usr = get_user_by('login', wppa('is_owner'));
            if ($usr) {
                $dispname = $usr->display_name;
            } else {
                $dispname = wppa('is_owner');
            }
            // User deleted
            $various = sprintf(__('Various albums by %s', 'wp-photo-album-plus'), $dispname);
        } else {
            $various = __('Various albums', 'wp-photo-album-plus');
        }
        if (wppa('is_slide')) {
            $value = $is_albenum ? $various : wppa_get_album_name($alb);
            $href = wppa_get_permalink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-album=' . wppa('start_album');
            $ajax = wppa_get_ajaxlink() . 'wppa-cover=0&amp;wppa-occur=' . wppa('occur') . '&amp;wppa-album=' . wppa('start_album');
            $title = $is_albenum ? __('Albums:', 'wp-photo-album-plus') . ' ' . wppa('start_album') : __('Album:', 'wp-photo-album-plus') . ' ' . $value;
            wppa_bcitem($value, $href, $title, 'b7', $ajax);
        }
        $value = $is_albenum ? $various : wppa_get_album_name($alb);
        $href = '';
        $title = '';
        $class = 'b10';
        wppa_bcitem($value, $href, $title, $class);
    }
    // 'Go to thumbnail display' - icon
    if (wppa('is_slide') && !wppa('calendar')) {
        if (wppa_switch('bc_slide_thumblink')) {
            //				$pg = ( ( wppa_opt('thumb_page_size' ) == wppa_opt( 'slideshow_pagesize' ) ) && wppa_get_curpage() != '1' ) ? '&wppa-page='.wppa_get_curpage() : '';
            //				$thumbhref .= $pg;
            if ($virtual) {
                if ($thumbhref) {
                    $thumbhref = wppa_trim_wppa_($thumbhref);
                    $fs = wppa_opt('fontsize_nav');
                    if ($fs != '') {
                        $fs += 3;
                    } else {
                        $fs = '15';
                    }
                    // iconsize = fontsize+3, Default to 15
                    $imgs = 'height: ' . $fs . 'px; margin:0 0 -3px 0; padding:0; box-shadow:none;';
                    wppa_out('<a href="' . $thumbhref . '" title="' . __('Thumbnail view', 'wp-photo-album-plus') . '" class="wppa-nav-text" style="' . __wcs('wppa-nav-text') . 'float:right; cursor:pointer;" ' . 'onmouseover="jQuery(\'#wppa-tnv-' . wppa('mocc') . '\').css(\'display\', \'none\'); jQuery(\'#wppa-tnvh-' . wppa('mocc') . '\').css(\'display\', \'\')" ' . 'onmouseout="jQuery(\'#wppa-tnv-' . wppa('mocc') . '\').css(\'display\', \'\'); jQuery(\'#wppa-tnvh-' . wppa('mocc') . '\').css(\'display\', \'none\')" >' . '<img id="wppa-tnv-' . wppa('mocc') . '" class="wppa-tnv" src="' . wppa_get_imgdir() . 'application_view_icons.png" alt="' . __('Thumbs', 'wp-photo-album-plus') . '" style="' . $imgs . '" />' . '<img id="wppa-tnvh-' . wppa('mocc') . '" class="wppa-tnv" src="' . wppa_get_imgdir() . 'application_view_icons_hover.png" alt="' . __('Thumbs', 'wp-photo-album-plus') . '" style="display:none;' . $imgs . '" />' . '</a>');
                }
            } else {
                $s = wppa('src') ? '&wppa-searchstring=' . urlencode(wppa('searchstring')) : '';
                $onclick = "wppaDoAjaxRender( " . wppa('mocc') . ", '" . wppa_get_album_url_ajax(wppa('start_album'), '0') . "&amp;wppa-photos-only=1" . $s . "', '" . wppa_convert_to_pretty(wppa_get_album_url(wppa('start_album'), '0') . '&wppa-photos-only=1' . $s) . "' )";
                $fs = wppa_opt('fontsize_nav');
                if ($fs != '') {
                    $fs += 3;
                } else {
                    $fs = '15';
                }
                // iconsize = fontsize+3, Default to 15
                $imgs = 'height: ' . $fs . 'px; margin:0 0 -3px 0; padding:0; box-shadow:none;';
                wppa_out('<a title="' . __('Thumbnail view', 'wp-photo-album-plus') . '" class="wppa-nav-text" style="' . __wcs('wppa-nav-text') . 'float:right; cursor:pointer;" ' . 'onclick="' . $onclick . '" ' . 'onmouseover="jQuery(\'#wppa-tnv-' . wppa('mocc') . '\').css(\'display\', \'none\'); jQuery(\'#wppa-tnvh-' . wppa('mocc') . '\').css(\'display\', \'\')" ' . 'onmouseout="jQuery(\'#wppa-tnv-' . wppa('mocc') . '\').css(\'display\', \'\'); jQuery(\'#wppa-tnvh-' . wppa('mocc') . '\').css(\'display\', \'none\')" >' . '<img id="wppa-tnv-' . wppa('mocc') . '" class="wppa-tnv" src="' . wppa_get_imgdir() . 'application_view_icons.png" alt="' . __('Thumbs', 'wp-photo-album-plus') . '" style="' . $imgs . '" />' . '<img id="wppa-tnvh-' . wppa('mocc') . '" class="wppa-tnv" src="' . wppa_get_imgdir() . 'application_view_icons_hover.png" alt="' . __('Thumbs', 'wp-photo-album-plus') . '" style="display:none;' . $imgs . '" />' . '</a>');
            }
        }
    }
    // Close the breadcrumb box
    wppa_out('<div style="clear:both;" ></div>');
    wppa_out('</div>');
}
function wppa_prep_for_csv($data)
{
    // Replace " by ""
    $result = str_replace('"', '""', $data);
    if (wppa_is_int($result)) {
        $result = strval(intval($result));
    } elseif ($result) {
        $result = '"' . $result . '"';
    }
    return $result;
}
function wppa_import_photos($delp = false, $dela = false, $delz = false, $delv = false, $delu = false, $delc = false, $delf = false)
{
    global $wpdb;
    global $warning_given;
    global $wppa_supported_photo_extensions;
    global $wppa_supported_video_extensions;
    global $wppa_supported_audio_extensions;
    $warning_given = false;
    // Get this users current source directory setting
    $user = wppa_get_user();
    $source_type = get_option('wppa_import_source_type_' . $user, 'local');
    if ($source_type == 'remote') {
        wppa('is_remote', true);
    }
    $source = get_option('wppa_import_source_' . $user, WPPA_DEPOT_PATH);
    $depot = WPPA_ABSPATH . $source;
    // Filesystem
    $depoturl = get_bloginfo('wpurl') . '/' . $source;
    // url
    // See what's in there
    $files = wppa_get_import_files();
    // First extract zips if our php version is ok
    $idx = '0';
    $zcount = 0;
    if (PHP_VERSION_ID >= 50207) {
        foreach ($files as $zipfile) {
            if (isset($_POST['file-' . $idx])) {
                $ext = strtolower(substr(strrchr($zipfile, "."), 1));
                if ($ext == 'zip') {
                    $err = wppa_extract($zipfile, $delz);
                    if ($err == '0') {
                        $zcount++;
                    }
                }
                // if ext = zip
            }
            // if isset
            $idx++;
        }
        // foreach
    }
    // Now see if albums must be created
    $idx = '0';
    $acount = 0;
    foreach ($files as $album) {
        if (isset($_POST['file-' . $idx])) {
            $ext = strtolower(substr(strrchr($album, "."), 1));
            if ($ext == 'amf') {
                $name = '';
                $desc = '';
                $aord = '0';
                $parent = '0';
                $porder = '0';
                $owner = '';
                $handle = fopen($album, "r");
                if ($handle) {
                    $buffer = fgets($handle, 4096);
                    while (!feof($handle)) {
                        $tag = substr($buffer, 0, 5);
                        $len = strlen($buffer) - 6;
                        // substract 5 for label and one for eol
                        $data = substr($buffer, 5, $len);
                        switch ($tag) {
                            case 'name=':
                                $name = $data;
                                break;
                            case 'desc=':
                                $desc = wppa_txt_to_nl($data);
                                break;
                            case 'aord=':
                                if (is_numeric($data)) {
                                    $aord = $data;
                                }
                                break;
                            case 'prnt=':
                                if ($data == __('--- none ---', 'wp-photo-album-plus')) {
                                    $parent = '0';
                                } elseif ($data == __('--- separate ---', 'wp-photo-album-plus')) {
                                    $parent = '-1';
                                } else {
                                    $prnt = wppa_get_album_id($data);
                                    if ($prnt != '') {
                                        $parent = $prnt;
                                    } else {
                                        $parent = '0';
                                        wppa_warning_message(__('Unknown parent album:', 'wp-photo-album-plus') . ' ' . $data . ' ' . __('--- none --- used.', 'wp-photo-album-plus'));
                                    }
                                }
                                break;
                            case 'pord=':
                                if (is_numeric($data)) {
                                    $porder = $data;
                                }
                                break;
                            case 'ownr=':
                                $owner = $data;
                                break;
                        }
                        $buffer = fgets($handle, 4096);
                    }
                    // while !foef
                    fclose($handle);
                    if (wppa_get_album_id($name) != '') {
                        wppa_warning_message('Album already exists ' . stripslashes($name));
                        if ($dela) {
                            unlink($album);
                        }
                    } else {
                        $id = basename($album);
                        $id = substr($id, 0, strpos($id, '.'));
                        $id = wppa_create_album_entry(array('id' => $id, 'name' => stripslashes($name), 'description' => stripslashes($desc), 'a_order' => $aord, 'a_parent' => $parent, 'p_order_by' => $porder, 'owner' => $owner));
                        if ($id === false) {
                            wppa_error_message(__('Could not create album.', 'wp-photo-album-plus'));
                        } else {
                            //$id = wppa_get_album_id( $name );
                            wppa_set_last_album($id);
                            wppa_index_add('album', $id);
                            wppa_ok_message(__('Album #', 'wp-photo-album-plus') . ' ' . $id . ': ' . stripslashes($name) . ' ' . __('Added.', 'wp-photo-album-plus'));
                            if ($dela) {
                                unlink($album);
                            }
                            $acount++;
                            wppa_clear_cache();
                            wppa_flush_treecounts($id);
                        }
                        // album added
                    }
                    // album did not exist
                }
                // if handle ( file open )
            }
            // if its an album
        }
        // if isset
        $idx++;
    }
    // foreach file
    // Now the photos
    $idx = '0';
    $pcount = '0';
    $totpcount = '0';
    // find album id
    if (isset($_POST['cre-album'])) {
        // use album ngg gallery name for ngg conversion
        $album = wppa_get_album_id(strip_tags($_POST['cre-album']));
        if (!$album) {
            // the album does not exist yet, create it
            $name = strip_tags($_POST['cre-album']);
            $desc = sprintf(__('This album has been converted from ngg gallery %s', 'wp-photo-album-plus'), $name);
            $uplim = '0/0';
            // Unlimited not to destroy the conversion process!!
            $album = wppa_create_album_entry(array('name' => $name, 'description' => $desc, 'upload_limit' => $uplim));
            if ($album === false) {
                wppa_error_message(__('Could not create album.', 'wp-photo-album-plus') . '<br/>Query = ' . $query);
                wp_die('Sorry, cannot continue');
            }
        }
    } elseif (isset($_POST['wppa-photo-album'])) {
        $album = $_POST['wppa-photo-album'];
    } else {
        $album = '0';
    }
    // Report starting process
    wppa_ok_message(__('Processing files, please wait...', 'wp-photo-album-plus') . ' ' . __('If the line of dots stops growing or your browser reports Ready, your server has given up. In that case: try again', 'wp-photo-album-plus') . ' <a href="' . wppa_dbg_url(get_admin_url() . 'admin.php?page=wppa_import_photos') . '">' . __('here.', 'wp-photo-album-plus') . '</a>');
    // Do them all
    foreach (array_keys($files) as $file_idx) {
        $unsanitized_path_name = $files[$file_idx];
        $file = $files[$file_idx];
        wppa_is_wppa_tree($file);
        // Sets wppa( 'is_wppa_tree' )
        if (isset($_POST['use-backup']) && is_file($file . '_backup')) {
            $file = $file . '_backup';
        }
        $file = wppa_sanitize_file_name($file);
        if (isset($_POST['file-' . $idx]) || wppa('ajax')) {
            if (wppa('is_wppa_tree')) {
                if (wppa('ajax')) {
                    wppa('ajax_import_files', basename(wppa_compress_tree_path($file)));
                }
            } else {
                if (wppa('ajax')) {
                    wppa('ajax_import_files', basename($file));
                }
            }
            $ext = strtolower(substr(strrchr($file, "."), 1));
            $ext = str_replace('_backup', '', $ext);
            if (in_array($ext, $wppa_supported_photo_extensions)) {
                // See if a metafile exists
                //$meta = substr( $file, 0, strlen( $file ) - 3 ).'pmf';
                $meta = wppa_strip_ext($unsanitized_path_name) . '.PMF';
                if (!is_file($meta)) {
                    $meta = wppa_strip_ext($unsanitized_path_name) . '.pmf';
                }
                // find all data: name, desc, porder form metafile
                if (is_file($meta)) {
                    $alb = wppa_get_album_id(wppa_get_meta_album($meta));
                    $name = wppa_get_meta_name($meta);
                    $desc = wppa_txt_to_nl(wppa_get_meta_desc($meta));
                    $porder = wppa_get_meta_porder($meta);
                    $linkurl = wppa_get_meta_linkurl($meta);
                    $linktitle = wppa_get_meta_linktitle($meta);
                } else {
                    $alb = $album;
                    // default album
                    $name = '';
                    // default name
                    $desc = '';
                    // default description
                    $porder = '0';
                    // default p_order
                    $linkurl = '';
                    $linktitle = '';
                }
                // If there is a video or audio with the same name, this is the poster.
                $is_poster = wppa_file_is_in_album(wppa_strip_ext(basename($file)) . '.xxx', $alb);
                if ($is_poster) {
                    // Delete possible poster sourcefile
                    wppa_delete_source(basename($file), $alb);
                    // Remove possible existing posters, the file-extension may be different as before
                    $old_photo = wppa_strip_ext(wppa_get_photo_path($is_poster));
                    $old_thumb = wppa_strip_ext(wppa_get_thumb_path($is_poster));
                    foreach ($wppa_supported_photo_extensions as $pext) {
                        if (is_file($old_photo . '.' . $pext)) {
                            unlink($old_photo . '.' . $pext);
                        }
                        if (is_file($old_thumb . '.' . $pext)) {
                            unlink($old_thumb . '.' . $pext);
                        }
                    }
                    // Clear sizes on db
                    wppa_update_photo(array('thumbx' => '0', 'thumby' => '0', 'photox' => '0', 'photoy' => '0'));
                    // Make new files
                    $bret = wppa_make_the_photo_files($file, $is_poster, strtolower(wppa_get_ext(basename($file))));
                    if ($bret) {
                        // Success
                        if (wppa('ajax')) {
                            wppa('ajax_import_files_done', true);
                        }
                        wppa_save_source($file, basename($file), $alb);
                        wppa_make_o1_source($is_poster);
                        $pcount++;
                        $totpcount += $bret;
                        if ($delp) {
                            unlink($file);
                        }
                    } else {
                        // Failed
                        if (!wppa('ajax')) {
                            wppa_error_message('Failed to add poster for item ' . $is_poster);
                        }
                        if ($delf) {
                            unlink($file);
                        }
                    }
                } elseif (isset($_POST['wppa-update'])) {
                    if (wppa('is_wppa_tree')) {
                        $tmp = explode('/wppa/', $file);
                        $name = str_replace('/', '', $tmp[1]);
                    }
                    $iret = wppa_update_photo_files($unsanitized_path_name, $name);
                    if ($iret) {
                        if (wppa('ajax')) {
                            wppa('ajax_import_files_done', true);
                        }
                        $pcount++;
                        $totpcount += $iret;
                        if ($delp) {
                            unlink($unsanitized_path_name);
                        }
                    } else {
                        if ($delf) {
                            unlink($unsanitized_path_name);
                        }
                    }
                } else {
                    if (is_numeric($alb) && $alb != '0') {
                        if (wppa('is_wppa_tree')) {
                            $tmp = explode('/wppa/', $file);
                            $id = str_replace('/', '', $tmp[1]);
                            $name = $id;
                        } else {
                            $id = basename($file);
                        }
                        if (wppa_switch('void_dups') && wppa_file_is_in_album($id, $alb)) {
                            wppa_warning_message(sprintf(__('Photo %s already exists in album %s. (1)', 'wp-photo-album-plus'), $id, $alb));
                            wppa('ajax_import_files_error', __('Duplicate', 'wp-photo-album-plus'));
                            if ($delf) {
                                unlink($file);
                            }
                        } else {
                            $id = substr($id, 0, strpos($id, '.'));
                            if (!is_numeric($id) || !wppa_is_id_free('photo', $id)) {
                                $id = 0;
                            }
                            if (wppa_insert_photo($unsanitized_path_name, $alb, stripslashes($name), stripslashes($desc), $porder, $id, stripslashes($linkurl), stripslashes($linktitle))) {
                                if (wppa('ajax')) {
                                    wppa('ajax_import_files_done', true);
                                }
                                $pcount++;
                                if ($delp) {
                                    unlink($unsanitized_path_name);
                                    if (is_file($meta)) {
                                        unlink($meta);
                                    }
                                }
                            } else {
                                wppa_error_message(__('Error inserting photo', 'wp-photo-album-plus') . ' ' . basename($file) . '.');
                                if ($delf) {
                                    unlink($unsanitized_path_name);
                                }
                            }
                        }
                    } else {
                        wppa_error_message(sprintf(__('Error inserting photo %s, unknown or non existent album.', 'wp-photo-album-plus'), basename($file)));
                    }
                }
                // Insert
            }
        }
        $idx++;
        if ($source_type == 'remote') {
            unset($files[$file_idx]);
        }
        if (wppa_is_time_up()) {
            wppa_warning_message(sprintf(__('Time out. %s photos imported. Please restart this operation.', 'wp-photo-album-plus'), $pcount));
            wppa_set_last_album($album);
            if ($source_type == 'remote') {
                update_option('wppa_import_source_url_found_' . $user, $files);
            }
            return;
        }
    }
    // foreach $files
    if ($source_type == 'remote') {
        update_option('wppa_import_source_url_found_' . $user, $files);
    }
    // Now the dirs to album imports
    $idx = '0';
    $dircount = '0';
    global $photocount;
    $photocount = '0';
    $iret = true;
    foreach ($files as $file) {
        if (basename($file) != '.' && basename($file) != '..' && (isset($_POST['file-' . $idx]) || isset($_GET['continue']))) {
            if (is_dir($file)) {
                $iret = wppa_import_dir_to_album($file, '0');
                if (wppa_is_time_up() && wppa_switch('auto_continue')) {
                    wppa('continue', 'continue');
                }
                $dircount++;
            }
        }
        $idx++;
        if ($iret == false) {
            break;
        }
        // Time out
    }
    // Now the video files
    $videocount = '0';
    $alb = isset($_POST['wppa-video-album']) ? $_POST['wppa-video-album'] : '0';
    if (wppa('ajax') && !$alb) {
        wppa('ajax_import_files_error', __('Unknown album', 'wp-photo-album-plus'));
    } else {
        foreach (array_keys($files) as $idx) {
            $file = $files[$idx];
            if (isset($_POST['file-' . $idx]) || wppa('ajax')) {
                if (wppa('ajax')) {
                    wppa('ajax_import_files', wppa_sanitize_file_name(basename($file)));
                }
                /* */
                $ext = strtolower(substr(strrchr($file, "."), 1));
                if (in_array($ext, $wppa_supported_video_extensions)) {
                    if (is_numeric($alb) && $alb != '0') {
                        // Do we have this filename with ext xxx in this album?
                        $filename = wppa_strip_ext(basename($file)) . '.xxx';
                        $id = wppa_file_is_in_album($filename, $alb);
                        // Or maybe the poster is already there
                        foreach ($wppa_supported_photo_extensions as $pext) {
                            if (!$id) {
                                $id = wppa_file_is_in_album(str_replace('xxx', $pext, $filename), $alb);
                            }
                        }
                        // This filename already exists: is the poster. Fix the filename in the photo info
                        if ($id) {
                            $fname = wppa_get_photo_item($id, 'filename');
                            $fname = wppa_strip_ext($fname) . '.xxx';
                            // Fix filename and ext in photo info
                            wppa_update_photo(array('id' => $id, 'filename' => $fname, 'ext' => 'xxx'));
                        }
                        // Add new entry
                        if (!$id) {
                            $id = wppa_create_photo_entry(array('album' => $alb, 'filename' => $filename, 'ext' => 'xxx', 'name' => wppa_strip_ext($filename)));
                            wppa_flush_treecounts($alb);
                        }
                        // Add video filetype
                        $newpath = wppa_strip_ext(wppa_get_photo_path($id)) . '.' . $ext;
                        $fs = filesize($file);
                        if ($fs > 1024 * 1024 * 64 || $delv) {
                            // copy fails for files > 64 Mb
                            // Remove old version if already exists
                            if (is_file($newpath)) {
                                unlink($newpath);
                            }
                            rename($file, $newpath);
                        } else {
                            copy($file, $newpath);
                        }
                        if (wppa('ajax')) {
                            wppa('ajax_import_files_done', true);
                        }
                        // Make sure ext is set to xxx after adding video to an existing poster
                        wppa_update_photo(array('id' => $id, 'ext' => 'xxx'));
                        // Book keeping
                        $videocount++;
                    } else {
                        wppa_error_message(sprintf(__('Error inserting video %s, unknown or non existent album.', 'wp-photo-album-plus'), basename($file)));
                    }
                }
            }
        }
    }
    // Now the audio files
    $audiocount = '0';
    $alb = isset($_POST['wppa-audio-album']) ? $_POST['wppa-audio-album'] : '0';
    if (wppa('ajax') && !$alb) {
        wppa('ajax_import_files_error', __('Unknown album', 'wp-photo-album-plus'));
    } else {
        foreach (array_keys($files) as $idx) {
            $file = $files[$idx];
            if (isset($_POST['file-' . $idx]) || wppa('ajax')) {
                if (wppa('ajax')) {
                    wppa('ajax_import_files', wppa_sanitize_file_name(basename($file)));
                }
                $ext = strtolower(substr(strrchr($file, "."), 1));
                if (in_array($ext, $wppa_supported_audio_extensions)) {
                    if (is_numeric($alb) && $alb != '0') {
                        // Do we have this filename with ext xxx in this album?
                        $filename = wppa_strip_ext(basename($file)) . '.xxx';
                        $id = wppa_file_is_in_album($filename, $alb);
                        // Or maybe the poster is already there
                        foreach ($wppa_supported_photo_extensions as $pext) {
                            if (!$id) {
                                $id = wppa_file_is_in_album(str_replace('xxx', $pext, $filename), $alb);
                            }
                        }
                        // This filename already exists: is the poster. Fix the filename in the photo info
                        if ($id) {
                            $fname = wppa_get_photo_item($id, 'filename');
                            $fname = wppa_strip_ext($fname) . '.xxx';
                            // Fix filename and ext in photo info
                            wppa_update_photo(array('id' => $id, 'filename' => $fname, 'ext' => 'xxx'));
                        }
                        // Add new entry
                        if (!$id) {
                            $id = wppa_create_photo_entry(array('album' => $alb, 'filename' => $filename, 'ext' => 'xxx', 'name' => wppa_strip_ext($filename)));
                            wppa_flush_treecounts($alb);
                        }
                        // Add audio filetype
                        $newpath = wppa_strip_ext(wppa_get_photo_path($id)) . '.' . $ext;
                        copy($file, $newpath);
                        if ($delu) {
                            unlink($file);
                        }
                        if (wppa('ajax')) {
                            wppa('ajax_import_files_done', true);
                        }
                        // Make sure ext is set to xxx after adding audio to an existing poster
                        wppa_update_photo(array('id' => $id, 'ext' => 'xxx'));
                        // Book keeping
                        $audiocount++;
                    } else {
                        wppa_error_message(sprintf(__('Error inserting audio %s, unknown or non existent album.', 'wp-photo-album-plus'), basename($file)));
                    }
                }
            }
        }
    }
    // The csv files. NOT with ajax
    $csvcount = wppa_get_csvcount($files);
    if ($csvcount) {
        $csvcount = '0';
        if (!wppa('ajax')) {
            if (is_array($files)) {
                // Make sure the feature is on
                if (!wppa_switch('custom_fields')) {
                    wppa_update_option('wppa_custom_fields', 'yes');
                    echo '<b>' . __('Custom datafields enabled', 'wp-photo-album-plus') . '</b><br />';
                }
                // Get the captions we already have
                $cust_labels = array();
                for ($i = '0'; $i < '10'; $i++) {
                    $cust_labels[$i] = wppa_opt('custom_caption_' . $i);
                }
                // Process the files
                $photos_processed_csv = '0';
                $photos_skipped_csv = '0';
                $is_db_table = false;
                $tables = array(WPPA_ALBUMS, WPPA_PHOTOS, WPPA_RATING, WPPA_COMMENTS, WPPA_IPTC, WPPA_EXIF, WPPA_INDEX, WPPA_SESSION);
                foreach (array_keys($files) as $idx) {
                    $this_skipped = '0';
                    $file = $files[$idx];
                    if (isset($_POST['file-' . $idx]) || isset($_GET['continue'])) {
                        $ext = strtolower(wppa_get_ext($file));
                        if ($ext == 'csv') {
                            // See if it is a db table
                            foreach (array_keys($tables) as $idx) {
                                $table_name = str_replace($wpdb->prefix, '', $tables[$idx]);
                                if (strpos($file, $table_name . '.csv') !== false) {
                                    $is_db_table = $tables[$idx];
                                    // Only administrators may do this
                                    if (!current_user_can('administrator')) {
                                        wppa_error_messgae(__('Only administrators are allowed to import db table data.', 'wp-photo-album-plus'));
                                        return;
                                    }
                                }
                            }
                            if ($is_db_table) {
                                echo '<b>' . __('Processing db table', 'wp-photo-album-plus') . ' ' . $is_db_table . '</b><br />';
                                wppa_log('dbg', __('Processing db table', 'wp-photo-album-plus') . ' ' . $is_db_table);
                            } else {
                                echo '<b>' . __('Processing', 'wp-photo-album-plus') . ' ' . basename($file) . '</b><br />';
                                wppa_log('dbg', __('Processing', 'wp-photo-album-plus') . ' ' . basename($file));
                            }
                            // Copy the file to a temp file
                            $tempfile = dirname($file) . '/temp.csv';
                            copy($file, $tempfile);
                            // Open file
                            $handle = fopen($tempfile, "rt");
                            if (!$handle) {
                                wppa_error_message(__('Can not open file. Can not continue. (1)', 'wp-photo-album-plus'));
                                return;
                            }
                            $write_handle = fopen($file, "wt");
                            if (!$write_handle) {
                                wppa_error_message(__('Can not open file. Can not continue. (2)', 'wp-photo-album-plus'));
                                return;
                            }
                            // Read header
                            $header = fgets($handle, 4096);
                            if (!$header) {
                                wppa_error_message(__('Can not read header. Can not continue.', 'wp-photo-album-plus'));
                                fclose($handle);
                                return;
                            }
                            fputs($write_handle, $header);
                            echo __('Read header:', 'wp-photo-album-plus') . ' ' . $header . '<br />';
                            // Is it a db table?
                            if ($is_db_table) {
                                // Functions for inserting db table data
                                $entry_functions = array(WPPA_ALBUMS => 'wppa_create_album_entry', WPPA_PHOTOS => 'wppa_create_photo_entry', WPPA_RATING => 'wppa_create_rating_entry', WPPA_COMMENTS => 'wppa_create_comments_entry', WPPA_IPTC => 'wppa_create_iptc_entry', WPPA_EXIF => 'wppa_create_exif_entry', WPPA_INDEX => 'wppa_create_index_entry');
                                // Interprete and verify header. All fields from .csv MUST be in table fields, else fail
                                $csv_fields = str_getcsv($header);
                                $db_fields = $wpdb->get_results("DESCRIBE `" . $is_db_table . "`", ARRAY_A);
                                foreach ($csv_fields as $csv_field) {
                                    $ok = false;
                                    foreach ($db_fields as $db_field) {
                                        if ($db_field['Field'] === $csv_field) {
                                            $ok = true;
                                        }
                                    }
                                    if (!$ok) {
                                        wppa_error_message('Field ' . $csv_field . ' not found in db table ' . $is_db_table . ' description');
                                        wppa_error_message(__('Invalid header. Can not continue.', 'wp-photo-album-plus'));
                                        fclose($handle);
                                        return;
                                    }
                                }
                                // Now process the lines
                                while (!feof($handle)) {
                                    $dataline = fgets($handle, 16 * 4096);
                                    if ($dataline) {
                                        $data_arr = str_getcsv($dataline);
                                        // Embedded newlines?
                                        while (count($csv_fields) > count($data_arr) && !feof($handle)) {
                                            // Assume continue after embedded linebreak
                                            $dataline .= "\n" . fgets($handle, 16 * 4096);
                                            $data_arr = str_getcsv($dataline);
                                        }
                                        reset($data_arr);
                                        $id = trim(current($data_arr));
                                        if (wppa_is_int($id) && $id > '0') {
                                            wppa_dbg_msg('Processing id ' . $id);
                                            $existing_data = $wpdb->get_row("SELECT * FROM `" . $is_db_table . "` WHERE `id` = {$id}", ARRAY_A);
                                            // If entry exists:
                                            // 1. save existing data,
                                            // 2. remove entry,
                                            if ($existing_data) {
                                                $data = $existing_data;
                                                $wpdb->query("DELETE FROM `" . $is_db_table . "` WHERE `id` = {$id}");
                                            }
                                            // Entry does not / no longer exist, add csv data to data array
                                            foreach (array_keys($csv_fields) as $key) {
                                                if (isset($data_arr[$key])) {
                                                    $data[$csv_fields[$key]] = $data_arr[$key];
                                                }
                                            }
                                            // Insert 'new' entry
                                            if (isset($entry_functions[$is_db_table])) {
                                                $iret = call_user_func_array($entry_functions[$is_db_table], array($data));
                                                if ($iret) {
                                                    $photos_processed_csv++;
                                                } else {
                                                    // Write back to original file
                                                    fputs($write_handle, $dataline);
                                                    $photos_skipped_csv++;
                                                    $this_skipped++;
                                                }
                                            } else {
                                                wppa_error_message('Table ' . $is_db_table . 'not supported');
                                                return;
                                            }
                                        } else {
                                            wppa_error_message('Id field not positive numeric: ' . $id);
                                            // Write back to original file
                                            fputs($write_handle, $dataline);
                                            $photos_skipped_csv++;
                                            $this_skipped++;
                                        }
                                    }
                                    // Time up?
                                    if (wppa_is_time_up() && wppa_switch('auto_continue')) {
                                        wppa('continue', 'continue');
                                        // Copy rest of file back to original
                                        while (!feof($handle)) {
                                            $temp = fgets($handle, 16 * 4096);
                                            fputs($write_handle, $temp);
                                        }
                                    }
                                }
                            } else {
                                // Interprete header
                                $captions = str_getcsv($header);
                                if (!is_array($captions) || count($captions) < '2') {
                                    wppa_error_message(__('Invalid header. Can not continue.', 'wp-photo-album-plus'));
                                    fclose($handle);
                                    return;
                                }
                                foreach (array_keys($captions) as $key) {
                                    if ($key == '0') {
                                        if (!in_array(strtolower(trim($captions['0'])), array('name', 'photoname', 'filename'))) {
                                            wppa_error_message(__('Invalid header. First item must be \'name\', \'photoname\' or \'filename\'', 'wp-photo-album-plus'));
                                            fclose($handle);
                                            return;
                                        }
                                    } elseif (!in_array($captions[$key], $cust_labels)) {
                                        if (!in_array('', $cust_labels)) {
                                            wppa_error_message(__('All available custom data fields are in use. There is no space for', 'wp-photo-album-plus') . ' ' . $captions[$key]);
                                            fclose($handle);
                                            return;
                                        }
                                        // Add a new caption
                                        $i = '0';
                                        while ($cust_labels[$i]) {
                                            $i++;
                                        }
                                        $cust_labels[$i] = $captions[$key];
                                        wppa_update_option('wppa_custom_caption_' . $i, $cust_labels[$i]);
                                        wppa_update_option('wppa_custom_visible_' . $i, 'yes');
                                        wppa_log('dbg', sprintf(__('New caption %s added.', 'wp-photo-album-plus'), $cust_labels[$i]));
                                    }
                                }
                                // Find the correlation between caption index and custom data index.
                                $pointers = array();
                                for ($i = '1'; $i < count($captions); $i++) {
                                    for ($j = '0'; $j < '10'; $j++) {
                                        if ($captions[$i] == $cust_labels[$j]) {
                                            $pointers[$j] = $i;
                                        }
                                    }
                                }
                                // Now process the lines
                                while (!feof($handle)) {
                                    $dataline = fgets($handle, 4096);
                                    if ($dataline) {
                                        wppa_log('dbg', __('Read data:', 'wp-photo-album-plus') . ' ' . trim($dataline));
                                        $data_arr = str_getcsv($dataline);
                                        foreach (array_keys($data_arr) as $i) {
                                            if (!seems_utf8($data_arr[$i])) {
                                                $data_arr[$i] = utf8_encode($data_arr[$i]);
                                            }
                                        }
                                        $search = $data_arr[0];
                                        switch (strtolower($captions[0])) {
                                            case 'photoname':
                                                $photos = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `name` = %s", $data_arr[0]), ARRAY_A);
                                                break;
                                            case 'filename':
                                                $photos = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `filename` = %s", $data_arr[0]), ARRAY_A);
                                                break;
                                            case 'name':
                                                $photos = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `name` = %s OR `filename` = %s", $data_arr[0], $data_arr[0]), ARRAY_A);
                                                break;
                                        }
                                        if ($photos) {
                                            foreach ($photos as $photo) {
                                                $cust_data = $photo['custom'] ? unserialize($photo['custom']) : array('', '', '', '', '', '', '', '', '', '');
                                                foreach (array_keys($pointers) as $p) {
                                                    $cust_data[$p] = wppa_sanitize_custom_field($data_arr[$pointers[$p]]);
                                                }
                                                wppa_update_photo(array('id' => $photo['id'], 'custom' => serialize($cust_data)));
                                                $photos_processed_csv++;
                                            }
                                            wppa_log('dbg', 'Processed: ' . $data_arr[0]);
                                        } else {
                                            wppa_log('dbg', 'Could not find: ' . $data_arr[0]);
                                            // Write back to original file
                                            fputs($write_handle, $dataline);
                                            $photos_skipped_csv++;
                                            $this_skipped++;
                                        }
                                        echo '.';
                                    }
                                    // Time up?
                                    if (wppa_is_time_up() && wppa_switch('auto_continue')) {
                                        wppa('continue', 'continue');
                                        // Copy rest of file back to original
                                        while (!feof($handle)) {
                                            $temp = fgets($handle, 4096);
                                            fputs($write_handle, $temp);
                                        }
                                    }
                                }
                            }
                            fclose($handle);
                            fclose($write_handle);
                            $csvcount++;
                            // Remove tempfile
                            unlink($tempfile);
                            // Remove orig file
                            if (!$this_skipped && !wppa_is_time_up()) {
                                unlink($file);
                            }
                        }
                    }
                }
            }
        }
    }
    wppa_ok_message(__('Done processing files.', 'wp-photo-album-plus'));
    if ($pcount == '0' && $acount == '0' && $zcount == '0' && $dircount == '0' && $photocount == '0' && $videocount == '0' && $audiocount == '0' && $csvcount == '0') {
        wppa_warning_message(__('No files to import.', 'wp-photo-album-plus'));
    } else {
        $msg = '';
        if ($zcount) {
            $msg .= $zcount . ' ' . __('Zipfiles extracted.', 'wp-photo-album-plus') . ' ';
        }
        if ($acount) {
            $msg .= $acount . ' ' . __('Albums created.', 'wp-photo-album-plus') . ' ';
        }
        if ($dircount) {
            $msg .= $dircount . ' ' . __('Directory to album imports.', 'wp-photo-album-plus') . ' ';
        }
        if ($photocount) {
            $msg .= ' ' . sprintf(__('With total %s photos.', 'wppa', 'wp-photo-album-plus'), $photocount) . ' ';
        }
        if ($pcount) {
            if (isset($_POST['wppa-update'])) {
                $msg .= $pcount . ' ' . __('Photos updated', 'wp-photo-album-plus');
                if ($totpcount != $pcount) {
                    $msg .= ' ' . sprintf(__('to %s locations', 'wp-photo-album-plus'), $totpcount);
                }
                $msg .= '.';
            } else {
                $msg .= $pcount . ' ' . __('single photos imported.', 'wp-photo-album-plus') . ' ';
            }
        }
        if ($videocount) {
            $msg .= $videocount . ' ' . __('Videos imported.', 'wp-photo-album-plus');
        }
        if ($audiocount) {
            $msg .= $audiocount . ' ' . __('Audios imported.', 'wp-photo-album-plus');
        }
        if ($csvcount) {
            $msg .= $csvcount . ' ' . __('CSVs imported,', 'wp-photo-album-plus') . ' ' . $photos_processed_csv . ' ' . __('items processed.', 'wp-photo-album-plus') . ' ' . $photos_skipped_csv . ' ' . __('items skipped.', 'wp-photo-album-plus');
        }
        wppa_ok_message($msg);
        wppa_set_last_album($album);
    }
}
function wppa_get_widgetphotos($alb, $option = '')
{
    global $wpdb;
    if (!$alb) {
        return false;
    }
    $photos = false;
    $query = '';
    // Compile status clause
    switch (wppa_opt('potd_status_filter')) {
        case 'publish':
            $statusclause = " `status` = 'publish' ";
            break;
        case 'featured':
            $statusclause = " `status` = 'featured' ";
            break;
        case 'gold':
            $statusclause = " `status` = 'gold' ";
            break;
        case 'silver':
            $statusclause = " `status` = 'silver' ";
            break;
        case 'bronze':
            $statusclause = " `status` = 'bronze' ";
            break;
        case 'anymedal':
            $statusclause = " `status` IN ( 'gold', 'silver', 'bronze' ) ";
            break;
        default:
            $statusclause = " `status` <> 'scheduled' ";
            if (!is_user_logged_in()) {
                $statusclause .= " AND `status` <> 'private' ";
            }
    }
    // If physical album(s) and include subalbums is active, make it an enumeration(with ',' as seperator)
    if (wppa_opt('potd_album_type') == 'physical' && wppa_switch('potd_include_subs')) {
        $alb = str_replace(',', '.', $alb);
        $alb = wppa_expand_enum(wppa_alb_to_enum_children($alb));
        $alb = str_replace('.', ',', $alb);
    }
    // If physical albums and inverse selection is active, invert selection
    if (wppa_opt('potd_album_type') == 'physical' && wppa_switch('potd_inverse')) {
        $albs = explode(',', $alb);
        $all = $wpdb->get_col("SELECT `id` FROM `" . WPPA_ALBUMS . "` ");
        $alb = implode(',', array_diff($all, $albs));
    }
    /* Now find out the final query */
    /* Physical albums */
    // Is it a single album?
    if (wppa_is_int($alb)) {
        $query = $wpdb->prepare("SELECT `id`, `p_order` " . "FROM `" . WPPA_PHOTOS . "` " . "WHERE `album` = %s " . "AND " . $statusclause . $option, $alb);
    } elseif (strchr($alb, ',')) {
        $alb = trim($alb, ',');
        $query = "SELECT `id`, `p_order` " . "FROM `" . WPPA_PHOTOS . "` " . "WHERE `album` IN ( " . $alb . " ) " . "AND " . $statusclause . $option;
    } elseif ($alb == 'all') {
        $query = "SELECT `id`, `p_order` " . "FROM `" . WPPA_PHOTOS . "` " . "WHERE " . $statusclause . $option;
    } elseif ($alb == 'sep') {
        $albs = $wpdb->get_results("SELECT `id`, `a_parent` FROM `" . WPPA_ALBUMS . "`", ARRAY_A);
        $query = "SELECT `id`, `p_order` FROM `" . WPPA_PHOTOS . "` WHERE ( `album` = '0' ";
        $first = true;
        foreach ($albs as $a) {
            if ($a['a_parent'] == '-1') {
                $query .= "OR `album` = '" . $a['id'] . "' ";
            }
        }
        $query .= ") AND " . $statusclause . $option;
    } elseif ($alb == 'all-sep') {
        $albs = $wpdb->get_results("SELECT `id`, `a_parent` FROM `" . WPPA_ALBUMS . "`", ARRAY_A);
        $query = "SELECT `id`, `p_order` FROM `" . WPPA_PHOTOS . "` WHERE ( `album` IN ('0'";
        foreach ($albs as $a) {
            if ($a['a_parent'] != '-1') {
                $query .= ",'" . $a['id'] . "'";
            }
        }
        $query .= ") ) AND " . $statusclause . $option;
    } elseif ($alb == 'topten') {
        // Find the 'top' policy
        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;
        }
        // It is assumed that status is ok for top rated photos
        $query = "SELECT `id`, `p_order` FROM `" . WPPA_PHOTOS . "` ORDER BY " . $sortby . " LIMIT " . wppa_opt('topten_count');
        $query .= $option;
    }
    // Do the query
    if ($query) {
        $photos = $wpdb->get_results($query, ARRAY_A);
        wppa_dbg_msg('Potd query: ' . $query);
    } else {
        $photos = array();
    }
    // Ready
    return $photos;
}
function wppa_have_access($alb)
{
    global $wpdb;
    global $current_user;
    //	if ( !$alb ) $alb = 'any'; //return false;
    // See if there is any album accessable
    if (!$alb) {
        // == 'any' ) {
        // Administrator has always access OR If all albums are public
        if (current_user_can('administrator') || !wppa_switch('wppa_owner_only')) {
            $albs = $wpdb->get_results("SELECT `id` FROM `" . WPPA_ALBUMS . "`");
            wppa_dbg_q('Q209');
            if ($albs) {
                return true;
            } else {
                return false;
            }
            // No albums in system
        }
        // Any --- public --- albums?
        $albs = $wpdb->get_results("SELECT `id` FROM `" . WPPA_ALBUMS . "` WHERE `owner` = '--- public ---'");
        wppa_dbg_q('Q210');
        if ($albs) {
            return true;
        }
        // Any logged out created albums? ( owner = ip )
        $albs = $wpdb->get_results("SELECT `owner` FROM `" . WPPA_ALBUMS . "`", ARRAY_A);
        if ($albs) {
            foreach ($albs as $a) {
                if (wppa_is_int(str_replace('.', '', $a['owner']))) {
                    return true;
                }
            }
        }
        // Any albums owned by this user?
        if (is_user_logged_in()) {
            get_currentuserinfo();
            $user = $current_user->user_login;
            $any_albs = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_ALBUMS . "` WHERE `owner` = %s", $user));
            wppa_dbg_q('Q211');
            if ($any_albs) {
                return true;
            } else {
                return false;
            }
            // No albums for user accessable
        }
    } else {
        // Administrator has always access
        if (current_user_can('administrator')) {
            return true;
        }
        // Do NOT change this into 'wppa_admin', it will enable access to all albums at backend while owners only
        // If all albums are public
        if (!wppa_switch('wppa_owner_only')) {
            return true;
        }
        // Find the owner
        $owner = '';
        if (is_array($alb)) {
            $owner = $alb['owner'];
        } elseif (is_numeric($alb)) {
            $owner = $wpdb->get_var($wpdb->prepare("SELECT `owner` FROM `" . WPPA_ALBUMS . "` WHERE `id` = %s", $alb));
            wppa_dbg_q('Q212');
        }
        // -- public --- ?
        if ($owner == '--- public ---') {
            return true;
        }
        if (wppa_is_int(str_replace('.', '', $owner))) {
            return true;
        }
        // Find the user
        if (is_user_logged_in()) {
            get_currentuserinfo();
            if ($current_user->user_login == $owner) {
                return true;
            }
        }
    }
    return false;
}
function wppa_ajax_callback()
{
    global $wpdb;
    global $wppa_session;
    wppa('ajax', true);
    wppa('error', '0');
    wppa('out', '');
    $wppa_session['page']--;
    $wppa_session['ajax']++;
    wppa_save_session();
    // ALTHOUGH IF WE ARE HERE AS FRONT END VISITOR, is_admin() is true.
    // So, $wppa_opt switches are 'yes' or 'no' and not true or false.
    // So, always use the function wppa_switch( $slug ) to test on a bool setting
    // Globally check query args to prevent php injection
    $wppa_args = array('album', 'photo', 'slide', 'cover', 'occur', 'woccur', 'searchstring', 'topten', 'lasten', 'comten', 'featen', 'single', 'photos-only', 'debug', 'relcount', 'upldr', 'owner', 'rootsearch');
    foreach ($_REQUEST as $arg) {
        if (in_array(str_replace('wppa-', '', $arg), $wppa_args)) {
            if (strpos($arg, '<?') !== false) {
                die('Security check failure #91');
            }
            if (strpos($arg, '?>') !== false) {
                die('Security check failure #92');
            }
        }
    }
    wppa_vfy_arg('wppa-action', true);
    wppa_vfy_arg('photo-id');
    wppa_vfy_arg('comment-id');
    wppa_vfy_arg('moccur');
    wppa_vfy_arg('comemail', true);
    wppa_vfy_arg('comname', true);
    wppa_vfy_arg('tag', true);
    $wppa_action = $_REQUEST['wppa-action'];
    switch ($wppa_action) {
        case 'getssiptclist':
            $tag = str_replace('H', '#', $_REQUEST['tag']);
            $mocc = $_REQUEST['moccur'];
            $oldvalue = '';
            if (strpos($wppa_session['supersearch'], ',') !== false) {
                $ss_data = explode(',', $wppa_session['supersearch']);
                if (count($ss_data) == '4') {
                    if ($ss_data['0'] == 'p') {
                        if ($ss_data['1'] == 'i') {
                            if ($ss_data['2'] == $_REQUEST['tag']) {
                                $oldvalue = $ss_data['3'];
                            }
                        }
                    }
                }
            }
            $iptcdata = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_IPTC . "` WHERE `photo` > '0' AND `tag` = %s ORDER BY `description`", $tag), ARRAY_A);
            $last = '';
            $any = false;
            if (is_array($iptcdata)) {
                foreach ($iptcdata as $item) {
                    $desc = sanitize_text_field($item['description']);
                    $desc = str_replace(array(chr(0), chr(1), chr(2), chr(3), chr(4), chr(5), chr(6), chr(7)), '', $desc);
                    if ($desc != $last) {
                        $sel = $oldvalue && $oldvalue == $desc ? 'selected="selected"' : '';
                        if ($sel) {
                            echo 'selected:' . $oldvalue;
                        }
                        $ddesc = strlen($desc) > '32' ? substr($desc, 0, 30) . '...' : $desc;
                        echo '<option' . ' value="' . esc_attr($desc) . '"' . ' class="wppa-iptclist-' . $mocc . '"' . ' ' . $sel . ' >' . $ddesc . '</option>';
                        $last = $desc;
                        $any = true;
                    }
                }
            }
            if (!$any) {
                $query = $wpdb->prepare("DELETE FROM `" . WPPA_IPTC . "` WHERE `photo` = '0' AND `tag` = %s", $tag);
                $wpdb->query($query);
                //				wppa_log( 'dbg', $query );
            }
            wppa_exit();
            break;
        case 'getssexiflist':
            $tag = str_replace('H', '#', $_REQUEST['tag']);
            $mocc = $_REQUEST['moccur'];
            $oldvalue = '';
            if (strpos($wppa_session['supersearch'], ',') !== false) {
                $ss_data = explode(',', $wppa_session['supersearch']);
                if (count($ss_data) == '4') {
                    if ($ss_data['0'] == 'p') {
                        if ($ss_data['1'] == 'e') {
                            if ($ss_data['2'] == $_REQUEST['tag']) {
                                $oldvalue = $ss_data['3'];
                            }
                        }
                    }
                }
            }
            $exifdata = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_EXIF . "` WHERE `photo` > '0' AND `tag` = %s ORDER BY `description`", $tag), ARRAY_A);
            $last = '';
            $any = false;
            if (is_array($exifdata)) {
                foreach ($exifdata as $item) {
                    $desc = sanitize_text_field($item['description']);
                    $desc = str_replace(array(chr(0), chr(1), chr(2), chr(3), chr(4), chr(5), chr(6), chr(7)), '', $desc);
                    if ($desc != $last) {
                        $sel = $oldvalue && $oldvalue == $desc ? 'selected="selected"' : '';
                        $ddesc = strlen($desc) > '32' ? substr($desc, 0, 30) . '...' : $desc;
                        echo '<option' . ' value="' . esc_attr($desc) . '"' . ' class="wppa-exiflist-' . $mocc . '"' . ' ' . $sel . ' >' . $ddesc . '</option>';
                        $last = $desc;
                        $any = true;
                    }
                }
            }
            if (!$any) {
                $query = $wpdb->prepare("DELETE FROM `" . WPPA_EXIF . "` WHERE `photo` = '0' AND `tag` = %s", $tag);
                $wpdb->query($query);
                //				wppa_log( 'dbg', $query );
            }
            wppa_exit();
            break;
        case 'front-edit':
            if (!isset($_REQUEST['photo-id'])) {
                die('Missing required argument');
            }
            $photo = $_REQUEST['photo-id'];
            $ok = false;
            if (current_user_can('wppa_admin')) {
                $ok = true;
            }
            if (wppa_get_user() == wppa_get_photo_owner($photo) && (current_user_can('wppa_upload') || is_user_logged_in() && wppa_switch('upload_edit'))) {
                $ok = true;
            }
            if (!$ok) {
                die('You do not have sufficient rights to do this');
            }
            require_once 'wppa-photo-admin-autosave.php';
            wppa('front_edit', true);
            echo '	<div style="padding-bottom:4px;height:24px;" >
						<span style="color:#777;" >
							<i>' . __('All modifications are instantly updated on the server. The <b style="color:#070" >Remark</b> field keeps you informed on the actions taken at the background.', 'wp-photo-album-plus') . '</i>
						</span>
						<input id="wppa-fe-exit" type="button" style="float:right;color:red;font-weight:bold;" onclick="window.opener.location.reload( true );window.close();" value="' . __('Exit & Refresh', 'wp-photo-album-plus') . '" />
						<div id="wppa-fe-count" style="float:right;" ></div>
					</div><div style="clear:both;"></div>';
            wppa_album_photos('', $photo);
            wppa_exit();
            break;
        case 'do-comment':
            // Security check
            $mocc = $_REQUEST['moccur'];
            $nonce = $_REQUEST['wppa-nonce'];
            if (!wp_verify_nonce($nonce, 'wppa-nonce-' . $mocc)) {
                _e('Security check failure', 'wp-photo-album-plus');
                wppa_exit();
            }
            // Correct the fact that this is a non-admin operation, if it is only
            if (is_admin()) {
                require_once 'wppa-non-admin.php';
            }
            wppa('mocc', $_REQUEST['moccur']);
            wppa('comment_photo', isset($_REQUEST['photo-id']) ? $_REQUEST['photo-id'] : '0');
            wppa('comment_id', isset($_REQUEST['comment-edit']) ? $_REQUEST['comment-edit'] : '0');
            $comment_allowed = !wppa_switch('comment_login') || is_user_logged_in();
            if (wppa_switch('show_comments') && $comment_allowed) {
                //				if ( wppa_switch( 'search_comments' ) ) wppa_index_remove( 'photo', $_REQUEST['photo-id'] );
                wppa_do_comment($_REQUEST['photo-id']);
                // Process the comment
                if (wppa_switch('search_comments')) {
                    wppa_index_update('photo', $_REQUEST['photo-id']);
                }
            }
            wppa('no_esc', true);
            echo wppa_comment_html($_REQUEST['photo-id'], $comment_allowed);
            // Retrieve the new commentbox content
            wppa_exit();
            break;
        case 'import':
            require_once 'wppa-upload.php';
            _wppa_page_import();
            wppa_exit();
            break;
        case 'approve':
            $iret = '0';
            if (!current_user_can('wppa_moderate') && !current_user_can('wppa_comments')) {
                _e('You do not have the rights to moderate photos this way', 'wp-photo-album-plus');
                wppa_exit();
            }
            if (isset($_REQUEST['photo-id']) && current_user_can('wppa_moderate')) {
                $iret = $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `status` = 'publish' WHERE `id` = %s", $_REQUEST['photo-id']));
                wppa_flush_upldr_cache('photoid', $_REQUEST['photo-id']);
                $alb = $wpdb->get_var($wpdb->prepare("SELECT `album` FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $_REQUEST['photo-id']));
                wppa_clear_taglist();
                wppa_flush_treecounts($alb);
            }
            if (isset($_REQUEST['comment-id'])) {
                $iret = $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_COMMENTS . "` SET `status` = 'approved' WHERE `id` = %s", $_REQUEST['comment-id']));
            }
            if ($iret) {
                echo 'OK';
            } else {
                if (isset($_REQUEST['photo-id'])) {
                    if (current_user_can('wppa_moderate')) {
                        echo sprintf(__('Failed to update stutus of photo %s', 'wp-photo-album-plus'), $_REQUEST['photo-id']) . "\n" . __('Please refresh the page', 'wp-photo-album-plus');
                    } else {
                        _e('Security check failure', 'wp-photo-album-plus');
                    }
                }
                if (isset($_REQUEST['comment-id'])) {
                    echo sprintf(__('Failed to update stutus of comment %s', 'wp-photo-album-plus'), $_REQUEST['comment-id']) . "\n" . __('Please refresh the page', 'wp-photo-album-plus');
                }
            }
            wppa_exit();
        case 'remove':
            if (isset($_REQUEST['photo-id'])) {
                // Remove photo
                if (wppa_user_is('administrator') || current_user_can('wppa_moderate') || wppa_get_user() == wppa_get_photo_owner($_REQUEST['photo-id']) && wppa_switch('upload_edit')) {
                    // Frontend delete?
                    wppa_delete_photo($_REQUEST['photo-id']);
                    echo 'OK||' . __('Photo removed', 'wp-photo-album-plus');
                    wppa_exit();
                }
            }
            if (!current_user_can('wppa_moderate') && !current_user_can('wppa_comments')) {
                _e('You do not have the rights to moderate photos this way', 'wp-photo-album-plus');
                wppa_exit();
            }
            if (isset($_REQUEST['photo-id'])) {
                // Remove photo
                if (!current_user_can('wppa_moderate')) {
                    _e('Security check failure', 'wp-photo-album-plus');
                    wppa_exit();
                }
                wppa_delete_photo($_REQUEST['photo-id']);
                echo 'OK||' . __('Photo removed', 'wp-photo-album-plus');
                wppa_exit();
            }
            if (isset($_REQUEST['comment-id'])) {
                // Remove comment
                $iret = $wpdb->query($wpdb->prepare("DELETE FROM `" . WPPA_COMMENTS . "` WHERE `id`= %s", $_REQUEST['comment-id']));
                if ($iret) {
                    echo 'OK||' . __('Comment removed', 'wp-photo-album-plus');
                } else {
                    _e('Could not remove comment', 'wp-photo-album-plus');
                }
                wppa_exit();
            }
            _e('Unexpected error', 'wp-photo-album-plus');
            wppa_exit();
        case 'downloadalbum':
            // Feature enabled?
            if (!wppa_switch('allow_download_album')) {
                echo '||ER||' . __('This feature is not enabled on this website', 'wp-photo-album-plus');
                wppa_exit();
            }
            // Validate args
            $alb = $_REQUEST['album-id'];
            $status = "`status` <> 'pending' AND `status` <> 'scheduled'";
            if (!is_user_logged_in()) {
                $status .= " AND `status` <> 'private'";
            }
            $photos = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s AND ( ( " . $status . " ) OR owner = %s ) " . wppa_get_photo_order($alb), $alb, wppa_get_user()), ARRAY_A);
            if (!$photos) {
                echo '||ER||' . __('The album is empty', 'wp-photo-album-plus');
                wppa_exit();
            }
            // Remove obsolete files
            wppa_delete_obsolete_tempfiles();
            // Open zipfile
            if (!class_exists('ZipArchive')) {
                echo '||ER||' . __('Unable to create zip archive', 'wp-photo-album-plus');
                wppa_exit();
            }
            $zipfilename = wppa_get_album_name($alb);
            $zipfilename = wppa_sanitize_file_name($zipfilename . '.zip');
            // Remove illegal chars
            $zipfilepath = WPPA_UPLOAD_PATH . '/temp/' . $zipfilename;
            if (is_file($zipfilepath)) {
                //		unlink( $zipfilepath );	// Debug
            }
            $wppa_zip = new ZipArchive();
            $iret = $wppa_zip->open($zipfilepath, 1);
            if ($iret !== true) {
                echo '||ER||' . sprintf(__('Unable to create zip archive. code = %s', 'wp-photo-album-plus'), $iret);
                wppa_exit();
            }
            // Add photos to zip
            $stop = false;
            foreach ($photos as $p) {
                if (wppa_is_time_up()) {
                    wppa_log('obs', 'Time up during album to zip creation');
                    $stop = true;
                } else {
                    $id = $p['id'];
                    if (!wppa_is_multi($id)) {
                        $source = wppa_switch('download_album_source') && is_file(wppa_get_source_path($id)) ? wppa_get_source_path($id) : wppa_get_photo_path($id);
                        if (is_file($source)) {
                            $dest = $p['filename'] ? wppa_sanitize_file_name($p['filename']) : wppa_sanitize_file_name(wppa_strip_ext($p['name']) . '.' . $p['ext']);
                            $dest = wppa_fix_poster_ext($dest, $id);
                            $iret = $wppa_zip->addFile($source, $dest);
                            // To prevent too may files open, and to have at least a file when there are too many photos, close and re-open
                            $wppa_zip->close();
                            $wppa_zip->open($zipfilepath);
                            // wppa_log( 'dbg', 'Added ' . basename($source) . ' to ' . basename($zipfilepath));
                        }
                    }
                }
                if ($stop) {
                    break;
                }
            }
            // Close zip and return
            $zipcount = $wppa_zip->numFiles;
            $wppa_zip->close();
            // A zip is created
            $desturl = WPPA_UPLOAD_URL . '/temp/' . $zipfilename;
            echo $desturl . '||OK||';
            if ($zipcount != count($photos)) {
                echo sprintf(__('Only %s out of %s photos could be added to the zipfile', 'wp-photo-album-plus'), $zipcount, count($photos));
            }
            wppa_exit();
            break;
        case 'getalbumzipurl':
            $alb = $_REQUEST['album-id'];
            $zipfilename = wppa_get_album_name($alb);
            $zipfilename = wppa_sanitize_file_name($zipfilename . '.zip');
            // Remove illegal chars
            $zipfilepath = WPPA_UPLOAD_PATH . '/temp/' . $zipfilename;
            $zipfileurl = WPPA_UPLOAD_URL . '/temp/' . $zipfilename;
            if (is_file($zipfilepath)) {
                echo $zipfileurl;
            } else {
                echo 'ER';
            }
            wppa_exit();
            break;
        case 'makeorigname':
            $photo = $_REQUEST['photo-id'];
            $from = $_REQUEST['from'];
            if ($from == 'fsname') {
                $type = wppa_opt('art_monkey_link');
            } elseif ($from == 'popup') {
                $type = wppa_opt('art_monkey_popup_link');
            } else {
                echo '||7||' . __('Unknown source of request', 'wp-photo-album-plus');
                wppa_exit();
            }
            $data = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $photo), ARRAY_A);
            if ($data) {
                // The photo is supposed to exist
                // Make the name
                if ($data['filename']) {
                    $name = $data['filename'];
                } else {
                    $name = __($data['name'], 'wp-photo-album-plus');
                }
                $name = wppa_sanitize_file_name($name);
                // Remove illegal chars
                $name = preg_replace('/\\.[^.]*$/', '', $name);
                // Remove file extension
                if (strlen($name) == '0') {
                    echo '||1||' . __('Empty filename', 'wp-photo-album-plus');
                    wppa_exit();
                }
                // Make the file
                if (wppa_switch('artmonkey_use_source')) {
                    if (is_file(wppa_get_source_path($photo))) {
                        $source = wppa_get_source_path($photo);
                    } else {
                        $source = wppa_get_photo_path($photo);
                    }
                } else {
                    $source = wppa_get_photo_path($photo);
                }
                $source = wppa_fix_poster_ext($source, $photo);
                // Fix the extension for mm items.
                if ($data['ext'] == 'xxx') {
                    $data['ext'] = wppa_get_ext($source);
                }
                $dest = WPPA_UPLOAD_PATH . '/temp/' . $name . '.' . $data['ext'];
                $zipfile = WPPA_UPLOAD_PATH . '/temp/' . $name . '.zip';
                $tempdir = WPPA_UPLOAD_PATH . '/temp';
                if (!is_dir($tempdir)) {
                    @mkdir($tempdir);
                }
                if (!is_dir($tempdir)) {
                    echo '||2||' . __('Unable to create tempdir', 'wp-photo-album-plus');
                    wppa_exit();
                }
                // Remove obsolete files
                wppa_delete_obsolete_tempfiles();
                // Make the files
                if ($type == 'file') {
                    copy($source, $dest);
                    $ext = $data['ext'];
                } elseif ($type == 'zip') {
                    if (!class_exists('ZipArchive')) {
                        echo '||8||' . __('Unable to create zip archive', 'wp-photo-album-plus');
                        wppa_exit();
                    }
                    $ext = 'zip';
                    $wppa_zip = new ZipArchive();
                    $wppa_zip->open($zipfile, 1);
                    $wppa_zip->addFile($source, basename($dest));
                    $wppa_zip->close();
                } else {
                    echo '||6||' . __('Unknown type', 'wp-photo-album-plus');
                    wppa_exit();
                }
                $desturl = WPPA_UPLOAD_URL . '/temp/' . $name . '.' . $ext;
                echo '||0||' . $desturl;
                // No error: return url
                wppa_exit();
            } else {
                echo '||9||' . __('The photo does no longer exist', 'wp-photo-album-plus');
                wppa_exit();
            }
            wppa_exit();
            break;
        case 'tinymcedialog':
            $result = wppa_make_tinymce_dialog();
            echo $result;
            wppa_exit();
            break;
        case 'bumpviewcount':
            $nonce = $_REQUEST['wppa-nonce'];
            if (wp_verify_nonce($nonce, 'wppa-check')) {
                wppa_bump_viewcount('photo', $_REQUEST['wppa-photo']);
            } else {
                _e('Security check failure', 'wp-photo-album-plus');
            }
            wppa_exit();
            break;
        case 'rate':
            // Get commandline args
            $photo = $_REQUEST['wppa-rating-id'];
            $rating = $_REQUEST['wppa-rating'];
            $occur = $_REQUEST['wppa-occur'];
            $index = $_REQUEST['wppa-index'];
            $nonce = $_REQUEST['wppa-nonce'];
            // Make errortext
            $errtxt = __('An error occurred while processing you rating request.', 'wp-photo-album-plus');
            $errtxt .= "\n" . __('Maybe you opened the page too long ago to recognize you.', 'wp-photo-album-plus');
            $errtxt .= "\n" . __('You may refresh the page and try again.', 'wp-photo-album-plus');
            $wartxt = __('Althoug an error occurred while processing your rating, your vote has been registered.', 'wp-photo-album-plus');
            $wartxt .= "\n" . __('However, this may not be reflected in the current pageview', 'wp-photo-album-plus');
            // Check on validity
            if (!wp_verify_nonce($nonce, 'wppa-check')) {
                echo '0||100||' . $errtxt;
                wppa_exit();
                // Nonce check failed
            }
            if (wppa_opt('rating_max') == '1' && $rating != '1') {
                echo '0||106||' . $errtxt . ':' . $rating;
                wppa_exit();
                // Value out of range
            } elseif (wppa_opt('rating_max') == '5' && !in_array($rating, array('-1', '1', '2', '3', '4', '5'))) {
                echo '0||106||' . $errtxt . ':' . $rating;
                wppa_exit();
                // Value out of range
            } elseif (wppa_opt('rating_max') == '10' && !in_array($rating, array('-1', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'))) {
                echo '0||106||' . $errtxt . ':' . $rating;
                wppa_exit();
                // Value out of range
            }
            // Get other data
            if (!$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $photo))) {
                echo '0||999||' . __('Photo has been removed.', 'wp-photo-album-plus');
                wppa_exit();
            }
            $user = wppa_get_user();
            $mylast = $wpdb->get_row($wpdb->prepare('SELECT * FROM `' . WPPA_RATING . '` WHERE `photo` = %s AND `user` = %s ORDER BY `id` DESC LIMIT 1', $photo, $user), ARRAY_A);
            $myavgrat = '0';
            // Init
            // Rate own photo?
            if (wppa_get_photo_item($photo, 'owner') == $user && !wppa_switch('allow_owner_votes')) {
                echo '0||900||' . __('Sorry, you can not rate your own photos', 'wp-photo-album-plus');
                wppa_exit();
            }
            // Already a pending one?
            $pending = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_RATING . "` WHERE `photo` = %s AND `user` = %s AND `status` = %s", $photo, $user, 'pending'));
            // Has user motivated his vote?
            $hascommented = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_COMMENTS . "` WHERE `photo` = %s AND `user` = %s", $photo, wppa_get_user('display')));
            if ($pending) {
                if (!$hascommented) {
                    echo '0||900||' . __('Please enter a comment.', 'wp-photo-album-plus');
                    wppa_exit();
                } else {
                    $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_RATING . "` SET `status` = 'publish' WHERE `photo` = %s AND `user` = %s", $photo, $user));
                }
            }
            if (wppa_switch('vote_needs_comment')) {
                $ratingstatus = $hascommented ? 'publish' : 'pending';
            } else {
                $ratingstatus = 'publish';
            }
            // When done, we have to echo $occur.'||'.$photo.'||'.$index.'||'.$myavgrat.'||'.$allavgrat.'||'.$discount.||.$hascommented.||.$message;
            // So we have to do: process rating and find new $myavgrat, $allavgrat and $discount ( $occur, $photo and $index are known )
            // Case 0: Illegal second vote. Frontend takes care of this, but a hacker could enter an ajaxlink manually
            if ($mylast && (!(wppa_switch('rating_change') || wppa_switch('rating_multi')) || $mylast['value'] < '0' || $mylast['value'] > '0' && $rating == '-1')) {
                echo '0||109||' . __('Security check failure.', 'wp-photo-album-plus');
                wppa_exit();
            }
            // Case 1: value = -1 this is a legal dislike vote
            if ($rating == '-1') {
                // Add my dislike
                $iret = wppa_create_rating_entry(array('photo' => $photo, 'value' => $rating, 'user' => $user, 'status' => $ratingstatus));
                if (!$iret) {
                    echo '0||101||' . $errtxt;
                    wppa_exit();
                    // Fail on storing vote
                }
                // Add points
                wppa_add_credit_points(wppa_opt('cp_points_rating'), __('Photo rated', 'wp-photo-album-plus'), $photo, $rating);
                wppa_dislike_check($photo);
                // Check for email to be sent every .. dislikes
                if (!is_file(wppa_get_thumb_path($photo))) {
                    // Photo is removed
                    echo $occur . '||' . $photo . '||' . $index . '||-1||-1|0||' . wppa_opt('dislike_delete');
                    wppa_exit();
                }
            } elseif (!$mylast) {
                // Add my vote
                $iret = wppa_create_rating_entry(array('photo' => $photo, 'value' => $rating, 'user' => $user, 'status' => $ratingstatus));
                if (!$iret) {
                    echo '0||102||' . $errtxt;
                    wppa_exit();
                    // Fail on storing vote
                }
                // Add points
                wppa_add_credit_points(wppa_opt('cp_points_rating'), __('Photo rated', 'wp-photo-album-plus'), $photo, $rating);
            } elseif (wppa_switch('rating_change')) {
                // Votechanging is allowed
                $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_RATING . '` SET `value` = %s WHERE `photo` = %s AND `user` = %s LIMIT 1', $rating, $photo, $user));
                if ($iret === false) {
                    echo '0||103||' . $errtxt;
                    wppa_exit();
                    // Fail on update
                }
            } elseif (wppa_switch('rating_multi')) {
                // Rating multi is allowed
                $iret = wppa_create_rating_entry(array('photo' => $photo, 'value' => $rating, 'user' => $user, 'status' => $ratingstatus));
                if (!$iret) {
                    echo '0||104||' . $errtxt;
                    wppa_exit();
                    // Fail on storing vote
                }
            } else {
                // Should never get here....
                echo '0||110||' . __('Unexpected error', 'wp-photo-album-plus');
                wppa_exit();
            }
            // Compute my avg rating
            $myrats = $wpdb->get_results($wpdb->prepare('SELECT * FROM `' . WPPA_RATING . '`  WHERE `photo` = %s AND `user` = %s AND `status` = %s ', $photo, $user, 'publish'), ARRAY_A);
            if ($myrats) {
                $sum = 0;
                $cnt = 0;
                foreach ($myrats as $rat) {
                    if ($rat['value'] == '-1') {
                        $sum += wppa_opt('dislike_value');
                    } else {
                        $sum += $rat['value'];
                    }
                    $cnt++;
                }
                $myavgrat = $sum / $cnt;
                $i = wppa_opt('rating_prec');
                $j = $i + '1';
                $myavgrat = sprintf('%' . $j . '.' . $i . 'f', $myavgrat);
            } else {
                $myavgrat = '0';
            }
            // Compute new allavgrat
            $ratings = $wpdb->get_results($wpdb->prepare('SELECT * FROM ' . WPPA_RATING . ' WHERE `photo` = %s AND `status` = %s', $photo, 'publish'), ARRAY_A);
            if ($ratings) {
                $sum = 0;
                $cnt = 0;
                foreach ($ratings as $rat) {
                    if ($rat['value'] == '-1') {
                        $sum += wppa_opt('dislike_value');
                    } else {
                        $sum += $rat['value'];
                    }
                    $cnt++;
                }
                $allavgrat = $sum / $cnt;
                if ($allavgrat == '10') {
                    $allavgrat = '9.99999999';
                }
                // For sort order reasons text field
            } else {
                $allavgrat = '0';
            }
            // Store it in the photo info
            $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `mean_rating` = %s WHERE `id` = %s', $allavgrat, $photo));
            if ($iret === false) {
                echo '0||106||' . $wartxt;
                wppa_exit();
                // Fail on save
            }
            // Compute rating_count and store in the photo info
            $ratcount = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_RATING . "` WHERE `photo` = %s", $photo));
            if ($ratcount !== false) {
                $iret = $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `rating_count` = %s WHERE `id` = %s", $ratcount, $photo));
                if ($iret === false) {
                    echo '0||107||' . $wartxt;
                    wppa_exit();
                    // Fail on save
                }
            }
            // Format $allavgrat for output
            $allavgratcombi = $allavgrat . '|' . $ratcount;
            // Compute dsilike count
            $discount = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_RATING . "` WHERE `photo` = %s AND `value` = -1 AND `status` = %s", $photo, 'publish'));
            if ($discount === false) {
                echo '0||108||' . $wartxt;
                wppa_exit();
                // Fail on save
            }
            // Test for possible medal
            wppa_test_for_medal($photo);
            // Success!
            wppa_clear_cache();
            if (wppa_switch('vote_needs_comment') && !$hascommented) {
                $message = __("Please explain your vote in a comment.\nYour vote will be discarded if you don't.\n\nAfter completing your comment,\nyou can refresh the page to see\nyour vote became effective.", 'wp-photo-album-plus');
            } else {
                $message = '';
            }
            echo $occur . '||' . $photo . '||' . $index . '||' . $myavgrat . '||' . $allavgratcombi . '||' . $discount . '||' . $hascommented . '||' . $message;
            break;
        case 'render':
            $tim_1 = microtime(true);
            $nq_1 = get_num_queries();
            // Correct the fact that this is a non-admin operation, if it is
            if (is_admin()) {
                require_once 'wppa-non-admin.php';
            }
            wppa_load_theme();
            // Register geo shortcode if google-maps-gpx-vieuwer is on board. GPX does it in wp_head(), what is not done in an ajax call
            //			if ( function_exists( 'gmapv3' ) ) add_shortcode( 'map', 'gmapv3' );
            // Get the post we are working for
            if (isset($_REQUEST['wppa-fromp'])) {
                $p = $_REQUEST['wppa-fromp'];
                if (wppa_is_int($p)) {
                    $GLOBALS['post'] = get_post($p);
                }
            }
            // Render
            echo wppa_albums();
            $tim_2 = microtime(true);
            $nq_2 = get_num_queries();
            $mem = memory_get_peak_usage(true) / 1024 / 1024;
            $msg = sprintf('WPPA Ajax render: db queries: WP:%d, WPPA+: %d in %4.2f seconds, using %4.2f MB memory max', $nq_1, $nq_2 - $nq_1, $tim_2 - $tim_1, $mem);
            echo '<script type="text/javascript">wppaConsoleLog( \'' . $msg . '\', \'force\' )</script>';
            break;
        case 'delete-photo':
            $photo = $_REQUEST['photo-id'];
            $nonce = $_REQUEST['wppa-nonce'];
            // Check validity
            if (!wp_verify_nonce($nonce, 'wppa_nonce_' . $photo)) {
                echo '||0||' . __('You do not have the rights to delete a photo', 'wp-photo-album-plus');
                wppa_exit();
                // Nonce check failed
            }
            if (!is_numeric($photo)) {
                echo '||0||' . __('Security check failure', 'wp-photo-album-plus');
                wppa_exit();
                // Nonce check failed
            }
            $album = $wpdb->get_var($wpdb->prepare('SELECT `album` FROM `' . WPPA_PHOTOS . '` WHERE `id` = %s', $photo));
            wppa_delete_photo($photo);
            wppa_clear_cache();
            echo '||1||<span style="color:red" >' . sprintf(__('Photo %s has been deleted', 'wp-photo-album-plus'), $photo) . '</span>';
            echo '||';
            $a = wppa_allow_uploads($album);
            if (!$a) {
                echo 'full';
            } else {
                echo 'notfull||' . $a;
            }
            break;
        case 'update-album':
            $album = $_REQUEST['album-id'];
            $nonce = $_REQUEST['wppa-nonce'];
            $item = $_REQUEST['item'];
            $value = $_REQUEST['value'];
            $value = wppa_decode($value);
            // Check validity
            if (!wp_verify_nonce($nonce, 'wppa_nonce_' . $album)) {
                echo '||0||' . __('You do not have the rights to update album information', 'wp-photo-album-plus') . $nonce;
                wppa_exit();
                // Nonce check failed
            }
            switch ($item) {
                case 'clear_ratings':
                    $photos = $wpdb->get_results($wpdb->prepare('SELECT * FROM `' . WPPA_PHOTOS . '` WHERE `album` = %s', $album), ARRAY_A);
                    if ($photos) {
                        foreach ($photos as $photo) {
                            $iret1 = $wpdb->query($wpdb->prepare('DELETE FROM `' . WPPA_RATING . '` WHERE `photo` = %s', $photo['id']));
                            $iret2 = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `mean_rating` = %s WHERE `id` = %s', '', $photo['id']));
                        }
                    }
                    if ($photos && $iret1 !== false && $iret2 !== false) {
                        echo '||97||' . __('<b>Ratings cleared</b>', 'wp-photo-album-plus') . '||' . __('No ratings for this photo.', 'wp-photo-album-plus');
                    } elseif ($photos) {
                        echo '||1||' . __('An error occurred while clearing ratings', 'wp-photo-album-plus');
                    } else {
                        echo '||97||' . __('<b>No photos in this album</b>', 'wp-photo-album-plus') . '||' . __('No ratings for this photo.', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'set_deftags':
                    // to be changed for large albums
                    $photos = $wpdb->get_results($wpdb->prepare('SELECT * FROM `' . WPPA_PHOTOS . '` WHERE `album` = %s', $album), ARRAY_A);
                    $deftag = $wpdb->get_var($wpdb->prepare('SELECT `default_tags` FROM `' . WPPA_ALBUMS . '` WHERE `id` = %s', $album));
                    if (is_array($photos)) {
                        foreach ($photos as $photo) {
                            $tags = wppa_sanitize_tags(wppa_filter_iptc(wppa_filter_exif($deftag, $photo['id']), $photo['id']));
                            $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `tags` = %s WHERE `id` = %s', $tags, $photo['id']));
                            wppa_index_update('photo', $photo['id']);
                        }
                    }
                    if ($photos && $iret !== false) {
                        echo '||97||' . __('<b>Tags set to defaults</b> (reload)', 'wp-photo-album-plus');
                    } elseif ($photos) {
                        echo '||1||' . __('An error occurred while setting tags', 'wp-photo-album-plus');
                    } else {
                        echo '||97||' . __('<b>No photos in this album</b>', 'wp-photo-album-plus');
                    }
                    wppa_clear_taglist();
                    wppa_exit();
                    break;
                case 'add_deftags':
                    $photos = $wpdb->get_results($wpdb->prepare('SELECT * FROM `' . WPPA_PHOTOS . '` WHERE `album` = %s', $album), ARRAY_A);
                    $deftag = $wpdb->get_var($wpdb->prepare('SELECT `default_tags` FROM `' . WPPA_ALBUMS . '` WHERE `id` = %s', $album));
                    if (is_array($photos)) {
                        foreach ($photos as $photo) {
                            $tags = wppa_sanitize_tags(wppa_filter_iptc(wppa_filter_exif($photo['tags'] . ',' . $deftag, $photo['id']), $photo['id']));
                            $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `tags` = %s WHERE `id` = %s', $tags, $photo['id']));
                            wppa_index_update('photo', $photo['id']);
                        }
                    }
                    if ($photos && $iret !== false) {
                        echo '||97||' . __('<b>Tags added width defaults</b> (reload)', 'wp-photo-album-plus');
                    } elseif ($photos) {
                        echo '||1||' . __('An error occurred while adding tags', 'wp-photo-album-plus');
                    } else {
                        echo '||97||' . __('<b>No photos in this album</b>', 'wp-photo-album-plus');
                    }
                    wppa_clear_taglist();
                    wppa_exit();
                    break;
                case 'name':
                    $value = trim(strip_tags($value));
                    if (!wppa_sanitize_file_name($value)) {
                        // Empty album name is not allowed
                        $value = 'Album-#' . $album;
                        echo '||5||' . sprintf(__('Album name may not be empty.<br />Reset to <b>%s</b>', 'wp-photo-album-plus'), $value);
                    }
                    $itemname = __('Name', 'wp-photo-album-plus');
                    break;
                case 'description':
                    $itemname = __('Description', 'wp-photo-album-plus');
                    if (wppa_switch('check_balance')) {
                        $value = str_replace(array('<br/>', '<br>'), '<br />', $value);
                        if (balanceTags($value, true) != $value) {
                            echo '||3||' . __('Unbalanced tags in album description!', 'wp-photo-album-plus');
                            wppa_exit();
                        }
                    }
                    $value = trim($value);
                    break;
                case 'a_order':
                    $itemname = __('Album order #', 'wp-photo-album-plus');
                    break;
                case 'main_photo':
                    $itemname = __('Cover photo', 'wp-photo-album-plus');
                    break;
                case 'a_parent':
                    $itemname = __('Parent album', 'wp-photo-album-plus');
                    wppa_flush_treecounts($album);
                    // Myself and my parents
                    wppa_flush_treecounts($value);
                    // My new parent
                    break;
                case 'p_order_by':
                    $itemname = __('Photo order', 'wp-photo-album-plus');
                    break;
                case 'alt_thumbsize':
                    $itemname = __('Use Alt thumbsize', 'wp-photo-album-plus');
                    break;
                case 'cover_type':
                    $itemname = __('Cover Type', 'wp-photo-album-plus');
                    break;
                case 'cover_linktype':
                    $itemname = __('Link type', 'wp-photo-album-plus');
                    break;
                case 'cover_linkpage':
                    $itemname = __('Link to', 'wp-photo-album-plus');
                    break;
                case 'owner':
                    $itemname = __('Owner', 'wp-photo-album-plus');
                    if ($value != '--- public ---' && !get_user_by('login', $value)) {
                        echo '||4||' . sprintf(__('User %s does not exist', 'wp-photo-album-plus'), $value);
                        wppa_exit();
                    }
                    break;
                case 'upload_limit_count':
                    wppa_ajax_check_range($value, false, '0', false, __('Upload limit count', 'wp-photo-album-plus'));
                    if (wppa('error')) {
                        wppa_exit();
                    }
                    $oldval = $wpdb->get_var($wpdb->prepare('SELECT `upload_limit` FROM ' . WPPA_ALBUMS . ' WHERE `id` = %s', $album));
                    $temp = explode('/', $oldval);
                    $value = $value . '/' . $temp[1];
                    $item = 'upload_limit';
                    $itemname = __('Upload limit count', 'wp-photo-album-plus');
                    break;
                case 'upload_limit_time':
                    $oldval = $wpdb->get_var($wpdb->prepare('SELECT `upload_limit` FROM ' . WPPA_ALBUMS . ' WHERE `id` = %s', $album));
                    $temp = explode('/', $oldval);
                    $value = $temp[0] . '/' . $value;
                    $item = 'upload_limit';
                    $itemname = __('Upload limit time', 'wp-photo-album-plus');
                    break;
                case 'default_tags':
                    $value = wppa_sanitize_tags($value, false, true);
                    $itemname = __('Default tags', 'wp-photo-album-plus');
                    break;
                case 'cats':
                    $value = wppa_sanitize_cats($value);
                    wppa_clear_catlist();
                    $itemname = __('Categories', 'wp-photo-album-plus');
                    break;
                case 'suba_order_by':
                    $itemname = __('Sub albums sort order', 'wp-photo-album-plus');
                    break;
                case 'year':
                case 'month':
                case 'day':
                case 'hour':
                case 'min':
                    $itemname = __('Schedule date/time', 'wp-photo-album-plus');
                    $scheduledtm = $wpdb->get_var($wpdb->prepare("SELECT `scheduledtm` FROM`" . WPPA_ALBUMS . "` WHERE `id` = %s", $album));
                    if (!$scheduledtm) {
                        $scheduledtm = wppa_get_default_scheduledtm();
                    }
                    $temp = explode(',', $scheduledtm);
                    if ($item == 'year') {
                        $temp[0] = $value;
                    }
                    if ($item == 'month') {
                        $temp[1] = $value;
                    }
                    if ($item == 'day') {
                        $temp[2] = $value;
                    }
                    if ($item == 'hour') {
                        $temp[3] = $value;
                    }
                    if ($item == 'min') {
                        $temp[4] = $value;
                    }
                    $scheduledtm = implode(',', $temp);
                    wppa_update_album(array('id' => $album, 'scheduledtm' => $scheduledtm));
                    echo '||0||' . sprintf(__('<b>%s</b> of album %s updated', 'wp-photo-album-plus'), $itemname, $album);
                    wppa_exit();
                    break;
                case 'setallscheduled':
                    $scheduledtm = $wpdb->get_var($wpdb->prepare("SELECT `scheduledtm` FROM `" . WPPA_ALBUMS . "` WHERE `id` = %s", $album));
                    if ($scheduledtm) {
                        $iret = $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `status` = 'scheduled', `scheduledtm` = %s WHERE `album` = %s", $scheduledtm, $album));
                        echo '||0||' . __('All photos set to scheduled per date', 'wp-photo-album-plus') . ' ( ' . $iret . ' ) ' . wppa_format_scheduledtm($scheduledtm);
                    }
                    wppa_exit();
                    break;
                default:
                    $itemname = $item;
            }
            $query = $wpdb->prepare('UPDATE ' . WPPA_ALBUMS . ' SET `' . $item . '` = %s WHERE `id` = %s', $value, $album);
            $iret = $wpdb->query($query);
            if ($iret !== false) {
                if ($item == 'name' || $item == 'description' || $item == 'cats') {
                    wppa_index_update('album', $album);
                }
                if ($item == 'name') {
                    wppa_create_pl_htaccess();
                }
                echo '||0||' . sprintf(__('<b>%s</b> of album %s updated', 'wp-photo-album-plus'), $itemname, $album);
                if ($item == 'upload_limit') {
                    echo '||';
                    $a = wppa_allow_uploads($album);
                    if (!$a) {
                        echo 'full';
                    } else {
                        echo 'notfull||' . $a;
                    }
                }
            } else {
                echo '||2||' . sprintf(__('An error occurred while trying to update <b>%s</b> of album %s', 'wp-photo-album-plus'), $itemname, $album);
                echo '<br>' . __('Press CTRL+F5 and try again.', 'wp-photo-album-plus');
            }
            wppa_clear_cache();
            wppa_exit();
            break;
        case 'update-comment-status':
            $photo = $_REQUEST['wppa-photo-id'];
            $nonce = $_REQUEST['wppa-nonce'];
            $comid = $_REQUEST['wppa-comment-id'];
            $comstat = $_REQUEST['wppa-comment-status'];
            // Check validity
            if (!wp_verify_nonce($nonce, 'wppa_nonce_' . $photo)) {
                echo '||0||' . __('You do not have the rights to update comment status', 'wp-photo-album-plus') . $nonce;
                wppa_exit();
                // Nonce check failed
            }
            //			if ( wppa_switch( 'search_comments' ) ) wppa_index_remove( 'photo', $photo );
            $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_COMMENTS . '` SET `status` = %s WHERE `id` = %s', $comstat, $comid));
            if (wppa_switch('search_comments')) {
                wppa_index_update('photo', $photo);
            }
            if ($iret !== false) {
                echo '||0||' . sprintf(__('Status of comment #%s updated', 'wp-photo-album-plus'), $comid);
            } else {
                echo '||1||' . sprintf(__('Error updating status comment #%s', 'wp-photo-album-plus'), $comid);
            }
            wppa_exit();
            break;
        case 'watermark-photo':
            $photo = $_REQUEST['photo-id'];
            $nonce = $_REQUEST['wppa-nonce'];
            // Check validity
            if (!wp_verify_nonce($nonce, 'wppa_nonce_' . $photo)) {
                echo '||1||' . __('You do not have the rights to change photos', 'wp-photo-album-plus');
                wppa_exit();
                // Nonce check failed
            }
            wppa_cache_thumb($photo);
            if (wppa_add_watermark($photo)) {
                if (wppa_switch('watermark_thumbs')) {
                    wppa_create_thumbnail($photo);
                    // create new thumb
                }
                echo '||0||' . __('Watermark applied', 'wp-photo-album-plus');
                wppa_exit();
            } else {
                echo '||1||' . __('An error occured while trying to apply a watermark', 'wp-photo-album-plus');
                wppa_exit();
            }
        case 'update-photo':
            $photo = $_REQUEST['photo-id'];
            $nonce = $_REQUEST['wppa-nonce'];
            $item = $_REQUEST['item'];
            $value = isset($_REQUEST['value']) ? $_REQUEST['value'] : '';
            $value = wppa_decode($value);
            // Check validity
            if (!wp_verify_nonce($nonce, 'wppa_nonce_' . $photo)) {
                echo '||0||' . __('You do not have the rights to update photo information', 'wp-photo-album-plus');
                wppa_exit();
                // Nonce check failed
            }
            if (substr($item, 0, 20) == 'wppa_watermark_file_' || substr($item, 0, 19) == 'wppa_watermark_pos_') {
                wppa_update_option($item, $value);
                echo '||0||' . sprintf(__('%s updated to %s.', 'wp-photo-album-plus'), $item, $value);
                wppa_exit();
            }
            switch ($item) {
                case 'exifdtm':
                    $format = '0000:00:00 00:00:00';
                    $err = '0';
                    // Length ok?
                    if (strlen($value) != 19) {
                        $err = '1';
                    }
                    // Check on digits, colons and space
                    for ($i = 0; $i < 19; $i++) {
                        $d = substr($value, $i, 1);
                        $f = substr($format, $i, 1);
                        switch ($f) {
                            case '0':
                                if (!in_array($d, array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))) {
                                    $err = '2';
                                }
                                break;
                            case ':':
                            case ' ':
                                if ($d != $f) {
                                    $err = '3';
                                }
                                break;
                        }
                    }
                    // Check on values if format correct, report first error only
                    if (!$err) {
                        $temp = explode(':', str_replace(' ', ':', $value));
                        if ($temp['0'] < '1970') {
                            $err = '11';
                        }
                        // Before UNIX epoch
                        if (!$err && $temp['0'] > date('Y')) {
                            $err = '12';
                        }
                        // Future
                        if (!$err && $temp['1'] < '1') {
                            $err = '13';
                        }
                        // Before january
                        if (!$err && $temp['1'] > '12') {
                            $err = '14';
                        }
                        // After december
                        if (!$err && $temp['2'] < '1') {
                            $err = '15';
                        }
                        // Before first of month
                        if (!$err && $temp['2'] > '31') {
                            $err = '17';
                        }
                        // After 31st ( forget about feb and months with 30 days )
                        if (!$err && $temp['3'] < '1') {
                            $err = '18';
                        }
                        // Before first hour
                        if (!$err && $temp['3'] > '24') {
                            $err = '19';
                        }
                        // Hour > 24
                        if (!$err && $temp['4'] < '1') {
                            $err = '20';
                        }
                        // Min < 1
                        if (!$err && $temp['4'] > '59') {
                            $err = '21';
                        }
                        // Min > 59
                        if (!$err && $temp['5'] < '1') {
                            $err = '22';
                        }
                        // Sec < 1
                        if (!$err && $temp['5'] > '59') {
                            $err = '23';
                        }
                        // Sec > 59
                    }
                    if ($err) {
                        echo '||1||' . sprintf(__('Format error %s. Must be yyyy:mm:dd hh:mm:ss', 'wp-photo-album-plus'), $err);
                    } else {
                        wppa_update_photo(array('id' => $photo, 'exifdtm' => $value));
                        echo '||0||' . __('Exif date/time updated', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'lat':
                    if (!is_numeric($value) || $value < '-90.0' || $value > '90.0') {
                        echo '||1||' . __('Enter a value > -90 and < 90', 'wp-photo-album-plus');
                        wppa_exit();
                    }
                    $photodata = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . WPPA_PHOTOS . ' WHERE `id` = %s', $photo), ARRAY_A);
                    $geo = $photodata['location'] ? $photodata['location'] : '///';
                    $geo = explode('/', $geo);
                    $geo = wppa_format_geo($value, $geo['3']);
                    $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `location` = %s WHERE `id` = %s', $geo, $photo));
                    if ($iret) {
                        echo '||0||' . __('Lattitude updated', 'wp-photo-album-plus');
                    } else {
                        echo '||1||' . __('Could not update lattitude', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'lon':
                    if (!is_numeric($value) || $value < '-180.0' || $value > '180.0') {
                        echo '||1||' . __('Enter a value > -180 and < 180', 'wp-photo-album-plus');
                        wppa_exit();
                    }
                    $photodata = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . WPPA_PHOTOS . ' WHERE `id` = %s', $photo), ARRAY_A);
                    $geo = $photodata['location'] ? $photodata['location'] : '///';
                    $geo = explode('/', $geo);
                    $geo = wppa_format_geo($geo['2'], $value);
                    $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `location` = %s WHERE `id` = %s', $geo, $photo));
                    if ($iret) {
                        echo '||0||' . __('Longitude updated', 'wp-photo-album-plus');
                    } else {
                        echo '||1||' . __('Could not update longitude', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'remake':
                    if (wppa_remake_files('', $photo)) {
                        wppa_bump_photo_rev();
                        wppa_bump_thumb_rev();
                        echo '||0||' . __('Photo files remade', 'wp-photo-album-plus');
                    } else {
                        echo '||2||' . __('Could not remake files', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'remakethumb':
                    if (wppa_create_thumbnail($photo)) {
                        echo '||0||' . __('Thumbnail remade', 'wp-photo-album-plus');
                    } else {
                        echo '||0||' . __('Could not remake thumbnail', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'rotright':
                case 'rot180':
                case 'rotleft':
                    switch ($item) {
                        case 'rotleft':
                            $angle = '90';
                            $dir = __('left', 'wp-photo-album-plus');
                            break;
                        case 'rot180':
                            $angle = '180';
                            $dir = __('180&deg;', 'wp-photo-album-plus');
                            break;
                        case 'rotright':
                            $angle = '270';
                            $dir = __('right', 'wp-photo-album-plus');
                            break;
                    }
                    wppa('error', wppa_rotate($photo, $angle));
                    if (!wppa('error')) {
                        wppa_update_modified($photo);
                        wppa_bump_photo_rev();
                        wppa_bump_thumb_rev();
                        echo '||0||' . sprintf(__('Photo %s rotated %s', 'wp-photo-album-plus'), $photo, $dir);
                    } else {
                        echo '||' . wppa('error') . '||' . sprintf(__('An error occurred while trying to rotate photo %s', 'wp-photo-album-plus'), $photo);
                    }
                    wppa_exit();
                    break;
                case 'moveto':
                    $photodata = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . WPPA_PHOTOS . ' WHERE `id` = %s', $photo), ARRAY_A);
                    if (wppa_switch('void_dups')) {
                        // Check for already exists
                        $exists = wppa_file_is_in_album($photodata['filename'], $value);
                        if ($exists) {
                            // Already exists
                            echo '||3||' . sprintf(__('A photo with filename %s already exists in album %s.', 'wp-photo-album-plus'), $photodata['filename'], $value);
                            wppa_exit();
                            break;
                        }
                    }
                    wppa_flush_treecounts($photodata['album']);
                    // Current album
                    wppa_flush_treecounts($value);
                    // New album
                    $iret = $wpdb->query($wpdb->prepare('UPDATE ' . WPPA_PHOTOS . ' SET `album` = %s WHERE `id` = %s', $value, $photo));
                    if ($iret !== false) {
                        wppa_move_source($photodata['filename'], $photodata['album'], $value);
                        echo '||99||' . sprintf(__('Photo %s has been moved to album %s (%s)', 'wp-photo-album-plus'), $photo, wppa_get_album_name($value), $value);
                    } else {
                        echo '||3||' . sprintf(__('An error occurred while trying to move photo %s', 'wp-photo-album-plus'), $photo);
                    }
                    wppa_exit();
                    break;
                case 'copyto':
                    $photodata = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . WPPA_PHOTOS . ' WHERE `id` = %s', $photo), ARRAY_A);
                    if (wppa_switch('void_dups')) {
                        // Check for already exists
                        $exists = wppa_file_is_in_album($photodata['filename'], $value);
                        if ($exists) {
                            // Already exists
                            echo '||4||' . sprintf(__('A photo with filename %s already exists in album %s.', 'wp-photo-album-plus'), $photodata['filename'], $value);
                            wppa_exit();
                            break;
                        }
                    }
                    wppa('error', wppa_copy_photo($photo, $value));
                    wppa_flush_treecounts($value);
                    // New album
                    if (!wppa('error')) {
                        echo '||0||' . sprintf(__('Photo %s copied to album %s (%s)', 'wp-photo-album-plus'), $photo, wppa_get_album_name($value), $value);
                    } else {
                        echo '||4||' . sprintf(__('An error occurred while trying to copy photo %s', 'wp-photo-album-plus'), $photo);
                        echo '<br>' . __('Press CTRL+F5 and try again.', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'status':
                    if (!current_user_can('wppa_moderate') && !current_user_can('wppa_admin')) {
                        die('Security check failure #78');
                    }
                    wppa_flush_treecounts(wppa_get_photo_item($photo, 'album'));
                    // $wpdb->get_var( $wpdb->prepare( "SELECT `album` FROM `".WPPA_PHOTOS."` WHERE `id` = %s", $photo ) ) );
                // $wpdb->get_var( $wpdb->prepare( "SELECT `album` FROM `".WPPA_PHOTOS."` WHERE `id` = %s", $photo ) ) );
                case 'owner':
                case 'name':
                case 'description':
                case 'p_order':
                case 'linkurl':
                case 'linktitle':
                case 'linktarget':
                case 'tags':
                case 'alt':
                case 'videox':
                case 'videoy':
                    switch ($item) {
                        case 'name':
                            $value = strip_tags($value);
                            $itemname = __('Name', 'wp-photo-album-plus');
                            break;
                        case 'description':
                            $itemname = __('Description', 'wp-photo-album-plus');
                            if (wppa_switch('check_balance')) {
                                $value = str_replace(array('<br/>', '<br>'), '<br />', $value);
                                if (balanceTags($value, true) != $value) {
                                    echo '||3||' . __('Unbalanced tags in photo description!', 'wp-photo-album-plus');
                                    wppa_exit();
                                }
                            }
                            break;
                        case 'p_order':
                            $itemname = __('Photo order #', 'wp-photo-album-plus');
                            break;
                        case 'owner':
                            $usr = get_user_by('login', $value);
                            if (!$usr) {
                                echo '||4||' . sprintf(__('User %s does not exists', 'wp-photo-album-plus'), $value);
                                wppa_exit();
                            }
                            $value = $usr->user_login;
                            // Correct possible case mismatch
                            wppa_flush_upldr_cache('photoid', $photo);
                            // Current owner
                            wppa_flush_upldr_cache('username', $value);
                            // New owner
                            $itemname = __('Owner', 'wp-photo-album-plus');
                            break;
                        case 'linkurl':
                            $itemname = __('Link url', 'wp-photo-album-plus');
                            break;
                        case 'linktitle':
                            $itemname = __('Link title', 'wp-photo-album-plus');
                            break;
                        case 'linktarget':
                            $itemname = __('Link target', 'wp-photo-album-plus');
                            break;
                        case 'tags':
                            $value = wppa_sanitize_tags($value, false, true);
                            $value = wppa_sanitize_tags(wppa_filter_iptc(wppa_filter_exif($value, $photo), $photo));
                            wppa_clear_taglist();
                            $itemname = __('Photo Tags', 'wp-photo-album-plus');
                            break;
                        case 'status':
                            wppa_clear_taglist();
                            wppa_flush_upldr_cache('photoid', $photo);
                            $itemname = __('Status', 'wp-photo-album-plus');
                            break;
                        case 'alt':
                            $itemname = __('HTML Alt', 'wp-photo-album-plus');
                            $value = strip_tags(stripslashes($value));
                            break;
                        case 'videox':
                            $itemname = __('Video width', 'wp-photo-album-plus');
                            if (!wppa_is_int($value) || $value < '0') {
                                echo '||3||' . __('Please enter an integer value >= 0', 'wp-photo-album-plus');
                                wppa_exit();
                            }
                            break;
                        case 'videoy':
                            $itemname = __('Video height', 'wp-photo-album-plus');
                            if (!wppa_is_int($value) || $value < '0') {
                                echo '||3||' . __('Please enter an integer value >= 0', 'wp-photo-album-plus');
                                wppa_exit();
                            }
                            break;
                        default:
                            $itemname = $item;
                    }
                    //				if ( $item == 'name' || $item == 'description' || $item == 'tags' ) wppa_index_quick_remove( 'photo', $photo );
                    $iret = $wpdb->query($wpdb->prepare('UPDATE ' . WPPA_PHOTOS . ' SET `' . $item . '` = %s WHERE `id` = %s', $value, $photo));
                    if ($item == 'name' || $item == 'description' || $item == 'tags') {
                        wppa_index_update('photo', $photo);
                    }
                    if ($item == 'status' && $value != 'scheduled') {
                        wppa_update_photo(array('id' => $photo, 'scheduledtm' => ''));
                    }
                    if ($item == 'status') {
                        wppa_flush_treecounts(wppa_get_photo_item($photo, 'album'));
                    }
                    if ($iret !== false) {
                        wppa_update_modified($photo);
                        if (wppa_is_video($photo)) {
                            echo '||0||' . sprintf(__('<b>%s</b> of video %s updated', 'wp-photo-album-plus'), $itemname, $photo);
                        } else {
                            echo '||0||' . sprintf(__('<b>%s</b> of photo %s updated', 'wp-photo-album-plus'), $itemname, $photo);
                        }
                    } else {
                        echo '||2||' . sprintf(__('An error occurred while trying to update <b>%s</b> of photo %s', 'wp-photo-album-plus'), $itemname, $photo);
                        echo '<br>' . __('Press CTRL+F5 and try again.', 'wp-photo-album-plus');
                        wppa_exit();
                    }
                    break;
                case 'year':
                case 'month':
                case 'day':
                case 'hour':
                case 'min':
                    $itemname = __('Schedule date/time', 'wp-photo-album-plus');
                    $scheduledtm = $wpdb->get_var($wpdb->prepare("SELECT `scheduledtm` FROM`" . WPPA_PHOTOS . "` WHERE `id` = %s", $photo));
                    if (!$scheduledtm) {
                        $scheduledtm = wppa_get_default_scheduledtm();
                    }
                    $temp = explode(',', $scheduledtm);
                    if ($item == 'year') {
                        $temp[0] = $value;
                    }
                    if ($item == 'month') {
                        $temp[1] = $value;
                    }
                    if ($item == 'day') {
                        $temp[2] = $value;
                    }
                    if ($item == 'hour') {
                        $temp[3] = $value;
                    }
                    if ($item == 'min') {
                        $temp[4] = $value;
                    }
                    $scheduledtm = implode(',', $temp);
                    wppa_update_photo(array('id' => $photo, 'scheduledtm' => $scheduledtm, 'status' => 'scheduled'));
                    wppa_flush_treecounts($wpdb->get_var($wpdb->prepare("SELECT `album` FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $photo)));
                    wppa_flush_upldr_cache('photoid', $photo);
                    if (wppa_is_video($photo)) {
                        echo '||0||' . sprintf(__('<b>%s</b> of video %s updated', 'wp-photo-album-plus'), $itemname, $photo);
                    } else {
                        echo '||0||' . sprintf(__('<b>%s</b> of photo %s updated', 'wp-photo-album-plus'), $itemname, $photo);
                    }
                    break;
                case 'custom_0':
                case 'custom_1':
                case 'custom_2':
                case 'custom_3':
                case 'custom_4':
                case 'custom_5':
                case 'custom_6':
                case 'custom_7':
                case 'custom_8':
                case 'custom_9':
                    $index = substr($item, -1);
                    $custom = wppa_get_photo_item($photo, 'custom');
                    if ($custom) {
                        $custom_data = unserialize($custom);
                    } else {
                        $custom_data = array('', '', '', '', '', '', '', '', '', '');
                    }
                    $custom_data[$index] = strip_tags($value);
                    $custom = serialize($custom_data);
                    wppa_update_photo(array('id' => $photo, 'custom' => $custom, 'modified' => time()));
                    wppa_index_update('photo', $photo);
                    echo '||0||' . sprintf(__('<b>Custom field %s</b> of photo %s updated', 'wp-photo-album-plus'), wppa_opt('custom_caption_' . $index), $photo);
                    break;
                case 'file':
                    // Check on upload error
                    if ($_FILES['photo']['error']) {
                        echo '||' . $_FILES['photo']['error'] . '||' . __('<b>Error during upload.</b>', 'wp-photo-album-plus');
                        wppa_exit();
                    }
                    // Save new source
                    wppa_save_source($_FILES['photo']['tmp_name'], wppa_get_photo_item($photo, 'filename'), wppa_get_photo_item($photo, 'album'));
                    // Make the files
                    $bret = wppa_make_the_photo_files($_FILES['photo']['tmp_name'], $photo, strtolower(wppa_get_ext($_FILES['photo']['name'])));
                    if ($bret) {
                        // Update timestamps and sizes
                        $alb = wppa_get_photo_item($photo, 'album');
                        wppa_update_album(array('id' => $alb, 'modified' => time()));
                        wppa_update_photo(array('id' => $photo, 'modified' => time(), 'thumbx' => '0', 'thumby' => '0', 'photox' => '0', 'photoy' => '0'));
                        // Report success
                        echo '||0||' . __('Photo files updated.', 'wp-photo-album-plus');
                    } else {
                        // Report fail
                        echo '||1||' . __('Could not update files.', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'stereo':
                    $t = microtime(true);
                    wppa_update_photo(array('id' => $photo, 'stereo' => $value));
                    wppa_create_stereo_images($photo);
                    wppa_create_thumbnail($photo);
                    $t = microtime(true) - $t;
                    echo '||0||' . sprintf(__('Stereo mode updated in %d milliseconds', 'wp-photo-album-plus'), floor($t * 1000));
                    wppa_exit();
                    break;
                default:
                    echo '||98||This update action is not implemented yet( ' . $item . ' )';
                    wppa_exit();
            }
            wppa_clear_cache();
            break;
            // The wppa-settings page calls ajax with $wppa_action == 'update-option';
        // The wppa-settings page calls ajax with $wppa_action == 'update-option';
        case 'update-option':
            // Verify that we are legally here
            $nonce = $_REQUEST['wppa-nonce'];
            if (!wp_verify_nonce($nonce, 'wppa-nonce')) {
                echo '||1||' . __('You do not have the rights to update settings', 'wp-photo-album-plus');
                wppa_exit();
                // Nonce check failed
            }
            // Initialize
            $old_minisize = wppa_get_minisize();
            // Remember for later, maybe we do something that requires regen
            $option = $_REQUEST['wppa-option'];
            // The option to be processed
            $value = isset($_REQUEST['value']) ? wppa_decode($_REQUEST['value']) : '';
            // The new value, may also contain & # and +
            $value = stripslashes($value);
            $value = trim($value);
            // Remaove surrounding spaces
            $alert = '';
            // Init the return string data
            wppa('error', '0');
            //
            $title = '';
            //
            // If it is a font family, change all double quotes into single quotes as this destroys much more than you would like
            if (strpos($option, 'wppa_fontfamily_') !== false) {
                $value = str_replace('"', "'", $value);
            }
            $option = wppa_decode($option);
            // Dispatch on option
            if (substr($option, 0, 16) == 'wppa_iptc_label_') {
                $tag = substr($option, 16);
                $q = $wpdb->prepare("UPDATE `" . WPPA_IPTC . "` SET `description`=%s WHERE `tag`=%s AND `photo`='0'", $value, $tag);
                $bret = $wpdb->query($q);
                // Produce the response text
                if ($bret) {
                    $output = '||0||' . $tag . ' updated to ' . $value . '||';
                } else {
                    $output = '||1||Failed to update ' . $tag . '||';
                }
                echo $output;
                wppa_exit();
            } elseif (substr($option, 0, 17) == 'wppa_iptc_status_') {
                $tag = substr($option, 17);
                $q = $wpdb->prepare("UPDATE `" . WPPA_IPTC . "` SET `status`=%s WHERE `tag`=%s AND `photo`='0'", $value, $tag);
                $bret = $wpdb->query($q);
                // Produce the response text
                if ($bret) {
                    $output = '||0||' . $tag . ' updated to ' . $value . '||';
                } else {
                    $output = '||1||Failed to update ' . $tag . '||';
                }
                echo $output;
                wppa_exit();
            } elseif (substr($option, 0, 16) == 'wppa_exif_label_') {
                $tag = substr($option, 16);
                $q = $wpdb->prepare("UPDATE `" . WPPA_EXIF . "` SET `description`=%s WHERE `tag`=%s AND `photo`='0'", $value, $tag);
                $bret = $wpdb->query($q);
                // Produce the response text
                if ($bret) {
                    $output = '||0||' . $tag . ' updated to ' . $value . '||';
                } else {
                    $output = '||1||Failed to update ' . $tag . '||';
                }
                echo $output;
                wppa_exit();
            } elseif (substr($option, 0, 17) == 'wppa_exif_status_') {
                $tag = substr($option, 17);
                $q = $wpdb->prepare("UPDATE `" . WPPA_EXIF . "` SET `status`=%s WHERE `tag`=%s AND `photo`='0'", $value, $tag);
                $bret = $wpdb->query($q);
                // Produce the response text
                if ($bret) {
                    $output = '||0||' . $tag . ' updated to ' . $value . '||';
                } else {
                    $output = '||1||Failed to update ' . $tag . '||';
                }
                echo $output;
                wppa_exit();
            } elseif (substr($option, 0, 5) == 'caps-') {
                // Is capability setting
                global $wp_roles;
                //$R = new WP_Roles;
                $setting = explode('-', $option);
                if ($value == 'yes') {
                    $wp_roles->add_cap($setting[2], $setting[1]);
                    echo '||0||' . __('Capability granted', 'wp-photo-album-plus') . '||';
                    wppa_exit();
                } elseif ($value == 'no') {
                    $wp_roles->remove_cap($setting[2], $setting[1]);
                    echo '||0||' . __('Capability withdrawn', 'wp-photo-album-plus') . '||';
                    wppa_exit();
                } else {
                    echo '||1||Invalid value: ' . $value . '||';
                    wppa_exit();
                }
            } else {
                switch ($option) {
                    case 'wppa_colwidth':
                        //	 ??	  fixed   low	high	title
                        wppa_ajax_check_range($value, 'auto', '100', false, __('Column width.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_initial_colwidth':
                        wppa_ajax_check_range($value, false, '100', false, __('Initial width.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_fullsize':
                        wppa_ajax_check_range($value, false, '100', false, __('Full size.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_maxheight':
                        wppa_ajax_check_range($value, false, '100', false, __('Max height.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_thumbsize':
                        wppa_ajax_check_range($value, false, '50', false, __('Thumbnail size.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_tf_width':
                        wppa_ajax_check_range($value, false, '50', false, __('Thumbnail frame width', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_tf_height':
                        wppa_ajax_check_range($value, false, '50', false, __('Thumbnail frame height', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_tn_margin':
                        wppa_ajax_check_range($value, false, '0', false, __('Thumbnail Spacing', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_min_thumbs':
                        wppa_ajax_check_range($value, false, '0', false, __('Photocount treshold.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_thumb_page_size':
                        wppa_ajax_check_range($value, false, '0', false, __('Thumb page size.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_smallsize':
                        wppa_ajax_check_range($value, false, '50', false, __('Cover photo size.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_album_page_size':
                        wppa_ajax_check_range($value, false, '0', false, __('Album page size.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_topten_count':
                        wppa_ajax_check_range($value, false, '2', false, __('Number of TopTen photos', 'wp-photo-album-plus'), '40');
                        break;
                    case 'wppa_topten_size':
                        wppa_ajax_check_range($value, false, '32', false, __('Widget image thumbnail size', 'wp-photo-album-plus'), wppa_get_minisize());
                        break;
                    case 'wppa_max_cover_width':
                        wppa_ajax_check_range($value, false, '150', false, __('Max Cover width', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_text_frame_height':
                        wppa_ajax_check_range($value, false, '0', false, __('Minimal description height', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_cover_minheight':
                        wppa_ajax_check_range($value, false, '0', false, __('Minimal cover height', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_head_and_text_frame_height':
                        wppa_ajax_check_range($value, false, '0', false, __('Minimal text frame height', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_bwidth':
                        wppa_ajax_check_range($value, '', '0', false, __('Border width', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_bradius':
                        wppa_ajax_check_range($value, '', '0', false, __('Border radius', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_box_spacing':
                        wppa_ajax_check_range($value, '', '-20', '100', __('Box spacing', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_popupsize':
                        $floor = wppa_opt('thumbsize');
                        $temp = wppa_opt('smallsize');
                        if ($temp > $floor) {
                            $floor = $temp;
                        }
                        wppa_ajax_check_range($value, false, $floor, wppa_opt('fullsize'), __('Popup size', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_fullimage_border_width':
                        wppa_ajax_check_range($value, '', '0', false, __('Fullsize border width', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_lightbox_bordersize':
                        wppa_ajax_check_range($value, false, '0', false, __('Lightbox Bordersize', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_ovl_border_width':
                        wppa_ajax_check_range($value, false, '0', '16', __('Lightbox Borderwidth', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_ovl_border_radius':
                        wppa_ajax_check_range($value, false, '0', '16', __('Lightbox Borderradius', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_comment_count':
                        wppa_ajax_check_range($value, false, '2', '40', __('Number of Comment widget entries', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_comment_size':
                        wppa_ajax_check_range($value, false, '32', wppa_get_minisize(), __('Comment Widget image thumbnail size', 'wp-photo-album-plus'), wppa_get_minisize());
                        break;
                    case 'wppa_thumb_opacity':
                        wppa_ajax_check_range($value, false, '0', '100', __('Opacity.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_cover_opacity':
                        wppa_ajax_check_range($value, false, '0', '100', __('Opacity.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_star_opacity':
                        wppa_ajax_check_range($value, false, '0', '50', __('Opacity.', 'wp-photo-album-plus'));
                        break;
                        //				case 'wppa_filter_priority':
                        //					wppa_ajax_check_range( $value, false, wppa_opt( 'shortcode_priority' ), false, __( 'Filter priority' ,'wp-photo-album-plus' ) );
                        //					break;
                        //				case 'wppa_shortcode_priority':
                        //					wppa_ajax_check_range( $value, false, '0', wppa_opt( 'filter_priority' ) - '1', __( 'Shortcode_priority', 'wp-photo-album-plus' ) );
                        //					break;
                    //				case 'wppa_filter_priority':
                    //					wppa_ajax_check_range( $value, false, wppa_opt( 'shortcode_priority' ), false, __( 'Filter priority' ,'wp-photo-album-plus' ) );
                    //					break;
                    //				case 'wppa_shortcode_priority':
                    //					wppa_ajax_check_range( $value, false, '0', wppa_opt( 'filter_priority' ) - '1', __( 'Shortcode_priority', 'wp-photo-album-plus' ) );
                    //					break;
                    case 'wppa_gravatar_size':
                        wppa_ajax_check_range($value, false, '10', '256', __('Avatar size', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_watermark_opacity':
                        wppa_ajax_check_range($value, false, '0', '100', __('Watermark opacity', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_watermark_opacity_text':
                        wppa_ajax_check_range($value, false, '0', '100', __('Watermark opacity', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_ovl_txt_lines':
                        wppa_ajax_check_range($value, 'auto', '0', '24', __('Number of text lines', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_ovl_opacity':
                        wppa_ajax_check_range($value, false, '0', '100', __('Overlay opacity', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_upload_limit_count':
                        wppa_ajax_check_range($value, false, '0', false, __('Upload limit', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_dislike_mail_every':
                        wppa_ajax_check_range($value, false, '0', false, __('Notify inappropriate', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_dislike_set_pending':
                        wppa_ajax_check_range($value, false, '0', false, __('Dislike pending', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_dislike_delete':
                        wppa_ajax_check_range($value, false, '0', false, __('Dislike delete', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_max_execution_time':
                        wppa_ajax_check_range($value, false, '0', '900', __('Max execution time', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_cp_points_comment':
                    case 'wppa_cp_points_rating':
                    case 'wppa_cp_points_upload':
                        wppa_ajax_check_range($value, false, '0', false, __('Cube Points points', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_jpeg_quality':
                        wppa_ajax_check_range($value, false, '20', '100', __('JPG Image quality', 'wp-photo-album-plus'));
                        if (wppa_cdn('admin') == 'cloudinary' && !wppa('out')) {
                            wppa_delete_derived_from_cloudinary();
                        }
                        break;
                    case 'wppa_imgfact_count':
                        wppa_ajax_check_range($value, false, '1', '24', __('Number of coverphotos', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_dislike_value':
                        wppa_ajax_check_range($value, false, '-10', '0', __('Dislike value', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_slideshow_pagesize':
                        wppa_ajax_check_range($value, false, '0', false, __('Slideshow pagesize', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_pagelinks_max':
                        wppa_ajax_check_range($value, false, '0', false, __('Max Pagelinks', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_start_pause_symbol_size':
                        wppa_ajax_check_range($value, false, '0', false, __('Start/pause symbol size', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_start_pause_symbol_bradius':
                        wppa_ajax_check_range($value, false, '0', false, __('Start/pause symbol border radius', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_stop_symbol_size':
                        wppa_ajax_check_range($value, false, '0', false, __('Stop symbol size', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_stop_symbol_bradius':
                        wppa_ajax_check_range($value, false, '0', false, __('Stop symbol border radius', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_rating_clear':
                        $iret1 = $wpdb->query('TRUNCATE TABLE ' . WPPA_RATING);
                        $iret2 = $wpdb->query('UPDATE ' . WPPA_PHOTOS . ' SET mean_rating="0", rating_count="0" WHERE id > -1');
                        if ($iret1 !== false && $iret2 !== false) {
                            delete_option('wppa_' . WPPA_RATING . '_lastkey');
                            $title = __('Ratings cleared', 'wp-photo-album-plus');
                        } else {
                            $title = __('Could not clear ratings', 'wp-photo-album-plus');
                            $alert = $title;
                            wppa('error', '1');
                        }
                        break;
                    case 'wppa_viewcount_clear':
                        $iret = $wpdb->query("UPDATE `" . WPPA_PHOTOS . "` SET `views` = '0'") && $wpdb->query("UPDATE `" . WPPA_ALBUMS . "` SET `views` = '0'");
                        if ($iret !== false) {
                            $title = __('Viewcounts cleared', 'wp-photo-album-plus');
                        } else {
                            $title = __('Could not clear viewcounts', 'wp-photo-album-plus');
                            $alert = $title;
                            wppa('error', '1');
                        }
                        break;
                    case 'wppa_iptc_clear':
                        $iret = $wpdb->query('TRUNCATE TABLE ' . WPPA_IPTC);
                        if ($iret !== false) {
                            delete_option('wppa_' . WPPA_IPTC . '_lastkey');
                            $title = __('IPTC data cleared', 'wp-photo-album-plus');
                            $alert = __('Refresh this page to clear table X', 'wp-photo-album-plus');
                            update_option('wppa_index_need_remake', 'yes');
                        } else {
                            $title = __('Could not clear IPTC data', 'wp-photo-album-plus');
                            $alert = $title;
                            wppa('error', '1');
                        }
                        break;
                    case 'wppa_exif_clear':
                        $iret = $wpdb->query('TRUNCATE TABLE ' . WPPA_EXIF);
                        if ($iret !== false) {
                            delete_option('wppa_' . WPPA_EXIF . '_lastkey');
                            $title = __('EXIF data cleared', 'wp-photo-album-plus');
                            $alert = __('Refresh this page to clear table XI', 'wp-photo-album-plus');
                            update_option('wppa_index_need_remake', 'yes');
                        } else {
                            $title = __('Could not clear EXIF data', 'wp-photo-album-plus');
                            $alert = $title;
                            wppa('error', '1');
                        }
                        break;
                    case 'wppa_recup':
                        $result = wppa_recuperate_iptc_exif();
                        echo '||0||' . __('Recuperation performed', 'wp-photo-album-plus') . '||' . $result;
                        wppa_exit();
                        break;
                    case 'wppa_bgcolor_thumbnail':
                        $value = trim(strtolower($value));
                        if (strlen($value) != '7' || substr($value, 0, 1) != '#') {
                            wppa('error', '1');
                        } else {
                            for ($i = 1; $i < 7; $i++) {
                                if (!in_array(substr($value, $i, 1), array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'))) {
                                    wppa('error', '1');
                                }
                            }
                        }
                        if (!wppa('error')) {
                            $old_minisize--;
                        } else {
                            $alert = __('Illegal format. Please enter a 6 digit hexadecimal color value. Example: #77bbff', 'wp-photo-album-plus');
                        }
                        break;
                    case 'wppa_thumb_aspect':
                        $old_minisize--;
                        // Trigger regen message
                        break;
                    case 'wppa_rating_max':
                        if ($value == '5' && wppa_opt('rating_max') == '10') {
                            $rats = $wpdb->get_results('SELECT `id`, `value` FROM `' . WPPA_RATING . '`', ARRAY_A);
                            if ($rats) {
                                foreach ($rats as $rat) {
                                    $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_RATING . '` SET `value` = %s WHERE `id` = %s', $rat['value'] / 2, $rat['id']));
                                }
                            }
                        }
                        if ($value == '10' && wppa_opt('rating_max') == '5') {
                            $rats = $wpdb->get_results('SELECT `id`, `value` FROM `' . WPPA_RATING . '`', ARRAY_A);
                            if ($rats) {
                                foreach ($rats as $rat) {
                                    $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_RATING . '` SET `value` = %s WHERE `id` = %s', $rat['value'] * 2, $rat['id']));
                                }
                            }
                        }
                        update_option('wppa_rerate_status', 'Required');
                        $alert .= __('You just changed a setting that requires the recalculation of ratings.', 'wp-photo-album-plus');
                        $alert .= ' ' . __('Please run the appropriate action in Table VIII.', 'wp-photo-album-plus');
                        wppa_update_option($option, $value);
                        wppa('error', '0');
                        break;
                    case 'wppa_newphoto_description':
                        if (wppa_switch('check_balance') && balanceTags($value, true) != $value) {
                            $alert = __('Unbalanced tags in photo description!', 'wp-photo-album-plus');
                            wppa('error', '1');
                        } else {
                            wppa_update_option($option, $value);
                            wppa('error', '0');
                            $alert = '';
                            wppa_index_compute_skips();
                        }
                        break;
                    case 'wppa_keep_source':
                        $dir = wppa_opt('source_dir');
                        if (!is_dir($dir)) {
                            @mkdir($dir);
                        }
                        if (!is_dir($dir) || !is_writable($dir)) {
                            wppa('error', '1');
                            $alert = sprintf(__('Unable to create or write to %s', 'wp-photo-album-plus'), $dir);
                        }
                        break;
                    case 'wppa_source_dir':
                        $olddir = wppa_opt('source_dir');
                        $value = rtrim($value, '/');
                        if (strpos($value . '/', WPPA_UPLOAD_PATH . '/') !== false) {
                            wppa('error', '1');
                            $alert = sprintf(__('Source can not be inside the wppa folder.', 'wp-photo-album-plus'));
                        } else {
                            $dir = $value;
                            if (!is_dir($dir)) {
                                @mkdir($dir);
                            }
                            if (!is_dir($dir) || !is_writable($dir)) {
                                wppa('error', '1');
                                $alert = sprintf(__('Unable to create or write to %s', 'wp-photo-album-plus'), $dir);
                            } else {
                                @rmdir($olddir);
                                // try to remove when empty
                            }
                        }
                        break;
                    case 'wppa_newpag_content':
                        if (strpos($value, 'w#album') === false) {
                            $alert = __('The content must contain w#album', 'wp-photo-album-plus');
                            wppa('error', '1');
                        }
                        break;
                    case 'wppa_gpx_shortcode':
                        if (strpos($value, 'w#lat') === false || strpos($value, 'w#lon') === false) {
                            $alert = __('The content must contain w#lat and w#lon', 'wp-photo-album-plus');
                            wppa('error', '1');
                        }
                        break;
                    case 'wppa_i_responsive':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_colwidth', 'auto');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_colwidth', '640');
                        }
                        break;
                    case 'wppa_i_downsize':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_resize_on_upload', 'yes');
                            if (wppa_opt('resize_to') == '0') {
                                wppa_update_option('wppa_resize_to', '1024x768');
                            }
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_resize_on_upload', 'no');
                        }
                        break;
                    case 'wppa_i_source':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_keep_source_admin', 'yes');
                            wppa_update_option('wppa_keep_source_frontend', 'yes');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_keep_source_admin', 'no');
                            wppa_update_option('wppa_keep_source_frontend', 'no');
                        }
                        break;
                    case 'wppa_i_userupload':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_user_upload_on', 'yes');
                            wppa_update_option('wppa_user_upload_login', 'yes');
                            wppa_update_option('wppa_owner_only', 'yes');
                            wppa_update_option('wppa_upload_moderate', 'yes');
                            wppa_update_option('wppa_upload_edit', 'yes');
                            wppa_update_option('wppa_upload_notify', 'yes');
                            wppa_update_option('wppa_grant_an_album', 'yes');
                            $grantparent = wppa_opt('grant_parent');
                            if (!wppa_album_exists($grantparent)) {
                                $id = wppa_create_album_entry(array('name' => __('Members', 'wp-photo-album-plus'), 'description' => __('Parent of the member albums', 'wp-photo-album-plus'), 'a_parent' => '-1', 'upload_limit' => '0/0'));
                                if ($id) {
                                    wppa_index_add('album', $id);
                                    wppa_update_option('wppa_grant_parent', $id);
                                }
                                $my_post = array('post_title' => __('Members', 'wp-photo-album-plus'), 'post_content' => '[wppa type="content" album="' . $id . '"][/wppa]', 'post_status' => 'publish', 'post_type' => 'page');
                                $pagid = wp_insert_post($my_post);
                            }
                            wppa_update_option('wppa_alt_is_restricted', 'yes');
                            wppa_update_option('wppa_link_is_restricted', 'yes');
                            wppa_update_option('wppa_covertype_is_restricted', 'yes');
                            wppa_update_option('wppa_porder_restricted', 'yes');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_user_upload_on', 'no');
                        }
                        break;
                    case 'wppa_i_rating':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_rating_on', 'yes');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_rating_on', 'no');
                        }
                        break;
                    case 'wppa_i_comment':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_show_comments', 'yes');
                            wppa_update_option('wppa_comment_moderation', 'all');
                            wppa_update_option('wppa_comment_notify', 'admin');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_show_comments', 'no');
                        }
                        break;
                    case 'wppa_i_share':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_share_on', 'yes');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_share_on', 'no');
                        }
                        break;
                    case 'wppa_i_iptc':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_show_iptc', 'yes');
                            wppa_update_option('wppa_save_iptc', 'yes');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_show_iptc', 'no');
                            wppa_update_option('wppa_save_iptc', 'no');
                        }
                        break;
                    case 'wppa_i_exif':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_show_exif', 'yes');
                            wppa_update_option('wppa_save_exif', 'yes');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_show_exif', 'no');
                            wppa_update_option('wppa_save_exif', 'no');
                        }
                        break;
                    case 'wppa_i_gpx':
                        if ($value == 'yes') {
                            $custom_content = wppa_opt('custom_content');
                            if (strpos($custom_content, 'w#location') === false) {
                                $custom_content = $custom_content . ' w#location';
                                wppa_update_option('wppa_custom_content', $custom_content);
                            }
                            if (!wppa_switch('custom_on')) {
                                wppa_update_option('wppa_custom_on', 'yes');
                            }
                            if (wppa_opt('gpx_implementation') == 'none') {
                                wppa_update_option('wppa_gpx_implementation', 'wppa-plus-embedded');
                            }
                        }
                        break;
                    case 'wppa_i_fotomoto':
                        if ($value == 'yes') {
                            $custom_content = wppa_opt('custom_content');
                            if (strpos($custom_content, 'w#fotomoto') === false) {
                                $custom_content = 'w#fotomoto ' . $custom_content;
                                wppa_update_option('wppa_custom_content', $custom_content);
                            }
                            if (!wppa_switch('custom_on')) {
                                wppa_update_option('wppa_custom_on', 'yes');
                            }
                            wppa_update_option('wppa_fotomoto_on', 'yes');
                            wppa_update_option('wppa_custom_on', 'yes');
                        }
                        break;
                    case 'wppa_i_video':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_enable_video', 'yes');
                        } else {
                            wppa_update_option('wppa_enable_video', 'no');
                        }
                        break;
                    case 'wppa_i_audio':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_enable_audio', 'yes');
                        } else {
                            wppa_update_option('wppa_enable_audio', 'no');
                        }
                        break;
                    case 'wppa_i_done':
                        $value = 'done';
                        break;
                    case 'wppa_search_tags':
                    case 'wppa_search_cats':
                    case 'wppa_search_comments':
                        update_option('wppa_index_need_remake', 'yes');
                        break;
                    case 'wppa_blacklist_user':
                        // Does user exist?
                        $value = trim($value);
                        $user = get_user_by('login', $value);
                        // seems to be case insensitive
                        if ($user && $user->user_login === $value) {
                            $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `status` = 'pending' WHERE `owner` = %s", $value));
                            $black_listed_users = get_option('wppa_black_listed_users', array());
                            if (!in_array($value, $black_listed_users)) {
                                $black_listed_users[] = $value;
                                update_option('wppa_black_listed_users', $black_listed_users);
                            }
                            $alert = esc_js(sprintf(__('User %s has been blacklisted.', 'wp-photo-album-plus'), $value));
                        } else {
                            $alert = esc_js(sprintf(__('User %s does not exist.', 'wp-photo-album-plus'), $value));
                        }
                        $value = '';
                        break;
                    case 'wppa_un_blacklist_user':
                        $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `status` = 'publish' WHERE `owner` = %s", $value));
                        $black_listed_users = get_option('wppa_black_listed_users', array());
                        if (in_array($value, $black_listed_users)) {
                            foreach (array_keys($black_listed_users) as $usr) {
                                if ($black_listed_users[$usr] == $value) {
                                    unset($black_listed_users[$usr]);
                                }
                            }
                            update_option('wppa_black_listed_users', $black_listed_users);
                        }
                        $value = '0';
                        break;
                    case 'wppa_fotomoto_on':
                        if ($value == 'yes') {
                            $custom_content = wppa_opt('custom_content');
                            if (strpos($custom_content, 'w#fotomoto') === false) {
                                $custom_content = 'w#fotomoto ' . $custom_content;
                                wppa_update_option('wppa_custom_content', $custom_content);
                                $alert = __('The content of the Custom box has been changed to display the Fotomoto toolbar.', 'wp-photo-album-plus') . ' ';
                            }
                            if (!wppa_switch('custom_on')) {
                                wppa_update_option('wppa_custom_on', 'yes');
                                $alert .= __('The display of the custom box has been enabled', 'wp-photo-album-plus');
                            }
                        }
                        break;
                    case 'wppa_gpx_implementation':
                        if ($value != 'none') {
                            $custom_content = wppa_opt('custom_content');
                            if (strpos($custom_content, 'w#location') === false) {
                                $custom_content = $custom_content . ' w#location';
                                wppa_update_option('wppa_custom_content', $custom_content);
                                $alert = __('The content of the Custom box has been changed to display maps.', 'wp-photo-album-plus') . ' ';
                            }
                            if (!wppa_switch('custom_on')) {
                                wppa_update_option('wppa_custom_on', 'yes');
                                $alert .= __('The display of the custom box has been enabled', 'wp-photo-album-plus');
                            }
                        }
                        break;
                    case 'wppa_regen_thumbs_skip_one':
                        $last = get_option('wppa_regen_thumbs_last', '0');
                        $skip = $last + '1';
                        update_option('wppa_regen_thumbs_last', $skip);
                        break;
                    case 'wppa_remake_skip_one':
                        $last = get_option('wppa_remake_last', '0');
                        $skip = $last + '1';
                        update_option('wppa_remake_last', $skip);
                        break;
                    case 'wppa_errorlog_purge':
                        @unlink(WPPA_CONTENT_PATH . '/wppa-depot/admin/error.log');
                        break;
                    case 'wppa_pl_dirname':
                        $value = wppa_sanitize_file_name($value);
                        $value = trim($value, ' /');
                        if (!$value) {
                            wppa('error', '714');
                            wppa_out(__('This value can not be empty', 'wp-photo-album-plus'));
                        } else {
                            wppa_create_pl_htaccess($value);
                        }
                        break;
                    case 'wppa_new_tag_value':
                        $value = wppa_sanitize_tags($value, false, true);
                        break;
                    case 'wppa_up_tagselbox_content_1':
                    case 'wppa_up_tagselbox_content_2':
                    case 'wppa_up_tagselbox_content_3':
                        $value = wppa_sanitize_tags($value);
                        break;
                    case 'wppa_wppa_set_shortcodes':
                        $value = str_replace(' ', '', $value);
                        break;
                    case 'wppa_enable_video':
                        // if off: set all statusses of videos to pending
                        break;
                    default:
                        wppa('error', '0');
                        $alert = '';
                }
            }
            if (wppa('error')) {
                if (!$title) {
                    $title = sprintf(__('Failed to set %s to %s', 'wp-photo-album-plus'), $option, $value);
                }
                if (!$alert) {
                    $alert .= wppa('out');
                }
            } else {
                wppa_update_option($option, $value);
                if (!$title) {
                    $title = sprintf(__('Setting %s updated to %s', 'wp-photo-album-plus'), $option, $value);
                }
            }
            // Save possible error
            $error = wppa('error');
            // Something to do after changing the setting?
            wppa_initialize_runtime(true);
            // force reload new values
            // .htaccess
            wppa_create_wppa_htaccess();
            // Thumbsize
            $new_minisize = wppa_get_minisize();
            if ($old_minisize != $new_minisize) {
                update_option('wppa_regen_thumbs_status', 'Required');
                $alert .= __('You just changed a setting that requires the regeneration of thumbnails.', 'wp-photo-album-plus');
                $alert .= ' ' . __('Please run the appropriate action in Table VIII.', 'wp-photo-album-plus');
            }
            // Produce the response text
            $output = '||' . $error . '||' . esc_attr($title) . '||' . esc_js($alert);
            echo $output;
            wppa_clear_cache();
            wppa_exit();
            break;
            // End update-option
        // End update-option
        case 'maintenance':
            $slug = $_POST['slug'];
            $nonce = $_REQUEST['wppa-nonce'];
            if (!wp_verify_nonce($nonce, 'wppa-nonce')) {
                echo 'Security check failure||' . $slug . '||Error||0';
                wppa_exit();
            }
            echo wppa_do_maintenance_proc($slug);
            wppa_exit();
            break;
        case 'maintenancepopup':
            $slug = $_POST['slug'];
            $nonce = $_REQUEST['wppa-nonce'];
            if (!wp_verify_nonce($nonce, 'wppa-nonce')) {
                echo 'Security check failure||' . $slug . '||Error||0';
                wppa_exit();
            }
            echo wppa_do_maintenance_popup($slug);
            wppa_exit();
            break;
        case 'do-fe-upload':
            if (is_admin()) {
                require_once 'wppa-non-admin.php';
            }
            wppa_user_upload();
            echo wppa('out');
            wppa_exit();
            break;
        case 'sanitizetags':
            $tags = isset($_GET['tags']) ? $_GET['tags'] : '';
            $album = isset($_GET['album']) ? $_GET['album'] : '0';
            $deftags = $album ? wppa_get_album_item($album, 'default_tags') : '';
            $tags = $deftags ? $tags . ',' . $deftags : $tags;
            echo wppa_sanitize_tags($tags, false, true);
            wppa_exit();
            break;
        case 'destroyalbum':
            $album = isset($_GET['album']) ? $_GET['album'] : '0';
            if (!$album) {
                _e('Missing album id', 'wp-photo-album-plus');
                wppa_exit();
            }
            $nonce = isset($_GET['nonce']) ? $_GET['nonce'] : '';
            if (!$nonce || !wp_verify_nonce($nonce, 'wppa_nonce_' . $album)) {
                echo 'Security check failure #798';
                wppa_exit();
            }
            // May I?
            $imay = true;
            if (!wppa_switch('user_destroy_on')) {
                $may = false;
            }
            if (wppa_switch('user_create_login')) {
                if (!is_user_logged_in()) {
                    $may = false;
                }
                // Must login
            }
            if (!wppa_have_access($album)) {
                $may = false;
                // No album access
            }
            if (wppa_is_user_blacklisted()) {
                $may = false;
            }
            if (!$imay) {
                _e('You do not have the rights to delete this album', 'wp-photo-album-plus');
                wppa_exit();
            }
            // I may
            require_once 'wppa-album-admin-autosave.php';
            wppa_del_album($album, '');
            wppa_exit();
            break;
        default:
            // Unimplemented $wppa-action
            die('-1');
    }
    wppa_exit();
}
function wppa_walbum_sanitize($walbum)
{
    $result = strtolower($walbum);
    $result = strip_tags($result);
    if (strstr($result, 'all-sep')) {
        $result = 'all-sep';
    } elseif (strstr($result, 'all')) {
        $result = 'all';
    } elseif (strstr($result, 'sep')) {
        $result = 'sep';
    } elseif (strstr($result, 'topten')) {
        $result = 'topten';
    } elseif (strstr($result, 'clr')) {
        $result = '';
    } else {
        // Change multiple commas to one
        while (substr_count($result, ',,')) {
            $result = str_replace(',,', ',', $result);
        }
        // remove leading and trailing commas
        $result = trim($result, ',');
        // Check for illegal chars
        $temp = str_replace(',', '', $result);
        if ($temp && !wppa_is_int($temp)) {
            // $result contains other chars than numbers and comma's
            $result = 'clr';
        }
    }
    return $result;
}
Beispiel #26
0
function wppa_album_desc($key)
{
    // Virtual albums have no name
    if (wppa_is_virtual()) {
        return;
    }
    // Album enumerations have no name
    if (strlen(wppa('start_album')) > '0' && !wppa_is_int(wppa('start_album'))) {
        return;
    }
    $result = '';
    if (wppa_opt('albdesc_on_thumbarea') == $key && wppa('start_album')) {
        $desc = wppa_get_album_desc(wppa('start_album'));
        if ($key == 'top') {
            $result .= '<div' . ' id="wppa-albdesc-' . wppa('mocc') . '"' . ' class="wppa-box-text wppa-black"' . ' style="padding-right:6px;' . __wcs('wppa-box-text') . __wcs('wppa-black') . '"' . ' >' . $desc . '</div>' . '<div style="clear:both" ></div>';
        }
        if ($key == 'bottom') {
            $result .= '<div' . ' id="wppa-albdesc-b-' . wppa('mocc') . '"' . ' class="wppa-box-text wppa-black"' . ' style="clear:both; padding-right:6px;' . __wcs('wppa-box-text') . __wcs('wppa-black') . '"' . ' >' . $desc . '</div>';
        }
    }
    wppa_out($result);
}
Beispiel #27
0
function wppa_cache_thumb($id, $data = '')
{
    global $wpdb;
    global $thumb;
    static $thumb_cache_2;
    // Action?
    if ($id == 'invalidate') {
        if (isset($thumb_cache_2[$data])) {
            unset($thumb_cache_2[$data]);
        }
        $thumb = false;
        return false;
    }
    if ($id == 'add') {
        if (!$data) {
            // Nothing to add
            return false;
        } elseif (isset($data['id'])) {
            // Add a single thumb to 2nd level cache
            $thumb_cache_2[$data['id']] = $data;
            // Looks valid
        } elseif (count($data) > 10000) {
            return false;
            // Too many, may cause out of memory error
        } else {
            foreach ($data as $thumb) {
                // Add multiple
                if (isset($thumb['id'])) {
                    // Looks valid
                    $thumb_cache_2[$thumb['id']] = $thumb;
                }
            }
        }
        return false;
    }
    if ($id == 'count') {
        if (is_array($thumb_cache_2)) {
            return count($thumb_cache_2);
        } else {
            return false;
        }
    }
    if (!wppa_is_int($id) || $id < '1') {
        wppa_dbg_msg('Invalid arg wppa_cache_thumb(' . $id . ')', 'red');
        $thumb = false;
        return false;
    }
    // In first level cache?
    if (isset($thumb['id']) && $thumb['id'] == $id) {
        wppa_dbg_q('G-T1');
        return $thumb;
    }
    // In  second level cache?
    if (!empty($thumb_cache_2)) {
        if (in_array($id, array_keys($thumb_cache_2))) {
            $thumb = $thumb_cache_2[$id];
            wppa_dbg_q('G-T2');
            return $thumb;
        }
    }
    // Not in cache, do query
    $thumb = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $id), ARRAY_A);
    wppa_dbg_q('Q-P');
    // Found one?
    if ($thumb) {
        // Store in second level cache
        $thumb_cache_2[$id] = $thumb;
        return $thumb;
    } else {
        wppa_dbg_msg('Photo ' . $id . ' does not exist', 'red');
        return false;
    }
}
function _wppa_sidebar_page_options()
{
    global $wpdb;
    $options_error = false;
    if (isset($_GET['walbum'])) {
        $walbum = wppa_walbum_sanitize($_GET['walbum']);
        wppa_update_option('wppa_widget_album', $walbum);
    }
    if (isset($_REQUEST['wppa-set-submit'])) {
        if (!wp_verify_nonce($_REQUEST['wppa-update-check'], 'wppa-update-check')) {
            echo 'Trying:' . $_REQUEST['wppa-update-check'];
        }
        if (isset($_POST['wppa-widgettitle'])) {
            wppa_update_option('wppa_widgettitle', $_POST['wppa-widgettitle']);
        }
        if (isset($_POST['wppa-potd-align'])) {
            wppa_update_option('wppa_potd_align', $_POST['wppa-potd-align']);
        }
        if (isset($_POST['wppa-widget-albums'])) {
            wppa_update_option('wppa_widget_album', wppa_walbum_sanitize($_POST['wppa-widget-albums']));
        }
        if (isset($_POST['wppa-widget-photo'])) {
            wppa_update_option('wppa_widget_photo', $_POST['wppa-widget-photo']);
        }
        if (isset($_POST['wppa-widget-method'])) {
            wppa_update_option('wppa_widget_method', $_POST['wppa-widget-method']);
        }
        if (isset($_REQUEST['wppa-widget-period'])) {
            wppa_update_option('wppa_widget_period', $_REQUEST['wppa-widget-period']);
        }
        if (isset($_POST['wppa-widget-subtitle'])) {
            wppa_update_option('wppa_widget_subtitle', $_POST['wppa-widget-subtitle']);
        }
        if (isset($_POST['wppa-widget-linkpage'])) {
            wppa_update_option('wppa_widget_linkpage', $_POST['wppa-widget-linkpage']);
        }
        if (isset($_POST['wppa-widget-linkurl'])) {
            wppa_update_option('wppa_widget_linkurl', $_POST['wppa-widget-linkurl']);
        }
        if (isset($_POST['wppa-widget-linktitle'])) {
            wppa_update_option('wppa_widget_linktitle', $_POST['wppa-widget-linktitle']);
        }
        if (isset($_POST['wppa-widget-linktype'])) {
            wppa_update_option('wppa_widget_linktype', $_POST['wppa-widget-linktype']);
        }
        if (isset($_POST['wppa-widget-status-filter'])) {
            wppa_update_option('wppa_widget_status_filter', $_POST['wppa-widget-status-filter']);
        }
        if (isset($_POST['wppa-potd-offset'])) {
            wppa_update_option('wppa_potd_offset', $_POST['wppa-potd-offset']);
        }
        if (isset($_POST['wppa-potd-widget-width'])) {
            if (wppa_check_numeric($_POST['wppa-potd-widget-width'], '100', __('Widget Photo Width.', 'wp-photo-album-plus'))) {
                wppa_update_option('wppa_potd_widget_width', $_POST['wppa-potd-widget-width']);
            } else {
                $options_error = true;
            }
        }
        if (!$options_error && isset($_POST['wppa-set-submit'])) {
            wppa_update_message(__('Changes Saved. Don\'t forget to activate the widget!', 'wp-photo-album-plus'));
        }
    }
    wppa_initialize_runtime('force');
    ?>
	
	<div class="wrap">
		<?php 
    $iconurl = WPPA_URL . '/images/settings32.png';
    ?>
		<div id="icon-album" class="icon32" style="background: transparent url(<?php 
    echo $iconurl;
    ?>
) no-repeat">
			<br />
		</div>
		<h2><?php 
    _e('Photo of the Day Widget Settings', 'wp-photo-album-plus');
    ?>
</h2>
		
		<?php 
    $action_url = wppa_dbg_url(get_admin_url() . 'admin.php?page=wppa_photo_of_the_day');
    ?>
		
		<form action="<?php 
    echo $action_url;
    ?>
" method="post">
			<?php 
    echo wp_nonce_field('wppa-update-check', 'wppa-update-check');
    ?>

			<table class="form-table wppa-table wppa-photo-table">
				<tbody>
					<tr valign="top">
						<th scope="row">
							<label ><?php 
    _e('Widget Title:', 'wp-photo-album-plus');
    ?>
</label>
						</th>
						<td>
							<input type="text" name="wppa-widgettitle" id="wppa-widgettitle" value="<?php 
    echo wppa_opt('widgettitle');
    ?>
" />
							<span class="description"><br/><?php 
    _e('Enter/modify the title for the widget. This is a default and can be overriden at widget activation.', 'wp-photo-album-plus');
    ?>
</span>
						</td>
					</tr>	
					
					<tr valign="top">
						<th scope="row">
							<label ><?php 
    _e('Widget Photo Width:', 'wp-photo-album-plus');
    ?>
</label>
						</th>
						<td>
							<input type="text" name="wppa-potd-widget-width" id="wppa-potd-widget-width" value="<?php 
    echo wppa_opt('potd_widget_width');
    ?>
" style="width: 50px;" />
							<?php 
    _e('pixels.', 'wp-photo-album-plus');
    echo ' ';
    _e('Horizontal alignment:', 'wp-photo-album-plus');
    ?>
							<select name="wppa-potd-align" id="wppa-potd-align">
								<?php 
    $ali = wppa_opt('potd_align');
    ?>
								<?php 
    $sel = 'selected="selected"';
    ?>
								<option value="none" <?php 
    if ($ali == 'none') {
        echo $sel;
    }
    ?>
><?php 
    _e('--- none ---', 'wp-photo-album-plus');
    ?>
</option>
								<option value="left" <?php 
    if ($ali == 'left') {
        echo $sel;
    }
    ?>
><?php 
    _e('left', 'wp-photo-album-plus');
    ?>
</option>
								<option value="center" <?php 
    if ($ali == 'center') {
        echo $sel;
    }
    ?>
><?php 
    _e('center', 'wp-photo-album-plus');
    ?>
</option>
								<option value="right" <?php 
    if ($ali == 'right') {
        echo $sel;
    }
    ?>
><?php 
    _e('right', 'wp-photo-album-plus');
    ?>
</option>
							</select>
							<span class="description"><br/><?php 
    _e('Enter the desired display width and alignment of the photo in the sidebar.', 'wp-photo-album-plus');
    ?>
</span>
						</td>
					</tr>

					<tr valign="top">
						<th scope="row">
							<label ><?php 
    _e('Use album(s):', 'wp-photo-album-plus');
    ?>
</label>
						</th>
						<td>
							<script type="text/javascript">
							/* <![CDATA[ */
							function wppaCheckWa() {
								document.getElementById('wppa-spin').style.visibility = 'visible';
								document.getElementById('wppa-upd').style.visibility = 'hidden';
								var album = document.getElementById('wppa-wa').value;
								if ( album != 'all' && album != 'sep' && album != 'all-sep' && album != 'topten' && album != 'clr' )
									album = document.getElementById('wppa-was').value + ',' + album;
								var url = "<?php 
    echo wppa_dbg_url(get_admin_url() . 'admin.php?page=wppa_photo_of_the_day');
    ?>
&walbum=" + album;
								document.location.href = url;
							}
							/* ]]> */
							</script>
							<?php 
    _e('Select:', 'wp-photo-album-plus');
    ?>
<select name="wppa-widget-album" id="wppa-wa" onchange="wppaCheckWa()" ><?php 
    echo wppa_walbum_select(wppa_opt('widget_album'));
    ?>
</select>
							<img id="wppa-spin" src="<?php 
    echo wppa_get_imgdir();
    ?>
wpspin.gif" style="visibility:hidden;"/>
							<?php 
    _e('Or Edit:', 'wp-photo-album-plus');
    ?>
<input type="text" name="wppa-widget-albums" id="wppa-was" value="<?php 
    echo wppa_opt('widget_album');
    ?>
" />
							<input class="button-primary" name="wppa-upd" id="wppa-upd" value="<?php 
    _e('Update thumbnails', 'wp-photo-album-plus');
    ?>
" onclick="wppaCheckWa()" />
							<span class="description"><br/>
								<?php 
    _e('Select or edit the album(s) you want to use the photos of for the widget.', 'wp-photo-album-plus');
    ?>
								<br />
								<?php 
    _e('If you want a <b>- special -</b> selection or get rid of it, you may need to use <b>- start over -</b> first.', 'wp-photo-album-plus');
    ?>
							</span>
						</td>
					</tr>
					<!-- Status filter -->
					<tr valign="top" >
						<th scope="row" >
							<label ><?php 
    _e('Status filter:', 'wp-photo-album-plus');
    ?>
</label>
						</th>
						<td>
							<?php 
    $sel = 'selected="selected"';
    ?>
							<?php 
    $filter = wppa_opt('widget_status_filter');
    ?>
							<select name="wppa-widget-status-filter" >
								<option value="" <?php 
    if ($filter == 'none') {
        echo $sel;
    }
    ?>
><?php 
    _e('- none -', 'wp-photo-album-plus');
    ?>
</option>
								<option value="publish" <?php 
    if ($filter == 'publish') {
        echo $sel;
    }
    ?>
 ><?php 
    _e('Publish', 'wp-photo-album-plus');
    ?>
</option>
								<option value="featured" <?php 
    if ($filter == 'featured') {
        echo $sel;
    }
    ?>
 ><?php 
    _e('Featured', 'wp-photo-album-plus');
    ?>
</option>
								<option value="gold" <?php 
    if ($filter == 'gold') {
        echo $sel;
    }
    ?>
 ><?php 
    _e('Gold', 'wp-photo-album-plus');
    ?>
</option>
								<option value="silver" <?php 
    if ($filter == 'silver') {
        echo $sel;
    }
    ?>
 ><?php 
    _e('Silver', 'wp-photo-album-plus');
    ?>
</option>
								<option value="bronze" <?php 
    if ($filter == 'bronze') {
        echo $sel;
    }
    ?>
 ><?php 
    _e('Bronze', 'wp-photo-album-plus');
    ?>
</option>
								<option value="anymedal" <?php 
    if ($filter == 'anymedal') {
        echo $sel;
    }
    ?>
 ><?php 
    _e('Any medal', 'wp-photo-album-plus');
    ?>
</option>
							</select>
						</td>
					</tr>
					<tr valign="top" >
						<th scope="row">
							<label ><?php 
    _e('Display method:', 'wp-photo-album-plus');
    ?>
</label>
						</th>
						<td>
							<?php 
    $sel = 'selected="selected"';
    ?>
							<?php 
    $method = wppa_opt('widget_method');
    ?>
							<select name="wppa-widget-method" id="wppa-wm" onchange="wppaCheckWidgetMethod()" >
								<option value="1" <?php 
    if ($method == '1') {
        echo $sel;
    }
    ?>
><?php 
    _e('Fixed photo', 'wp-photo-album-plus');
    ?>
</option> 
								<option value="2" <?php 
    if ($method == '2') {
        echo $sel;
    }
    ?>
><?php 
    _e('Random', 'wp-photo-album-plus');
    ?>
</option>
								<option value="3" <?php 
    if ($method == '3') {
        echo $sel;
    }
    ?>
><?php 
    _e('Last upload', 'wp-photo-album-plus');
    ?>
</option>
								<option value="4" <?php 
    if ($method == '4') {
        echo $sel;
    }
    ?>
><?php 
    _e('Change every', 'wp-photo-album-plus');
    ?>
</option>
							</select>
							<?php 
    $period = wppa_opt('widget_period');
    $text = esc_attr(__('The page will now be reloaded', 'wp-photo-album-plus'));
    $onchange = esc_attr('alert(\'' . $text . '\');wppaPotdChangePeriod()');
    ?>
							<script type="text/javascript" >
								function wppaPotdChangePeriod() {
									var url = '<?php 
    echo $action_url;
    ?>
';
									url += '&wppa-set-submit=1';
									url += '&wppa-update-check='+jQuery('#wppa-update-check').val();
									url += '&wppa-widget-period='+jQuery('#wppa-wp').val();
									document.location.href = url;
								}
							</script>
							<select name="wppa-widget-period" id="wppa-wp" onchange="<?php 
    echo $onchange;
    ?>
" >
								<option value="0" <?php 
    if ($period == '0') {
        echo $sel;
    }
    ?>
><?php 
    _e('pageview.', 'wp-photo-album-plus');
    ?>
</option>
								<option value="1" <?php 
    if ($period == '1') {
        echo $sel;
    }
    ?>
><?php 
    _e('hour.', 'wp-photo-album-plus');
    ?>
</option>
								<option value="24" <?php 
    if ($period == '24') {
        echo $sel;
    }
    ?>
><?php 
    _e('day.', 'wp-photo-album-plus');
    ?>
</option>
								<option value="168" <?php 
    if ($period == '168') {
        echo $sel;
    }
    ?>
><?php 
    _e('week.', 'wp-photo-album-plus');
    ?>
</option>
								<option value="736" <?php 
    if ($period == '736') {
        echo $sel;
    }
    ?>
><?php 
    _e('month.', 'wp-photo-album-plus');
    ?>
</option>
								<option value="day-of-week" <?php 
    if ($period == 'day-of-week') {
        echo $sel;
    }
    ?>
><?php 
    _e('day of week is order#', 'wp-photo-album-plus');
    ?>
</option>
								<option value="day-of-month" <?php 
    if ($period == 'day-of-month') {
        echo $sel;
    }
    ?>
><?php 
    _e('day of month is order#', 'wp-photo-album-plus');
    ?>
</option>
								<option value="day-of-year" <?php 
    if ($period == 'day-of-year') {
        echo $sel;
    }
    ?>
><?php 
    _e('day of year is order#', 'wp-photo-album-plus');
    ?>
</option>
							</select>
							<span class="description"><br/><?php 
    _e('Select how the widget should display.', 'wp-photo-album-plus');
    ?>
</span>
							<div class="wppa-order" >
							<?php 
    if (substr(wppa_opt('widget_period'), 0, 7) == 'day-of-') {
        switch (substr(wppa_opt('widget_period'), 7)) {
            case 'week':
                $n_days = '7';
                $date_key = 'w';
                break;
            case 'month':
                $n_days = '31';
                $date_key = 'd';
                break;
            case 'year':
                $n_days = '366';
                $date_key = 'z';
                break;
        }
        while (get_option('wppa_potd_offset', '0') > $n_days) {
            update_option('wppa_potd_offset', get_option('wppa_potd_offset') - $n_days);
        }
        echo sprintf(__('Current day# = %s, offset =', 'wp-photo-album-plus'), date_i18n($date_key)) . ' ';
        echo '<select name="wppa-potd-offset" >';
        $day = '0';
        while ($day < $n_days) {
            echo '<option value="' . $day . '" ' . (get_option('wppa_potd_offset', '0') == $day ? 'selected="selected"' : '') . ' >' . $day . '</option>';
            $day++;
        }
        echo '</select>';
        $photo_order = date_i18n($date_key) - get_option('wppa_potd_offset', '0');
        while ($photo_order < '1') {
            $photo_order += $n_days;
        }
        echo '. ' . sprintf(__('Todays photo order# = %s.', 'wp-photo-album-plus'), $photo_order);
        $photo = wppa_get_potd();
        if ($photo) {
            echo ' <img src="' . wppa_fix_poster_ext(wppa_get_thumb_url($photo['id']), $photo['id']) . '" style="width:100px;" />';
        } else {
            echo ' ' . __('Not found.', 'wp-photo-album-plus');
        }
    }
    ?>
							</div>
						</td>
					</tr>
<?php 
    $linktype = wppa_opt('widget_linktype');
    if ($linktype != 'custom') {
        ?>
						<tr>
							<th scope="row">
								<label ><?php 
        _e('Link to:', 'wp-photo-album-plus');
        ?>
</label>
							</th>
							<td>
								<?php 
        _e('Links are set on the <b>Photo Albums -> Settings</b> screen.', 'wp-photo-album-plus');
        ?>
							</td>
						</tr>
<?php 
    } else {
        ?>
						<tr class="wppa-wlu" >
							<th scope="row">
								<label ><?php 
        _e('Link to:', 'wp-photo-album-plus');
        ?>
</label>
							</th>
							<td>
								<?php 
        _e('Title:', 'wp-photo-album-plus');
        ?>
								<input type="text" name="wppa-widget-linktitle" id="wppa-widget-linktitle" value="<?php 
        echo wppa_opt('widget_linktitle');
        ?>
"style="width:20%" />
								<?php 
        _e('Url:', 'wp-photo-album-plus');
        ?>
								<input type="text"  name="wppa-widget-linkurl" id="wppa-widget-linkurl" value="<?php 
        echo wppa_opt('widget_linkurl');
        ?>
" style="width:50%" />
								<span class="description"><br/><?php 
        _e('Enter the title and the url. Do\'nt forget the HTTP://', 'wp-photo-album-plus');
        ?>
</span>
							</td>
						</tr>
<?php 
    }
    ?>
					<!--<script type="text/javascript">wppaCheckWidgetLink()</script>-->
					<tr>
						<th scope="row">
							<label ><?php 
    _e('Subtitle:', 'wp-photo-album-plus');
    ?>
</label>
						</th>
						<td>
							<?php 
    $subtit = wppa_opt('widget_subtitle');
    ?>
							<select name="wppa-widget-subtitle" id="wppa-st" >
								<option value="none" <?php 
    if ($subtit == 'none') {
        echo $sel;
    }
    ?>
><?php 
    _e('--- none ---', 'wp-photo-album-plus');
    ?>
</option>
								<option value="name" <?php 
    if ($subtit == 'name') {
        echo $sel;
    }
    ?>
><?php 
    _e('Photo Name', 'wp-photo-album-plus');
    ?>
</option>
								<option value="desc" <?php 
    if ($subtit == 'desc') {
        echo $sel;
    }
    ?>
><?php 
    _e('Description', 'wp-photo-album-plus');
    ?>
</option>
								<option value="owner" <?php 
    if ($subtit == 'owner') {
        echo $sel;
    }
    ?>
><?php 
    _e('Owner', 'wp-photo-album-plus');
    ?>
</option>
							</select>
							<span class="description"><br/><?php 
    _e('Select the content of the subtitle.', 'wp-photo-album-plus');
    ?>
</span>	
						</td>
					</tr>
				</tbody>
			</table>
			<p>
				<input type="submit" class="button-primary" name="wppa-set-submit" value="<?php 
    _e('Save Changes', 'wp-photo-album-plus');
    ?>
" />
			</p>
			<?php 
    $alb = wppa_opt('widget_album');
    $opt = wppa_is_int($alb) ? ' ' . wppa_get_photo_order($alb) . ' ' : '';
    $photos = wppa_get_widgetphotos($alb, $opt);
    if (empty($photos)) {
        echo '<p>' . __('No photos yet in this album.', 'wp-photo-album-plus') . '</p>';
    } else {
        $curid = wppa_opt('widget_photo');
        // Process photos
        foreach ($photos as $photo) {
            $id = $photo['id'];
            // Open container div
            echo '<div' . ' class="photoselect"' . ' style="' . 'width:180px;' . 'height:300px;' . '" >';
            // Open image container div
            echo '<div' . ' style="' . 'width:180px;' . 'height:135px;' . 'overflow:hidden;' . 'text-align:center;' . '" >';
            // The image if a video
            if (wppa_is_video($id)) {
                echo wppa_get_video_html(array('id' => $id, 'style' => 'width:180px;'));
            } else {
                echo '<img' . ' src=" ' . wppa_fix_poster_ext(wppa_get_thumb_url($id), $id) . '"' . ' style="' . 'max-width:180px;' . 'max-height:135px;' . 'margin:auto;' . '"' . ' alt="' . esc_attr(wppa_get_photo_name($photo['id'])) . '" />';
                // Audio ?
                if (wppa_has_audio($id)) {
                    echo wppa_get_audio_html(array('id' => $id, 'style' => 'width:180px;' . 'position:relative;' . 'bottom:' . (wppa_get_audio_control_height() + 4) . 'px;'));
                }
            }
            // Close image container div
            echo '</div>';
            ?>
						<div style="clear:both;width:100%;margin:3px 0;" >
							<div style="font-size:9px; line-height:10px;float:left;"><?php 
            echo '(#' . $photo['p_order'] . ')';
            ?>
</div>
							<input style="float:right;" type="radio" name="wppa-widget-photo" id="wppa-widget-photo<?php 
            echo $id;
            ?>
" value="<?php 
            echo $id;
            ?>
" <?php 
            if ($id == $curid) {
                echo 'checked="checked"';
            }
            ?>
/>
						</div>
						<div style="clear:both;overflow:auto;height:150px" >
							<div style="font-size:11px; overflow:hidden;"><?php 
            echo wppa_get_photo_name($photo['id']);
            ?>
</div>
							<div style="font-size:9px; line-height:10px;"><?php 
            echo wppa_get_photo_desc($photo['id']);
            ?>
</div>
						</div>
					</div>
					<?php 
        }
        echo '<div class="clear"></div>';
    }
    ?>
			<script type="text/javascript">wppaCheckWidgetMethod();</script>
			<br />
			<p>
				<input type="submit" class="button-primary" name="wppa-set-submit" value="<?php 
    _e('Save Changes', 'wp-photo-album-plus');
    ?>
" />
			</p>
		</form>
	</div>
<?php 
}
function wppa_is_wanted_empty($thumbs)
{
    if (!wppa_switch('show_empty_thumblist')) {
        return false;
    }
    // Feature not enabled
    if (is_array($thumbs) && count($thumbs) > wppa_get_mincount()) {
        return false;
    }
    // Album is not empty
    if (wppa_is_virtual()) {
        return false;
    }
    // wanted empty only on real albums
    if (!wppa_is_int(wppa('start_album'))) {
        return false;
    }
    // Only seingle albums, no enumerations
    if (wppa('albums_only')) {
        return false;
    }
    // Explicitly no thumbs
    //	if ( wppa_switch( 'thumbs_first' ) && wppa_get_curpage() != '1' ) return false;			// Only on page 1 if thumbs first
    wppa('current_album', wppa('start_album'));
    // Make sure upload knows the album
    return true;
}
function wppa_album_desc($key)
{
    global $wppa;
    global $wpdb;
    if ($wppa['is_upldr']) {
        return;
    }
    if ($wppa['is_comten']) {
        return;
    }
    if ($wppa['is_lasten']) {
        return;
    }
    if ($wppa['is_featen']) {
        return;
    }
    if ($wppa['supersearch']) {
        return;
    }
    if ($wppa['searchstring']) {
        return;
    }
    if ($wppa['is_tag']) {
        return;
    }
    if (strlen($wppa['start_album']) > '0' && !wppa_is_int($wppa['start_album'])) {
        return;
    }
    // Album enumeration
    $result = '';
    if (wppa_opt('wppa_albdesc_on_thumbarea') == $key && $wppa['current_album']) {
        $desc = wppa_get_album_desc($wppa['current_album']);
        if ($key == 'top') {
            $result .= '<div id="wppa-albdesc-' . $wppa['mocc'] . '" class="wppa-box-text wppa-black" style="padding-right:6px;' . __wcs('wppa-box-text') . __wcs('wppa-black') . '" >' . $desc . '</div><div style="clear:both" ></div>';
        }
        if ($key == 'bottom') {
            $result .= '<div id="wppa-albdesc-b-' . $wppa['mocc'] . '" class="wppa-box-text wppa-black" style="clear:both; padding-right:6px;' . __wcs('wppa-box-text') . __wcs('wppa-black') . '" >' . $desc . '</div>';
        }
    }
    $wppa['out'] .= $result;
}