function wppa_make_the_photo_files($file, $id, $ext)
{
    global $wpdb;
    $thumb = wppa_cache_thumb($id);
    $src_size = @getimagesize($file, $info);
    // If the given file is not an image file, log error and exit
    if (!$src_size) {
        if (is_admin()) {
            wppa_error_message(sprintf(__('ERROR: File %s is not a valid picture file.', 'wp-photo-album-plus'), $file));
        } else {
            wppa_alert(sprintf(__('ERROR: File %s is not a valid picture file.', 'wp-photo-album-plus'), $file));
        }
        return false;
    }
    // Find output path photo file
    $newimage = wppa_get_photo_path($id);
    if ($ext) {
        $newimage = wppa_strip_ext($newimage) . '.' . strtolower($ext);
    }
    // If Resize on upload is checked
    if (wppa_switch('resize_on_upload')) {
        // Picture sizes
        $src_width = $src_size[0];
        // Temp convert to logical width if stereo
        if ($thumb['stereo']) {
            $src_width /= 2;
        }
        $src_height = $src_size[1];
        // Max sizes
        if (wppa_opt('resize_to') == '0') {
            // from fullsize
            $max_width = wppa_opt('fullsize');
            $max_height = wppa_opt('maxheight');
        } else {
            // from selection
            $screen = explode('x', wppa_opt('resize_to'));
            $max_width = $screen[0];
            $max_height = $screen[1];
        }
        // If orientation needs +/- 90 deg rotation, swap max x and max y
        $ori = wppa_get_exif_orientation($file);
        if ($ori >= 5 && $ori <= 8) {
            $t = $max_width;
            $max_width = $max_height;
            $max_height = $t;
        }
        // Is source more landscape or more portrait than max window
        if ($src_width / $src_height > $max_width / $max_height) {
            // focus on width
            $focus = 'W';
            $need_downsize = $src_width > $max_width;
        } else {
            // focus on height
            $focus = 'H';
            $need_downsize = $src_height > $max_height;
        }
        // Convert back to physical size
        if ($thumb['stereo']) {
            $src_width *= 2;
        }
        // Downsize required ?
        if ($need_downsize) {
            // Find mime type
            $mime = $src_size[2];
            // Create the source image
            switch ($mime) {
                // mime type
                case 1:
                    // gif
                    $temp = @imagecreatefromgif($file);
                    if ($temp) {
                        $src = imagecreatetruecolor($src_width, $src_height);
                        imagecopy($src, $temp, 0, 0, 0, 0, $src_width, $src_height);
                        imagedestroy($temp);
                    } else {
                        $src = false;
                    }
                    break;
                case 2:
                    // jpeg
                    if (!function_exists('wppa_imagecreatefromjpeg')) {
                        wppa_log('Error', 'Function wppa_imagecreatefromjpeg does not exist.');
                    }
                    $src = @wppa_imagecreatefromjpeg($file);
                    break;
                case 3:
                    // png
                    $src = @imagecreatefrompng($file);
                    break;
            }
            if (!$src) {
                wppa_log('Error', 'Image file ' . $file . ' is corrupt while downsizing photo');
                return false;
            }
            // Create the ( empty ) destination image
            if ($focus == 'W') {
                if ($thumb['stereo']) {
                    $max_width *= 2;
                }
                $dst_width = $max_width;
                $dst_height = round($max_width * $src_height / $src_width);
            } else {
                $dst_height = $max_height;
                $dst_width = round($max_height * $src_width / $src_height);
            }
            $dst = imagecreatetruecolor($dst_width, $dst_height);
            // If Png, save transparancy
            if ($mime == 3) {
                imagealphablending($dst, false);
                imagesavealpha($dst, true);
            }
            // Do the copy
            imagecopyresampled($dst, $src, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height);
            // Remove source image
            imagedestroy($src);
            // Save the photo
            switch ($mime) {
                // mime type
                case 1:
                    imagegif($dst, $newimage);
                    break;
                case 2:
                    imagejpeg($dst, $newimage, wppa_opt('jpeg_quality'));
                    break;
                case 3:
                    imagepng($dst, $newimage, 6);
                    break;
            }
            // Remove destination image
            imagedestroy($dst);
        } else {
            // No downsize needed, picture is small enough
            copy($file, $newimage);
        }
    } else {
        copy($file, $newimage);
    }
    // File successfully created ?
    if (is_file($newimage)) {
        // Make sure file is accessable
        wppa_chmod($newimage);
        // Optimize file
        wppa_optimize_image_file($newimage);
    } else {
        if (is_admin()) {
            wppa_error_message(__('ERROR: Resized or copied image could not be created.', 'wp-photo-album-plus'));
        } else {
            wppa_alert(__('ERROR: Resized or copied image could not be created.', 'wp-photo-album-plus'));
        }
        return false;
    }
    // Process the iptc data
    wppa_import_iptc($id, $info);
    // Process the exif data
    wppa_import_exif($id, $file);
    // GPS
    wppa_get_coordinates($file, $id);
    // Set ( update ) exif date-time if available
    $exdt = wppa_get_exif_datetime($file);
    if ($exdt) {
        wppa_update_photo(array('id' => $id, 'exifdtm' => $exdt));
    }
    // Check orientation
    wppa_orientate_image($id, wppa_get_exif_orientation($file));
    // Compute and save sizes
    wppa_get_photox($id, 'force');
    // Show progression
    if (is_admin() && !wppa('ajax')) {
        echo '.';
    }
    // Update CDN
    $cdn = wppa_cdn('admin');
    if ($cdn) {
        switch ($cdn) {
            case 'cloudinary':
                wppa_upload_to_cloudinary($id);
                break;
            default:
                wppa_dbg_msg('Missing upload instructions for ' . $cdn, 'red', 'force');
        }
    }
    // Create stereo images
    wppa_create_stereo_images($id);
    // Create thumbnail...
    wppa_create_thumbnail($id);
    // Clear (super)cache
    wppa_clear_cache();
    return true;
}
function wppa_setup($force = false)
{
    global $silent;
    global $wpdb;
    global $wppa_revno;
    global $current_user;
    global $wppa_error;
    $old_rev = get_option('wppa_revision', '100');
    if ($old_rev == $wppa_revno && !$force) {
        return;
    }
    // Nothing to do here
    wppa_clear_cache(true);
    // Clear cache
    $wppa_error = false;
    // Init no error
    $create_albums = "CREATE TABLE " . WPPA_ALBUMS . " (\r\n\t\t\t\t\tid bigint(20) NOT NULL,\r\n\t\t\t\t\tname text NOT NULL,\r\n\t\t\t\t\tdescription text NOT NULL,\r\n\t\t\t\t\ta_order smallint(5) NOT NULL,\r\n\t\t\t\t\tmain_photo bigint(20) NOT NULL,\r\n\t\t\t\t\ta_parent bigint(20) NOT NULL,\r\n\t\t\t\t\tp_order_by smallint(5) NOT NULL,\r\n\t\t\t\t\tcover_linktype tinytext NOT NULL,\r\n\t\t\t\t\tcover_linkpage bigint(20) NOT NULL,\r\n\t\t\t\t\towner text NOT NULL,\r\n\t\t\t\t\ttimestamp tinytext NOT NULL,\r\n\t\t\t\t\tmodified tinytext NOT NULL,\r\n\t\t\t\t\tupload_limit tinytext NOT NULL,\r\n\t\t\t\t\talt_thumbsize tinytext NOT NULL,\r\n\t\t\t\t\tdefault_tags tinytext NOT NULL,\r\n\t\t\t\t\tcover_type tinytext NOT NULL,\r\n\t\t\t\t\tsuba_order_by tinytext NOT NULL,\r\n\t\t\t\t\tviews bigint(20) NOT NULL default '0',\r\n\t\t\t\t\tcats tinytext NOT NULL,\r\n\t\t\t\t\tscheduledtm tinytext NOT NULL,\r\n\t\t\t\t\tPRIMARY KEY  (id)\r\n\t\t\t\t\t) DEFAULT CHARACTER SET utf8;";
    $create_photos = "CREATE TABLE " . WPPA_PHOTOS . " (\r\n\t\t\t\t\tid bigint(20) NOT NULL,\r\n\t\t\t\t\talbum bigint(20) NOT NULL,\r\n\t\t\t\t\text tinytext NOT NULL,\r\n\t\t\t\t\tname text NOT NULL,\r\n\t\t\t\t\tdescription longtext NOT NULL,\r\n\t\t\t\t\tp_order smallint(5) NOT NULL,\r\n\t\t\t\t\tmean_rating tinytext NOT NULL,\r\n\t\t\t\t\tlinkurl text NOT NULL,\r\n\t\t\t\t\tlinktitle text NOT NULL,\r\n\t\t\t\t\tlinktarget tinytext NOT NULL,\r\n\t\t\t\t\towner text NOT NULL,\r\n\t\t\t\t\ttimestamp tinytext NOT NULL,\r\n\t\t\t\t\tstatus tinytext NOT NULL,\r\n\t\t\t\t\trating_count bigint(20) NOT NULL default '0',\r\n\t\t\t\t\ttags tinytext NOT NULL,\r\n\t\t\t\t\talt tinytext NOT NULL,\r\n\t\t\t\t\tfilename tinytext NOT NULL,\r\n\t\t\t\t\tmodified tinytext NOT NULL,\r\n\t\t\t\t\tlocation tinytext NOT NULL,\r\n\t\t\t\t\tviews bigint(20) NOT NULL default '0',\r\n\t\t\t\t\tpage_id bigint(20) NOT NULL default '0',\r\n\t\t\t\t\texifdtm tinytext NOT NULL,\r\n\t\t\t\t\tvideox smallint(5) NOT NULL default '0',\r\n\t\t\t\t\tvideoy smallint(5) NOT NULL default '0',\r\n\t\t\t\t\tthumbx smallint(5) NOT NULL default '0',\r\n\t\t\t\t\tthumby smallint(5) NOT NULL default '0',\r\n\t\t\t\t\tphotox smallint(5) NOT NULL default '0',\r\n\t\t\t\t\tphotoy smallint(5) NOT NULL default '0',\r\n\t\t\t\t\tscheduledtm tinytext NOT NULL,\r\n\t\t\t\t\tcustom longtext NOT NULL,\r\n\t\t\t\t\tstereo smallint NOT NULL default '0',\r\n\t\t\t\t\tPRIMARY KEY  (id),\r\n\t\t\t\t\tKEY albumkey (album)\r\n\t\t\t\t\t) DEFAULT CHARACTER SET utf8;";
    $create_rating = "CREATE TABLE " . WPPA_RATING . " (\r\n\t\t\t\t\tid bigint(20) NOT NULL,\r\n\t\t\t\t\ttimestamp tinytext NOT NULL,\r\n\t\t\t\t\tphoto bigint(20) NOT NULL,\r\n\t\t\t\t\tvalue smallint(5) NOT NULL,\r\n\t\t\t\t\tuser text NOT NULL,\r\n\t\t\t\t\tstatus tinytext NOT NULL,\r\n\t\t\t\t\tPRIMARY KEY  (id),\r\n\t\t\t\t\tKEY photokey (photo)\r\n\t\t\t\t\t) DEFAULT CHARACTER SET utf8;";
    $create_comments = "CREATE TABLE " . WPPA_COMMENTS . " (\r\n\t\t\t\t\tid bigint(20) NOT NULL,\r\n\t\t\t\t\ttimestamp tinytext NOT NULL,\r\n\t\t\t\t\tphoto bigint(20) NOT NULL,\r\n\t\t\t\t\tuser text NOT NULL,\r\n\t\t\t\t\tip tinytext NOT NULL,\r\n\t\t\t\t\temail text NOT NULL,\r\n\t\t\t\t\tcomment text NOT NULL,\r\n\t\t\t\t\tstatus tinytext NOT NULL,\r\n\t\t\t\t\tPRIMARY KEY  (id),\r\n\t\t\t\t\tKEY photokey (photo)\r\n\t\t\t\t\t) DEFAULT CHARACTER SET utf8;";
    $create_iptc = "CREATE TABLE " . WPPA_IPTC . " (\r\n\t\t\t\t\tid bigint(20) NOT NULL,\r\n\t\t\t\t\tphoto bigint(20) NOT NULL,\r\n\t\t\t\t\ttag tinytext NOT NULL,\r\n\t\t\t\t\tdescription text NOT NULL,\r\n\t\t\t\t\tstatus tinytext NOT NULL,\r\n\t\t\t\t\tPRIMARY KEY  (id),\r\n\t\t\t\t\tKEY photokey (photo)\r\n\t\t\t\t\t) DEFAULT CHARACTER SET utf8;";
    $create_exif = "CREATE TABLE " . WPPA_EXIF . " (\r\n\t\t\t\t\tid bigint(20) NOT NULL,\r\n\t\t\t\t\tphoto bigint(20) NOT NULL,\r\n\t\t\t\t\ttag tinytext NOT NULL,\r\n\t\t\t\t\tdescription text NOT NULL,\r\n\t\t\t\t\tstatus tinytext NOT NULL,\r\n\t\t\t\t\tPRIMARY KEY  (id),\r\n\t\t\t\t\tKEY photokey (photo)\r\n\t\t\t\t\t) DEFAULT CHARACTER SET utf8;";
    $create_index = "CREATE TABLE " . WPPA_INDEX . " (\r\n\t\t\t\t\tid bigint(20) NOT NULL,\r\n\t\t\t\t\tslug tinytext NOT NULL,\r\n\t\t\t\t\talbums text NOT NULL,\r\n\t\t\t\t\tphotos text NOT NULL,\r\n\t\t\t\t\tPRIMARY KEY  (id),\r\n\t\t\t\t\tKEY slugkey (slug(20))\r\n\t\t\t\t\t) DEFAULT CHARACTER SET utf8;";
    $create_session = "CREATE TABLE " . WPPA_SESSION . " (\r\n\t\t\t\t\tid bigint(20) NOT NULL,\r\n\t\t\t\t\tsession tinytext NOT NULL,\r\n\t\t\t\t\ttimestamp tinytext NOT NULL,\r\n\t\t\t\t\tuser tinytext NOT NULL,\r\n\t\t\t\t\tip tinytext NOT NULL,\r\n\t\t\t\t\tstatus tinytext NOT NULL,\r\n\t\t\t\t\tdata text NOT NULL,\r\n\t\t\t\t\tcount bigint(20) NOT NULL default '0',\r\n\t\t\t\t\tPRIMARY KEY  (id),\r\n\t\t\t\t\tKEY sessionkey (session(20))\r\n\t\t\t\t\t) DEFAULT CHARACTER SET utf8;";
    require_once WPPA_ABSPATH . 'wp-admin/includes/upgrade.php';
    // Create or update db tables
    $tn = array(WPPA_ALBUMS, WPPA_PHOTOS, WPPA_RATING, WPPA_COMMENTS, WPPA_IPTC, WPPA_EXIF, WPPA_INDEX, WPPA_SESSION);
    $tc = array($create_albums, $create_photos, $create_rating, $create_comments, $create_iptc, $create_exif, $create_index, $create_session);
    $idx = 0;
    while ($idx < 8) {
        $a0 = wppa_table_exists($tn[$idx]);
        dbDelta($tc[$idx]);
        $a1 = wppa_table_exists($tn[$idx]);
        if (WPPA_DEBUG) {
            if (!$a0) {
                if ($a1) {
                    wppa_ok_message('Database table ' . $tn[$idx] . ' created.');
                } else {
                    wppa_error_message('Could not create database table ' . $tn[$idx]);
                }
            } else {
                wppa_ok_message('Database table ' . $tn[$idx] . ' updated.');
            }
        }
        $idx++;
    }
    // Although we do not rely om auto increment, it may help avoiding concurrency conflicts
    $wpdb->query("ALTER TABLE `" . WPPA_SESSION . "` MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT");
    // Clear Session
    $wpdb->query("TRUNCATE TABLE `" . WPPA_SESSION . "`");
    wppa_session_start();
    // Convert any changed and remove obsolete setting options
    if ($old_rev > '100') {
        // On update only
        if ($old_rev <= '402') {
            wppa_convert_setting('wppa_coverphoto_left', 'no', 'wppa_coverphoto_pos', 'right');
            wppa_convert_setting('wppa_coverphoto_left', 'yes', 'wppa_coverphoto_pos', 'left');
        }
        if ($old_rev <= '440') {
            wppa_convert_setting('wppa_fadein_after_fadeout', 'yes', 'wppa_animation_type', 'fadeafter');
            wppa_convert_setting('wppa_fadein_after_fadeout', 'no', 'wppa_animation_type', 'fadeover');
        }
        if ($old_rev <= '450') {
            wppa_remove_setting('wppa_fadein_after_fadeout');
            wppa_copy_setting('wppa_show_bbb', 'wppa_show_bbb_widget');
            wppa_convert_setting('wppa_comment_use_gravatar', 'yes', 'wppa_comment_gravatar', 'mm');
            wppa_convert_setting('wppa_comment_use_gravatar', 'no', 'wppa_comment_gravatar', 'none');
            wppa_remove_setting('wppa_comment_use_gravatar');
            wppa_revalue_setting('wppa_start_slide', 'yes', 'run');
            wppa_revalue_setting('wppa_start_slide', 'no', 'still');
            wppa_rename_setting('wppa_accesslevel', 'wppa_accesslevel_admin');
            wppa_remove_setting('wppa_charset');
            wppa_remove_setting('wppa_chmod');
            wppa_remove_setting('wppa_coverphoto_left');
            wppa_remove_setting('wppa_2col_treshold');
            wppa_remove_setting('wppa_album_admin_autosave');
            wppa_remove_setting('wppa_doublethevotes');
            wppa_remove_setting('wppa_halvethevotes');
            wppa_remove_setting('wppa_lightbox_overlaycolor');
            wppa_remove_setting('wppa_lightbox_overlayopacity');
            wppa_remove_setting('wppa_multisite');
            wppa_remove_setting('wppa_set_access_by');
            wppa_remove_setting('wppa_accesslevel_admin');
            wppa_remove_setting('wppa_accesslevel_upload');
            wppa_remove_setting('wppa_accesslevel_sidebar');
        }
        if ($old_rev <= '452') {
            wppa_copy_setting('wppa_fontfamily_numbar', 'wppa_fontfamily_numbar_active');
            wppa_copy_setting('wppa_fontsize_numbar', 'wppa_fontsize_numbar_active');
            wppa_copy_setting('wppa_fontcolor_numbar', 'wppa_fontcolor_numbar_active');
            wppa_copy_setting('wppa_fontweight_numbar', 'wppa_fontweight_numbar_active');
        }
        if ($old_rev <= '455') {
            // rating_count added to WPPA_PHOTOS
            $phs = $wpdb->get_results('SELECT `id` FROM `' . WPPA_PHOTOS . '`', ARRAY_A);
            if ($phs) {
                foreach ($phs as $ph) {
                    $cnt = $wpdb->get_var($wpdb->prepare('SELECT COUNT(*) FROM `' . WPPA_RATING . '` WHERE `photo` = %s', $ph['id']));
                    $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `rating_count` = %s WHERE `id` = %s', $cnt, $ph['id']));
                }
            }
        }
        if ($old_rev < '470') {
            // single photo re-impl. has its own links, clone from slideshow
            wppa_copy_setting('wppa_slideshow_linktype', 'wppa_sphoto_linktype');
            wppa_copy_setting('wppa_slideshow_blank', 'wppa_sphoto_blank');
            wppa_copy_setting('wppa_slideshow_overrule', 'wppa_sphoto_overrule');
        }
        if ($old_rev <= '474') {
            // Convert album and photo descriptions to contain html in stead of htmlspecialchars. Allowing html is assumed, if not permitted, wppa_html will convert to specialcars.
            // html
            $at = 0;
            $ah = 0;
            $pt = 0;
            $ph = 0;
            $albs = $wpdb->get_results('SELECT `id`, `description` FROM ' . WPPA_ALBUMS, ARRAY_A);
            if ($albs) {
                foreach ($albs as $alb) {
                    $at++;
                    if (html_entity_decode($alb['description']) != $alb['description']) {
                        $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_ALBUMS . '` SET `description` = %s WHERE `id` = %s', html_entity_decode($alb['description']), $alb['id']));
                        $ah++;
                    }
                }
            }
            $phots = $wpdb->get_results('SELECT `id`, `description` FROM ' . WPPA_PHOTOS, ARRAY_A);
            if ($phots) {
                foreach ($phots as $phot) {
                    $pt++;
                    if (html_entity_decode($phot['description']) != $phot['description']) {
                        $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `description` = %s WHERE `id` = %s', html_entity_decode($phot['description']), $phot['id']));
                        $ph++;
                    }
                }
            }
            if (WPPA_DEBUG) {
                if ($ah || $ph) {
                    wppa_ok_message($ah . ' out of ' . $at . ' albums and ' . $ph . ' out of ' . $pt . ' photos html converted');
                }
            }
        }
        if ($old_rev <= '482') {
            // Share box added
            $so = get_option('wppa_slide_order', '0,1,2,3,4,5,6,7,8,9');
            if (strlen($so) == '19') {
                wppa_update_option('wppa_slide_order', $so . ',10');
            }
            $so = get_option('wppa_slide_order_split', '0,1,2,3,4,5,6,7,8,9,10');
            if (strlen($so) == '22') {
                wppa_update_option('wppa_slide_order_split', $so . ',11');
            }
            wppa_remove_setting('wppa_sharetype');
            wppa_copy_setting('wppa_bgcolor_namedesc', 'wppa_bgcolor_share');
            wppa_copy_setting('wppa_bcolor_namedesc', 'wppa_bcolor_share');
        }
        if ($old_rev <= '4811') {
            wppa_rename_setting('wppa_comment_count', 'wppa_comten_count');
            wppa_rename_setting('wppa_comment_size', 'wppa_comten_size');
        }
        if ($old_rev <= '4910') {
            wppa_copy_setting('wppa_show_bread', 'wppa_show_bread_posts');
            wppa_copy_setting('wppa_show_bread', 'wppa_show_bread_pages');
            wppa_remove_setting('wppa_show_bread');
        }
        if ($old_rev <= '5000') {
            wppa_remove_setting('wppa_autoclean');
        }
        if ($old_rev <= '5010') {
            wppa_copy_setting('wppa_apply_newphoto_desc', 'wppa_apply_newphoto_desc_user');
        }
        if ($old_rev <= '5107') {
            delete_option('wppa_taglist');
            // Forces recreation
        }
        if ($old_rev <= '5205') {
            if (get_option('wppa_list_albums_desc', 'nil') == 'yes') {
                $value = get_option('wppa_list_albums_by', '0') * '-1';
                wppa_update_option('wppa_list_albums_by', $value);
                wppa_remove_setting('wppa_list_albums_desc');
            }
            if (get_option('wppa_list_photos_desc', 'nil') == 'yes') {
                $value = get_option('wppa_list_photos_by', '0') * '-1';
                wppa_update_option('wppa_list_photos_by', $value);
                wppa_remove_setting('wppa_list_photos_desc');
            }
        }
        if ($old_rev <= '5207') {
            if (get_option('wppa_strip_file_ext', 'nil') == 'yes') {
                wppa_update_option('wppa_newphoto_name_method', 'noext');
                delete_option('wppa_strip_file_ext');
            }
        }
        if ($old_rev <= '5307') {
            $wpdb->query("TRUNCATE TABLE `" . WPPA_SESSION . "`");
        }
        if ($old_rev <= '5308') {
            wppa_flush_treecounts();
        }
        if ($old_rev <= '5410') {
            wppa_copy_setting('wppa_widget_width', 'wppa_potd_widget_width');
            wppa_flush_upldr_cache('all');
            // New format
        }
        if ($old_rev == '5421' || $old_rev == '5420.99') {
            // The rev where the bug was
            if ($wppa_revno >= '5422') {
                // The rev where we fix it
                if (get_option('wppa_rating_on', 'no') == 'yes') {
                    // Only if rating used
                    if (get_option('wppa_ajax_non_admin', 'yes') == 'no') {
                        // Only if backend ajax
                        update_option('wppa_rerate_status', __('Required', 'wp-photo-album-plus'));
                        // Make sure they see the message
                    }
                }
            }
        }
        if ($old_rev <= '5500') {
            wppa_create_pl_htaccess(get_option('wppa_pl_dirname', 'wppa-pl'));
            // Remake due to fix in wppa_sanitize_file_name()
        }
        if ($old_rev <= '6103') {
            wppa_copy_setting('wppa_owner_only', 'wppa_upload_owner_only');
        }
        if ($old_rev <= '6305') {
            if (get_option('wppa_comment_captcha') == 'no') {
                update_option('wppa_comment_captcha', 'none');
            }
            if (get_option('wppa_comment_captcha') == 'yes') {
                update_option('wppa_comment_captcha', 'all');
            }
        }
        if ($old_rev <= '6310') {
            $wpdb->query("UPDATE `" . WPPA_PHOTOS . "` SET `timestamp` = '0' WHERE `timestamp` = ''");
            $wpdb->query("UPDATE `" . WPPA_PHOTOS . "` SET `modified` = `timestamp` WHERE `modified` = '' OR `modified` = '0'");
        }
        if ($old_rev <= '6312') {
            $wpdb->query("UPDATE `" . WPPA_ALBUMS . "` SET `timestamp` = '0' WHERE `timestamp` = ''");
            $wpdb->query("UPDATE `" . WPPA_ALBUMS . "` SET `modified` = `timestamp` WHERE `modified` = '' OR `modified` = '0'");
            wppa_copy_setting('wppa_wppa_set_shortcodes', 'wppa_set_shortcodes');
            wppa_remove_setting('wppa_wppa_set_shortcodes');
            wppa_copy_setting('wppa_max_album_newtime', 'wppa_max_album_modtime');
            wppa_copy_setting('wppa_max_photo_newtime', 'wppa_max_photo_modtime');
        }
        if ($old_rev <= '6316') {
            wppa_remove_setting('wppa_start_symbol_url');
            wppa_remove_setting('wppa_pause_symbol_url');
            wppa_remove_setting('wppa_stop_symbol_url');
        }
    }
    // Set Defaults
    wppa_set_defaults();
    // Check required directories
    if (!wppa_check_dirs()) {
        $wppa_error = true;
    }
    // Create .htaccess file in .../wp-content/uploads/wppa
    wppa_create_wppa_htaccess();
    // Copy factory supplied watermarks
    $frompath = WPPA_PATH . '/watermarks';
    $watermarks = glob($frompath . '/*.png');
    if (is_array($watermarks)) {
        foreach ($watermarks as $fromfile) {
            $tofile = WPPA_UPLOAD_PATH . '/watermarks/' . basename($fromfile);
            @copy($fromfile, $tofile);
        }
    }
    // Copy factory supplied watermark fonts
    $frompath = WPPA_PATH . '/fonts';
    $fonts = glob($frompath . '/*');
    if (is_array($fonts)) {
        foreach ($fonts as $fromfile) {
            if (is_file($fromfile)) {
                $tofile = WPPA_UPLOAD_PATH . '/fonts/' . basename($fromfile);
                @copy($fromfile, $tofile);
            }
        }
    }
    // Copy audiostub.jpg, the default audiostub
    $fromfile = WPPA_PATH . '/images/audiostub.jpg';
    $tofile = WPPA_UPLOAD_PATH . '/audiostub';
    if (!is_file($tofile . '.jpg') && !is_file($tofile . '.gif') && !is_file($tofile . '.png')) {
        @copy($fromfile, $tofile . '.jpg');
        wppa_update_option('wppa_audiostub', 'audiostub.jpg');
    }
    // Check if this update comes with a new wppa-theme.php and/or a new wppa-style.css
    // If so, produce message
    $key = '0';
    if ($old_rev < '5400') {
        // theme changed since...
        $usertheme = get_theme_root() . '/' . get_option('template') . '/wppa-theme.php';
        if (is_file($usertheme)) {
            $key += '2';
        }
    }
    if ($old_rev < '5211') {
        // css changed since...
        $userstyle = get_theme_root() . '/' . get_option('stylesheet') . '/wppa-style.css';
        if (is_file($userstyle)) {
            $key += '1';
        } else {
            $userstyle = get_theme_root() . '/' . get_option('template') . '/wppa-style.css';
            if (is_file($userstyle)) {
                $key += '1';
            }
        }
    }
    if ($key) {
        $msg = '<center>' . __('IMPORTANT UPGRADE NOTICE', 'wp-photo-album-plus') . '</center><br/>';
        if ($key == '1' || $key == '3') {
            $msg .= '<br/>' . __('Please CHECK your customized WPPA-STYLE.CSS file against the newly supplied one. You may wish to add or modify some attributes. Be aware of the fact that most settings can now be set in the admin settings page.', 'wp-photo-album-plus');
        }
        if ($key == '2' || $key == '3') {
            $msg .= '<br/>' . __('Please REPLACE your customized WPPA-THEME.PHP file by the newly supplied one, or just remove it from your theme directory. You may modify it later if you wish. Your current customized version is NOT compatible with this version of the plugin software.', 'wp-photo-album-plus');
        }
        wppa_ok_message($msg);
    }
    // Check if db is ok
    if (!wppa_check_database()) {
        $wppa_error = true;
    }
    // Remove dynamic files
    $files = glob(WPPA_PATH . '/wppa-init.*.js');
    if ($files) {
        foreach ($files as $file) {
            @unlink($file);
            // Will be auto re-created
        }
    }
    @unlink(WPPA_PATH . '/wppa-dynamic.css');
    // Will be auto re-created
    // Done!
    if (!$wppa_error) {
        $old_rev = round($old_rev);
        // might be 0.01 off
        if ($old_rev < $wppa_revno) {
            // was a real upgrade,
            wppa_update_option('wppa_prevrev', $old_rev);
            // Remember prev rev. For support purposes. They say they stay up to rev, but they come from stoneage...
        }
        wppa_update_option('wppa_revision', $wppa_revno);
        if (WPPA_DEBUG) {
            if (is_multisite()) {
                wppa_ok_message(sprintf(__('WPPA+ successfully updated in multi site mode to db version %s.', 'wp-photo-album-plus'), $wppa_revno));
            } else {
                wppa_ok_message(sprintf(__('WPPA+ successfully updated in single site mode to db version %s.', 'wp-photo-album-plus'), $wppa_revno));
            }
        }
    } else {
        if (WPPA_DEBUG) {
            wppa_error_message(__('An error occurred during update', 'wp-photo-album-plus'));
        }
    }
}
function _wppa_comment_admin()
{
    global $wpdb;
    $continue = true;
    // Check input
    wppa_vfy_arg('tab', true);
    wppa_vfy_arg('edit_id');
    wppa_vfy_arg('wppa-page');
    wppa_vfy_arg('commentid');
    wppa_vfy_arg('delete_id');
    if (isset($_GET['tab'])) {
        if ($_GET['tab'] == 'edit') {
            $id = $_GET['edit_id'];
            $comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM " . WPPA_COMMENTS . " WHERE id = %s LIMIT 1", $id), ARRAY_A);
            if ($comment) {
                ?>
			<div class="wrap">
				<?php 
                $iconurl = WPPA_URL . '/img/comment.png';
                ?>
				<div id="icon-album" class="icon32" style="background: transparent url(<?php 
                echo $iconurl;
                ?>
) no-repeat">
					<br />
				</div>
				<h2><?php 
                _e('Photo Albums -> Edit Comment', 'wp-photo-album-plus');
                ?>
</h2>
				<?php 
                $action = wppa_dbg_url(get_admin_url() . 'admin.php?page=wppa_manage_comments');
                if (isset($_GET['wppa-page'])) {
                    $action .= '&compage=' . strval(intval($_GET['wppa-page']));
                }
                if (isset($_GET['commentid'])) {
                    $action .= '&commentid=' . strval(intval($_GET['commentid']));
                }
                ?>
				<form action="<?php 
                echo $action;
                ?>
" method="post">

					<?php 
                wp_nonce_field('$wppa_nonce', WPPA_NONCE);
                ?>
					<input type="hidden" name="edit_comment" value="<?php 
                echo $comment['id'];
                ?>
" />
					<table class="form-table albumtable">
						<tbody>
							<tr style="vertical-align:top" >
								<th>
									<?php 
                $photo = $wpdb->get_row($wpdb->prepare("SELECT * FROM " . WPPA_PHOTOS . " WHERE id =  %s", $comment['photo']), "ARRAY_A");
                ?>
									<?php 
                $url = wppa_fix_poster_ext(wppa_get_thumb_url($comment['photo']), $comment['photo']);
                ?>
									<img src="<?php 
                echo $url;
                ?>
" />
								</th>
								<td>
									<?php 
                echo __($photo['name']) . '<br/><br/>' . __(stripslashes($photo['description']));
                ?>
								</td>
							</tr>
							<tr>
								<th scope="row"><label ><?php 
                _e('Photo:', 'wp-photo-album-plus');
                ?>
</label></th>
								<td><?php 
                echo $comment['photo'];
                ?>
</td>
							</tr>
							<tr>
								<th scope="row"><label ><?php 
                _e('Album:', 'wp-photo-album-plus');
                ?>
</label></th>
								<td><?php 
                echo wppa_get_album_name($photo['album']);
                ?>
								</td>
							</tr>
							<tr>
								<th scope="row"><label ><?php 
                _e('User:'******'wp-photo-album-plus');
                ?>
</label></th>
								<td><input style="width:300px;" type="text" name="user" value="<?php 
                echo $comment['user'];
                ?>
" /></td>
							</tr>
							<tr>
								<th scope="row"><label ><?php 
                _e('Email:', 'wp-photo-album-plus');
                ?>
</label></th>
								<td><input style="width:300px;" type="text" name="email" value="<?php 
                echo $comment['email'];
                ?>
" /></td>
							</tr>
							<tr>
								<th scope="row"><label><?php 
                _e('Comment:', 'wp-photo-album-plus');
                ?>
</label></th>
								<td><textarea style="width:300px; height:150px;" name="comment"><?php 
                echo esc_textarea(stripslashes($comment['comment']));
                ?>
</textarea></td>
							</tr>
						</tbody>
					</table>
					<p>
						<input type="submit" class="button-primary" name="wppa_submit" value="<?php 
                _e('Save Changes', 'wp-photo-album-plus');
                ?>
" />
					</p>
				</form>
			<?php 
            }
            $continue = false;
        }
        if ($_GET['tab'] == 'delete') {
            $id = strval(intval($_GET['delete_id']));
            $photo = $wpdb->get_var($wpdb->prepare("SELECT `photo` FROM `" . WPPA_COMMENTS . "` WHERE `id` = %s", $id));
            $iret = $wpdb->query($wpdb->prepare("DELETE FROM `" . WPPA_COMMENTS . "` WHERE `id` = %s LIMIT 1", $id));
            if ($iret !== false) {
                if (wppa_switch('search_comments')) {
                    wppa_index_update('photo', $photo);
                }
                wppa_update_message(__('Comment deleted', 'wp-photo-album-plus'));
            } else {
                wppa_error_message('Error deleting comment');
            }
            $continue = true;
        }
    }
    if ($continue) {
        // Update anything or do bulkaction
        if (isset($_POST['wppa_submit'])) {
            // Security check
            check_admin_referer('$wppa_nonce', WPPA_NONCE);
            // Updates
            $iret = true;
            if (isset($_POST['wppa_comadmin_show'])) {
                wppa_update_option('wppa_comadmin_show', $_POST['wppa_comadmin_show']);
            }
            if (isset($_POST['wppa_comadmin_linkpage'])) {
                wppa_update_option('wppa_comadmin_linkpage', $_POST['wppa_comadmin_linkpage']);
            }
            if (isset($_POST['wppa_comadmin_order'])) {
                wppa_update_option('wppa_comadmin_order', $_POST['wppa_comadmin_order']);
            }
            if (isset($_POST['edit_comment'])) {
                $iret = wppa_edit_comment($_POST['edit_comment']);
            }
            // Bulk actions
            if (isset($_POST['bulkaction'])) {
                switch ($_POST['bulkaction']) {
                    case 'approveall':
                        $coms_to_proc = $wpdb->get_results("SELECT `id` FROM `" . WPPA_COMMENTS . "` WHERE status = 'pending'", ARRAY_A);
                        $query = "UPDATE " . WPPA_COMMENTS . " SET status = 'approved' WHERE status = 'pending'";
                        if ($wpdb->query($query) === false) {
                            wppa_error_message(__('Could not bulk update status', 'wp-photo-album-plus'));
                            $iret = false;
                        } else {
                            if ($coms_to_proc) {
                                foreach ($coms_to_proc as $item) {
                                    wppa_send_comment_approved_email($item['id']);
                                }
                            }
                            $iret = true;
                        }
                        break;
                    case 'spamall':
                        $query = "UPDATE " . WPPA_COMMENTS . " SET status = 'spam' WHERE status = 'pending'";
                        if ($wpdb->query($query) === false) {
                            wppa_error_message(__('Could not bulk update status', 'wp-photo-album-plus'));
                            $iret = false;
                        } else {
                            $iret = true;
                        }
                        break;
                    case 'delspam':
                        $query = "DELETE FROM " . WPPA_COMMENTS . " WHERE status = 'spam'";
                        if ($wpdb->query($query) === false) {
                            wppa_error_message(__('Could not bulk delete spam', 'wp-photo-album-plus'));
                            $iret = false;
                        }
                        break;
                }
            }
            if ($iret) {
                wppa_update_message(__('Changes Saved', 'wp-photo-album-plus'));
            }
            // Clear (super)cache
            wppa_clear_cache();
        }
        // Submit
        // Delete trash
        $query = "DELETE FROM " . WPPA_COMMENTS . " WHERE status = 'trash'";
        $wpdb->query($query);
        // Initialize normal display
        $wppa_comadmin_linkpage = get_option('wppa_comadmin_linkpage', '0');
        if ($wppa_comadmin_linkpage) {
            $exists = $wpdb->get_var("SELECT `post_title` FROM `" . $wpdb->posts . "` WHERE `ID` = " . $wppa_comadmin_linkpage);
            if (!$exists) {
                $wppa_comadmin_linkpage = '0';
                update_option('wppa_comadmin_linkpage', '0');
            }
        }
        $moderating = isset($_REQUEST['commentid']);
        ?>
		<div class="wrap">
			<?php 
        $iconurl = WPPA_URL . '/img/comment.png';
        ?>
			<div id="icon-album" class="icon32" style="background: transparent url(<?php 
        echo $iconurl;
        ?>
) no-repeat">
				<br />
			</div>
			<h2>
				<?php 
        if ($moderating) {
            _e('Photo Albums -> Moderate Comment', 'wp-photo-album-plus');
        } else {
            _e('Photo Albums -> Comment admin', 'wp-photo-album-plus');
        }
        ?>
			</h2>

			<?php 
        if (!wppa_switch('show_comments')) {
            _e('<h3>The Comment system is not activated</h3><p>To activate: check Table II item 18 on the <b>Photo Albums -> Settings</b> screen and press <b>Save Changes</b>', 'wp-photo-album-plus');
        }
        ?>

			<?php 
        if (!$moderating) {
            ?>
			<!-- Statistics -->
			<table>
				<tbody>
					<tr>
						<td><h3 style="margin:0; color:#777777;"><?php 
            _e('Total:', 'wp-photo-album-plus');
            ?>
</h3></td>
						<td><h3 style="margin:0;"><?php 
            $count = $wpdb->get_var("SELECT COUNT(*) FROM `" . WPPA_COMMENTS . "`");
            echo $count;
            ?>
</h3></td>
					</tr>
					<tr>
						<td><h3 style="margin:0; color:green;"><?php 
            _e('Approved:', 'wp-photo-album-plus');
            ?>
</h3></td>
						<td><h3 style="margin:0;"><?php 
            $count = $wpdb->get_var("SELECT COUNT(*) FROM `" . WPPA_COMMENTS . "` WHERE `status` = 'approved'");
            echo $count;
            ?>
</h3></td>
					</tr>
					<tr>
						<td><h3 style="margin:0; color:#e66f00;"><?php 
            _e('Pending:', 'wp-photo-album-plus');
            ?>
</h3></td>
						<td><h3 style="margin:0;"><?php 
            $count = $wpdb->get_var("SELECT COUNT(*) FROM `" . WPPA_COMMENTS . "` WHERE `status` = 'pending'");
            echo $count;
            ?>
</h3></td>
					</tr>
					<tr>
						<td><h3 style="margin:0; color:red;"><?php 
            _e('Spam:', 'wp-photo-album-plus');
            ?>
</h3></td>
						<td><h3 style="margin:0;"><?php 
            $count = $wpdb->get_var("SELECT COUNT(*) FROM `" . WPPA_COMMENTS . "` WHERE `status` = 'spam'");
            echo $count;
            ?>
</h3></td>
					</tr>
					<?php 
            if (wppa_opt('spam_maxage') != 'none') {
                ?>
					<tr>
						<td><h3 style="margin:0; color:red;"><?php 
                _e('Auto deleted spam:', 'wp-photo-album-plus');
                ?>
</h3></td>
						<td><h3 style="margin:0;"><?php 
                echo get_option('wppa_spam_auto_delcount', '0');
                ?>
</h3></td>
					</tr>
					<?php 
            }
            ?>
				</tbody>
			</table>
			<!-- end statistics -->

			<!-- Settings -->
			<div style="border:1px solid #ccc; padding:4px; margin:4px 0" >
				<h3><?php 
            _e('Settings', 'wp-photo-album-plus');
            ?>
</h3>
				<form action="<?php 
            echo wppa_dbg_url(get_admin_url() . 'admin.php?page=wppa_manage_comments');
            ?>
" method="post">
					<p>
						<?php 
            wp_nonce_field('$wppa_nonce', WPPA_NONCE);
            _e('Linkpage:', 'wp-photo-album-plus');
            ?>
						<select name="wppa_comadmin_linkpage">
							<option value="0" <?php 
            if ($wppa_comadmin_linkpage == '0') {
                echo 'selected="selected"';
            }
            ?>
 disabled="disabled" ><?php 
            _e('--- Please select a page ---', 'wp-photo-album-plus');
            ?>
</option>
							<?php 
            $query = "SELECT `ID`, `post_title`, `post_content` FROM `" . $wpdb->posts . "` WHERE `post_type` = 'page' AND `post_status` = 'publish' ORDER BY `post_title` ASC";
            $pages = $wpdb->get_results($query, ARRAY_A);
            if ($pages) {
                foreach ($pages as $page) {
                    if (stripos($page['post_content'], '%%wppa%%') !== false || stripos($page['post_content'], '[wppa') !== false) {
                        if ($wppa_comadmin_linkpage == $page['ID']) {
                            $sel = 'selected="selected"';
                        } else {
                            $sel = '';
                        }
                        echo '<option value="' . $page['ID'] . '" ' . $sel . '>' . __($page['post_title'], 'wp-photo-album-plus') . '</option>';
                    }
                }
            }
            ?>
						</select>
						<?php 
            _e('You can see the photo and all its comments on the selected page by clicking on the thumbnail image', 'wp-photo-album-plus');
            ?>
					</p>
					<?php 
            $comment_show = wppa_opt('comadmin_show');
            ?>
					<p>
						<?php 
            _e('Display status:', 'wp-photo-album-plus');
            ?>
						<select name="wppa_comadmin_show">
							<option value="all" <?php 
            if ($comment_show == 'all') {
                echo 'selected="selected"';
            }
            ?>
><?php 
            _e('all', 'wp-photo-album-plus');
            ?>
</option>
							<option value="pending" <?php 
            if ($comment_show == 'pending') {
                echo 'selected="selected"';
            }
            ?>
><?php 
            _e('pending', 'wp-photo-album-plus');
            ?>
</option>
							<option value="approved" <?php 
            if ($comment_show == 'approved') {
                echo 'selected="selected"';
            }
            ?>
><?php 
            _e('approved', 'wp-photo-album-plus');
            ?>
</option>
							<option value="spam" <?php 
            if ($comment_show == 'spam') {
                echo 'selected="selected"';
            }
            ?>
><?php 
            _e('spam', 'wp-photo-album-plus');
            ?>
</option>
						</select>
						<?php 
            $comment_order = wppa_opt('comadmin_order');
            ?>
						<?php 
            _e('Display order:', 'wp-photo-album-plus');
            ?>
						<select name="wppa_comadmin_order">
							<option value="timestamp" <?php 
            if ($comment_order == 'timestamp') {
                echo 'selected="selected"';
            }
            ?>
><?php 
            _e('timestamp', 'wp-photo-album-plus');
            ?>
</option>
							<option value="photo" <?php 
            if ($comment_order == 'photo') {
                echo 'selected="selected"';
            }
            ?>
><?php 
            _e('photo', 'wp-photo-album-plus');
            ?>
</option>
						</select>
						<?php 
            _e('Bulk action:', 'wp-photo-album-plus');
            ?>
						<select name="bulkaction">
							<option value=""><?php 
            ?>
</option>
							<option value="approveall"><?php 
            _e('Approve all pending', 'wp-photo-album-plus');
            ?>
</option>
							<option value="spamall"><?php 
            _e('Move all pending to spam', 'wp-photo-album-plus');
            ?>
</option>
							<option value="delspam"><?php 
            _e('Delete all spam', 'wp-photo-album-plus');
            ?>
</option>
						</select>
						<input type="submit" class="button-primary" name="wppa_submit" value="<?php 
            _e('Save Settings / Perform bulk action', 'wp-photo-album-plus');
            ?>
" />
					</p>
				</form>
			</div>
			<!-- End Settings -->

			<?php 
        }
        if ($moderating) {
            $pagesize = '1';
            $where = " WHERE `id` = '" . $_REQUEST['commentid'] . "'";
            $order = '';
            $curpage = '1';
            $limit = '';
        } else {
            $pagsize = wppa_opt('comment_admin_pagesize');
            $where = $comment_show == 'all' ? '' : " WHERE `status` = '" . $comment_show . "'";
            $order = " ORDER BY `" . $comment_order . "`";
            if ($comment_order == 'timestamp') {
                $order .= " DESC";
            }
            if (isset($_GET['wppa-page'])) {
                $curpage = strval(intval($_GET['wppa-page']));
                $offset = (strval(intval($_GET['wppa-page'])) - 1) * $pagsize;
                $limit = " LIMIT " . $offset . "," . $pagsize;
            } else {
                $limit = ' LIMIT 0,' . $pagsize;
                $curpage = '1';
            }
            if ($pagsize == '0') {
                $limit = '';
            }
            // Paginating is off
            $nitems = $wpdb->get_var("SELECT COUNT(*) FROM " . WPPA_COMMENTS . $where);
            $link = wppa_dbg_url(get_admin_url() . 'admin.php?page=wppa_manage_comments');
            wppa_admin_page_links($curpage, $pagsize, $nitems, $link);
        }
        ?>
			<table class="widefat">
				<thead style="font-weight: bold" class="">
					<tr>
						<th scope="col"><?php 
        _e('Photo', 'wp-photo-album-plus');
        ?>
<br />
										<?php 
        _e('(Album)', 'wp-photo-album-plus');
        ?>
</th>
						<th scope="col"><?php 
        _e('#', 'wp-photo-album-plus');
        ?>
</th>
						<th scope="col"><?php 
        _e('IP', 'wp-photo-album-plus');
        ?>
</th>
						<th scope="col"><?php 
        _e('User', 'wp-photo-album-plus');
        ?>
</th>
						<th scope="col"><?php 
        _e('Email', 'wp-photo-album-plus');
        ?>
</th>
						<th scope="col"><?php 
        _e('Time since', 'wp-photo-album-plus');
        ?>
</th>
						<th scope="col"><?php 
        _e('Comment', 'wp-photo-album-plus');
        ?>
</th>
						<th scope="col" style="width: 130px;" ><?php 
        _e('Status', 'wp-photo-album-plus');
        ?>
</th>
						<th scope="col"><?php 
        _e('Edit', 'wp-photo-album-plus');
        ?>
</th>
						<th scope="col"><?php 
        _e('Delete', 'wp-photo-album-plus');
        ?>
</th>
					</tr>
				</thead>
				<tbody class="wppa_table_1">
					<?php 
        $comments = $wpdb->get_results("SELECT * FROM `" . WPPA_COMMENTS . "`" . $where . $order . $limit, ARRAY_A);
        if ($comments) {
            foreach ($comments as $com) {
                ?>
							<tr>
								<?php 
                $photo = $wpdb->get_row($wpdb->prepare("SELECT * FROM " . WPPA_PHOTOS . " WHERE id = %s", $com['photo']), 'ARRAY_A');
                if ($photo) {
                    $alb = $photo['album'];
                    $pname = __($photo['name'], 'wp-photo-album-plus');
                    $albname = '(' . wppa_get_album_name($alb) . ')';
                } else {
                    $alb = '';
                    $pname = '';
                    $albname = '';
                }
                if ($wppa_comadmin_linkpage == '0') {
                    ?>
									<td style="text-align:center">
										<img src="<?php 
                    echo wppa_fix_poster_ext(wppa_get_thumb_url($com['photo']), $com['photo']);
                    ?>
" style="max-height:64px;max-width:64px;" />
										<br />
										<?php 
                    echo $albname;
                    ?>
									</td><?php 
                } else {
                    $url = get_page_link($wppa_comadmin_linkpage);
                    if (strpos($url, '?')) {
                        $url .= '&';
                    } else {
                        $url .= '?';
                    }
                    $url .= 'wppa-album=' . $alb . '&wppa-photo=' . $com['photo'] . '&wppa-occur=1';
                    ?>
									<td style="text-align:center">
										<a href="<?php 
                    echo $url;
                    ?>
" target="_blank">
											<img title="<?php 
                    _e('Click to see the fullsize photo and all comments', 'wp-photo-album-plus');
                    ?>
" src="<?php 
                    echo wppa_fix_poster_ext(wppa_get_thumb_url($com['photo']), $com['photo']);
                    ?>
" style="max-height:64px;max-width:64px;" />
										</a>
										<br />
										<?php 
                    echo $albname;
                    ?>
									</td><?php 
                }
                ?>
								<td><?php 
                echo $com['photo'];
                ?>
</td>
								<td><?php 
                echo $com['ip'];
                ?>
</td>
								<td><?php 
                echo $com['user'];
                ?>
</td>
								<td><?php 
                if ($com['email']) {
                    $subject = str_replace(' ', '%20', sprintf(__('Reply to your comment on photo: %s on %s', 'wp-photo-album-plus'), $pname, get_bloginfo('name')));
                    echo '<a href="mailto:' . $com['email'] . '?Subject=' . $subject . '" title="' . __('Reply', 'wp-photo-album-plus') . '" >' . $com['email'] . '</a>';
                } else {
                    echo $com['email'];
                }
                ?>
								</td>
								<td><?php 
                echo wppa_get_time_since($com['timestamp']);
                ?>
</td>
								<td><?php 
                echo stripslashes($com['comment']);
                ?>
</td>
								<td>
									<input type="hidden" id="photo-nonce-<?php 
                echo $com['photo'];
                ?>
" value="<?php 
                echo wp_create_nonce('wppa_nonce_' . $com['photo']);
                ?>
" />
									<select name="status['<?php 
                echo $com['id'];
                ?>
']" onchange="jQuery('#wppa-comment-spin-<?php 
                echo $com['id'];
                ?>
').css('visibility', 'visible'); wppaAjaxUpdateCommentStatus(<?php 
                echo $com['photo'];
                ?>
, <?php 
                echo $com['id'];
                ?>
, this.value)">
										<option value="pending" 	<?php 
                if ($com['status'] == 'pending') {
                    echo 'selected="selected"';
                }
                ?>
><?php 
                _e('Pending', 'wp-photo-album-plus');
                ?>
</option>
										<option value="approved" 	<?php 
                if ($com['status'] == 'approved') {
                    echo 'selected="selected"';
                }
                ?>
><?php 
                _e('Approved', 'wp-photo-album-plus');
                ?>
</option>
										<option value="spam" 		<?php 
                if ($com['status'] == 'spam') {
                    echo 'selected="selected"';
                }
                ?>
><?php 
                _e('Spam', 'wp-photo-album-plus');
                ?>
</option>
									</select>
									<img id="wppa-comment-spin-<?php 
                echo $com['id'];
                ?>
" src="<?php 
                echo wppa_get_imgdir() . 'spinner.gif';
                ?>
" style="visibility:hidden" />
								</td>
								<?php 
                $url = wppa_dbg_url(get_admin_url() . 'admin.php?page=wppa_manage_comments&tab=edit&edit_id=' . $com['id']);
                if (isset($_GET['wppa-page'])) {
                    $url .= '&compage=' . strval(intval($_GET['wppa-page']));
                }
                if (isset($_GET['commentid'])) {
                    $url .= '&commentid=' . strval(intval($_GET['commentid']));
                }
                ?>
								<?php 
                $delurl = wppa_dbg_url(get_admin_url() . 'admin.php?page=wppa_manage_comments&tab=delete&delete_id=' . $com['id']);
                ?>
								<td style="color:green; cursor:pointer;" onclick="document.location='<?php 
                echo $url;
                ?>
'"><b><?php 
                _e('Edit', 'wp-photo-album-plus');
                ?>
</b></td>
								<td style="color:red; cursor:pointer;" onclick="if (confirm('<?php 
                _e('Are you sure you want to delete this comment?', 'wp-photo-album-plus');
                ?>
')) document.location = '<?php 
                echo $delurl;
                ?>
';"><b><?php 
                _e('Delete', 'wp-photo-album-plus');
                ?>
</b></td>
							</tr>
						<?php 
            }
        }
        ?>
				</tbody>
				<tfoot style="font-weight: bold" class="">
					<tr>
						<th scope="col"><?php 
        _e('Photo', 'wp-photo-album-plus');
        ?>
<br />
										<?php 
        _e('(Album)', 'wp-photo-album-plus');
        ?>
</th>
						<th scope="col"><?php 
        _e('#', 'wp-photo-album-plus');
        ?>
</th>
						<th scope="col"><?php 
        _e('IP', 'wp-photo-album-plus');
        ?>
</th>
						<th scope="col"><?php 
        _e('User', 'wp-photo-album-plus');
        ?>
</th>
						<th scope="col"><?php 
        _e('Email', 'wp-photo-album-plus');
        ?>
</th>
						<th scope="col"><?php 
        _e('Time since', 'wp-photo-album-plus');
        ?>
</th>
						<th scope="col"><?php 
        _e('Comment', 'wp-photo-album-plus');
        ?>
</th>
						<th scope="col"><?php 
        _e('Status', 'wp-photo-album-plus');
        ?>
</th>
						<th scope="col"><?php 
        _e('Edit', 'wp-photo-album-plus');
        ?>
</th>
						<th scope="col"><?php 
        _e('Delete', 'wp-photo-album-plus');
        ?>
</th>
					</tr>
				</tfoot>
			</table>
			<?php 
        if (!$moderating) {
            wppa_admin_page_links($curpage, $pagsize, $nitems, $link);
        }
        ?>
		</form>
	</div>
	<?php 
    }
}
Ejemplo n.º 4
0
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_do_comment($id)
{
    global $wpdb;
    global $wppa_done;
    if ($wppa_done) {
        return;
    }
    // Prevent multiple
    $wppa_done = true;
    $time = time();
    $photo = isset($_REQUEST['photo']) ? strval(intval($_REQUEST['photo'])) : '0';
    //wppa_get_get( 'photo' );
    if (!$photo) {
        $photo = isset($_REQUEST['photo-id']) ? strval(intval($_REQUEST['photo-id'])) : '0';
    }
    //wppa_get_get( 'photo' );
    if (!$photo) {
        die('Photo id missing while processing a comment');
    }
    $user = sanitize_user(wppa_get_post('comname'));
    if (!$user) {
        die('Illegal attempt to enter a comment 1');
    }
    $email = sanitize_email(wppa_get_post('comemail'));
    if (!$email) {
        if (wppa_switch('comment_email_required')) {
            die('Illegal attempt to enter a comment 2');
        } else {
            $email = wppa_get_user();
        }
        // If email not present and not required, use his IP
    }
    // Retrieve and filter comment
    $comment = wppa_get_post('comment');
    $comment = trim($comment);
    $comment = wppa_decode($comment);
    $comment = strip_tags($comment);
    $save_comment = str_replace("\n", '<br />', $comment);
    // Resque newline chars
    $save_comment = stripslashes($save_comment);
    $policy = wppa_opt('comment_moderation');
    switch ($policy) {
        case 'all':
            $status = 'pending';
            break;
        case 'logout':
            $status = is_user_logged_in() ? 'approved' : 'pending';
            break;
        case 'none':
            $status = 'approved';
            break;
    }
    if (current_user_can('wppa_moderate')) {
        $status = 'approved';
    }
    // Need not moderate comments issued by moderator
    // Editing a comment?
    $cedit = wppa_get_post('comment-edit', '0');
    if (!wppa_is_int($cedit)) {
        wp_die('Security check falure 14');
    }
    // Check captcha
    if (is_user_logged_in() && wppa_opt('comment_captcha') == 'all' || !is_user_logged_in() && wppa_opt('comment_captcha') != 'none') {
        $captkey = $id;
        if ($cedit) {
            $captkey = $wpdb->get_var($wpdb->prepare('SELECT `timestamp` FROM `' . WPPA_COMMENTS . '` WHERE `id` = %s', $cedit));
        }
        wppa_dbg_q('Q43');
        if (!wppa_check_captcha($captkey)) {
            $status = 'spam';
        }
    }
    // Process ( edited ) comment
    if ($comment) {
        if ($cedit) {
            $query = $wpdb->prepare("UPDATE `" . WPPA_COMMENTS . "`" . " SET `comment` = %s, `user` = %s, `email` = %s, `status` = %s, `timestamp` = %s " . " WHERE `id` = %s LIMIT 1", $save_comment, $user, $email, $status, time(), $cedit);
            wppa_dbg_q('Q44');
            $iret = $wpdb->query($query);
            if ($iret !== false) {
                wppa('comment_id', $cedit);
            }
        } else {
            // See if a refresh happened
            $old_entry = $wpdb->prepare('SELECT * FROM `' . WPPA_COMMENTS . '` WHERE `photo` = %s AND `user` = %s AND `comment` = %s LIMIT 1', $photo, $user, $save_comment);
            $iret = $wpdb->query($old_entry);
            if ($iret) {
                if (wppa('debug')) {
                    echo '<script type="text/javascript">alert( "Duplicate comment ignored" )</script>';
                }
                return;
            }
            $key = wppa_create_comments_entry(array('photo' => $photo, 'user' => $user, 'email' => $email, 'comment' => $save_comment, 'status' => $status));
            if ($key) {
                wppa('comment_id', $key);
            }
        }
        if ($iret !== false) {
            if ($status != 'spam') {
                if ($cedit) {
                    if (wppa_switch('comment_notify_added')) {
                        echo '<script id="cme" type="text/javascript">alert( "' . __('Comment edited', 'wp-photo-album-plus') . '" );jQuery( "#cme" ).html( "" );</script>';
                    }
                } else {
                    // SUCCESSFUL COMMENT, ADD POINTS
                    wppa_add_credit_points(wppa_opt('cp_points_comment'), __('Photo comment', 'wp-photo-album-plus'), $id);
                    // SEND EMAILS
                    // Initialize
                    $subj = __('Comment on photo:', 'wp-photo-album-plus') . ' ' . wppa_get_photo_name($id);
                    $usr = $user;
                    if (is_user_logged_in()) {
                        global $current_user;
                        get_currentuserinfo();
                        $usr = $current_user->display_name;
                    }
                    $returnurl = wppa_get_post('returnurl');
                    $sentto = array();
                    // Setup standard content
                    $cont['0'] = $usr . ' ' . __('wrote on photo', 'wp-photo-album-plus') . ' ' . wppa_get_photo_name($id) . ':';
                    $cont['1'] = '<blockquote style="color:#000077; background-color: #dddddd; border:1px solid black; padding: 6px; border-radius 4px;" ><em> ' . stripslashes($comment) . '</em></blockquote>';
                    $cont['2'] = $returnurl ? '<a href="' . $returnurl . '" >' . __('Reply', 'wp-photo-album-plus') . '</a>' : '';
                    $cont2 = '<a href="' . get_admin_url() . 'admin.php?page=wppa_manage_comments&commentid=' . $key . '" >' . __('Moderate comment admin', 'wp-photo-album-plus') . '</a>';
                    $cont3 = '<a href="' . get_admin_url() . 'admin.php?page=wppa_admin_menu&tab=cmod&photo=' . $id . '" >' . __('Moderate manage photo', 'wp-photo-album-plus') . '</a>';
                    $cont3a = '<a href="' . get_admin_url() . 'admin.php?page=wppa_edit_photo&photo=' . $id . '" >' . __('Edit photo', 'wp-photo-album-plus') . '</a>';
                    // Process various types of emails
                    if (is_numeric(wppa_opt('comment_notify'))) {
                        // Mail specific user
                        $moduser = get_userdata(wppa_opt('comment_notify'));
                        $to = $moduser->user_email;
                        if (user_can($moduser, 'wppa_comments')) {
                            $cont['3'] = $cont2;
                        } else {
                            $cont['3'] = '';
                        }
                        if (user_can($moduser, 'wppa_admin')) {
                            $cont['4'] = $cont3;
                        } else {
                            $cont['4'] = '';
                        }
                        $cont['5'] = __('You receive this email as you are assigned to moderate', 'wp-photo-album-plus');
                        // Send!
                        wppa_send_mail($to, $subj, $cont, $photo, wppa_switch('mail_upl_email') ? $email : 'void', $returnurl);
                        $sentto[] = $moduser->login_name;
                    }
                    if (wppa_opt('comment_notify') == 'admin' || wppa_opt('comment_notify') == 'both' || wppa_opt('comment_notify') == 'upadmin') {
                        // Mail admin
                        $moduser = get_user_by('id', '1');
                        if (!in_array($moduser->login_name, $sentto)) {
                            // Already sent him?
                            $to = get_bloginfo('admin_email');
                            $cont['3'] = $cont2;
                            $cont['4'] = $cont3;
                            $cont['5'] = __('You receive this email as administrator of the site', 'wp-photo-album-plus');
                            // Send!
                            wppa_send_mail($to, $subj, $cont, $photo, $email, $returnurl);
                            $sentto[] = $moduser->login_name;
                        }
                    }
                    if (wppa_opt('comment_notify') == 'upload' || wppa_opt('comment_notify') == 'upadmin' || wppa_opt('comment_notify') == 'upowner') {
                        // Mail uploader
                        $uploader = $wpdb->get_var($wpdb->prepare("SELECT `owner` FROM `" . WPPA_PHOTOS . "` WHERE `id` = %d", $id));
                        $moduser = get_user_by('login', $uploader);
                        if ($moduser) {
                            // else it's an ip address ( anonymus uploader )
                            if (!in_array($moduser->login_name, $sentto)) {
                                // Already sent him?
                                $to = $moduser->user_email;
                                $cont['3'] = user_can($moduser, 'wppa_comments') ? $cont2 : '';
                                if (user_can($moduser, 'wppa_admin')) {
                                    $cont['4'] = $cont3;
                                } elseif (wppa_switch('upload_edit')) {
                                    $cont['4'] = $cont3a;
                                } else {
                                    $cont['4'] = '';
                                }
                                $cont['5'] = __('You receive this email as uploader of the photo', 'wp-photo-album-plus');
                                // Send!
                                wppa_send_mail($to, $subj, $cont, $photo, wppa_switch('mail_upl_email') ? $email : 'void', $returnurl);
                                $sentto[] = $moduser->login_name;
                            }
                        }
                    }
                    if (wppa_opt('comment_notify') == 'owner' || wppa_opt('comment_notify') == 'both' || wppa_opt('comment_notify') == 'upowner') {
                        // Mail album owner
                        $alb = $wpdb->get_var($wpdb->prepare("SELECT `album` FROM `" . WPPA_PHOTOS . "` WHERE `id` = %d", $id));
                        $owner = $wpdb->get_var($wpdb->prepare("SELECT `owner` FROM `" . WPPA_ALBUMS . "` WHERE `id` = %d", $alb));
                        if ($owner == '--- public ---') {
                            $owner = 'admin';
                        }
                        $moduser = get_user_by('login', $owner);
                        if (!in_array($moduser->login_name, $sentto)) {
                            // Already sent him?
                            $to = $moduser->user_email;
                            if (user_can($moduser, 'wppa_comments')) {
                                $cont['3'] = $cont2;
                            } else {
                                $cont['3'] = '';
                            }
                            if (user_can($moduser, 'wppa_admin')) {
                                $cont['4'] = $cont3;
                            } else {
                                $cont['4'] = '';
                            }
                            $cont['5'] = __('You receive this email as owner of the album', 'wp-photo-album-plus');
                            // Send!
                            wppa_send_mail($to, $subj, $cont, $photo, wppa_switch('mail_upl_email') ? $email : 'void', $returnurl);
                            $sentto[] = $moduser->login_name;
                        }
                    }
                    if (wppa_switch('com_notify_previous')) {
                        // Mail users already commented on this photo
                        $cmnts = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_COMMENTS . "` WHERE `photo` = %d", $photo), ARRAY_A);
                        if ($cmnts) {
                            foreach ($cmnts as $cmnt) {
                                $user = $cmnt['user'];
                                if (!in_array($user, $sentto)) {
                                    $cmuser = get_user_by('login', $user);
                                    if ($cmuser) {
                                        // Not to an ip
                                        $to = $cmuser->user_email;
                                        $cont['3'] = '';
                                        $cont['4'] = '';
                                        $cont['5'] = __('You receive this email because you commented this photo earlier.', 'wp-photo-album-plus');
                                        // Send!
                                        wppa_send_mail($to, $subj, $cont, $photo, wppa_switch('mail_upl_email') ? $email : 'void', $returnurl);
                                        $sentto[] = $to;
                                    }
                                }
                            }
                        }
                    }
                    /* to do
                    					if ( wppa_switch(  'wppa_mail_ats' ) ) {
                    						// Mail to @dest
                    						// Find @dest in $comment
                    
                    						// Mail them
                    
                    					}
                    */
                    // Process any pending votes of this user for this photo if rating needs comment, do it anyway, feature may have been on but now off
                    //				if ( wppa_switch( 'vote_needs_comment' ) ) {
                    $iret = $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_RATING . "` SET `status` = 'publish' WHERE `photo` = %s AND `user` = %s", $id, wppa_get_user()));
                    if ($iret) {
                        wppa_rate_photo($id);
                    }
                    // Recalc ratings for this photo
                    //				}
                    // Notyfy user
                    if (wppa_switch('comment_notify_added')) {
                        echo '<script id="cme" type="text/javascript">alert( "' . __('Comment added', 'wp-photo-album-plus') . '" );jQuery( "#cme" ).html( "" );</script>';
                    }
                }
            } else {
                echo '<script type="text/javascript">' . 'alert( "' . __('Sorry, you gave a wrong answer.\\n\\nPlease try again to solve the computation.', 'wp-photo-album-plus') . '" )' . '</script>';
            }
            wppa('comment_photo', $id);
            wppa('comment_text', $comment);
            // Clear ( super )cache
            wppa_clear_cache();
        } else {
            echo '<script type="text/javascript">alert( "' . __('Could not process comment.\\nProbably timed out.', 'wp-photo-album-plus') . '" )</script>';
        }
    } else {
        // Empty comment
    }
}
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();
}