function wppa_insert_photo($file = '', $alb = '', $name = '', $desc = '', $porder = '0', $id = '0', $linkurl = '', $linktitle = '')
{
    global $wpdb;
    global $warning_given_small;
    $album = wppa_cache_album($alb);
    if (!wppa_allow_uploads($alb)) {
        if (is_admin() && !wppa('ajax')) {
            wppa_error_message(sprintf(__('Album %s is full', 'wp-photo-album-plus'), wppa_get_album_name($alb)));
        } else {
            wppa_alert(sprintf(__('Album %s is full', 'wp-photo-album-plus'), wppa_get_album_name($alb)));
        }
        return false;
    }
    if ($file != '' && $alb != '') {
        // Get the name if not given
        if ($name == '') {
            $name = basename($file);
        }
        // Sanitize name
        $filename = wppa_sanitize_file_name($name);
        $name = wppa_sanitize_photo_name($name);
        // If not dups allowed and its already here, quit
        if (isset($_POST['wppa-nodups']) || wppa_switch('void_dups')) {
            $exists = wppa_file_is_in_album($filename, $alb);
            if ($exists) {
                if (isset($_POST['del-after-p'])) {
                    unlink($file);
                    $msg = __('Photo %s already exists in album number %s. Removed from depot.', 'wp-photo-album-plus');
                } else {
                    $msg = __('Photo %s already exists in album number %s.', 'wp-photo-album-plus');
                }
                wppa_warning_message(sprintf($msg, $name, $alb));
                return false;
            }
        }
        // Verify file exists
        if (!wppa('is_remote') && !file_exists($file)) {
            if (!is_dir(dirname($file))) {
                wppa_error_message('Error: Directory ' . dirname($file) . ' does not exist.');
                return false;
            }
            if (!is_writable(dirname($file))) {
                wppa_error_message('Error: Directory ' . dirname($file) . ' is not writable.');
                return false;
            }
            wppa_error_message('Error: File ' . $file . ' does not exist.');
            return false;
        }
        //		else {
        //			wppa_ok_message( 'Good: File '.$file.' exists.' );
        //		}
        // Get and verify the size
        $img_size = getimagesize($file);
        if ($img_size) {
            if (wppa_check_memory_limit('', $img_size['0'], $img_size['1']) === false) {
                wppa_error_message(sprintf(__('ERROR: Attempt to upload a photo that is too large to process (%s).', 'wp-photo-album-plus'), $name) . wppa_check_memory_limit());
                wppa('ajax_import_files_error', __('Too big', 'wp-photo-album-plus'));
                return false;
            }
            if (!$warning_given_small && ($img_size['0'] < wppa_get_minisize() && $img_size['1'] < wppa_get_minisize())) {
                wppa_warning_message(__('WARNING: You are uploading photos that are too small. Photos must be larger than the thumbnail size and larger than the coverphotosize.', 'wp-photo-album-plus'));
                wppa('ajax_import_files_error', __('Too small', 'wp-photo-album-plus'));
                $warning_given_small = true;
            }
        } else {
            wppa_error_message(__('ERROR: Unable to retrieve image size of', 'wp-photo-album-plus') . ' ' . $name . ' ' . __('Are you sure it is a photo?', 'wp-photo-album-plus'));
            wppa('ajax_import_files_error', __('No imagesize', 'wp-photo-album-plus'));
            return false;
        }
        // Get ext based on mimetype, regardless of ext
        switch ($img_size[2]) {
            // mime type
            case 1:
                $ext = 'gif';
                break;
            case 2:
                $ext = 'jpg';
                break;
            case 3:
                $ext = 'png';
                break;
            default:
                wppa_error_message(__('Unsupported mime type encountered:', 'wp-photo-album-plus') . ' ' . $img_size[2] . '.');
                return false;
        }
        // Get an id if not yet there
        if ($id == '0') {
            $id = wppa_nextkey(WPPA_PHOTOS);
        }
        // Get opt deflt desc if empty
        if ($desc == '' && wppa_switch('apply_newphoto_desc')) {
            $desc = stripslashes(wppa_opt('newphoto_description'));
        }
        // Reset rating
        $mrat = '0';
        // Find ( new ) owner
        $owner = wppa_get_user();
        // Validate album
        if (!is_numeric($alb) || $alb < '1') {
            wppa_error_message(__('Album not known while trying to add a photo', 'wp-photo-album-plus'));
            return false;
        }
        if (!wppa_have_access($alb)) {
            wppa_error_message(sprintf(__('Album %s does not exist or is not accessable while trying to add a photo', 'wp-photo-album-plus'), $alb));
            return false;
        }
        $status = wppa_switch('upload_moderate') && !current_user_can('wppa_admin') ? 'pending' : 'publish';
        // Add photo to db
        $id = wppa_create_photo_entry(array('id' => $id, 'album' => $alb, 'ext' => $ext, 'name' => $name, 'p_order' => $porder, 'description' => $desc, 'linkurl' => $linkurl, 'linktitle' => $linktitle, 'owner' => $owner, 'status' => $status, 'filename' => $filename));
        if (!$id) {
            wppa_error_message(__('Could not insert photo.', 'wp-photo-album-plus'));
        } else {
            // Save the source
            wppa_save_source($file, $filename, $alb);
            wppa_flush_treecounts($alb);
            wppa_update_album(array('id' => $alb, 'modified' => time()));
            wppa_flush_upldr_cache('photoid', $id);
        }
        // Make the photo files
        if (wppa_make_the_photo_files($file, $id, $ext)) {
            // Repair photoname if not supplied and not standard
            wppa_set_default_name($id, $name);
            // Tags
            wppa_set_default_tags($id);
            // Index
            wppa_index_add('photo', $id);
            // and add watermark ( optionally ) to fullsize image only
            wppa_add_watermark($id);
            // also to thumbnail?
            if (wppa_switch('watermark_thumbs')) {
                wppa_create_thumbnail($id);
            }
            // Is it a default coverimage?
            wppa_check_coverimage($id);
            return $id;
        }
    } else {
        wppa_error_message(__('ERROR: Unknown file or album.', 'wp-photo-album-plus'));
        return false;
    }
}
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_frontend_file_upload($file, $alb)
{
    global $wpdb;
    // Log upload attempt
    wppa_log('Upl', 'FE Upload attempt of file ' . $file['name'] . ', size=' . filesize($file['tmp_name']));
    $album = wppa_cache_album($alb);
    if (!wppa_allow_uploads($alb) || !wppa_allow_user_uploads()) {
        wppa_alert(__('Max uploads reached', 'wp-photo-album-plus'));
        return false;
    }
    if ($file['error'] != '0') {
        wppa_alert(__('Error during upload', 'wp-photo-album-plus'));
        return false;
    }
    $imgsize = getimagesize($file['tmp_name']);
    if (!is_array($imgsize)) {
        wppa_alert(__('Uploaded file is not an image', 'wp-photo-album-plus'));
        return false;
    }
    if ($imgsize[2] < 1 || $imgsize[2] > 3) {
        wppa_alert(sprintf(__('Only gif, jpg and png image files are supported. Returned filetype = %d.', 'wp-photo-album-plus'), $imagesize[2]));
        return false;
    }
    $ms = wppa_opt('upload_fronend_maxsize');
    if ($ms) {
        // Max size configured
        if ($imgsize[0] > $ms || $imgsize[0] > $ms) {
            wppa_alert(sprintf(__('Uploaded file is larger than the allowed maximum of %d x %d pixels.', 'wp-photo-album-plus'), $ms, $ms));
            return false;
        }
    }
    if (wppa_switch('void_dups')) {
        // Check for already exists
        if (wppa_file_is_in_album(wppa_sanitize_file_name($file['name']), $alb)) {
            wppa_alert(sprintf(__('Uploaded file %s already exists in this album.', 'wp-photo-album-plus'), wppa_sanitize_file_name($file['name'])));
            return false;
        }
    }
    $mayupload = wppa_check_memory_limit('', $imgsize[0], $imgsize[1]);
    if ($mayupload === false) {
        $maxsize = wppa_check_memory_limit(false);
        if (is_array($maxsize)) {
            wppa_alert(sprintf(__('The image is too big. Max photo size: %d x %d (%2.1f MegaPixel)', 'wp-photo-album-plus'), $maxsize['maxx'], $maxsize['maxy'], $maxsize['maxp'] / (1024 * 1024)));
            return false;
        }
    }
    switch ($imgsize[2]) {
        // mime type
        case 1:
            $ext = 'gif';
            break;
        case 2:
            $ext = 'jpg';
            break;
        case 3:
            $ext = 'png';
            break;
    }
    if (wppa_get_post('user-name')) {
        $name = wppa_get_post('user-name');
    } else {
        $name = $file['name'];
    }
    $name = wppa_sanitize_photo_name($name);
    $desc = balanceTags(wppa_get_post('user-desc'), true);
    $linktarget = '_self';
    $status = wppa_switch('upload_moderate') && !current_user_can('wppa_admin') ? 'pending' : 'publish';
    $filename = wppa_sanitize_file_name($file['name']);
    $id = wppa_create_photo_entry(array('album' => $alb, 'ext' => $ext, 'name' => $name, 'description' => $desc, 'status' => $status, 'filename' => $filename));
    if (!$id) {
        wppa_alert(__('Could not insert photo into db.', 'wp-photo-album-plus'));
        return false;
    } else {
        wppa_save_source($file['tmp_name'], $filename, $alb);
        wppa_update_album(array('id' => $alb, 'modified' => time()));
        wppa_flush_treecounts($alb);
        wppa_flush_upldr_cache('photoid', $id);
    }
    if (wppa_make_the_photo_files($file['tmp_name'], $id, $ext)) {
        // Repair photoname if not standard
        if (!wppa_get_post('user-name')) {
            wppa_set_default_name($id, $file['name']);
        }
        // Custom data
        if (wppa_switch('fe_custom_fields')) {
            $custom_data = array('', '', '', '', '', '', '', '', '', '');
            for ($i = '0'; $i < '10'; $i++) {
                if (isset($_POST['wppa-user-custom-' . $i])) {
                    $custom_data[$i] = strip_tags($_POST['wppa-user-custom-' . $i]);
                }
            }
            wppa_update_photo(array('id' => $id, 'custom' => serialize($custom_data)));
        }
        // Default tags
        wppa_set_default_tags($id);
        // Custom tags
        $tags = wppa_get_photo_item($id, 'tags');
        $oldt = $tags;
        for ($i = '1'; $i < '4'; $i++) {
            if (isset($_POST['wppa-user-tags-' . $i])) {
                // Existing tags
                $tags .= ',' . implode(',', $_POST['wppa-user-tags-' . $i]);
            }
        }
        if (isset($_POST['wppa-new-tags'])) {
            // New tags
            $newt = $_POST['wppa-new-tags'];
            $tags .= ',' . $newt;
        } else {
            $newt = '';
        }
        $tags = wppa_sanitize_tags(str_replace(array('\'', '"'), ',', wppa_filter_iptc(wppa_filter_exif($tags, $id), $id)));
        if ($tags != $oldt) {
            // Added tag(s)
            wppa_update_photo(array('id' => $id, 'tags' => $tags));
        }
        // Index
        wppa_index_add('photo', $id);
        // Tags
        if ($tags) {
            wppa_clear_taglist();
            // Forces recreation
        }
        // and add watermark ( optionally ) to fullsize image only
        wppa_add_watermark($id);
        // Also to thumbnail?
        if (wppa_switch('watermark_thumbs')) {
            wppa_create_thumbnail($id);
            // create new thumb
        }
        // Is it a default coverimage?
        wppa_check_coverimage($id);
        // Mail
        if (wppa_switch('upload_notify')) {
            $to = get_bloginfo('admin_email');
            $subj = sprintf(__('New photo uploaded: %s', 'wp-photo-album-plus'), $name);
            $cont['0'] = sprintf(__('User %1$s uploaded photo %2$s into album %3$s', 'wp-photo-album-plus'), wppa_get_user(), $id, wppa_get_album_name($alb));
            if (wppa_switch('upload_moderate') && !current_user_can('wppa_admin')) {
                $cont['1'] = __('This upload requires moderation', 'wp-photo-album-plus');
                $cont['2'] = '<a href="' . get_admin_url() . 'admin.php?page=wppa_admin_menu&tab=pmod&photo=' . $id . '" >' . __('Moderate manage photo', 'wp-photo-album-plus') . '</a>';
            } else {
                $cont['1'] = __('Details:', 'wp-photo-album-plus');
                $cont['1'] .= ' <a href="' . get_admin_url() . 'admin.php?page=wppa_admin_menu&tab=pmod&photo=' . $id . '" >' . __('Manage photo', 'wp-photo-album-plus') . '</a>';
            }
            wppa_send_mail($to, $subj, $cont, $id);
        }
        return true;
    } else {
        return false;
    }
}
function wppa_do_maintenance_proc($slug)
{
    global $wpdb;
    global $thumb;
    global $wppa_opt;
    global $wppa_session;
    global $wppa_supported_video_extensions;
    global $wppa_supported_audio_extensions;
    // Check for multiple maintenance procs
    if (!wppa_switch('wppa_maint_ignore_concurrency_error')) {
        $all_slugs = array('wppa_remake_index_albums', 'wppa_remove_empty_albums', 'wppa_remake_index_photos', 'wppa_apply_new_photodesc_all', 'wppa_append_to_photodesc', 'wppa_remove_from_photodesc', 'wppa_remove_file_extensions', 'wppa_readd_file_extensions', 'wppa_regen_thumbs', 'wppa_rerate', 'wppa_recup', 'wppa_file_system', 'wppa_cleanup', 'wppa_remake', 'wppa_list_index', 'wppa_blacklist_user', 'wppa_un_blacklist_user', 'wppa_rating_clear', 'wppa_viewcount_clear', 'wppa_iptc_clear', 'wppa_exif_clear', 'wppa_watermark_all', 'wppa_create_all_autopages', 'wppa_leading_zeros', 'wppa_add_gpx_tag', 'wppa_optimize_ewww', 'wppa_comp_sizes', 'wppa_edit_tag');
        foreach (array_keys($all_slugs) as $key) {
            if ($all_slugs[$key] != $slug) {
                if (get_option($all_slugs[$key] . '_togo', '0')) {
                    // Process running
                    return __('You can run only one maintenance procedure at a time', 'wppa') . '||' . $slug . '||' . __('Error', 'wppa') . '||' . '' . '||' . '';
                }
            }
        }
    }
    // Lock this proc
    update_option($slug . '_user', wppa_get_user());
    // Initialize
    $endtime = time() + '5';
    // Allow for 5 seconds
    $chunksize = '1000';
    $lastid = strval(intval(get_option($slug . '_last', '0')));
    $errtxt = '';
    $id = '0';
    $topid = '0';
    $reload = '';
    if (!isset($wppa_session)) {
        $wppa_session = array();
    }
    if (!isset($wppa_session[$slug . '_fixed'])) {
        $wppa_session[$slug . '_fixed'] = '0';
    }
    if (!isset($wppa_session[$slug . '_deleted'])) {
        $wppa_session[$slug . '_deleted'] = '0';
    }
    if (!isset($wppa_session[$slug . '_skipped'])) {
        $wppa_session[$slug . '_skipped'] = '0';
    }
    if ($lastid == '0') {
        $wppa_session[$slug . '_fixed'] = '0';
        $wppa_session[$slug . '_deleted'] = '0';
        $wppa_session[$slug . '_skipped'] = '0';
    }
    // Pre-processing needed?
    if ($lastid == '0') {
        switch ($slug) {
            case 'wppa_remake_index_albums':
                $wpdb->query("UPDATE `" . WPPA_INDEX . "` SET `albums` = ''");
                break;
            case 'wppa_remake_index_photos':
                $wpdb->query("UPDATE `" . WPPA_INDEX . "` SET `photos` = ''");
                wppa_index_compute_skips();
                break;
            case 'wppa_recup':
                $wpdb->query("DELETE FROM `" . WPPA_IPTC . "` WHERE `photo` <> '0'");
                $wpdb->query("DELETE FROM `" . WPPA_EXIF . "` WHERE `photo` <> '0'");
                break;
            case 'wppa_file_system':
                if (get_option('wppa_file_system') == 'flat') {
                    update_option('wppa_file_system', 'to-tree');
                }
                if (get_option('wppa_file_system') == 'tree') {
                    update_option('wppa_file_system', 'to-flat');
                }
                break;
            case 'wppa_cleanup':
                $orphan_album = get_option('wppa_orphan_album', '0');
                $album_exists = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM`" . WPPA_ALBUMS . "` WHERE `id` = %s", $orphan_album));
                if (!$album_exists) {
                    $orphan_album = false;
                }
                if (!$orphan_album) {
                    $orphan_album = wppa_create_album_entry(array('name' => __('Orphan photos', 'wppa'), 'a_parent' => '-1', 'description' => __('This album contains refound lost photos', 'wppa')));
                    update_option('wppa_orphan_album', $orphan_album);
                }
                break;
        }
    }
    // Dispatch on albums / photos / single actions
    switch ($slug) {
        case 'wppa_remake_index_albums':
        case 'wppa_remove_empty_albums':
            // Process albums
            $table = WPPA_ALBUMS;
            $topid = $wpdb->get_var("SELECT `id` FROM `" . WPPA_ALBUMS . "` ORDER BY `id` DESC LIMIT 1");
            $albums = $wpdb->get_results("SELECT * FROM `" . WPPA_ALBUMS . "` WHERE `id` > " . $lastid . " ORDER BY `id` LIMIT 100", ARRAY_A);
            wppa_cache_album('add', $albums);
            if ($albums) {
                foreach ($albums as $album) {
                    $id = $album['id'];
                    switch ($slug) {
                        case 'wppa_remake_index_albums':
                            wppa_index_add('album', $id);
                            break;
                        case 'wppa_remove_empty_albums':
                            $p = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s", $id));
                            $a = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_ALBUMS . "` WHERE `a_parent` = %s", $id));
                            if (!$a && !$p) {
                                $wpdb->query($wpdb->prepare("DELETE FROM `" . WPPA_ALBUMS . "` WHERE `id` = %s", $id));
                                wppa_delete_album_source($id);
                                wppa_flush_treecounts($id);
                                wppa_index_remove('album', $id);
                            }
                            break;
                    }
                    // Test for timeout / ready
                    $lastid = $id;
                    update_option($slug . '_last', $lastid);
                    if (time() > $endtime) {
                        break;
                    }
                    // Time out
                }
            } else {
                // Nothing to do, Done anyway
                $lastid = $topid;
            }
            break;
            // End process albums
        // End process albums
        case 'wppa_remake_index_photos':
            $chunksize = '100';
        case 'wppa_apply_new_photodesc_all':
        case 'wppa_append_to_photodesc':
        case 'wppa_remove_from_photodesc':
        case 'wppa_remove_file_extensions':
        case 'wppa_readd_file_extensions':
        case 'wppa_regen_thumbs':
        case 'wppa_rerate':
        case 'wppa_recup':
        case 'wppa_file_system':
        case 'wppa_cleanup':
        case 'wppa_remake':
        case 'wppa_watermark_all':
        case 'wppa_create_all_autopages':
        case 'wppa_leading_zeros':
        case 'wppa_add_gpx_tag':
        case 'wppa_optimize_ewww':
        case 'wppa_comp_sizes':
        case 'wppa_edit_tag':
            // Process photos
            $table = WPPA_PHOTOS;
            if ($slug == 'wppa_cleanup') {
                $topid = get_option('wppa_' . WPPA_PHOTOS . '_lastkey', '1') * 10;
                $photos = array();
                for ($i = $lastid + '1'; $i <= $topid; $i++) {
                    $photos[]['id'] = $i;
                }
            } else {
                $topid = $wpdb->get_var("SELECT `id` FROM `" . WPPA_PHOTOS . "` ORDER BY `id` DESC LIMIT 1");
                $photos = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `id` > " . $lastid . " ORDER BY `id` LIMIT " . $chunksize, ARRAY_A);
            }
            if ($slug == 'wppa_edit_tag') {
                $edit_tag = get_option('wppa_tag_to_edit');
                $new_tag = get_option('wppa_new_tag_value');
            }
            if (!$photos && $slug == 'wppa_file_system') {
                $fs = get_option('wppa_file_system');
                if ($fs == 'to-tree') {
                    $to = 'tree';
                } elseif ($fs == 'to-flat') {
                    $to = 'flat';
                } else {
                    $to = $fs;
                }
            }
            if ($photos) {
                foreach ($photos as $photo) {
                    $thumb = $photo;
                    // Make globally known
                    $id = $photo['id'];
                    switch ($slug) {
                        case 'wppa_remake_index_photos':
                            wppa_index_add('photo', $id);
                            break;
                        case 'wppa_apply_new_photodesc_all':
                            $value = $wppa_opt['wppa_newphoto_description'];
                            $description = trim($value);
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_append_to_photodesc':
                            $value = trim($wppa_opt['wppa_append_text']);
                            if (!$value) {
                                return 'Unexpected error: missing text to append||' . $slug . '||Error||0';
                            }
                            $description = rtrim($photo['description'] . ' ' . $value);
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_remove_from_photodesc':
                            $value = trim($wppa_opt['wppa_remove_text']);
                            if (!$value) {
                                return 'Unexpected error: missing text to remove||' . $slug . '||Error||0';
                            }
                            $description = rtrim(str_replace($value, '', $photo['description']));
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_remove_file_extensions':
                            if (!wppa_is_video($id)) {
                                $name = str_replace(array('.jpg', '.png', '.gif', '.JPG', '.PNG', '.GIF'), '', $photo['name']);
                                if ($name != $photo['name']) {
                                    // Modified photo name
                                    $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name, $id));
                                }
                            }
                            break;
                        case 'wppa_readd_file_extensions':
                            if (!wppa_is_video($id)) {
                                $name = str_replace(array('.jpg', '.png', 'gif', '.JPG', '.PNG', '.GIF'), '', $photo['name']);
                                if ($name == $photo['name']) {
                                    // Name had no fileextension
                                    $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name . '.' . $photo['ext'], $id));
                                }
                            }
                            break;
                        case 'wppa_regen_thumbs':
                            if (!wppa_is_video($id) || file_exists(str_replace('xxx', 'jpg', wppa_get_photo_path($id)))) {
                                wppa_create_thumbnail($id);
                            }
                            break;
                        case 'wppa_rerate':
                            wppa_rate_photo($id);
                            break;
                        case 'wppa_recup':
                            $a_ret = wppa_recuperate($id);
                            if ($a_ret['iptcfix']) {
                                $wppa_session[$slug . '_fixed']++;
                            }
                            if ($a_ret['exiffix']) {
                                $wppa_session[$slug . '_fixed']++;
                            }
                            break;
                        case 'wppa_file_system':
                            $fs = get_option('wppa_file_system');
                            if ($fs == 'to-tree' || $fs == 'to-flat') {
                                if ($fs == 'to-tree') {
                                    $from = 'flat';
                                    $to = 'tree';
                                } else {
                                    $from = 'tree';
                                    $to = 'flat';
                                }
                                // Media files
                                if (wppa_is_multi($id)) {
                                    // Can NOT use wppa_has_audio() or wppa_is_video(), they use wppa_get_photo_path() without fs switch!!
                                    $exts = array_merge($wppa_supported_video_extensions, $wppa_supported_audio_extensions);
                                    $pathfrom = wppa_get_photo_path($id, $from);
                                    $pathto = wppa_get_photo_path($id, $to);
                                    //	wppa_log( 'dbg', 'Trying: '.$pathfrom );
                                    foreach ($exts as $ext) {
                                        if (is_file(str_replace('.xxx', '.' . $ext, $pathfrom))) {
                                            //	wppa_log( 'dbg',  str_replace( '.xxx', '.'.$ext, $pathfrom ).' -> '.str_replace( '.xxx', '.'.$ext, $pathto ));
                                            @rename(str_replace('.xxx', '.' . $ext, $pathfrom), str_replace('.xxx', '.' . $ext, $pathto));
                                        }
                                    }
                                }
                                // Poster / photo
                                if (file_exists(wppa_fix_poster_ext(wppa_get_photo_path($id, $from), $id))) {
                                    @rename(wppa_fix_poster_ext(wppa_get_photo_path($id, $from), $id), wppa_fix_poster_ext(wppa_get_photo_path($id, $to), $id));
                                }
                                // Thumbnail
                                if (file_exists(wppa_fix_poster_ext(wppa_get_thumb_path($id, $from), $id))) {
                                    @rename(wppa_fix_poster_ext(wppa_get_thumb_path($id, $from), $id), wppa_fix_poster_ext(wppa_get_thumb_path($id, $to), $id));
                                }
                            }
                            break;
                        case 'wppa_cleanup':
                            $photo_files = glob(WPPA_UPLOAD_PATH . '/' . $id . '.*');
                            // Remove dirs
                            if ($photo_files) {
                                foreach (array_keys($photo_files) as $key) {
                                    if (is_dir($photo_files[$key])) {
                                        unset($photo_files[$key]);
                                    }
                                }
                            }
                            // files left? process
                            if ($photo_files) {
                                foreach ($photo_files as $photo_file) {
                                    $basename = basename($photo_file);
                                    $ext = substr($basename, strpos($basename, '.') + '1');
                                    if (!$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $id))) {
                                        // no db entry for this photo
                                        if (wppa_is_id_free(WPPA_PHOTOS, $id)) {
                                            if (wppa_create_photo_entry(array('id' => $id, 'album' => $orphan_album, 'ext' => $ext, 'filename' => $basename))) {
                                                // Can create entry
                                                $wppa_session[$slug . '_fixed']++;
                                                // Bump counter
                                                wppa_log('Debug', 'Lost photo file ' . $photo_file . ' recovered');
                                            } else {
                                                wppa_log('Debug', 'Unable to recover lost photo file ' . $photo_file . ' Create photo entry failed');
                                            }
                                        } else {
                                            wppa_log('Debug', 'Could not recover lost photo file ' . $photo_file . ' The id is not free');
                                        }
                                    }
                                }
                            }
                            break;
                        case 'wppa_remake':
                            if (wppa_remake_files('', $id)) {
                                $wppa_session[$slug . '_fixed']++;
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_watermark_all':
                            if (!wppa_is_video($id)) {
                                if (wppa_add_watermark($id)) {
                                    wppa_create_thumbnail($id);
                                    // create new thumb
                                    $wppa_session[$slug . '_fixed']++;
                                } else {
                                    $wppa_session[$slug . '_skipped']++;
                                }
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_create_all_autopages':
                            wppa_get_the_auto_page($id);
                            break;
                        case 'wppa_leading_zeros':
                            $name = $photo['name'];
                            if (wppa_is_int($name)) {
                                $target_len = wppa_opt('wppa_zero_numbers');
                                $name = strval(intval($name));
                                while (strlen($name) < $target_len) {
                                    $name = '0' . $name;
                                }
                            }
                            if ($name !== $photo['name']) {
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name, $id));
                            }
                            break;
                        case 'wppa_add_gpx_tag':
                            $tags = $photo['tags'];
                            $temp = explode('/', $photo['location']);
                            if (!isset($temp['2'])) {
                                $temp['2'] = false;
                            }
                            if (!isset($temp['3'])) {
                                $temp['3'] = false;
                            }
                            $lat = $temp['2'];
                            $lon = $temp['3'];
                            if ($lat < 0.01 && $lat > -0.01 && $lon < 0.01 && $lon > -0.01) {
                                $lat = false;
                                $lon = false;
                            }
                            if ($photo['location'] && strpos($tags, 'Gpx') === false && $lat && $lon) {
                                // Add it
                                $tags = wppa_sanitize_tags($tags . ',Gpx');
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                wppa_index_update('photo', $photo['id']);
                                wppa_clear_taglist();
                            } elseif (strpos($tags, 'Gpx') !== false && !$lat && !$lon) {
                                // Remove it
                                $tags = wppa_sanitize_tags(str_replace('Gpx', '', $tags));
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                wppa_index_update('photo', $photo['id']);
                                wppa_clear_taglist();
                            }
                            break;
                        case 'wppa_optimize_ewww':
                            $file = wppa_get_photo_path($photo['id']);
                            if (is_file($file)) {
                                ewww_image_optimizer($file, 4, false, false, false);
                            }
                            $file = wppa_get_thumb_path($photo['id']);
                            if (is_file($file)) {
                                ewww_image_optimizer($file, 4, false, false, false);
                            }
                            break;
                        case 'wppa_comp_sizes':
                            $tx = 0;
                            $ty = 0;
                            $px = 0;
                            $py = 0;
                            $file = wppa_get_photo_path($photo['id']);
                            if (is_file($file)) {
                                $temp = getimagesize($file);
                                if (is_array($temp)) {
                                    $px = $temp[0];
                                    $py = $temp[1];
                                }
                            }
                            $file = wppa_get_thumb_path($photo['id']);
                            if (is_file($file)) {
                                $temp = getimagesize($file);
                                if (is_array($temp)) {
                                    $tx = $temp[0];
                                    $ty = $temp[1];
                                }
                            }
                            wppa_update_photo(array('id' => $photo['id'], 'thumbx' => $tx, 'thumby' => $ty, 'photox' => $px, 'photoy' => $py));
                            break;
                        case 'wppa_edit_tag':
                            $phototags = explode(',', wppa_get_photo_item($photo['id'], 'tags'));
                            if (in_array($edit_tag, $phototags)) {
                                foreach (array_keys($phototags) as $key) {
                                    if ($phototags[$key] == $edit_tag) {
                                        $phototags[$key] = $new_tag;
                                    }
                                }
                                $tags = wppa_sanitize_tags(implode(',', $phototags));
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                $wppa_session[$slug . '_fixed']++;
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                    }
                    // Test for timeout / ready
                    $lastid = $id;
                    update_option($slug . '_last', $lastid);
                    if (time() > $endtime) {
                        break;
                    }
                    // Time out
                }
            } else {
                // Nothing to do, Done anyway
                $lastid = $topid;
                wppa_log('Debug', 'Maintenance proc ' . $slug . ': Done!');
            }
            break;
            // End process photos
            // Single action maintenance modules
            //		case 'wppa_list_index':
            //			break;
            //		case 'wppa_blacklist_user':
            //			break;
            //		case 'wppa_un_blacklist_user':
            //			break;
            //		case 'wppa_rating_clear':
            //			break;
            //		case 'wppa_viewcount_clear':
            //			break;
            //		case 'wppa_iptc_clear':
            //			break;
            //		case 'wppa_exif_clear':
            //			break;
        // End process photos
        // Single action maintenance modules
        //		case 'wppa_list_index':
        //			break;
        //		case 'wppa_blacklist_user':
        //			break;
        //		case 'wppa_un_blacklist_user':
        //			break;
        //		case 'wppa_rating_clear':
        //			break;
        //		case 'wppa_viewcount_clear':
        //			break;
        //		case 'wppa_iptc_clear':
        //			break;
        //		case 'wppa_exif_clear':
        //			break;
        default:
            $errtxt = 'Unimplemented maintenance slug: ' . strip_tags($slug);
    }
    // either $albums / $photos has been exhousted ( for this try ) or time is up
    if ($slug == 'wppa_cleanup') {
        $togo = $topid - $lastid;
    } else {
        $togo = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . $table . "` WHERE `id` > %s ", $lastid));
    }
    $status = $togo ? 'Pending' : 'Ready';
    if ($togo) {
        update_option($slug . '_togo', $togo);
        update_option($slug . '_status', $status);
    } else {
        // Really done
        // Report fixed/skipped/deleted
        if ($wppa_session[$slug . '_fixed']) {
            $status .= ' fixed:' . $wppa_session[$slug . '_fixed'];
            unset($wppa_session[$slug . '_fixed']);
        }
        if ($wppa_session[$slug . '_skipped']) {
            $status .= ' skipped:' . $wppa_session[$slug . '_skipped'];
            unset($wppa_session[$slug . '_skipped']);
        }
        if ($wppa_session[$slug . '_deleted']) {
            $status .= ' deleted:' . $wppa_session[$slug . '_deleted'];
            unset($wppa_session[$slug . '_deleted']);
        }
        // Re-Init options
        delete_option($slug . '_togo', '');
        delete_option($slug . '_status', '');
        delete_option($slug . '_last', '0');
        delete_option($slug . '_user', '');
        // Post-processing needed?
        switch ($slug) {
            case 'wppa_remake_index_albums':
            case 'wppa_remake_index_photos':
                $wpdb->query("DELETE FROM `" . WPPA_INDEX . "` WHERE `albums` = '' AND `photos` = ''");
                // Remove empty entries
                delete_option('wppa_index_need_remake');
                break;
            case 'wppa_apply_new_photodesc_all':
            case 'wppa_append_to_photodesc':
            case 'wppa_remove_from_photodesc':
                update_option('wppa_remake_index_photos_status', __('Required', 'wppa'));
                break;
            case 'wppa_regen_thumbs':
                wppa_bump_thumb_rev();
                break;
            case 'wppa_file_system':
                wppa_update_option('wppa_file_system', $to);
                $reload = 'reload';
                break;
            case 'wppa_remake':
                wppa_bump_photo_rev();
                wppa_bump_thumb_rev();
                break;
            case 'wppa_edit_tag':
                wppa_clear_taglist();
                $reload = 'reload';
                break;
        }
    }
    return $errtxt . '||' . $slug . '||' . $status . '||' . $togo . '||' . $reload;
}
function wppa_do_frontend_file_upload($file, $alb)
{
    global $wpdb;
    global $wppa_supported_video_extensions;
    global $wppa_supported_audio_extensions;
    // Log upload attempt
    wppa_log('Upl', 'FE Upload attempt of file ' . $file['name'] . ', size=' . filesize($file['tmp_name']));
    $album = wppa_cache_album($alb);
    // Legal here?
    if (!wppa_allow_uploads($alb) || !wppa_allow_user_uploads()) {
        wppa_alert(__('Max uploads reached', 'wp-photo-album-plus'));
        return false;
    }
    // No error during upload?
    if ($file['error'] != '0') {
        wppa_alert(__('Error during upload', 'wp-photo-album-plus'));
        return false;
    }
    // Find the filename
    $filename = wppa_sanitize_file_name($file['name']);
    $filename = wppa_strip_ext($filename);
    // See if this filename with any extension already exists in this album
    $id = $wpdb->get_var("SELECT `id` FROM `" . WPPA_PHOTOS . "` WHERE `filename` LIKE '" . $filename . ".%' AND `album` = " . $alb);
    // Addition to an av item?
    if ($id) {
        $is_av = wppa_get_photo_item($id, 'ext') == 'xxx';
    } else {
        $is_av = false;
    }
    // see if audio / video and process
    if (wppa_switch('enable_video') && wppa_switch('user_upload_video_on') && in_array(strtolower(wppa_get_ext($file['name'])), $wppa_supported_video_extensions) || wppa_switch('enable_audio') && wppa_switch('user_upload_audio_on') && in_array(strtolower(wppa_get_ext($file['name'])), $wppa_supported_audio_extensions)) {
        $is_av = true;
        // Find the name
        if (wppa_get_post('user-name')) {
            $name = wppa_get_post('user-name');
        } else {
            $name = $file['name'];
        }
        $name = wppa_sanitize_photo_name($name);
        $filename .= '.xxx';
        // update entry
        if ($id) {
            wppa_update_photo(array('id' => $id, 'ext' => 'xxx', 'filename' => $filename));
        }
        // Add new entry
        if (!$id) {
            $id = wppa_create_photo_entry(array('album' => $alb, 'filename' => $filename, 'ext' => 'xxx', 'name' => $name, 'description' => balanceTags(wppa_get_post('user-desc'), true)));
            if (!$id) {
                wppa_alert(__('Could not insert media into db.', 'wp-photo-album-plus'));
                return false;
            }
        }
        // Housekeeping
        wppa_update_album(array('id' => $alb, 'modified' => time()));
        wppa_flush_treecounts($alb);
        wppa_flush_upldr_cache('photoid', $id);
        // Add video filetype
        $ext = strtolower(wppa_get_ext($file['name']));
        $newpath = wppa_strip_ext(wppa_get_photo_path($id)) . '.' . $ext;
        copy($file['tmp_name'], $newpath);
        // Repair name if not standard
        if (!wppa_get_post('user-name')) {
            wppa_set_default_name($id, $file['name']);
        }
        // tags
        wppa_fe_add_tags($id);
        // custom
        wppa_fe_add_custom($id);
        // Done!
        return $id;
    }
    // If not already an existing audio / video; Forget the id from a previously found item with the same filename.
    if (!$is_av) {
        $id = false;
    }
    // Is it an image?
    $imgsize = getimagesize($file['tmp_name']);
    if (!is_array($imgsize)) {
        wppa_alert(__('Uploaded file is not an image', 'wp-photo-album-plus'));
        return false;
    }
    // Is it a supported image filetype?
    if ($imgsize[2] != IMAGETYPE_GIF && $imgsize[2] != IMAGETYPE_JPEG && $imgsize[2] != IMAGETYPE_PNG) {
        wppa_alert(sprintf(__('Only gif, jpg and png image files are supported. Returned info = %s.', 'wp-photo-album-plus'), wppa_serialize($imgsize)), false, false);
        return false;
    }
    // Is it not too big?
    $ms = wppa_opt('upload_fronend_maxsize');
    if ($ms) {
        // Max size configured
        if ($imgsize[0] > $ms || $imgsize[1] > $ms) {
            wppa_alert(sprintf(__('Uploaded file is larger than the allowed maximum of %d x %d pixels.', 'wp-photo-album-plus'), $ms, $ms));
            return false;
        }
    }
    // Check for already exists
    if (wppa_switch('void_dups')) {
        if (wppa_file_is_in_album(wppa_sanitize_file_name($file['name']), $alb)) {
            wppa_alert(sprintf(__('Uploaded file %s already exists in this album.', 'wp-photo-album-plus'), wppa_sanitize_file_name($file['name'])));
            return false;
        }
    }
    // Check for max memory needed to rocess image?
    $mayupload = wppa_check_memory_limit('', $imgsize[0], $imgsize[1]);
    if ($mayupload === false) {
        $maxsize = wppa_check_memory_limit(false);
        if (is_array($maxsize)) {
            wppa_alert(sprintf(__('The image is too big. Max photo size: %d x %d (%2.1f MegaPixel)', 'wp-photo-album-plus'), $maxsize['maxx'], $maxsize['maxy'], $maxsize['maxp'] / (1024 * 1024)));
            return false;
        }
    }
    // Find extension from mimetype
    switch ($imgsize[2]) {
        // mime type
        case 1:
            $ext = 'gif';
            break;
        case 2:
            $ext = 'jpg';
            break;
        case 3:
            $ext = 'png';
            break;
    }
    // Did the user supply a photoname?
    if (wppa_get_post('user-name')) {
        $name = wppa_get_post('user-name');
    } else {
        $name = $file['name'];
    }
    // Sanitize input
    $name = wppa_sanitize_photo_name($name);
    $desc = balanceTags(wppa_get_post('user-desc'), true);
    // If BlogIt! and no descrption given, use name field - this is for the shortcode used: typ"mphoto"
    if (!$desc && isset($_POST['wppa-blogit'])) {
        $desc = 'w#name';
    }
    // Find status and other needed data
    $linktarget = '_self';
    $status = wppa_switch('upload_moderate') && !current_user_can('wppa_admin') ? 'pending' : 'publish';
    if (wppa_switch('fe_upload_private')) {
        $status = 'private';
    }
    $filename = wppa_sanitize_file_name($file['name']);
    // Create new entry if this is not a posterfile
    if (!$is_av) {
        $id = wppa_create_photo_entry(array('album' => $alb, 'ext' => $ext, 'name' => $name, 'description' => $desc, 'status' => $status, 'filename' => $filename));
    }
    if (!$id) {
        wppa_alert(__('Could not insert photo into db.', 'wp-photo-album-plus'));
        return false;
    } else {
        wppa_save_source($file['tmp_name'], $filename, $alb);
        wppa_make_o1_source($id);
        wppa_update_album(array('id' => $alb, 'modified' => time()));
        wppa_flush_treecounts($alb);
        wppa_flush_upldr_cache('photoid', $id);
    }
    if (wppa_make_the_photo_files($file['tmp_name'], $id, $ext)) {
        // Repair photoname if not standard
        if (!wppa_get_post('user-name')) {
            wppa_set_default_name($id, $file['name']);
        }
        // Custom data
        wppa_fe_add_custom($id);
        // Add tags
        wppa_fe_add_tags($id);
        // and add watermark ( optionally ) to fullsize image only
        wppa_add_watermark($id);
        // Also to thumbnail?
        if (wppa_switch('watermark_thumbs')) {
            wppa_create_thumbnail($id);
            // create new thumb
        }
        // Is it a default coverimage?
        wppa_check_coverimage($id);
        // Mail
        if (wppa_switch('upload_notify')) {
            $to = get_bloginfo('admin_email');
            $subj = sprintf(__('New photo uploaded: %s', 'wp-photo-album-plus'), $name);
            $cont['0'] = sprintf(__('User %1$s uploaded photo %2$s into album %3$s', 'wp-photo-album-plus'), wppa_get_user(), $id, wppa_get_album_name($alb));
            if (wppa_switch('upload_moderate') && !current_user_can('wppa_admin')) {
                $cont['1'] = __('This upload requires moderation', 'wp-photo-album-plus');
                $cont['2'] = '<a href="' . get_admin_url() . 'admin.php?page=wppa_admin_menu&tab=pmod&photo=' . $id . '" >' . __('Moderate manage photo', 'wp-photo-album-plus') . '</a>';
            } else {
                $cont['1'] = __('Details:', 'wp-photo-album-plus');
                $cont['1'] .= ' <a href="' . get_admin_url() . 'admin.php?page=wppa_admin_menu&tab=pmod&photo=' . $id . '" >' . __('Manage photo', 'wp-photo-album-plus') . '</a>';
            }
            wppa_send_mail($to, $subj, $cont, $id);
        }
        return $id;
    }
    return false;
}
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;
}