function wppa_do_maintenance_proc($slug)
{
    global $wpdb;
    global $wppa_session;
    global $wppa_supported_video_extensions;
    global $wppa_supported_audio_extensions;
    // Check for multiple maintenance procs
    if (!wppa_switch('maint_ignore_concurrency_error') && !wppa_is_cron()) {
        $all_slugs = array('wppa_remake_index_albums', 'wppa_remove_empty_albums', 'wppa_remake_index_photos', 'wppa_apply_new_photodesc_all', 'wppa_append_to_photodesc', 'wppa_remove_from_photodesc', 'wppa_remove_file_extensions', 'wppa_readd_file_extensions', 'wppa_all_ext_to_lower', 'wppa_regen_thumbs', 'wppa_rerate', 'wppa_recup', 'wppa_file_system', 'wppa_cleanup', 'wppa_remake', 'wppa_list_index', 'wppa_blacklist_user', 'wppa_un_blacklist_user', 'wppa_rating_clear', 'wppa_viewcount_clear', 'wppa_iptc_clear', 'wppa_exif_clear', 'wppa_watermark_all', 'wppa_create_all_autopages', 'wppa_delete_all_autopages', 'wppa_leading_zeros', 'wppa_add_gpx_tag', 'wppa_optimize_ewww', 'wppa_comp_sizes', 'wppa_edit_tag', 'wppa_sync_cloud', 'wppa_sanitize_tags', 'wppa_sanitize_cats', 'wppa_test_proc', 'wppa_crypt_photos', 'wppa_crypt_albums', 'wppa_create_o1_files', 'wppa_owner_to_name_proc', 'wppa_move_all_photos');
        foreach (array_keys($all_slugs) as $key) {
            if ($all_slugs[$key] != $slug) {
                if (get_option($all_slugs[$key] . '_togo', '0')) {
                    // Process running
                    return __('You can run only one maintenance procedure at a time', 'wp-photo-album-plus') . '||' . $slug . '||' . __('Error', 'wp-photo-album-plus') . '||' . '' . '||' . '';
                }
            }
        }
    }
    // Lock this proc
    if (wppa_is_cron()) {
        update_option($slug . '_user', 'cron-job');
        update_option($slug . '_lasttimestamp', time());
    } else {
        update_option($slug . '_user', wppa_get_user());
    }
    // Extend session
    wppa_extend_session();
    // Initialize
    // Cron job: 30 sec, realtime: 5 sec
    $endtime = wppa_is_cron() ? time() + '30' : time() + '5';
    $chunksize = '1000';
    $lastid = strval(intval(get_option($slug . '_last', '0')));
    $errtxt = '';
    $id = '0';
    $topid = '0';
    $reload = '';
    $to_delete_from_cloudinary = array();
    if (!isset($wppa_session)) {
        $wppa_session = array();
    }
    if (!isset($wppa_session[$slug . '_fixed'])) {
        $wppa_session[$slug . '_fixed'] = '0';
    }
    if (!isset($wppa_session[$slug . '_added'])) {
        $wppa_session[$slug . '_added'] = '0';
    }
    if (!isset($wppa_session[$slug . '_deleted'])) {
        $wppa_session[$slug . '_deleted'] = '0';
    }
    if (!isset($wppa_session[$slug . '_skipped'])) {
        $wppa_session[$slug . '_skipped'] = '0';
    }
    if ($lastid == '0') {
        $wppa_session[$slug . '_fixed'] = '0';
        $wppa_session[$slug . '_deleted'] = '0';
        $wppa_session[$slug . '_skipped'] = '0';
    }
    wppa_save_session();
    // Pre-processing needed?
    if ($lastid == '0') {
        if (wppa_is_cron()) {
            wppa_log('Obs', 'Cron job ' . $slug . ' started.');
        } else {
            wppa_log('Obs', 'Maintenance proc ' . $slug . ' started.');
        }
        switch ($slug) {
            case 'wppa_remake_index_albums':
                // Pre-Clear album index only if not cron
                if (!wppa_is_cron()) {
                    $wpdb->query("UPDATE `" . WPPA_INDEX . "` SET `albums` = ''");
                }
                break;
            case 'wppa_remake_index_photos':
                // Pre-Clear photo index only if not cron
                if (!wppa_is_cron()) {
                    $wpdb->query("UPDATE `" . WPPA_INDEX . "` SET `photos` = ''");
                }
                wppa_index_compute_skips();
                break;
            case 'wppa_recup':
                // Pre-Clear exif and iptc tables only if not cron
                if (!wppa_is_cron()) {
                    $wpdb->query("DELETE FROM `" . WPPA_IPTC . "` WHERE `photo` <> '0'");
                    $wpdb->query("DELETE FROM `" . WPPA_EXIF . "` WHERE `photo` <> '0'");
                }
                break;
            case 'wppa_file_system':
                if (get_option('wppa_file_system') == 'flat') {
                    update_option('wppa_file_system', 'to-tree');
                }
                if (get_option('wppa_file_system') == 'tree') {
                    update_option('wppa_file_system', 'to-flat');
                }
                break;
            case 'wppa_cleanup':
                $orphan_album = get_option('wppa_orphan_album', '0');
                $album_exists = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM`" . WPPA_ALBUMS . "` WHERE `id` = %s", $orphan_album));
                if (!$album_exists) {
                    $orphan_album = false;
                }
                if (!$orphan_album) {
                    $orphan_album = wppa_create_album_entry(array('name' => __('Orphan photos', 'wp-photo-album-plus'), 'a_parent' => '-1', 'description' => __('This album contains refound lost photos', 'wp-photo-album-plus')));
                    update_option('wppa_orphan_album', $orphan_album);
                }
                break;
            case 'wppa_sync_cloud':
                if (!wppa_get_present_at_cloudinary_a()) {
                    // Still Initializing
                    $status = 'Initializing';
                    if (!isset($wppa_session['fun-count'])) {
                        $wppa_session['fun-count'] = 0;
                    }
                    $wppa_session['fun-count'] = ($wppa_session['fun-count'] + 1) % 3;
                    for ($i = 0; $i < $wppa_session['fun-count']; $i++) {
                        $status .= '.';
                    }
                    $togo = 'all';
                    $reload = false;
                    echo '||' . $slug . '||' . $status . '||' . $togo . '||' . $reload;
                    wppa_exit();
                }
                break;
            case 'wppa_crypt_albums':
                update_option('wppa_album_crypt_0', wppa_get_unique_album_crypt());
                update_option('wppa_album_crypt_1', wppa_get_unique_album_crypt());
                update_option('wppa_album_crypt_2', wppa_get_unique_album_crypt());
                update_option('wppa_album_crypt_3', wppa_get_unique_album_crypt());
                update_option('wppa_album_crypt_9', wppa_get_unique_album_crypt());
                break;
            case 'wppa_owner_to_name_proc':
                if (!wppa_switch('owner_to_name')) {
                    echo __('Feature must be enabled in Table IV-A28 first', 'wp-photo-album-plus') . '||' . $slug . '||||||';
                    wppa_exit();
                }
                break;
            case 'wppa_move_all_photos':
                $fromalb = get_option('wppa_move_all_photos_from');
                if (!wppa_album_exists($fromalb)) {
                    echo sprintf(__('From album %d does not exist', 'wp-photo-album-plus'), $fromalb);
                    wppa_exit();
                }
                $toalb = get_option('wppa_move_all_photos_to');
                if (!wppa_album_exists($toalb)) {
                    echo sprintf(__('To album %d does not exist', 'wp-photo-album-plus'), $toalb);
                    wppa_exit();
                }
                if ($fromalb == $toalb) {
                    echo __('From and To albums are identical', 'wp-photo-album-plus');
                    wppa_exit();
                }
                break;
        }
        wppa_save_session();
    }
    // Dispatch on albums / photos / single actions
    switch ($slug) {
        case 'wppa_remake_index_albums':
        case 'wppa_remove_empty_albums':
        case 'wppa_sanitize_cats':
        case 'wppa_crypt_albums':
            // Process albums
            $table = WPPA_ALBUMS;
            $topid = $wpdb->get_var("SELECT `id` FROM `" . WPPA_ALBUMS . "` ORDER BY `id` DESC LIMIT 1");
            $albums = $wpdb->get_results("SELECT * FROM `" . WPPA_ALBUMS . "` WHERE `id` > " . $lastid . " ORDER BY `id` LIMIT 100", ARRAY_A);
            wppa_cache_album('add', $albums);
            if ($albums) {
                foreach ($albums as $album) {
                    $id = $album['id'];
                    switch ($slug) {
                        case 'wppa_remake_index_albums':
                            // If done as cron job, no initial clear has been done
                            if (wppa_is_cron()) {
                                wppa_index_remove('album', $id);
                            }
                            wppa_index_add('album', $id);
                            break;
                        case 'wppa_remove_empty_albums':
                            $p = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s", $id));
                            $a = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_ALBUMS . "` WHERE `a_parent` = %s", $id));
                            if (!$a && !$p) {
                                $wpdb->query($wpdb->prepare("DELETE FROM `" . WPPA_ALBUMS . "` WHERE `id` = %s", $id));
                                wppa_delete_album_source($id);
                                wppa_flush_treecounts($id);
                                wppa_index_remove('album', $id);
                            }
                            break;
                        case 'wppa_sanitize_cats':
                            $cats = $album['cats'];
                            if ($cats) {
                                wppa_update_album(array('id' => $album['id'], 'cats' => wppa_sanitize_tags($cats)));
                            }
                            break;
                        case 'wppa_crypt_albums':
                            wppa_update_album(array('id' => $album['id'], 'crypt' => wppa_get_unique_album_crypt()));
                            break;
                    }
                    // Test for timeout / ready
                    $lastid = $id;
                    update_option($slug . '_last', $lastid);
                    if (time() > $endtime) {
                        break;
                    }
                    // Time out
                }
            } else {
                // Nothing to do, Done anyway
                $lastid = $topid;
            }
            break;
            // End process albums
        // End process albums
        case 'wppa_remake_index_photos':
        case 'wppa_apply_new_photodesc_all':
        case 'wppa_append_to_photodesc':
        case 'wppa_remove_from_photodesc':
        case 'wppa_remove_file_extensions':
        case 'wppa_readd_file_extensions':
        case 'wppa_all_ext_to_lower':
        case 'wppa_regen_thumbs':
        case 'wppa_rerate':
        case 'wppa_recup':
        case 'wppa_file_system':
        case 'wppa_cleanup':
        case 'wppa_remake':
        case 'wppa_watermark_all':
        case 'wppa_create_all_autopages':
        case 'wppa_delete_all_autopages':
        case 'wppa_leading_zeros':
        case 'wppa_add_gpx_tag':
        case 'wppa_optimize_ewww':
        case 'wppa_comp_sizes':
        case 'wppa_edit_tag':
        case 'wppa_sync_cloud':
        case 'wppa_sanitize_tags':
        case 'wppa_crypt_photos':
        case 'wppa_test_proc':
        case 'wppa_create_o1_files':
        case 'wppa_owner_to_name_proc':
        case 'wppa_move_all_photos':
            // Process photos
            $table = WPPA_PHOTOS;
            if ($slug == 'wppa_cleanup') {
                $topid = get_option('wppa_' . WPPA_PHOTOS . '_lastkey', '1') * 10;
                $photos = array();
                for ($i = $lastid + '1'; $i <= $topid; $i++) {
                    $photos[]['id'] = $i;
                }
            } else {
                $topid = $wpdb->get_var("SELECT `id` FROM `" . WPPA_PHOTOS . "` ORDER BY `id` DESC LIMIT 1");
                $photos = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `id` > " . $lastid . " ORDER BY `id` LIMIT " . $chunksize, ARRAY_A);
            }
            if ($slug == 'wppa_edit_tag') {
                $edit_tag = get_option('wppa_tag_to_edit');
                $new_tag = get_option('wppa_new_tag_value');
            }
            if (!$photos && $slug == 'wppa_file_system') {
                $fs = get_option('wppa_file_system');
                if ($fs == 'to-tree') {
                    $to = 'tree';
                } elseif ($fs == 'to-flat') {
                    $to = 'flat';
                } else {
                    $to = $fs;
                }
            }
            if ($photos) {
                foreach ($photos as $photo) {
                    $thumb = $photo;
                    // Make globally known
                    $id = $photo['id'];
                    switch ($slug) {
                        case 'wppa_remake_index_photos':
                            // If done as cron job, no initial clear has been done
                            if (wppa_is_cron()) {
                                wppa_index_remove('photo', $id);
                            }
                            wppa_index_add('photo', $id);
                            break;
                        case 'wppa_apply_new_photodesc_all':
                            $value = wppa_opt('newphoto_description');
                            $description = trim($value);
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_append_to_photodesc':
                            $value = trim(wppa_opt('append_text'));
                            if (!$value) {
                                return 'Unexpected error: missing text to append||' . $slug . '||Error||0';
                            }
                            $description = rtrim($photo['description'] . ' ' . $value);
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_remove_from_photodesc':
                            $value = trim(wppa_opt('remove_text'));
                            if (!$value) {
                                return 'Unexpected error: missing text to remove||' . $slug . '||Error||0';
                            }
                            $description = rtrim(str_replace($value, '', $photo['description']));
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_remove_file_extensions':
                            if (!wppa_is_video($id)) {
                                $name = str_replace(array('.jpg', '.png', '.gif', '.JPG', '.PNG', '.GIF'), '', $photo['name']);
                                if ($name != $photo['name']) {
                                    // Modified photo name
                                    $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name, $id));
                                }
                            }
                            break;
                        case 'wppa_readd_file_extensions':
                            if (!wppa_is_video($id)) {
                                $name = str_replace(array('.jpg', '.png', 'gif', '.JPG', '.PNG', '.GIF'), '', $photo['name']);
                                if ($name == $photo['name']) {
                                    // Name had no fileextension
                                    $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name . '.' . $photo['ext'], $id));
                                }
                            }
                            break;
                        case 'wppa_all_ext_to_lower':
                            $EXT = wppa_get_photo_item($id, 'ext');
                            $ext = strtolower($EXT);
                            if ($EXT != $ext) {
                                wppa_update_photo(array('id' => $id, 'ext' => $ext));
                                $fixed_this = true;
                            }
                            $EXT = strtoupper($ext);
                            $rawpath = wppa_strip_ext(wppa_get_photo_path($id));
                            $rawthumb = wppa_strip_ext(wppa_get_thumb_path($id));
                            $fixed_this = false;
                            if (wppa_is_multi($id)) {
                            } else {
                                if (is_file($rawpath . '.' . $EXT)) {
                                    if (is_file($rawpath . '.' . $ext)) {
                                        unlink($rawpath . '.' . $EXT);
                                    } else {
                                        rename($rawpath . '.' . $EXT, $rawpath . '.' . $ext);
                                    }
                                    $fixed_this = true;
                                }
                                if (is_file($rawthumb . '.' . $EXT)) {
                                    if (is_file($rawthumb . '.' . $ext)) {
                                        unlink($rawthumb . '.' . $EXT);
                                    } else {
                                        rename($rawthumb . '.' . $EXT, $rawthumb . '.' . $ext);
                                    }
                                    $fixed_this = true;
                                }
                            }
                            if ($fixed_this) {
                                $wppa_session[$slug . '_fixed']++;
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_regen_thumbs':
                            if (!wppa_is_video($id) || file_exists(str_replace('xxx', 'jpg', wppa_get_photo_path($id)))) {
                                wppa_create_thumbnail($id);
                            }
                            break;
                        case 'wppa_rerate':
                            wppa_rate_photo($id);
                            break;
                        case 'wppa_recup':
                            $a_ret = wppa_recuperate($id);
                            if ($a_ret['iptcfix']) {
                                $wppa_session[$slug . '_fixed']++;
                            }
                            if ($a_ret['exiffix']) {
                                $wppa_session[$slug . '_fixed']++;
                            }
                            break;
                        case 'wppa_file_system':
                            $fs = get_option('wppa_file_system');
                            if ($fs == 'to-tree' || $fs == 'to-flat') {
                                if ($fs == 'to-tree') {
                                    $from = 'flat';
                                    $to = 'tree';
                                } else {
                                    $from = 'tree';
                                    $to = 'flat';
                                }
                                // Media files
                                if (wppa_is_multi($id)) {
                                    // Can NOT use wppa_has_audio() or wppa_is_video(), they use wppa_get_photo_path() without fs switch!!
                                    $exts = array_merge($wppa_supported_video_extensions, $wppa_supported_audio_extensions);
                                    $pathfrom = wppa_get_photo_path($id, $from);
                                    $pathto = wppa_get_photo_path($id, $to);
                                    //	wppa_log( 'dbg', 'Trying: '.$pathfrom );
                                    foreach ($exts as $ext) {
                                        if (is_file(str_replace('.xxx', '.' . $ext, $pathfrom))) {
                                            //	wppa_log( 'dbg',  str_replace( '.xxx', '.'.$ext, $pathfrom ).' -> '.str_replace( '.xxx', '.'.$ext, $pathto ));
                                            @rename(str_replace('.xxx', '.' . $ext, $pathfrom), str_replace('.xxx', '.' . $ext, $pathto));
                                        }
                                    }
                                }
                                // Poster / photo
                                if (file_exists(wppa_fix_poster_ext(wppa_get_photo_path($id, $from), $id))) {
                                    @rename(wppa_fix_poster_ext(wppa_get_photo_path($id, $from), $id), wppa_fix_poster_ext(wppa_get_photo_path($id, $to), $id));
                                }
                                // Thumbnail
                                if (file_exists(wppa_fix_poster_ext(wppa_get_thumb_path($id, $from), $id))) {
                                    @rename(wppa_fix_poster_ext(wppa_get_thumb_path($id, $from), $id), wppa_fix_poster_ext(wppa_get_thumb_path($id, $to), $id));
                                }
                            }
                            break;
                        case 'wppa_cleanup':
                            $photo_files = glob(WPPA_UPLOAD_PATH . '/' . $id . '.*');
                            // Remove dirs
                            if ($photo_files) {
                                foreach (array_keys($photo_files) as $key) {
                                    if (is_dir($photo_files[$key])) {
                                        unset($photo_files[$key]);
                                    }
                                }
                            }
                            // files left? process
                            if ($photo_files) {
                                foreach ($photo_files as $photo_file) {
                                    $basename = basename($photo_file);
                                    $ext = substr($basename, strpos($basename, '.') + '1');
                                    if (!$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $id))) {
                                        // no db entry for this photo
                                        if (wppa_is_id_free(WPPA_PHOTOS, $id)) {
                                            if (wppa_create_photo_entry(array('id' => $id, 'album' => $orphan_album, 'ext' => $ext, 'filename' => $basename))) {
                                                // Can create entry
                                                $wppa_session[$slug . '_fixed']++;
                                                // Bump counter
                                                wppa_log('Debug', 'Lost photo file ' . $photo_file . ' recovered');
                                            } else {
                                                wppa_log('Debug', 'Unable to recover lost photo file ' . $photo_file . ' Create photo entry failed');
                                            }
                                        } else {
                                            wppa_log('Debug', 'Could not recover lost photo file ' . $photo_file . ' The id is not free');
                                        }
                                    }
                                }
                            }
                            break;
                        case 'wppa_remake':
                            $doit = true;
                            if (wppa_switch('remake_orientation_only')) {
                                $ori = wppa_get_exif_orientation(wppa_get_source_path($id));
                                if ($ori < '2') {
                                    $doit = false;
                                }
                            }
                            if (wppa_switch('remake_missing_only')) {
                                if (is_file(wppa_get_thumb_path($id)) && is_file(wppa_get_photo_path($id))) {
                                    $doit = false;
                                }
                            }
                            if ($doit && wppa_remake_files('', $id)) {
                                $wppa_session[$slug . '_fixed']++;
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_watermark_all':
                            if (!wppa_is_video($id)) {
                                if (wppa_add_watermark($id)) {
                                    wppa_create_thumbnail($id);
                                    // create new thumb
                                    $wppa_session[$slug . '_fixed']++;
                                } else {
                                    $wppa_session[$slug . '_skipped']++;
                                }
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_create_all_autopages':
                            wppa_get_the_auto_page($id);
                            break;
                        case 'wppa_delete_all_autopages':
                            wppa_remove_the_auto_page($id);
                            break;
                        case 'wppa_leading_zeros':
                            $name = $photo['name'];
                            if (wppa_is_int($name)) {
                                $target_len = wppa_opt('zero_numbers');
                                $name = strval(intval($name));
                                while (strlen($name) < $target_len) {
                                    $name = '0' . $name;
                                }
                            }
                            if ($name !== $photo['name']) {
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name, $id));
                            }
                            break;
                        case 'wppa_add_gpx_tag':
                            $tags = $photo['tags'];
                            $temp = explode('/', $photo['location']);
                            if (!isset($temp['2'])) {
                                $temp['2'] = false;
                            }
                            if (!isset($temp['3'])) {
                                $temp['3'] = false;
                            }
                            $lat = $temp['2'];
                            $lon = $temp['3'];
                            if ($lat < 0.01 && $lat > -0.01 && $lon < 0.01 && $lon > -0.01) {
                                $lat = false;
                                $lon = false;
                            }
                            if ($photo['location'] && strpos($tags, 'Gpx') === false && $lat && $lon) {
                                // Add it
                                $tags = wppa_sanitize_tags($tags . ',Gpx');
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                wppa_index_update('photo', $photo['id']);
                                wppa_clear_taglist();
                            } elseif (strpos($tags, 'Gpx') !== false && !$lat && !$lon) {
                                // Remove it
                                $tags = wppa_sanitize_tags(str_replace('Gpx', '', $tags));
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                wppa_index_update('photo', $photo['id']);
                                wppa_clear_taglist();
                            }
                            break;
                        case 'wppa_optimize_ewww':
                            $file = wppa_get_photo_path($photo['id']);
                            if (is_file($file)) {
                                ewww_image_optimizer($file, 4, false, false, false);
                            }
                            $file = wppa_get_thumb_path($photo['id']);
                            if (is_file($file)) {
                                ewww_image_optimizer($file, 4, false, false, false);
                            }
                            break;
                        case 'wppa_comp_sizes':
                            $tx = 0;
                            $ty = 0;
                            $px = 0;
                            $py = 0;
                            $file = wppa_get_photo_path($photo['id']);
                            if (is_file($file)) {
                                $temp = getimagesize($file);
                                if (is_array($temp)) {
                                    $px = $temp[0];
                                    $py = $temp[1];
                                }
                            }
                            $file = wppa_get_thumb_path($photo['id']);
                            if (is_file($file)) {
                                $temp = getimagesize($file);
                                if (is_array($temp)) {
                                    $tx = $temp[0];
                                    $ty = $temp[1];
                                }
                            }
                            wppa_update_photo(array('id' => $photo['id'], 'thumbx' => $tx, 'thumby' => $ty, 'photox' => $px, 'photoy' => $py));
                            break;
                        case 'wppa_edit_tag':
                            $phototags = explode(',', wppa_get_photo_item($photo['id'], 'tags'));
                            if (in_array($edit_tag, $phototags)) {
                                foreach (array_keys($phototags) as $key) {
                                    if ($phototags[$key] == $edit_tag) {
                                        $phototags[$key] = $new_tag;
                                    }
                                }
                                $tags = wppa_sanitize_tags(implode(',', $phototags));
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                $wppa_session[$slug . '_fixed']++;
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_sync_cloud':
                            $is_old = wppa_opt('max_cloud_life') && time() > $photo['timestamp'] + wppa_opt('max_cloud_life');
                            //	$is_in_cloud = @ getimagesize( wppa_get_cloudinary_url( $photo['id'], 'test_only' ) );
                            $is_in_cloud = isset($wppa_session['cloudinary_ids'][$photo['id']]);
                            //	wppa_log('Obs', 'Id='.$photo['id'].', is old='.$is_old.', in cloud='.$is_in_cloud);
                            if ($is_old && $is_in_cloud) {
                                $to_delete_from_cloudinary[] = strval($photo['id']);
                                if (count($to_delete_from_cloudinary) == 10) {
                                    wppa_delete_from_cloudinary($to_delete_from_cloudinary);
                                    $to_delete_from_cloudinary = array();
                                }
                                $wppa_session[$slug . '_deleted']++;
                            }
                            if (!$is_old && !$is_in_cloud) {
                                wppa_upload_to_cloudinary($photo['id']);
                                $wppa_session[$slug . '_added']++;
                            }
                            if ($is_old && !$is_in_cloud) {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            if (!$is_old && $is_in_cloud) {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_sanitize_tags':
                            $tags = $photo['tags'];
                            if ($tags) {
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => wppa_sanitize_tags($tags)));
                            }
                            break;
                        case 'wppa_crypt_photos':
                            wppa_update_photo(array('id' => $photo['id'], 'crypt' => wppa_get_unique_photo_crypt()));
                            break;
                        case 'wppa_create_o1_files':
                            wppa_make_o1_source($photo['id']);
                            break;
                        case 'wppa_owner_to_name_proc':
                            $iret = wppa_set_owner_to_name($id);
                            if ($iret === true) {
                                $wppa_session[$slug . '_fixed']++;
                            }
                            if ($iret === '0') {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_move_all_photos':
                            $fromalb = get_option('wppa_move_all_photos_from');
                            $toalb = get_option('wppa_move_all_photos_to');
                            $alb = wppa_get_photo_item($id, 'album');
                            if ($alb == $fromalb) {
                                wppa_update_photo(array('id' => $id, 'album' => $toalb));
                                wppa_move_source(wppa_get_photo_item($id, 'filename'), $fromalb, $toalb);
                                wppa_flush_treecounts($fromalb);
                                wppa_flush_treecounts($toalb);
                                $wppa_session[$slug . '_fixed']++;
                            }
                            break;
                        case 'wppa_test_proc':
                            $tags = '';
                            $albid = $photo['album'];
                            $albnam = wppa_get_album_item($albid, 'name');
                            $tags .= $albnam;
                            while ($albid > '0') {
                                $albid = wppa_get_album_item($albid, 'a_parent');
                                if ($albid > '0') {
                                    $tags .= ',' . wppa_get_album_item($albid, 'name');
                                }
                            }
                            wppa_update_photo(array('id' => $photo['id'], 'tags' => wppa_sanitize_tags($tags)));
                            break;
                    }
                    // Test for timeout / ready
                    $lastid = $id;
                    update_option($slug . '_last', $lastid);
                    if (time() > $endtime) {
                        break;
                    }
                    // Time out
                }
            } else {
                // Nothing to do, Done anyway
                $lastid = $topid;
                wppa_log('Debug', 'Maintenance proc ' . $slug . ': Done!');
            }
            break;
            // End process photos
            // Single action maintenance modules
            //		case 'wppa_list_index':
            //			break;
            //		case 'wppa_blacklist_user':
            //			break;
            //		case 'wppa_un_blacklist_user':
            //			break;
            //		case 'wppa_rating_clear':
            //			break;
            //		case 'wppa_viewcount_clear':
            //			break;
            //		case 'wppa_iptc_clear':
            //			break;
            //		case 'wppa_exif_clear':
            //			break;
        // End process photos
        // Single action maintenance modules
        //		case 'wppa_list_index':
        //			break;
        //		case 'wppa_blacklist_user':
        //			break;
        //		case 'wppa_un_blacklist_user':
        //			break;
        //		case 'wppa_rating_clear':
        //			break;
        //		case 'wppa_viewcount_clear':
        //			break;
        //		case 'wppa_iptc_clear':
        //			break;
        //		case 'wppa_exif_clear':
        //			break;
        default:
            $errtxt = 'Unimplemented maintenance slug: ' . strip_tags($slug);
    }
    // either $albums / $photos has been exhousted ( for this try ) or time is up
    // Post proc this try:
    switch ($slug) {
        case 'wppa_sync_cloud':
            if (count($to_delete_from_cloudinary) > 0) {
                wppa_delete_from_cloudinary($to_delete_from_cloudinary);
            }
            break;
    }
    // Find togo
    if ($slug == 'wppa_cleanup') {
        $togo = $topid - $lastid;
    } else {
        $togo = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . $table . "` WHERE `id` > %s ", $lastid));
    }
    // Find status
    if (!$errtxt) {
        $status = $togo ? 'Working' : 'Ready';
    } else {
        $status = 'Error';
    }
    // Not done yet?
    if ($togo) {
        // If a cron job, reschedule next chunk
        if (wppa_is_cron()) {
            update_option($slug . '_togo', $togo);
            update_option($slug . '_status', 'Running cron');
            wppa_schedule_maintenance_proc($slug);
        } else {
            update_option($slug . '_togo', $togo);
            update_option($slug . '_status', 'Pending');
        }
    } else {
        // Report fixed/skipped/deleted
        if ($wppa_session[$slug . '_fixed']) {
            $status .= ' fixed:' . $wppa_session[$slug . '_fixed'];
            unset($wppa_session[$slug . '_fixed']);
        }
        if ($wppa_session[$slug . '_added']) {
            $status .= ' added:' . $wppa_session[$slug . '_added'];
            unset($wppa_session[$slug . '_added']);
        }
        if ($wppa_session[$slug . '_deleted']) {
            $status .= ' deleted:' . $wppa_session[$slug . '_deleted'];
            unset($wppa_session[$slug . '_deleted']);
        }
        if ($wppa_session[$slug . '_skipped']) {
            $status .= ' skipped:' . $wppa_session[$slug . '_skipped'];
            unset($wppa_session[$slug . '_skipped']);
        }
        // Re-Init options
        update_option($slug . '_togo', '');
        update_option($slug . '_status', '');
        update_option($slug . '_last', '0');
        update_option($slug . '_user', '');
        update_option($slug . '_lasttimestamp', '0');
        // Post-processing needed?
        switch ($slug) {
            case 'wppa_remake_index_albums':
            case 'wppa_remake_index_photos':
                $wpdb->query("DELETE FROM `" . WPPA_INDEX . "` WHERE `albums` = '' AND `photos` = ''");
                // Remove empty entries
                delete_option('wppa_index_need_remake');
                break;
            case 'wppa_apply_new_photodesc_all':
            case 'wppa_append_to_photodesc':
            case 'wppa_remove_from_photodesc':
                update_option('wppa_remake_index_photos_status', __('Required', 'wp-photo-album-plus'));
                break;
            case 'wppa_regen_thumbs':
                wppa_bump_thumb_rev();
                break;
            case 'wppa_file_system':
                wppa_update_option('wppa_file_system', $to);
                $reload = 'reload';
                break;
            case 'wppa_remake':
                wppa_bump_photo_rev();
                wppa_bump_thumb_rev();
                break;
            case 'wppa_edit_tag':
                wppa_clear_taglist();
                if (wppa_switch('search_tags')) {
                    update_option('wppa_remake_index_photos_status', __('Required', 'wp-photo-album-plus'));
                }
                $reload = 'reload';
                break;
            case 'wppa_sanitize_tags':
                wppa_clear_taglist();
                break;
            case 'wppa_sanitize_cats':
                wppa_clear_catlist();
                break;
            case 'wppa_test_proc':
                wppa_clear_taglist();
                break;
            case 'wppa_sync_cloud':
                unset($wppa_session['cloudinary_ids']);
                break;
        }
        wppa_log('Obs', 'Maintenance proc ' . $slug . ' completed');
    }
    wppa_save_session();
    if (wppa_is_cron()) {
        wppa_log('obs', $errtxt . '||' . $slug . '||' . $status . '||' . $togo . '||' . $reload);
    }
    return $errtxt . '||' . $slug . '||' . $status . '||' . $togo . '||' . $reload;
}
function wppa_setup($force = false)
{
    global $silent;
    global $wpdb;
    global $wppa_revno;
    global $current_user;
    global $wppa_error;
    $old_rev = get_option('wppa_revision', '100');
    // If not a new install, remove obsolete tempfiles
    if ($old_rev > '100') {
        wppa_delete_obsolete_tempfiles();
    }
    if ($old_rev == $wppa_revno && !$force) {
        return;
    }
    // Nothing to do here
    wppa_clear_cache(true);
    // Clear cache
    delete_option('wppa_dismiss_admin_notice_scripts_are_obsolete');
    $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 text NOT NULL,\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\tcrypt 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 text 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\tclicks 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\tcrypt tinytext NOT NULL,\r\n\t\t\t\t\tPRIMARY KEY  (id),\r\n\t\t\t\t\tKEY albumkey (album),\r\n\t\t\t\t\tKEY statuskey (status(6))\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 AUTO_INCREMENT,\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 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++;
    }
    // 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');
        }
        if ($old_rev <= '6319') {
            if (get_option('wppa_cre_uploads_htaccess', 'no') == 'no') {
                update_option('wppa_cre_uploads_htaccess', 'remove');
            }
            if (get_option('wppa_cre_uploads_htaccess', 'no') == 'yes') {
                update_option('wppa_cre_uploads_htaccess', 'grant');
            }
        }
        if ($old_rev <= '6403') {
            wppa_copy_setting('wppa_thumbsize', 'wppa_film_thumbsize');
        }
        if ($old_rev <= '6408') {
            if (get_option('wppa_comment_email_required', 'yes')) {
                update_option('wppa_comment_email_required', 'required', false);
            } else {
                update_option('wppa_comment_email_required', 'none', false);
            }
        }
        if ($old_rev <= '6410') {
            @$wpdb->query("UPDATE `wp_options` SET `autoload` = 'no' WHERE `option_name` LIKE 'wppa_%'");
        }
        if ($old_rev <= '6411') {
            $old = get_option('wppa_upload_edit', 'no');
            if ($old == 'no') {
                update_option('wppa_upload_edit', 'none', false);
            }
            if ($old == 'yes') {
                update_option('wppa_upload_edit', 'classic', false);
            }
        }
        if ($old_rev <= '6414') {
            if (get_option('wppa_upload_edit', 'no') != 'no') {
                update_option('wppa_upload_delete', 'yes');
            }
            if (get_option('wppa_upload_edit_users') == 'equalname') {
                update_option('wppa_upload_edit_users', 'owner');
            }
        }
        if ($old_rev <= '6417') {
            $logfile = ABSPATH . 'wp-content/wppa-depot/admin/error.log';
            if (is_file($logfile)) {
                unlink($logfile);
            }
            update_option('wppa_album_crypt_9', wppa_get_unique_album_crypt());
        }
        if ($old_rev <= '6504') {
            wppa_rename_setting('wppa_widgettitle', 'wppa_potd_title');
            wppa_rename_setting('wppa_widget_linkurl', 'wppa_potd_linkurl');
            wppa_rename_setting('wppa_widget_linktitle', 'wppa_potd_linktitle');
            wppa_rename_setting('wppa_widget_subtitle', 'wppa_potd_subtitle');
            wppa_rename_setting('wppa_widget_counter', 'wppa_potd_counter');
            wppa_rename_setting('wppa_widget_album', 'wppa_potd_album');
            wppa_rename_setting('wppa_widget_status_filter', 'wppa_potd_status_filter');
            wppa_rename_setting('wppa_widget_method', 'wppa_potd_method');
            wppa_rename_setting('wppa_widget_period', 'wppa_potd_period');
        }
        if ($old_rev <= '6600') {
            wppa_create_pl_htaccess(get_option('wppa_pl_dirname', 'wppa-pl'));
            // Remake due to fix in wppa_create_pl_htaccess() and wppa_get_source_pl()
            if (get_option('wppa_run_wpautop_on_desc') == 'yes') {
                wppa_update_option('wppa_wpautop_on_desc', 'wpautop');
            }
            if (get_option('wppa_run_wpautop_on_desc') == 'no') {
                wppa_update_option('wppa_wpautop_on_desc', 'nil');
            }
        }
        if ($old_rev <= '6601') {
            if (get_option('wppa_bc_url', 'nil') != 'nil') {
                update_option('wppa_bc_url', str_replace('/images/', '/img/', get_option('wppa_bc_url', 'nil')));
            }
        }
        if ($old_rev <= '6602') {
            if (get_option('wppa_show_treecount') == 'yes') {
                wppa_update_option('wppa_show_treecount', 'detail');
            }
            if (get_option('wppa_show_treecount') == 'no') {
                wppa_update_option('wppa_show_treecount', '-none-');
            }
            if (get_option('wppa_count_on_title') == 'yes') {
                wppa_update_option('wppa_count_on_title', 'self');
            }
            if (get_option('wppa_count_on_title') == 'no') {
                wppa_update_option('wppa_count_on_title', '-none-');
            }
        }
        if ($old_rev <= '6606') {
            if (get_option('wppa_rating_dayly') == 'no') {
                wppa_update_option('wppa_rating_dayly', '0');
            }
        }
    }
    // 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
        }
    }
    if (is_file(WPPA_PATH . '/wppa-dynamic.css')) {
        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'));
        }
    }
    wppa_schedule_cleanup();
}
function wppa_create_album_entry($args)
{
    global $wpdb;
    $args = wp_parse_args((array) $args, array('id' => '0', 'name' => __('New Album', 'wp-photo-album-plus'), 'description' => '', 'a_order' => '0', 'main_photo' => wppa_opt('main_photo'), 'a_parent' => wppa_opt('default_parent'), 'p_order_by' => '0', 'cover_linktype' => wppa_opt('default_album_linktype'), 'cover_linkpage' => '0', 'owner' => wppa_get_user(), 'timestamp' => time(), 'modified' => time(), 'upload_limit' => wppa_opt('upload_limit_count') . '/' . wppa_opt('upload_limit_time'), 'alt_thumbsize' => '0', 'default_tags' => '', 'cover_type' => '', 'suba_order_by' => '', 'views' => '0', 'cats' => '', 'scheduledtm' => '', 'crypt' => wppa_get_unique_album_crypt()));
    if (!wppa_is_id_free(WPPA_ALBUMS, $args['id'])) {
        $args['id'] = wppa_nextkey(WPPA_ALBUMS);
    }
    $query = $wpdb->prepare("INSERT INTO `" . WPPA_ALBUMS . "` ( \t`id`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`name`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`description`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`a_order`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`main_photo`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`a_parent`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`p_order_by`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`cover_linktype`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`cover_linkpage`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`owner`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`timestamp`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`modified`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`upload_limit`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`alt_thumbsize`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`default_tags`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`cover_type`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`suba_order_by`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`views`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`cats`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`scheduledtm`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`crypt`\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tVALUES ( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s ,%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s )", $args['id'], trim($args['name']), trim($args['description']), $args['a_order'], $args['main_photo'], $args['a_parent'], $args['p_order_by'], $args['cover_linktype'], $args['cover_linkpage'], $args['owner'], $args['timestamp'], $args['modified'], $args['upload_limit'], $args['alt_thumbsize'], $args['default_tags'], $args['cover_type'], $args['suba_order_by'], $args['views'], $args['cats'], $args['scheduledtm'], $args['crypt']);
    $iret = $wpdb->query($query);
    if ($iret) {
        return $args['id'];
    } else {
        return false;
    }
}