function wppa_album_cover($id)
{
    global $wppa;
    // Init alt/even
    wppa('alt', 'alt');
    // Find the cover type
    $cover_type = wppa_get_album_item($id, 'cover_type') ? wppa_get_album_item($id, 'cover_type') : wppa_opt('wppa_cover_type');
    // Use the default setting
    // Find the cover photo position
    $wppa['coverphoto_pos'] = wppa_opt('wppa_coverphoto_pos');
    // Assume multicolumn responsive
    $is_mcr = true;
    // Dispatch on covertype
    switch ($cover_type) {
        case 'default':
            $is_mcr = false;
        case 'default-mcr':
            wppa_album_cover_default($id, $is_mcr);
            break;
        case 'imagefactory':
            $is_mcr = false;
        case 'imagefactory-mcr':
            if ($wppa['coverphoto_pos'] == 'left') {
                $wppa['coverphoto_pos'] = 'top';
            }
            if ($wppa['coverphoto_pos'] == 'right') {
                $wppa['coverphoto_pos'] = 'bottom';
            }
            wppa_album_cover_imagefactory($id, $is_mcr);
            break;
        case 'longdesc':
            $is_mcr = false;
        case 'longdesc-mcr':
            if ($wppa['coverphoto_pos'] == 'top') {
                $wppa['coverphoto_pos'] = 'left';
            }
            if ($wppa['coverphoto_pos'] == 'bottom') {
                $wppa['coverphoto_pos'] = 'right';
            }
            wppa_album_cover_longdesc($id, $is_mcr);
            break;
        default:
            $err = 'Unimplemented covertype: ' . $cover_type;
            wppa_dbg_msg($err);
            wppa_log('Err', $err);
    }
}
function wppa_album_cover($id)
{
    // Find the album specific cover type
    $cover_type = wppa_get_album_item($id, 'cover_type');
    // No type specified (0), use default
    if (!$cover_type) {
        $cover_type = wppa_opt('cover_type');
    }
    // Find the cover photo position
    wppa('coverphoto_pos', wppa_opt('coverphoto_pos'));
    // Assume multicolumn responsive
    $is_mcr = true;
    // Dispatch on covertype
    switch ($cover_type) {
        case 'default':
            $is_mcr = false;
        case 'default-mcr':
            wppa_album_cover_default($id, $is_mcr);
            break;
        case 'imagefactory':
            $is_mcr = false;
        case 'imagefactory-mcr':
            if (wppa('coverphoto_pos') == 'left') {
                wppa('coverphoto_pos', 'top');
            }
            if (wppa('coverphoto_pos') == 'right') {
                wppa('coverphoto_pos', 'bottom');
            }
            wppa_album_cover_imagefactory($id, $is_mcr);
            break;
        case 'longdesc':
            $is_mcr = false;
        case 'longdesc-mcr':
            if (wppa('coverphoto_pos') == 'top') {
                wppa('coverphoto_pos', 'left');
            }
            if (wppa('coverphoto_pos') == 'bottom') {
                wppa('coverphoto_pos', 'right');
            }
            wppa_album_cover_longdesc($id, $is_mcr);
            break;
        default:
            $err = 'Unimplemented covertype: ' . $cover_type;
            wppa_dbg_msg($err);
            wppa_log('Err', $err);
    }
}
function wppa_create_pl_htaccess($pl_dirname = '')
{
    global $wpdb;
    // Only supported on single sites at the moment
    if (is_multisite() && !WPPA_MULTISITE_GLOBAL) {
        return false;
    }
    // Where are the photo source files?
    $source_root = str_replace(ABSPATH, '', wppa_opt('wppa_source_dir'));
    // Find permalink root name
    if (!$pl_dirname) {
        $pl_dirname = wppa_opt('wppa_pl_dirname');
    }
    // If no pl_dirname, feature is disabled
    if (!$pl_dirname) {
        return false;
    }
    // Create pl root directory
    $pl_root = WPPA_CONTENT_PATH . '/' . $pl_dirname;
    if (!wppa_mktree($pl_root)) {
        wppa_log('Error', 'Can not create ' . $pl_root);
        return false;
    }
    // Create .htaccess file
    $file = fopen($pl_root . '/.htaccess', 'wb');
    if (!$file) {
        wppa_log('Error', 'Can not create ' . $pl_root . '/.htaccess');
        return false;
    }
    fwrite($file, '<IfModule mod_rewrite.c>');
    fwrite($file, "\n" . 'RewriteEngine On');
    // RewriteBase /wp-content/wppa-pl
    fwrite($file, "\n" . 'RewriteBase /' . str_replace(ABSPATH, '', $pl_root));
    $albs = $wpdb->get_results("SELECT `id`, `name` FROM `" . WPPA_ALBUMS . "` ORDER BY `name` DESC", ARRAY_A);
    if ($albs) {
        foreach ($albs as $alb) {
            $fm = wppa_sanitize_file_name($alb['name'], false);
            $to = $source_root . '/album-' . $alb['id'];
            fwrite($file, "\n" . 'RewriteRule ^' . $fm . '/(.*) /' . $to . '/$1 [NC]');
        }
    }
    fwrite($file, "\n" . '</IfModule>');
    fclose($file);
    return true;
}
function wppa_save_source($file, $name, $alb)
{
    $doit = true;
    // Frontend not enabled and not ajax ?
    if (!is_admin() && !wppa_switch('keep_source_frontend')) {
        $doit = false;
    }
    // Frontend not enabled and ajax ?
    if (isset($_REQUEST['wppa-action']) && $_REQUEST['wppa-action'] == 'do-fe-upload' && !wppa_switch('keep_source_frontend')) {
        $doit = false;
    }
    // Backend not enabled ?
    if ((!isset($_REQUEST['wppa-action']) || $_REQUEST['wppa-action'] != 'do-fe-upload') && is_admin() && !wppa_switch('keep_source_admin')) {
        $doit = false;
    }
    if ($doit) {
        if (!is_dir(wppa_opt('source_dir'))) {
            @wppa_mktree(wppa_opt('source_dir'));
        }
        $sourcedir = wppa_get_source_dir();
        if (!is_dir($sourcedir)) {
            @wppa_mktree($sourcedir);
        }
        $albdir = wppa_get_source_album_dir($alb);
        if (!is_dir($albdir)) {
            @wppa_mktree($albdir);
        }
        if (!is_dir($albdir)) {
            wppa_log('Err', 'Could not create source directory ' . $albdir);
        }
        $dest = $albdir . '/' . wppa_sanitize_file_name($name);
        if ($file != $dest) {
            @copy($file, $dest);
        }
        // Do not copy to self, and do not bother on failure
        if (is_file($dest)) {
            wppa_chmod($dest);
        } else {
            wppa_log('Err', 'Could not save ' . $dest, true);
        }
    }
}
function wppa_save_session()
{
    global $wpdb;
    global $wppa_session;
    static $last_query;
    // If no id can be found, give up
    if (!wppa_get_session_id()) {
        return false;
    }
    // If no id present, give up
    if (!isset($wppa_session['id'])) {
        return false;
    }
    // To prevent data overflow, only save the most recent 100 urls
    $c = count($wppa_session['uris']);
    if ($c > 100) {
        array_shift($wppa_session['uris']);
    }
    // Compose the query
    $query = $wpdb->prepare("UPDATE `" . WPPA_SESSION . "` SET `data` = %s WHERE `id` = %s", serialize($wppa_session), $wppa_session['id']);
    // Only update if data differs from previous update
    if ($query != $last_query) {
        // Do the query
        $iret = $wpdb->query($query);
        // Remember last successfull query
        if ($iret !== false) {
            $last_query = $query;
            //			wppa_log('Dbg', 'Saved session '.$wppa_session['id']);
            return true;
        }
        // No luck, maybe attemt to save a session that never started.
        // Mostly robots that modify their own ip.
        // Just ignore is the best way
        wppa_log('Dbg', 'Could not save session ' . $wppa_session['id']);
        //	$wppa_session = false;
        //	$last_query = false;
        //	wppa_session_start();
        return false;
    }
    // No error return
    return true;
}
function wppa_exif_clean_garbage($photo)
{
    global $wpdb;
    $items = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_EXIF . "` WHERE `photo` = %s", $photo), ARRAY_A);
    if (is_array($items)) {
        foreach ($items as $item) {
            $txt = sanitize_text_field($item['description']);
            $txt = str_replace(array(chr(0), chr(1), chr(2), chr(3), chr(4), chr(5), chr(6), chr(7)), '', $txt);
            // Cleaned text empty?
            if (!$txt) {
                // Garbage
                $wpdb->query($wpdb->prepare("DELETE FROM `" . WPPA_EXIF . "` WHERE `id` = %s", $item['id']));
                // Current label still used?
                $in_use = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_EXIF . "` WHERE `photo` <> '0' AND `tag` = %s", $item['tag']));
                if (!$in_use) {
                    $wpdb->query($wpdb->prepare("DELETE FROM `" . WPPA_EXIF . "` WHERE `photo` = '0' AND `tag` = %s", $item['tag']));
                    wppa_log('dbg', 'Exif tag label ' . $item['tag'] . ' removed.');
                }
            }
        }
    }
}
function wppa_get_photo_item($id, $item)
{
    $photo = wppa_cache_photo($id);
    if ($photo) {
        if (isset($photo[$item])) {
            return trim($photo[$item]);
        } else {
            wppa_log('Err', 'Photo item ' . $item . ' does not exist. ( get_photo_item )', true);
        }
    } else {
        wppa_log('Err', 'Photo ' . $id . ' does not exist. ( get_photo_item )', true);
    }
    return false;
}
function wppa_create_thumbnail($id, $use_source = true)
{
    // Find file to make thumbnail from
    $source_path = wppa_fix_poster_ext(wppa_get_source_path($id), $id);
    // Use source if requested and available
    if ($use_source) {
        if (!wppa_switch('watermark_thumbs') && is_file($source_path)) {
            $file = $source_path;
            // Use sourcefile
        } else {
            $file = wppa_fix_poster_ext(wppa_get_photo_path($id), $id);
            // Use photofile
        }
        // Non standard orientation files: never use source
        $orient = wppa_get_exif_orientation($file);
        if ($orient > '1') {
            $file = wppa_fix_poster_ext(wppa_get_photo_path($id), $id);
            // Use photofile
        }
    } else {
        $file = wppa_fix_poster_ext(wppa_get_photo_path($id), $id);
        // Use photofile
    }
    // Max side
    $max_side = wppa_get_minisize();
    // Check file
    if (!file_exists($file)) {
        return false;
    }
    // No file, fail
    $img_attr = getimagesize($file);
    if (!$img_attr) {
        return false;
    }
    // Not an image, fail
    // Retrieve aspect
    $asp_attr = explode(':', wppa_opt('thumb_aspect'));
    // Get output path
    $thumbpath = wppa_get_thumb_path($id);
    if (wppa_get_ext($thumbpath) == 'xxx') {
        // Video poster
        $thumbpath = wppa_strip_ext($thumbpath) . '.jpg';
    }
    // Source size
    $src_size_w = $img_attr[0];
    $src_size_h = $img_attr[1];
    // Temp convert width if stereo
    if (wppa_get_photo_item($id, 'stereo')) {
        $src_size_w /= 2;
    }
    // Mime type and thumb type
    $mime = $img_attr[2];
    $type = $asp_attr[2];
    // Source native aspect
    $src_asp = $src_size_h / $src_size_w;
    // Required aspect
    if ($type == 'none') {
        $dst_asp = $src_asp;
    } else {
        $dst_asp = $asp_attr[0] / $asp_attr[1];
    }
    // Convert back width if stereo
    if (wppa_get_photo_item($id, 'stereo')) {
        $src_size_w *= 2;
    }
    // Create the source image
    switch ($mime) {
        // mime type
        case 1:
            // gif
            $temp = @imagecreatefromgif($file);
            if ($temp) {
                $src = imagecreatetruecolor($src_size_w, $src_size_h);
                imagecopy($src, $temp, 0, 0, 0, 0, $src_size_w, $src_size_h);
                imagedestroy($temp);
            } else {
                $src = false;
            }
            break;
        case 2:
            // jpeg
            if (!function_exists('wppa_imagecreatefromjpeg')) {
                wppa_log('Error', 'Function wppa_imagecreatefromjpeg does not exist.');
            }
            $src = @wppa_imagecreatefromjpeg($file);
            break;
        case 3:
            // png
            $src = @imagecreatefrompng($file);
            break;
    }
    if (!$src) {
        wppa_log('Error', 'Image file ' . $file . ' is corrupt while creating thmbnail');
        return true;
    }
    // Compute the destination image size
    if ($dst_asp < 1.0) {
        // Landscape
        $dst_size_w = $max_side;
        $dst_size_h = round($max_side * $dst_asp);
    } else {
        // Portrait
        $dst_size_w = round($max_side / $dst_asp);
        $dst_size_h = $max_side;
    }
    // Create the ( empty ) destination image
    $dst = imagecreatetruecolor($dst_size_w, $dst_size_h);
    if ($mime == 3) {
        // Png, save transparancy
        imagealphablending($dst, false);
        imagesavealpha($dst, true);
    }
    // Fill with the required color
    $c = trim(strtolower(wppa_opt('bgcolor_thumbnail')));
    if ($c != '#000000') {
        $r = hexdec(substr($c, 1, 2));
        $g = hexdec(substr($c, 3, 2));
        $b = hexdec(substr($c, 5, 2));
        $color = imagecolorallocate($dst, $r, $g, $b);
        if ($color === false) {
            wppa_log('Err', 'Unable to set background color to: ' . $r . ', ' . $g . ', ' . $b . ' in wppa_create_thumbnail');
        } else {
            imagefilledrectangle($dst, 0, 0, $dst_size_w, $dst_size_h, $color);
        }
    }
    // Switch on what we have to do
    switch ($type) {
        case 'none':
            // Use aspect from fullsize image
            $src_x = 0;
            $src_y = 0;
            $src_w = $src_size_w;
            $src_h = $src_size_h;
            $dst_x = 0;
            $dst_y = 0;
            $dst_w = $dst_size_w;
            $dst_h = $dst_size_h;
            break;
        case 'clip':
            // Clip image to given aspect ratio
            if ($src_asp < $dst_asp) {
                // Source image more landscape than destination
                $dst_x = 0;
                $dst_y = 0;
                $dst_w = $dst_size_w;
                $dst_h = $dst_size_h;
                $src_x = round(($src_size_w - $src_size_h / $dst_asp) / 2);
                $src_y = 0;
                $src_w = round($src_size_h / $dst_asp);
                $src_h = $src_size_h;
            } else {
                $dst_x = 0;
                $dst_y = 0;
                $dst_w = $dst_size_w;
                $dst_h = $dst_size_h;
                $src_x = 0;
                $src_y = round(($src_size_h - $src_size_w * $dst_asp) / 2);
                $src_w = $src_size_w;
                $src_h = round($src_size_w * $dst_asp);
            }
            break;
        case 'padd':
            // Padd image to given aspect ratio
            if ($src_asp < $dst_asp) {
                // Source image more landscape than destination
                $dst_x = 0;
                $dst_y = round(($dst_size_h - $dst_size_w * $src_asp) / 2);
                $dst_w = $dst_size_w;
                $dst_h = round($dst_size_w * $src_asp);
                $src_x = 0;
                $src_y = 0;
                $src_w = $src_size_w;
                $src_h = $src_size_h;
            } else {
                $dst_x = round(($dst_size_w - $dst_size_h / $src_asp) / 2);
                $dst_y = 0;
                $dst_w = round($dst_size_h / $src_asp);
                $dst_h = $dst_size_h;
                $src_x = 0;
                $src_y = 0;
                $src_w = $src_size_w;
                $src_h = $src_size_h;
            }
            break;
        default:
            // Not implemented
            return false;
    }
    // Copy left half if stereo
    if (wppa_get_photo_item($id, 'stereo')) {
        $src_w /= 2;
    }
    // Do the copy
    imagecopyresampled($dst, $src, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
    // Save the thumb
    $thumbpath = wppa_strip_ext($thumbpath);
    switch ($mime) {
        // mime type
        case 1:
            $full_thumbpath = $thumbpath . '.gif';
            imagegif($dst, $full_thumbpath);
            break;
        case 2:
            $full_thumbpath = $thumbpath . '.jpg';
            imagejpeg($dst, $full_thumbpath, wppa_opt('jpeg_quality'));
            break;
        case 3:
            $full_thumbpath = $thumbpath . '.png';
            imagepng($dst, $full_thumbpath, 6);
            break;
    }
    // Cleanup
    imagedestroy($src);
    imagedestroy($dst);
    // Make sure file is accessable
    wppa_chmod($full_thumbpath);
    // Optimize
    wppa_optimize_image_file($full_thumbpath);
    // Compute and save sizes
    wppa_get_thumbx($id, 'force');
    // forces recalc x and y
    return true;
}
function wppa_error_message($msg, $fixed = false, $id = '')
{
    ?>
	<div id="wppa-er-<?php 
    echo $id;
    ?>
" class="error <?php 
    if ($fixed == 'fixed') {
        echo fade;
    }
    ?>
" <?php 
    if ($fixed == 'hidden') {
        echo 'style="display:none;"';
    }
    if ($fixed == 'fixed') {
        echo 'style="position: fixed;"';
    }
    ?>
><p><strong><?php 
    echo $msg;
    ?>
</strong></p></div>
<?php 
    wppa_log('Error', $msg);
}
function wppa_set_owner_to_name($id)
{
    global $wpdb;
    static $usercache;
    // Feature enabled?
    if (wppa_switch('owner_to_name')) {
        // Get photo data.
        $p = wppa_cache_thumb($id);
        // Find user of whose display name equals photoname
        if (isset($usercache[$p['name']])) {
            $user = $usercache[$p['name']];
        } else {
            $user = $wpdb->get_var($wpdb->prepare("SELECT `user_login` FROM `" . $wpdb->users . "` WHERE `display_name` = %s", $p['name']));
            if ($user) {
                $usercache[$p['name']] = $user;
            } else {
                $usercache[$p['name']] = false;
                // NULL is equal to ! isset() !!!
            }
        }
        if ($user) {
            if ($p['owner'] != $user) {
                wppa_update_photo(array('id' => $id, 'owner' => $user));
                wppa_cache_thumb('invalidate', $id);
                wppa_log('Obs', 'Owner of photo ' . $id . ' in album ' . wppa_get_photo_item($id, 'album') . ' set to: ' . $user);
                return true;
            } else {
                return '0';
            }
        }
    }
    return false;
}
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;
    }
}
Example #12
0
function wppa_session_end()
{
    global $wpdb;
    global $wppa_session;
    if (!wppa_get_session_id()) {
        return false;
    }
    $iret = $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_SESSION . "` SET `data` = %s WHERE `session` = %s", serialize($wppa_session), wppa_get_session_id()));
    if ($iret === false) {
        wppa_log('Error', 'Unable to save session.');
        return false;
    }
    return true;
}
function wppa_grant_albums($xparent = false)
{
    global $wpdb;
    static $grant_parents;
    static $my_albs_parents;
    static $owner;
    static $user;
    // Feature enabled?
    if (!wppa_switch('grant_an_album')) {
        return false;
    }
    // Owners only?
    if (!wppa_switch('owner_only')) {
        return false;
    }
    // User logged in?
    if (!is_user_logged_in()) {
        return false;
    }
    // Can user upload?
    if (!current_user_can('wppa_upload') && !wppa_switch('user_upload_on')) {
        return false;
    }
    // Init
    $albums_created = array();
    // Get required data if not done already
    // First get the grant parent album(s)
    if (!is_array($grant_parents)) {
        switch (wppa_opt('grant_parent_sel_method')) {
            case 'selectionbox':
                // Album ids are and expanded enumeration sep by , in the setting
                $grant_parents = explode(',', wppa_opt('grant_parent'));
                if (!is_array($grant_parents)) {
                    $grant_parents = array('0');
                }
                break;
            case 'category':
                // The option hold a category
                $grant_parents = $wpdb->get_col("SELECT `id` " . "FROM `" . WPPA_ALBUMS . "` " . "WHERE `cats` LIKE '%," . wppa_opt('grant_parent') . ",%'");
                break;
            case 'indexsearch':
                $temp = $wpdb->get_var("SELECT `albums` " . "FROM `" . WPPA_INDEX . "` " . "WHERE `slug` = '" . wppa_opt('grant_parent') . "'");
                $grant_parents = explode('.', wppa_expand_enum($temp));
                break;
        }
    }
    if (!$owner) {
        $owner = wppa_get_user('login');
        // The current users login name
    }
    if (!is_array($my_albs_parents)) {
        $query = $wpdb->prepare("SELECT DISTINCT `a_parent` FROM `" . WPPA_ALBUMS . "` WHERE `owner` = %s", $owner);
        $my_albs_parents = $wpdb->get_col($query);
        if (!is_array($my_albs_parents)) {
            $my_albs_parents = array();
        }
    }
    if (!$user) {
        $user = wppa_get_user(wppa_opt('grant_name'));
        // The current users name as how the album should be named
    }
    // If a parent is given and it is not a grant parent, quit
    if ($xparent && !in_array($xparent, $grant_parents)) {
        return false;
    }
    // If a parent is given, it will now be a grant parent (see directly above), only create the granted album inside this parent.
    if ($xparent) {
        $parents = array($xparent);
    } else {
        $parents = $grant_parents;
    }
    // Parent independant album data
    $name = $user;
    $desc = __('Default photo album for', 'wp-photo-album-plus') . ' ' . $user;
    // May be multiple granted parents. Check for all parents.
    foreach ($parents as $parent) {
        // Create only grant album if: parent is either -1 or existing
        if ($parent == '-1' || wppa_album_exists($parent)) {
            if (!in_array($parent, $my_albs_parents, true)) {
                // make an album for this user
                $id = wppa_create_album_entry(array('name' => $name, 'description' => $desc, 'a_parent' => $parent));
                if ($id) {
                    wppa_log('Obs', 'Album ' . wppa_get_album_name($parent) . '(' . $parent . ')' . ' -> ' . $id . ' for ' . $user . ' created.');
                    $albums_created[] = $id;
                    // Add this parent to the array of my albums parents
                    $my_albs_parents[] = $parent;
                } else {
                    wppa_log('Err', 'Could not create subalbum of ' . $parent . ' for ' . $user);
                }
                wppa_flush_treecounts($parent);
                wppa_index_add('album', $id);
            }
        }
    }
    // Remake permalink redirects
    if (!empty($albums_created)) {
        wppa_create_pl_htaccess();
    }
    return $albums_created;
}
function wppa_update_photo($args)
{
    global $wpdb;
    if (!is_array($args)) {
        return false;
    }
    if (!$args['id']) {
        return false;
    }
    $thumb = wppa_cache_thumb($args['id']);
    if (!$thumb) {
        return false;
    }
    $id = $args['id'];
    // If Timestamp update, make sure modified is updated to now
    if (isset($args['timestamp'])) {
        $args['modified'] = time();
    }
    foreach (array_keys($args) as $itemname) {
        $itemvalue = $args[$itemname];
        $doit = false;
        // Sanitize input
        switch ($itemname) {
            case 'id':
                break;
            case 'name':
                $itemvalue = wppa_strip_tags($itemvalue, 'all');
                $doit = true;
                break;
            case 'description':
                $itemvalue = balanceTags($itemvalue, true);
                $itemvalue = wppa_strip_tags($itemvalue, 'script&style');
                $doit = true;
                break;
            case 'timestamp':
            case 'modified':
                if (!$itemvalue) {
                    $itemvalue = time();
                }
                $doit = true;
                break;
            case 'scheduledtm':
            case 'exifdtm':
            case 'page_id':
                $doit = true;
                break;
            case 'status':
                $doit = true;
                break;
            case 'tags':
                $itemvalue = wppa_sanitize_tags($itemvalue);
                $doit = true;
                break;
            case 'thumbx':
            case 'thumby':
            case 'photox':
            case 'photoy':
            case 'videox':
            case 'videoy':
                $itemvalue = intval($itemvalue);
                $doit = true;
                break;
            case 'ext':
                $doit = true;
                break;
            case 'filename':
                $itemvalue = wppa_sanitize_file_name($itemvalue);
                $doit = true;
                break;
            case 'custom':
            case 'stereo':
                $doit = true;
                break;
            default:
                wppa_log('Error', 'Not implemented in wppa_update_photo(): ' . $itemname);
                return false;
        }
        if ($doit) {
            if ($wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `" . $itemname . "` = %s WHERE `id` = %s LIMIT 1", $itemvalue, $id))) {
                wppa_cache_photo('invalidate', $id);
            }
        }
    }
    return true;
}
 /** @see WP_Widget::widget */
 function widget($args, $instance)
 {
     global $wpdb;
     wppa('in_widget', 'potd');
     wppa_bump_mocc();
     require_once dirname(__FILE__) . '/wppa-links.php';
     require_once dirname(__FILE__) . '/wppa-styles.php';
     require_once dirname(__FILE__) . '/wppa-functions.php';
     require_once dirname(__FILE__) . '/wppa-thumbnails.php';
     require_once dirname(__FILE__) . '/wppa-boxes-html.php';
     require_once dirname(__FILE__) . '/wppa-slideshow.php';
     wppa_initialize_runtime();
     extract($args);
     $widget_title = apply_filters('widget_title', $instance['title']);
     // get the photo  ($image)
     $image = wppa_get_potd();
     // Make the HTML for current picture
     $widget_content = "\n" . '<!-- WPPA+ Photo of the day Widget start -->';
     $ali = wppa_opt('potd_align');
     if ($ali != 'none') {
         $align = 'text-align:' . $ali . ';';
     } else {
         $align = '';
     }
     $widget_content .= "\n" . '<div class="wppa-widget-photo" style="' . $align . ' padding-top:2px;position:relative;" >';
     if ($image) {
         $id = $image['id'];
         $w = wppa_opt('potd_widget_width');
         $ratio = wppa_get_photoy($id) / wppa_get_photox($id);
         $h = round($w * $ratio);
         $usethumb = wppa_use_thumb_file($id, wppa_opt('potd_widget_width'), '0');
         $imgurl = wppa_fix_poster_ext($usethumb ? wppa_get_thumb_url($id, '', $w, $h) : wppa_get_photo_url($id, '', $w, $h), $id);
         $name = wppa_get_photo_name($id);
         $page = in_array(wppa_opt('potd_linktype'), wppa('links_no_page')) && !wppa_switch('potd_counter') ? '' : wppa_get_the_landing_page('potd_linkpage', __('Photo of the day', 'wp-photo-album-plus'));
         $link = wppa_get_imglnk_a('potdwidget', $id);
         $is_video = wppa_is_video($id);
         $has_audio = wppa_has_audio($id);
         if ($link['is_lightbox']) {
             $lightbox = ($is_video ? ' data-videohtml="' . esc_attr(wppa_get_video_body($id)) . '"' . ' data-videonatwidth="' . wppa_get_videox($id) . '"' . ' data-videonatheight="' . wppa_get_videoy($id) . '"' : '') . ($has_audio ? ' data-audiohtml="' . esc_attr(wppa_get_audio_body($id)) . '"' : '') . ' ' . wppa('rel') . '="' . wppa_opt('lightbox_name') . '"' . ' data-alt="' . esc_attr(wppa_get_imgalt($id, true)) . '"';
         } else {
             $lightbox = '';
         }
         if ($link) {
             if ($link['is_lightbox']) {
                 $cursor = ' cursor:url(' . wppa_get_imgdir() . wppa_opt('magnifier') . '),pointer;';
                 $title = wppa_zoom_in($id);
                 $ltitle = wppa_get_lbtitle('potd', $id);
             } else {
                 $cursor = ' cursor:pointer;';
                 $title = $link['title'];
                 $ltitle = $title;
             }
         } else {
             $cursor = ' cursor:default;';
             $title = esc_attr(stripslashes(__($image['name'], 'wp-photo-album-plus')));
         }
         // The medal if on top
         $widget_content .= wppa_get_medal_html_a(array('id' => $id, 'size' => 'M', 'where' => 'top'));
         // The link, if any
         if ($link) {
             $widget_content .= "\n\t" . '<a href = "' . $link['url'] . '" target="' . $link['target'] . '" ' . $lightbox . ' ' . wppa('lbtitle') . '="' . $ltitle . '">';
         }
         // The image
         if (wppa_is_video($id)) {
             $widget_content .= "\n\t\t" . wppa_get_video_html(array('id' => $id, 'width' => wppa_opt('potd_widget_width'), 'title' => $title, 'controls' => wppa_opt('potd_linktype') == 'none', 'cursor' => $cursor));
         } else {
             $widget_content .= '<img' . ' src="' . $imgurl . '"' . ' style="width: ' . wppa_opt('potd_widget_width') . 'px;' . $cursor . '"' . ' ' . wppa_get_imgalt($id) . ($title ? 'title="' . $title . '"' : '') . ' />';
         }
         // Close the link
         if ($link) {
             $widget_content .= '</a>';
         }
         // The medal if at the bottom
         $widget_content .= wppa_get_medal_html_a(array('id' => $id, 'size' => 'M', 'where' => 'bot'));
         // The counter
         if (wppa_switch('potd_counter')) {
             // If we want this
             $alb = wppa_get_photo_item($id, 'album');
             $c = $wpdb->get_var("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `album` = " . $alb) - 1;
             if ($c > 0) {
                 if (wppa_opt('potd_counter_link') == 'thumbs') {
                     $lnk = wppa_get_album_url($alb, $page, 'thumbs', '1');
                 } elseif (wppa_opt('potd_counter_link') == 'slide') {
                     $lnk = wppa_get_slideshow_url($alb, $page, $id, '1');
                 } elseif (wppa_opt('potd_counter_link') == 'single') {
                     $lnk = wppa_encrypt_url(get_permalink($page) . '?occur=1&photo=' . $id);
                     //	wppa_get_image_page_url_by_id( $id, true, false, $page );
                 } else {
                     wppa_log('Err', 'Unimplemented counter link type in wppa-potd-widget: ' . wppa_opt('potd_counter_link'));
                 }
                 $widget_content .= '<a href="' . $lnk . '" >' . '<div style="font-size:12px;position:absolute;right:4px;bottom:4px;" >+' . $c . '</div>' . '</a>';
             }
         }
         // Audio
         if (wppa_has_audio($id)) {
             $widget_content .= wppa_get_audio_html(array('id' => $id, 'width' => wppa_opt('potd_widget_width'), 'controls' => true));
         }
     } else {
         // No image
         $widget_content .= __('Photo not found', 'wp-photo-album-plus');
     }
     $widget_content .= "\n" . '</div>';
     // Add subtitle, if any
     if ($image) {
         switch (wppa_opt('potd_subtitle')) {
             case 'none':
                 break;
             case 'name':
                 $widget_content .= '<div class="wppa-widget-text wppa-potd-text" style="' . $align . '">' . wppa_get_photo_name($id) . '</div>';
                 break;
             case 'desc':
                 $widget_content .= "\n" . '<div class="wppa-widget-text wppa-potd-text" style="' . $align . '">' . wppa_get_photo_desc($id) . '</div>';
                 break;
             case 'owner':
                 $owner = $image['owner'];
                 $user = get_user_by('login', $owner);
                 $owner = $user->display_name;
                 $widget_content .= "\n" . '<div class="wppa-widget-text wppa-potd-text" style="' . $align . '">' . __('By:', 'wp-photo-album-plus') . ' ' . $owner . '</div>';
                 break;
             default:
                 wppa_log('Err', 'Unimplemented potd_subtitle found in wppa-potd-widget: ' . wppa_opt('potd_subtitle'));
         }
     }
     $widget_content .= '<div style="clear:both;" ></div>';
     $widget_content .= "\n" . '<!-- WPPA+ Photo of the day Widget end -->';
     echo "\n" . $before_widget;
     if (!empty($widget_title)) {
         echo $before_title . $widget_title . $after_title;
     }
     echo $widget_content . $after_widget;
     wppa('in_widget', false);
 }
function wppa_album_photos_bulk($album)
{
    global $wpdb;
    // Check input
    wppa_vfy_arg('wppa-page');
    // Init
    $count = '0';
    $abort = false;
    if (isset($_POST['wppa-bulk-action'])) {
        check_admin_referer('wppa-bulk', 'wppa-bulk');
        if (isset($_POST['wppa-bulk-photo'])) {
            $ids = $_POST['wppa-bulk-photo'];
            $newalb = isset($_POST['wppa-bulk-album']) ? $_POST['wppa-bulk-album'] : '0';
            $status = isset($_POST['wppa-bulk-status']) ? $_POST['wppa-bulk-status'] : '';
            $owner = isset($_POST['wppa-bulk-owner']) ? $_POST['wppa-bulk-owner'] : '';
            $totcount = count($ids);
            if (!is_numeric($newalb)) {
                wp_die('Security check failure 1');
            }
            if (is_array($ids)) {
                foreach (array_keys($ids) as $id) {
                    $skip = false;
                    switch ($_POST['wppa-bulk-action']) {
                        case 'wppa-bulk-delete':
                            wppa_delete_photo($id);
                            break;
                        case 'wppa-bulk-move-to':
                            if ($newalb) {
                                $photo = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . WPPA_PHOTOS . ' WHERE `id` = %s', $id), ARRAY_A);
                                if (wppa_switch('void_dups')) {
                                    // Check for already exists
                                    $exists = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `filename` = %s AND `album` = %s", $photo['filename'], $newalb));
                                    if ($exists) {
                                        // Already exists
                                        wppa_error_message(sprintf(__('A photo with filename %s already exists in album %s.', 'wp-photo-album-plus'), $photo['filename'], $newalb));
                                        $skip = true;
                                    }
                                }
                                if ($skip) {
                                    continue;
                                }
                                wppa_flush_treecounts($photo['album']);
                                // Current album
                                wppa_flush_treecounts($newalb);
                                // New album
                                $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `album` = %s WHERE `id` = %s', $newalb, $id));
                                wppa_move_source($photo['filename'], $photo['album'], $newalb);
                            } else {
                                wppa_error_message('Unexpected error #4 in wppa_album_photos_bulk().');
                            }
                            break;
                        case 'wppa-bulk-copy-to':
                            if ($newalb) {
                                $photo = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . WPPA_PHOTOS . ' WHERE `id` = %s', $id), ARRAY_A);
                                if (wppa_switch('void_dups')) {
                                    // Check for already exists
                                    $exists = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `filename` = %s AND `album` = %s", $photo['filename'], $newalb));
                                    if ($exists) {
                                        // Already exists
                                        wppa_error_message(sprintf(__($exists . 'A photo with filename %s already exists in album %s.', 'wp-photo-album-plus'), $photo['filename'], $newalb));
                                        $skip = true;
                                    }
                                }
                                if ($skip) {
                                    continue;
                                }
                                wppa_copy_photo($id, $newalb);
                                wppa_flush_treecounts($newalb);
                            } else {
                                wppa_error_message('Unexpected error #3 in wppa_album_photos_bulk().');
                            }
                            break;
                        case 'wppa-bulk-status':
                            if (!in_array($status, array('publish', 'pending', 'featured', 'scheduled', 'gold', 'silver', 'bronze', 'private'))) {
                                wppa_log('error', 'Unknown status ' . strip_tags($status) . ' found in wppa-photo-admin-autosave.php -> wppa_album_photos_bulk()');
                                $status = 'publish';
                            }
                            if (current_user_can('wppa_admin') || current_user_can('wppa_moderate')) {
                                if ($status == 'publish' || $status == 'pending' || wppa_user_is('administrator') || !wppa_switch('ext_status_restricted')) {
                                    $wpdb->query("UPDATE `" . WPPA_PHOTOS . "` SET `status` = '" . $status . "' WHERE `id` = " . $id);
                                    wppa_flush_treecounts($id, wppa_get_photo_item($id, 'album'));
                                } else {
                                    wp_die('Security check failure 2');
                                }
                            } else {
                                wp_die('Security check failure 3');
                            }
                            break;
                        case 'wppa-bulk-owner':
                            if (wppa_user_is('administrator') && wppa_switch('photo_owner_change')) {
                                if ($owner) {
                                    $owner = sanitize_user($owner);
                                    $exists = $wpdb->get_var("SELECT COUNT(*) FROM `" . $wpdb->users . "` WHERE `user_login` = '" . $owner . "'");
                                    if ($exists) {
                                        $wpdb->query("UPDATE `" . WPPA_PHOTOS . "` SET `owner` = '" . $owner . "' WHERE `id` = " . $id);
                                    } else {
                                        wppa_error_message('A user with login name ' . $owner . ' does not exist.');
                                        $skip = true;
                                    }
                                } else {
                                    wp_die('Missing required arg in bulk change owner');
                                }
                            } else {
                                wp_die('Security check failure 4');
                            }
                            break;
                        default:
                            wppa_error_message('Unimplemented bulk action requested in wppa_album_photos_bulk().');
                            break;
                    }
                    if (!$skip) {
                        $count++;
                    }
                    if (wppa_is_time_up()) {
                        wppa_error_message(sprintf(__('Time is out after processing %d out of %d items.', 'wp-photo-album-plus'), $count, $totcount));
                        $abort = true;
                    }
                    if ($abort) {
                        break;
                    }
                }
            } else {
                wppa_error_message('Unexpected error #2 in wppa_album_photos_bulk().');
            }
        } else {
            wppa_error_message('Unexpected error #1 in wppa_album_photos_bulk().');
        }
        if ($count && !$abort) {
            switch ($_POST['wppa-bulk-action']) {
                case 'wppa-bulk-delete':
                    $message = sprintf(__('%d photos deleted.', 'wp-photo-album-plus'), $count);
                    break;
                case 'wppa-bulk-move-to':
                    $message = sprintf(__('%1$s photos moved to album %2$s.', 'wp-photo-album-plus'), $count, $newalb . ': ' . wppa_get_album_name($newalb));
                    break;
                case 'wppa-bulk-copy-to':
                    $message = sprintf(__('%1$s photos copied to album %2$s.', 'wp-photo-album-plus'), $count, $newalb . ': ' . wppa_get_album_name($newalb));
                    break;
                case 'wppa-bulk-status':
                    $message = sprintf(__('Changed status to %1$s on %2$s photos.', 'wp-photo-album-plus'), $status, $count);
                    break;
                case 'wppa-bulk-owner':
                    $message = sprintf(__('Changed owner to %1$s on %2$s photos.', 'wp-photo-album-plus'), $owner, $count);
                    break;
                default:
                    $message = sprintf(__('%d photos processed.', 'wp-photo-album-plus'), $count);
                    break;
            }
            wppa_ok_message($message);
        }
    }
    $pagesize = wppa_opt('photo_admin_pagesize');
    $page = isset($_GET['wppa-page']) ? $_GET['wppa-page'] : '1';
    $skip = ($page - '1') * $pagesize;
    $limit = $pagesize < '1' ? '' : ' LIMIT ' . $skip . ',' . $pagesize;
    if ($album) {
        if ($album == 'search') {
            $count = wppa_get_edit_search_photos('', 'count_only');
            $photos = wppa_get_edit_search_photos($limit);
            $link = wppa_dbg_url(get_admin_url() . 'admin.php?page=wppa_admin_menu&tab=edit&edit_id=' . $album . '&wppa-searchstring=' . wppa_sanitize_searchstring($_REQUEST['wppa-searchstring']) . '&bulk');
            wppa_show_search_statistics();
        } else {
            $counts = wppa_treecount_a($album);
            $count = $counts['selfphotos'] + $counts['pendphotos'];
            //$wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM `'.WPPA_PHOTOS.'` WHERE `album` = %s', $album ) );
            $photos = $wpdb->get_results($wpdb->prepare('SELECT * FROM `' . WPPA_PHOTOS . '` WHERE `album` = %s ' . wppa_get_photo_order($album, 'norandom') . $limit, $album), ARRAY_A);
            $link = wppa_dbg_url(get_admin_url() . 'admin.php?page=wppa_admin_menu&tab=edit&edit_id=' . $album . '&bulk');
        }
        if ($photos) {
            wppa_admin_page_links($page, $pagesize, $count, $link, '#manage-photos');
            ?>
			<script type="text/javascript" >
				function wppaBulkActionChange( elm, id ) {
					wppa_setCookie( 'wppa_bulk_action',elm.value,365 );
					if ( elm.value == 'wppa-bulk-move-to' || elm.value == 'wppa-bulk-copy-to' ) jQuery( '#wppa-bulk-album' ).css( 'display', 'inline' );
					else jQuery( '#wppa-bulk-album' ).css( 'display', 'none' );
					if ( elm.value == 'wppa-bulk-status' ) jQuery( '#wppa-bulk-status' ).css( 'display', 'inline' );
					else jQuery( '#wppa-bulk-status' ).css( 'display', 'none' );
					if ( elm.value == 'wppa-bulk-owner' ) jQuery( '#wppa-bulk-owner' ).css( 'display', 'inline' );
					else jQuery( '#wppa-bulk-owner' ).css( 'display', 'none' );
				}
				function wppaBulkDoitOnClick() {
					var photos = jQuery( '.wppa-bulk-photo' );
					var count=0;
					for ( i=0; i< photos.length; i++ ) {
						var photo = photos[i];
						if ( photo.checked ) count++;
					}
					if ( count == 0 ) {
						alert( 'No photos selected' );
						return false;
					}
					var action = document.getElementById( 'wppa-bulk-action' ).value;
					switch ( action ) {
						case '':
							alert( 'No action selected' );
							return false;
							break;
						case 'wppa-bulk-delete':
							break;
						case 'wppa-bulk-move-to':
						case 'wppa-bulk-copy-to':
							var album = document.getElementById( 'wppa-bulk-album' ).value;
							if ( album == 0 ) {
								alert( 'No album selected' );
								return false;
							}
							break;
						case 'wppa-bulk-status':
							var status = document.getElementById( 'wppa-bulk-status' ).value;
							if ( status == 0 ) {
								alert( 'No status selected' );
								return false;
							}
							break;
						case 'wppa-bulk-owner':
							var owner = documnet.getElementById( 'wppa-bulk-owner' ).value;
							if ( owner == 0 ) {
								alert( 'No new owner selected' );
								return false;
							}
							break;
						default:
							alert( 'Unimplemented action requested: '+action );
							return false;
							break;

					}
					return true;
				}
				function wppaSetThumbsize( elm ) {
					var thumbsize = elm.value;
					wppa_setCookie( 'wppa_bulk_thumbsize',thumbsize,365 );
					jQuery( '.wppa-bulk-thumb' ).css( 'max-width', thumbsize+'px' );
					jQuery( '.wppa-bulk-thumb' ).css( 'max-height', ( thumbsize/2 )+'px' );
					jQuery( '.wppa-bulk-dec' ).css( 'height', ( thumbsize/2 )+'px' );
				}
				jQuery( document ).ready( function() {
					var action = wppa_getCookie( 'wppa_bulk_action' );
					document.getElementById( 'wppa-bulk-action' ).value = action;
					if ( action == 'wppa-bulk-move-to' || action == 'wppa-bulk-copy-to' ) {
						jQuery( '#wppa-bulk-album' ).css( 'display','inline' );
						document.getElementById( 'wppa-bulk-album' ).value = wppa_getCookie( 'wppa_bulk_album' );
					}
					if ( action == 'wppa-bulk-status' ) {
						jQuery( '#wppa-bulk-status' ).css( 'display','inline' );
						document.getElementById( 'wppa-bulk-status' ).value = wppa_getCookie( 'wppa_bulk_status' );
					}
					if ( action == 'wppa-bulk-owner' ) {
						jQuery( '#wppa-bulk-owner' ).css( 'display','inline' );
						document.getElementById( 'wppa-bulk-owner' ).value = wppa_getCookie( 'wppa_bulk_owner' );
					}
				} );

			</script>
			<form action="<?php 
            echo $link . '&wppa-page=' . $page . '#manage-photos';
            ?>
" method="post" >
				<?php 
            wp_nonce_field('wppa-bulk', 'wppa-bulk');
            ?>
				<h3>
				<span style="font-weight:bold;" ><?php 
            _e('Bulk action:', 'wp-photo-album-plus');
            ?>
</span>
				<select id="wppa-bulk-action" name="wppa-bulk-action" onchange="wppaBulkActionChange( this, 'bulk-album' )" >
					<option value="" ></option>
					<option value="wppa-bulk-delete" ><?php 
            _e('Delete', 'wp-photo-album-plus');
            ?>
</option>
					<option value="wppa-bulk-move-to" ><?php 
            _e('Move to', 'wp-photo-album-plus');
            ?>
</option>
					<option value="wppa-bulk-copy-to" ><?php 
            _e('Copy to', 'wp-photo-album-plus');
            ?>
</option>
					<?php 
            if (current_user_can('wppa_admin') || current_user_can('wppa_moderate')) {
                ?>
						<option value="wppa-bulk-status" ><?php 
                _e('Set status to', 'wp-photo-album-plus');
                ?>
</option>
					<?php 
            }
            ?>
					<?php 
            if (wppa_user_is('administrator') && wppa_switch('photo_owner_change')) {
                ?>
						<option value="wppa-bulk-owner" ><?php 
                _e('Set owner to', 'wp-photo-album-plus');
                ?>
</option>
					<?php 
            }
            ?>
				</select>
				<select name="wppa-bulk-album" id="wppa-bulk-album" style="display:none;" onchange="wppa_setCookie( 'wppa_bulk_album',this.value,365 );" >
					<?php 
            echo wppa_album_select_a(array('checkaccess' => true, 'path' => wppa_switch('hier_albsel'), 'exclude' => $album, 'selected' => '0', 'addpleaseselect' => true));
            ?>
				</select>
				<select name="wppa-bulk-status" id="wppa-bulk-status" style="display:none;" onchange="wppa_setCookie( 'wppa_bulk_status',this.value,365 );" >
					<option value="" ><?php 
            _e('- select a status -', 'wp-photo-album-plus');
            ?>
</option>
					<option value="pending" ><?php 
            _e('Pending', 'wp-photo-album-plus');
            ?>
</option>
					<option value="publish" ><?php 
            _e('Publish', 'wp-photo-album-plus');
            ?>
</option>
					<?php 
            if (wppa_switch('ext_status_restricted') && !wppa_user_is('administrator')) {
                $dis = ' disabled';
            } else {
                $dis = '';
            }
            ?>
					<option value="featured"<?php 
            echo $dis;
            ?>
 ><?php 
            _e('Featured', 'wp-photo-album-plus');
            ?>
</option>
					<option value="gold" <?php 
            echo $dis;
            ?>
 ><?php 
            _e('Gold', 'wp-photo-album-plus');
            ?>
</option>
					<option value="silver" <?php 
            echo $dis;
            ?>
 ><?php 
            _e('Silver', 'wp-photo-album-plus');
            ?>
</option>
					<option value="bronze" <?php 
            echo $dis;
            ?>
 ><?php 
            _e('Bronze', 'wp-photo-album-plus');
            ?>
</option>
					<option value="scheduled" <?php 
            echo $dis;
            ?>
 ><?php 
            _e('Scheduled', 'wp-photo-album-plus');
            ?>
</option>
					<option value="private" <?php 
            echo $dis;
            ?>
 ><?php 
            _e('Private', 'wp-photo-album-plus');
            ?>
</option>
				</select>
				<!-- Owner -->
				<?php 
            $users = wppa_get_users();
            if (count($users)) {
                ?>
				<select name="wppa-bulk-owner" id="wppa-bulk-owner" style="display:none;" onchange="wppa_setCookie( 'wppa_bulk_owner',this.value,365 );">
					<option value="" ><?php 
                _e('- select an owner -', 'wp-photo-album-plus');
                ?>
</option>
					<?php 
                foreach ($users as $user) {
                    echo '<option value="' . $user['user_login'] . '" >' . $user['display_name'] . ' (' . $user['user_login'] . ')</option>';
                }
                ?>
				</select>
				<?php 
            } else {
                ?>
				<input name="wppa-bulk-owner" id="wppa-bulk-owner" style="display:none;" onchange="wppa_setCookie( 'wppa_bulk_owner',this.value,365 );" />
				<?php 
            }
            ?>
				<!-- Submit -->
				<input type="submit" onclick="return wppaBulkDoitOnClick()" class="button-primary" value="<?php 
            _e('Doit!', 'wp-photo-album-plus');
            ?>
" />
				<span style="font-family:sans-serif; font-size:12px; font-style:italic; font-weight:normal;" >
					<?php 
            _e('Pressing this button will reload the page after executing the selected action', 'wp-photo-album-plus');
            ?>
				</span>
				</h3>
				<table class="widefat" >
					<thead style="font-weight:bold;" >
						<td><input type="checkbox" class="wppa-bulk-photo" onchange="jQuery( '.wppa-bulk-photo' ).attr( 'checked', this.checked );" /></td>
						<td><?php 
            _e('ID', 'wp-photo-album-plus');
            ?>
</td>
						<td><?php 
            _e('Preview', 'wp-photo-album-plus');
            ?>
</td>
						<td><?php 
            _e('Name', 'wp-photo-album-plus');
            ?>
</td>
						<td><?php 
            _e('Description', 'wp-photo-album-plus');
            ?>
</td>
						<td><?php 
            _e('Status', 'wp-photo-album-plus');
            ?>
</td>
						<td><?php 
            _e('Owner', 'wp-photo-album-plus');
            ?>
</td>
						<td><?php 
            _e('Remark', 'wp-photo-album-plus');
            ?>
</td>
					</thead>
					<tbody>
						<?php 
            foreach ($photos as $photo) {
                ?>
						<?php 
                $id = $photo['id'];
                ?>
						<tr id="photoitem-<?php 
                echo $photo['id'];
                ?>
" >
							<!-- Checkbox -->
							<td>
								<input type="hidden" id="photo-nonce-<?php 
                echo $photo['id'];
                ?>
" value="<?php 
                echo wp_create_nonce('wppa_nonce_' . $photo['id']);
                ?>
" />
								<input type="checkbox" name="wppa-bulk-photo[<?php 
                echo $photo['id'];
                ?>
]" class="wppa-bulk-photo" />
							</td>
							<!-- ID and delete link -->
							<td><?php 
                echo $photo['id'];
                ?>
								<br /><a onclick="if ( confirm( '<?php 
                _e('Are you sure you want to delete this photo?', 'wp-photo-album-plus');
                ?>
' ) ) wppaAjaxDeletePhoto( <?php 
                echo $photo['id'];
                ?>
, '<td colspan=3 >', '</td>' )" style="color:red;font-weight:bold;"><?php 
                _e('Delete', 'wp-photo-album-plus');
                ?>
</a>
							</td>
							<!-- Preview -->
							<td style="min-width:240px; text-align:center;" >
							<?php 
                if (wppa_is_video($photo['id'])) {
                    ?>
								<a href="<?php 
                    echo str_replace('xxx', 'mp4', wppa_get_photo_url($photo['id']));
                    ?>
" target="_blank" title="Click to see fullsize" >
									<?php 
                    // Animating size changes of a video tag is not a good idea. It will rapidly screw up browser cache and cpu
                    ?>
									<?php 
                    echo wppa_get_video_html(array('id' => $id, 'height' => '60', 'controls' => false, 'tagid' => 'pa-id-' . $id, 'events' => ' onmouseover="jQuery( this ).css( \'height\', \'160\' )" onmouseout="jQuery( this ).css( \'height\', \'60\' )"', 'preload' => 'metadata', 'use_thumb' => true));
                    ?>
					<!--				<video preload="metadata" style="height:60px;" onmouseover="jQuery( this ).css( 'height', '160' )" onmouseout="jQuery( this ).css( 'height', '60' )" >
										<?php 
                    // echo wppa_get_video_body( $photo['id'] )
                    ?>
									</video>	-->
								</a>
							<?php 
                } else {
                    ?>
								<a href="<?php 
                    echo wppa_fix_poster_ext(wppa_get_photo_url($photo['id']), $photo['id']);
                    ?>
" target="_blank" title="Click to see fullsize" >
									<img class="wppa-bulk-thumb" src="<?php 
                    echo wppa_fix_poster_ext(wppa_get_thumb_url($photo['id']), $photo['id']);
                    ?>
" style="height:60px;" onmouseover="jQuery( this ).stop().animate( {height:120}, 100 )" onmouseout="jQuery( this ).stop().animate( {height:60}, 100 )" />
								</a>
							<?php 
                }
                ?>
							</td>
							<td style="width:25%;" >
								<input type="text" style="width:100%;" id="pname-<?php 
                echo $photo['id'];
                ?>
" onchange="wppaAjaxUpdatePhoto( <?php 
                echo $photo['id'];
                ?>
, 'name', this );" value="<?php 
                echo esc_attr(stripslashes($photo['name']));
                ?>
" />
								<?php 
                if (wppa_is_video($photo['id'])) {
                    echo '<br />' . wppa_get_videox($photo['id']) . ' x ' . wppa_get_videoy($photo['id']) . ' px.';
                } else {
                    $sp = wppa_get_source_path($photo['id']);
                    if (is_file($sp)) {
                        $ima = getimagesize($sp);
                        if (is_array($ima)) {
                            echo '<br />' . $ima['0'] . ' x ' . $ima['1'] . ' px.';
                        }
                    }
                }
                ?>
							</td>
							<!-- Description -->
							<td style="width:25%;" >
								<textarea class="wppa-bulk-dec" style="height:50px; width:100%" onchange="wppaAjaxUpdatePhoto( <?php 
                echo $photo['id'];
                ?>
, 'description', this )" ><?php 
                echo stripslashes($photo['description']);
                ?>
</textarea>
							</td>
							<!-- Status -->
							<td>
							<?php 
                if (current_user_can('wppa_admin') || current_user_can('wppa_moderate')) {
                    ?>
								<select id="status-<?php 
                    echo $photo['id'];
                    ?>
" onchange="wppaAjaxUpdatePhoto( <?php 
                    echo $photo['id'];
                    ?>
, 'status', this ); wppaPhotoStatusChange( <?php 
                    echo $photo['id'];
                    ?>
 ); ">
									<option value="pending" <?php 
                    if ($photo['status'] == 'pending') {
                        echo 'selected="selected"';
                    }
                    ?>
 ><?php 
                    _e('Pending', 'wp-photo-album-plus');
                    ?>
</option>
									<option value="publish" <?php 
                    if ($photo['status'] == 'publish') {
                        echo 'selected="selected"';
                    }
                    ?>
 ><?php 
                    _e('Publish', 'wp-photo-album-plus');
                    ?>
</option>
									<?php 
                    if (wppa_switch('ext_status_restricted') && !wppa_user_is('administrator')) {
                        $dis = ' disabled';
                    } else {
                        $dis = '';
                    }
                    ?>
									<option value="featured" <?php 
                    if ($photo['status'] == 'featured') {
                        echo 'selected="selected"';
                    }
                    echo $dis;
                    ?>
 ><?php 
                    _e('Featured', 'wp-photo-album-plus');
                    ?>
</option>
									<option value="gold" <?php 
                    if ($photo['status'] == 'gold') {
                        echo 'selected="selected"';
                    }
                    echo $dis;
                    ?>
 ><?php 
                    _e('Gold', 'wp-photo-album-plus');
                    ?>
</option>
									<option value="silver" <?php 
                    if ($photo['status'] == 'silver') {
                        echo 'selected="selected"';
                    }
                    echo $dis;
                    ?>
 ><?php 
                    _e('Silver', 'wp-photo-album-plus');
                    ?>
</option>
									<option value="bronze" <?php 
                    if ($photo['status'] == 'bronze') {
                        echo 'selected="selected"';
                    }
                    echo $dis;
                    ?>
 ><?php 
                    _e('Bronze', 'wp-photo-album-plus');
                    ?>
</option>
									<option value="scheduled" <?php 
                    if ($photo['status'] == 'scheduled') {
                        echo 'selected="selected"';
                    }
                    echo $dis;
                    ?>
 ><?php 
                    _e('Scheduled', 'wp-photo-album-plus');
                    ?>
</option>
									<option value="private" <?php 
                    if ($photo['status'] == 'private') {
                        echo 'selected="selected"';
                    }
                    echo $dis;
                    ?>
 ><?php 
                    _e('Private', 'wp-photo-album-plus');
                    ?>
</option>
								</select>
							<?php 
                } else {
                    if ($photo['status'] == 'pending') {
                        _e('Pending', 'wp-photo-album-plus');
                    } elseif ($photo['status'] == 'publish') {
                        _e('Publish', 'wp-photo-album-plus');
                    } elseif ($photo['status'] == 'featured') {
                        e('Featured');
                    } elseif ($photo['status'] == 'gold') {
                        _e('Gold', 'wp-photo-album-plus');
                    } elseif ($photo['status'] == 'silver') {
                        _e('Silver', 'wp-photo-album-plus');
                    } elseif ($photo['status'] == 'bronze') {
                        _e('Bronze', 'wp-photo-album-plus');
                    } elseif ($photo['status'] == 'scheduled') {
                        _e('Scheduled', 'wp-photo-album-plus');
                    } elseif ($photo['status'] == 'private') {
                        _e('Private', 'wp-photo-album-plus');
                    }
                }
                ?>
							</td>
							<!-- Owner -->
							<td>
								<?php 
                echo $photo['owner'];
                ?>
							</td>
							<!-- Remark -->
							<td id="photostatus-<?php 
                echo $photo['id'];
                ?>
" style="width:25%;" >
								<?php 
                _e('Not modified', 'wp-photo-album-plus');
                ?>
								<script type="text/javascript">wppaPhotoStatusChange( <?php 
                echo $photo['id'];
                ?>
 )</script>
							</td>
						</tr>
						<?php 
            }
            ?>
					</tbody>
					<tfoot style="font-weight:bold;" >
						<td><input type="checkbox" class="wppa-bulk-photo" onchange="jQuery( '.wppa-bulk-photo' ).attr( 'checked', this.checked );" /></td>
						<td><?php 
            _e('ID', 'wp-photo-album-plus');
            ?>
</td>
						<td><?php 
            _e('Preview', 'wp-photo-album-plus');
            ?>
</td>
						<td><?php 
            _e('Name', 'wp-photo-album-plus');
            ?>
</td>
						<td><?php 
            _e('Description', 'wp-photo-album-plus');
            ?>
</td>
						<td><?php 
            _e('Status', 'wp-photo-album-plus');
            ?>
</td>
						<td><?php 
            _e('Owner', 'wp-photo-album-plus');
            ?>
</td>
						<td><?php 
            _e('Remark', 'wp-photo-album-plus');
            ?>
</td>
					</tfoot>
				</table>
			</form>
			<?php 
            wppa_admin_page_links($page, $pagesize, $count, $link);
        } else {
            if ($page == '1') {
                if (isset($_REQUEST['wppa-searchstring'])) {
                    echo '<h3>' . __('No photos matching your search criteria.', 'wp-photo-album-plus') . '</h3>';
                } else {
                    echo '<h3>' . __('No photos yet in this album.', 'wp-photo-album-plus') . '</h3>';
                }
            } else {
                $page_1 = $page - '1';
                echo sprintf(__('Page %d is empty, try <a href="%s" >page %d</a>.', 'wp-photo-album-plus'), $page, $link . '&wppa-page=' . $page_1 . '#manage-photos', $page_1);
            }
        }
    } else {
        wppa_dbg_msg('Missing required argument in wppa_album_photos() 2', 'red', 'force');
    }
}
function wppa_fix_source_path()
{
    if (strpos(wppa_opt('source_dir'), ABSPATH) === 0) {
        return;
    }
    // Nothing to do here
    $wp_content = trim(str_replace(home_url(), '', content_url()), '/');
    // The source path should be: ( default ) WPPA_ABSPATH.WPPA_UPLOAD.'/wppa-source',
    // Or at least below WPPA_ABSPATH
    if (strpos(wppa_opt('source_dir'), WPPA_ABSPATH) === false) {
        if (strpos(wppa_opt('source_dir'), $wp_content) !== false) {
            // Its below wp-content
            $temp = explode($wp_content, wppa_opt('source_dir'));
            $temp['0'] = WPPA_ABSPATH;
            wppa_update_option('wppa_source_dir', implode($wp_content, $temp));
            wppa_log('Fix', 'Sourcepath set to ' . wppa_opt('source_dir'));
        } else {
            // Give up, set to default
            wppa_update_option('wppa_source_dir', WPPA_ABSPATH . WPPA_UPLOAD . '/wppa-source');
            wppa_log('Fix', 'Sourcepath set to default.');
        }
    }
}
function wppa_select($slug, $options, $values, $onchange = '', $class = '', $first_disable = false, $postaction = '', $max_width = '220')
{
    global $wppa_opt;
    global $wppa_defaults;
    if (!is_array($options)) {
        $html = __('There are no pages (yet) to link to.', 'wp-photo-album-plus');
        return $html;
    }
    // Check for wp delete_option bug
    $opt = get_option($slug, 'nil');
    if (!$opt && !in_array($opt, $values) && $slug != 'wppa_blacklist_user' && $slug != 'wppa_un_blacklist_user') {
        // Value can not be '' caused by a faulty delete_option() that did not remove the option but replaced the value by ''.
        update_option($slug, $wppa_defaults[$slug]);
        // Missing option takes the default
        wppa_opt($slug, $wppa_defaults[$slug]);
        // Also in memory
        wppa_log('Repair', 'Fixed option ' . $slug . ' set to ' . $wppa_defaults[$slug]);
    }
    $tit = __('Slug =', 'wp-photo-album-plus') . ' ' . $slug . "\n" . __('Values = ', 'wp-photo-album-plus');
    foreach ($values as $val) {
        $tit .= $val . ', ';
    }
    $tit = trim($tit, ', ');
    $title = wppa_switch('enable_shortcode_wppa_set') ? ' title="' . esc_attr($tit) . '"' : '';
    $html = '<select style="float:left; font-size: 11px; height: 20px; margin: 0px; padding: 0px; max-width:' . $max_width . 'px;" id="' . $slug . '"' . $title;
    //	if ($onchange != '')..
    $html .= ' onchange="' . $onchange . ';wppaAjaxUpdateOptionValue(\'' . $slug . '\', this);' . $postaction . '"';
    //	else $html .= ' onchange="wppaAjaxUpdateOptionValue(\''.$slug.'\', this)"';
    if ($class != '') {
        $html .= ' class="' . $class . '"';
    }
    $html .= '>';
    $val = get_option($slug);
    // value can be yes or no in Table 0 !! so do not use wppa_opt()
    $idx = 0;
    $cnt = count($options);
    while ($idx < $cnt) {
        $html .= "\n";
        $html .= '<option value="' . $values[$idx] . '" ';
        $dis = false;
        if ($idx == 0 && $first_disable) {
            $dis = true;
        }
        $opt = trim($options[$idx], '|');
        if ($opt != $options[$idx]) {
            $dis = true;
        }
        if ($val == $values[$idx]) {
            $html .= ' selected="selected"';
        }
        if ($dis) {
            $html .= ' disabled="disabled"';
        }
        $html .= '>' . $opt . '</option>';
        $idx++;
    }
    $html .= '</select>';
    $html .= '<img id="img_' . $slug . '" class="' . $class . '" src="' . wppa_get_imgdir() . 'star.png" title="' . __('Setting unmodified', 'wp-photo-album-plus') . '" style="padding:0 4px; float:left; height:16px; width:16px;" />';
    return $html;
}
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_create_pl_htaccess($pl_dirname = '')
{
    global $wpdb;
    $tim = time();
    // Only supported on single sites at the moment
    if (is_multisite() && !WPPA_MULTISITE_GLOBAL) {
        return false;
    }
    // If there are more than 200 albums, we do this as a cron job
    $n_albs = $wpdb->get_var("SELECT COUNT(*) FROM `" . WPPA_ALBUMS . "`");
    // Big site?
    if ($n_albs > 200) {
        // Are we a cron job?
        if (wppa_is_cron()) {
            // Remake required?
            if (!get_option('wppa_pl_htaccess_required')) {
                return false;
            }
        } else {
            // Tell cron it must be done
            update_option('wppa_pl_htaccess_required', true);
            return false;
        }
    } else {
        // In cron?
        if (wppa_is_cron()) {
            return false;
        }
    }
    // Either big in cron and required, or small and realtime
    // Where are the photo source files?
    $source_root = str_replace(ABSPATH, '', wppa_opt('source_dir'));
    // Find permalink root name
    if (!$pl_dirname) {
        $pl_dirname = wppa_opt('pl_dirname');
    }
    // If no pl_dirname, feature is disabled
    if (!$pl_dirname) {
        return false;
    }
    // Create pl root directory
    $pl_root = WPPA_CONTENT_PATH . '/' . $pl_dirname;
    if (!wppa_mktree($pl_root)) {
        wppa_log('Error', 'Can not create ' . $pl_root);
        return false;
    }
    // Create .htaccess file
    $file = fopen($pl_root . '/.htaccess', 'wb');
    if (!$file) {
        wppa_log('Error', 'Can not create ' . $pl_root . '/.htaccess');
        return false;
    }
    fwrite($file, '<IfModule mod_rewrite.c>');
    fwrite($file, "\n" . 'RewriteEngine On');
    // RewriteBase /wp-content/wppa-pl
    fwrite($file, "\n" . 'RewriteBase /' . str_replace(ABSPATH, '', $pl_root));
    $albs = $wpdb->get_results("SELECT `id`, `name` FROM `" . WPPA_ALBUMS . "` ORDER BY `name` DESC", ARRAY_A);
    if ($albs) {
        foreach ($albs as $alb) {
            $fm = wppa_get_album_name_for_pl($alb['id'], $alb['name']);
            $to = $source_root . '/album-' . $alb['id'];
            fwrite($file, "\n" . 'RewriteRule ^' . $fm . '/(.*) /' . $to . '/$1 [NC]');
        }
    }
    fwrite($file, "\n" . '</IfModule>');
    fclose($file);
    // Remove required flag
    delete_option('wppa_pl_htaccess_required');
    wppa_log('Dbg', 'Create pl_htaccess took ' . (time() - $tim) . ' seconds.');
    return true;
}
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;
}
Example #22
0
function wppa_verify_treecounts($alb, $key, $count)
{
    $treecounts = wppa_treecount_a($alb);
    $need_a = false;
    $need_p = false;
    // Number of albums ( $count ) equal to subalbums ( 'selfalbums' ) ?
    if ('albums' == $key) {
        if ($treecounts['selfalbums'] != $count) {
            // Faulty data
            $need_a = true;
        }
    }
    // Number of photos ( $count ) equal to photos in this album ( 'selfphotos' ( + opts ) )?
    if ('photos' == $key) {
        if (current_user_can('wppa_moderate')) {
            if ($treecounts['selfphotos'] + $treecounts['pendphotos'] + $treecounts['scheduledphotos'] != $count) {
                // Faulty data
                $need_p = true;
            }
        } else {
            if ($treecounts['selfphotos'] != $count) {
                // Faulty data
                $need_p = true;
            }
        }
    }
    // If no sub-albums, total number of photos should be equal to photos in this album ( 'selfphotos' )
    if (!$treecounts['selfalbums'] && $treecounts['photos'] != $treecounts['selfphotos']) {
        $need_p = true;
    }
    // Need recalc for reason albums fault?
    if ($need_a) {
        wppa_flush_treecounts($alb);
        wppa_log('Fix', 'Treecounts albums for album #' . $alb . ' (' . wppa_get_album_name($alb) . ')');
    }
    // Need recalc for reason photos fault?
    if ($need_p) {
        wppa_flush_treecounts($albumid);
        wppa_log('Fix', 'Treecounts photos for album #' . $alb . ' (' . wppa_get_album_name($alb) . ')');
    }
}
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_add_credit_points($amount, $reason = '', $id = '', $value = '', $user = '')
{
    // Anything to do?
    if (!$amount) {
        return;
    }
    // Initialize
    $bret = false;
    if ($user) {
        $usr = get_user_by('login', $user);
    } else {
        $usr = wp_get_current_user();
    }
    if (!$usr) {
        wppa_log('err', 'Could not add points to user ' . $user);
        return false;
    }
    // Cube points
    if (function_exists('cp_alterPoints')) {
        cp_alterPoints($usr->ID, $amount);
        $bret = true;
    }
    // myCred
    if (function_exists('mycred_add')) {
        $entry = $reason . ($id ? ', ' . __('Photo id =', 'wp-photo-album-plus') . ' ' . $id : '') . ($value ? ', ' . __('Value =', 'wp-photo-album-plus') . ' ' . $value : '');
        $bret = mycred_add(str_replace(' ', '_', $reason), $usr->ID, $amount, $entry, '', '', '');
    }
    return $bret;
}
function wppa_import_exif($id, $file, $nodelete = false)
{
    global $wpdb;
    static $labels;
    static $names;
    global $wppa;
    // Do we need this?
    if (!wppa_switch('wppa_save_exif')) {
        return;
    }
    // Check filetype
    if (!function_exists('exif_imagetype')) {
        return false;
    }
    $image_type = exif_imagetype($file);
    if ($image_type != IMAGETYPE_JPEG) {
        return false;
    }
    // Not supported image type
    // Get exif data
    if (!function_exists('exif_read_data')) {
        return false;
    }
    // Not supported by the server
    $exif = @exif_read_data($file, 'EXIF');
    if (!is_array($exif)) {
        return false;
    }
    // No data present
    // There is exif data for this image.
    // First delete any existing exif data for this image
    if (!$nodelete) {
        $wpdb->query($wpdb->prepare("DELETE FROM `" . WPPA_EXIF . "` WHERE `photo` = %s", $id));
        wppa_dbg_q('Q218');
    }
    // Find defined labels
    if (!is_array($labels)) {
        $result = $wpdb->get_results("SELECT * FROM `" . WPPA_EXIF . "` WHERE `photo` = '0' ORDER BY `tag`", ARRAY_A);
        wppa_dbg_q('Q219');
        if (!is_array($result)) {
            $result = array();
        }
        $labels = array();
        $names = array();
        foreach ($result as $res) {
            $labels[] = $res['tag'];
            $names[] = $res['description'];
        }
    }
    foreach (array_keys($exif) as $s) {
        // Process item
        wppa_dbg_msg('EXIF ' . $s . ' = ' . serialize($exif[$s]));
        // Check labels first
        $tag = '';
        if (in_array($s, $names)) {
            $i = 0;
            while ($i < count($labels)) {
                if ($names[$i] == $s) {
                    $tag = $labels[$i];
                }
            }
        }
        if ($tag == '') {
            $tag = wppa_exif_tag($s);
        }
        if ($tag == 'E#EA1C') {
            $tag = '';
        }
        // EA1C is explixitly undefined and will fail to register
        if ($tag == '') {
            continue;
        }
        if (!in_array($tag, $labels)) {
            // Add to labels
            $labels[] = $tag;
            $names[] = $s . ':';
            // Add to db
            $photo = '0';
            $desc = $s . ':';
            $status = 'display';
            if (substr($s, 0, 12) == 'UndefinedTag') {
                $status = 'hide';
            }
            $iret = wppa_create_exif_entry(array('photo' => $photo, 'tag' => $tag, 'description' => $desc, 'status' => $status));
            if (!$iret) {
                wppa_log('Warning 1', 'Could not add EXIF tag ' . $tag . ' for photo ' . $photo);
            }
        }
        // Now add poto specific data item
        // If its an array...
        if (is_array($exif[$s])) {
            // continue;
            $c = count($exif[$s]);
            $max = wppa_opt('wppa_exif_max_array_size');
            if ($max != '0' && $c > $max) {
                wppa_dbg_msg('Exif tag ' . $tag . ': array truncated form ' . $c . ' to ' . $max . ' elements for photo nr ' . $id . '.', 'red');
                $c = $max;
            }
            for ($i = 0; $i < $c; $i++) {
                $photo = $id;
                $desc = $exif[$s][$i];
                $status = 'default';
                $iret = wppa_create_exif_entry(array('photo' => $photo, 'tag' => $tag, 'description' => $desc, 'status' => $status));
                if (!$iret) {
                    wppa_log('Warning 2', 'Could not add EXIF tag ' . $tag . ' for photo ' . $photo);
                }
            }
        } else {
            $photo = $id;
            $desc = $exif[$s];
            $status = 'default';
            $iret = wppa_create_exif_entry(array('photo' => $photo, 'tag' => $tag, 'description' => $desc, 'status' => $status));
            if (!$iret) {
            }
            /* wppa_log( 'Warning 3', 'Could not add EXIF tag '.$tag.' for photo '.$photo.', desc = '.$desc ); */
            // Is junk, dont care
        }
    }
    wppa_exif_clean_garbage($id);
}
function wppa_create_textual_watermark_file($args)
{
    // See what we have
    $args = wp_parse_args((array) $args, array('content' => '---preview---', 'pos' => 'cencen', 'id' => '', 'font' => wppa_opt('wppa_textual_watermark_font'), 'text' => '', 'style' => wppa_opt('wppa_textual_watermark_type'), 'filebasename' => 'dummy', 'url' => false, 'width' => '', 'height' => '', 'transp' => '0'));
    // We may have been called from wppa_get_water_file_and_pos() just to find the settings
    // In this case there is no id given.
    $id = $args['id'];
    if (!$id && $args['content'] != '---preview---') {
        return false;
    }
    if ($id && wppa_is_video($id)) {
        //		return false;
    }
    // Set special values in case of preview
    if ($args['content'] == '---preview---') {
        $preview = true;
        $fontsize = $args['font'] == 'system' ? 5 : 12;
        $padding = 6;
        $linespacing = ceil($fontsize * 2 / 3);
    } else {
        $preview = false;
        $fontsize = wppa_opt('wppa_textual_watermark_size');
        if ($args['font'] == 'system') {
            $fontsize = min($fontsize, 5);
        }
        $padding = 12;
        $linespacing = ceil($fontsize * 2 / 3);
    }
    // Set font specific vars
    $fontfile = $args['font'] == 'system' ? '' : WPPA_UPLOAD_PATH . '/fonts/' . $args['font'] . '.ttf';
    // Output file
    if ($preview) {
        $filename = WPPA_UPLOAD_PATH . '/fonts/wmf' . $args['filebasename'] . '.png';
    } else {
        $filename = WPPA_UPLOAD_PATH . '/temp/wmf' . $args['filebasename'] . '.png';
    }
    // Preprocess the text
    if (!$args['text']) {
        switch ($args['content']) {
            case '---preview---':
                $text = strtoupper(substr($args['font'], 0, 1)) . strtolower(substr($args['font'], 1));
                break;
            case '---filename---':
                $text = wppa_get_photo_item($id, 'filename');
                break;
            case '---name---':
                $text = wppa_get_photo_name($id);
                break;
            case '---description---':
                $text = strip_tags(wppa_strip_tags(wppa_get_photo_desc($id), 'style&script'));
                break;
            case '---predef---':
                $text = wppa_opt('wppa_textual_watermark_text');
                if ($args['font'] != 'system') {
                    $text = str_replace('( c )', '&copy;', $text);
                    $text = str_replace('( R )', '&reg;', $text);
                }
                $text = html_entity_decode($text);
                $text = str_replace('w#site', get_bloginfo('url'), $text);
                $text = str_replace('w#owner', wppa_get_photo_item($id, 'owner'), $text);
                $text = str_replace('w#id', $id, $text);
                $text = str_replace('w#name', wppa_get_photo_name($id), $text);
                $text = str_replace('w#filename', wppa_get_photo_item($id, 'filename'), $text);
                $text = str_replace('w#timestamp', wppa_local_date(get_option('date_format', "F j, Y,") . ' ' . get_option('time_format', "g:i a"), wppa_get_photo_item($id, 'timestamp')), $text);
                $text = trim($text);
                break;
            default:
                wppa_log('Error', 'Unimplemented arg ' . $arg . ' in wppa_create_textual_watermark_file()');
                return false;
        }
    } else {
        $text = $args['text'];
    }
    // Any text anyway?
    if (!strlen($text)) {
        wppa_log('Error', 'No text for textual watermark. photo=' . $id);
        return false;
        // No text -> no watermark
    }
    // Split text on linebreaks
    $text = str_replace("\n", '\\n', $text);
    $lines = explode('\\n', $text);
    // Trim and remove empty lines
    $temp = $lines;
    $lines = array();
    foreach ($temp as $line) {
        $line = trim($line);
        if ($line) {
            $lines[] = $line;
        }
    }
    // Find image width
    if ($args['width']) {
        $image_width = $args['width'];
    } else {
        $image_width = '';
    }
    if ($args['height']) {
        $image_height = $args['height'];
    } else {
        $image_height = '';
    }
    if ($preview) {
        if (!$image_width) {
            $image_width = 2000;
        }
        if (!$image_height) {
            $image_height = 1000;
        }
    } else {
        //		$temp = getimagesize( wppa_get_photo_path( $id ) );
        $temp = wppa_get_imagexy($id);
        if (!is_array($temp)) {
            wppa_log('Error', 'Trying to apply a watermark on a non image file. Id = ' . $id);
            return false;
            // not an image
        }
        if (!$image_width) {
            $image_width = $temp[0];
        }
        if (!$image_height) {
            $image_height = $temp[1];
        }
    }
    $width_fits = false;
    while (!$width_fits) {
        // Find pixel linelengths
        foreach (array_keys($lines) as $key) {
            $lines[$key] = trim($lines[$key]);
            if ($args['font'] == 'system') {
                $lengths[$key] = strlen($lines[$key]) * imagefontwidth($fontsize);
            } else {
                $temp = imagettfbbox($fontsize, 0.0, $fontfile, $lines[$key]);
                $lengths[$key] = $temp[2] - $temp[0];
            }
        }
        $maxlen = wppa_array_max($lengths);
        // Find canvas size
        $nlines = count($lines);
        if ($args['font'] == 'system') {
            $lineheight = imagefontheight($fontsize);
        } else {
            $temp = imagettfbbox($fontsize, 0.0, $fontfile, $lines[0]);
            $lineheight = $temp[3] - $temp[7];
        }
        $canvas_width = wppa_array_max($lengths) + 4 * $padding;
        $canvas_height = ($lineheight + $linespacing) * count($lines) + 2 * $padding;
        // Does it fit?
        if ($canvas_width > $image_width) {
            // Break the longest line into two sublines. There should be a space in the right half, if not: fail
            $i = 0;
            $l = 0;
            foreach (array_keys($lines) as $key) {
                if (strlen($lines[$key]) > $l) {
                    $i = $key;
                    $l = strlen($lines[$key]);
                }
            }
            $temp = $lines;
            $lines = array();
            $j = 0;
            while ($j < $i) {
                $lines[$j] = $temp[$j];
                $j++;
            }
            //
            $j = $i;
            $llen = strlen($temp[$i]);
            $spos = floor($llen / 2);
            while ($spos < $llen && substr($temp[$i], $spos, 1) != ' ') {
                $spos++;
            }
            if ($spos == $llen) {
                // Unable to find a space, give up
                wppa_log('Error', 'Trying to apply a watermark that is too wide for the image. Id = ' . $id);
                return false;
                // too wide
            }
            $lines[$j] = substr($temp[$i], 0, $spos);
            $lines[$j + 1] = trim(str_replace($lines[$j], '', $temp[$i]));
            $i++;
            //
            $j = $i + 1;
            while ($j <= count($temp)) {
                $lines[$j] = $temp[$i];
                $j++;
            }
        } else {
            $width_fits = true;
        }
        if ($canvas_height > $image_height) {
            wppa_log('Error', 'Trying to apply a watermark that is too high for the image. Id = ' . $id);
            return false;
            // not an image
        }
    }
    // Create canvas
    $canvas = imagecreatetruecolor($canvas_width, $canvas_height);
    $bgcolor = imagecolorallocatealpha($canvas, 0, 0, 0, 127);
    // Transparent
    $white = imagecolorallocatealpha($canvas, 255, 255, 255, $args['transp']);
    $black = imagecolorallocatealpha($canvas, 0, 0, 0, $args['transp']);
    imagefill($canvas, 0, 0, $bgcolor);
    //	imagerectangle( $canvas, 0, 0, $canvas_width-1, $canvas_height-1, $white );	// debug
    // Define the text colors
    switch ($args['style']) {
        case 'tvstyle':
        case 'whiteonblack':
            $fg = $white;
            $bg = $black;
            break;
        case 'utopia':
        case 'blackonwhite':
            $fg = $black;
            $bg = $white;
            break;
        case 'white':
            $fg = $white;
            $bg = $bgcolor;
            break;
        case 'black':
            $fg = $black;
            $bg = $bgcolor;
            break;
    }
    // Plot the text
    foreach (array_keys($lines) as $lineno) {
        if (strpos($args['pos'], 'lft') !== false) {
            $indent = 0;
        } elseif (strpos($args['pos'], 'rht') !== false) {
            $indent = $maxlen - $lengths[$lineno];
        } else {
            $indent = floor(($maxlen - $lengths[$lineno]) / 2);
        }
        switch ($args['style']) {
            case 'tvstyle':
            case 'utopia':
                for ($i = -1; $i <= 1; $i++) {
                    for ($j = -1; $j <= 1; $j++) {
                        if ($args['font'] == 'system') {
                            imagestring($canvas, $fontsize, 2 * $padding + $i + $indent, $padding + $lineno * ($lineheight + $linespacing) + $j, $lines[$lineno], $bg);
                        } else {
                            imagettftext($canvas, $fontsize, 0, 2 * $padding + $i + $indent, $padding + ($lineno + 1) * $lineheight + $lineno * $linespacing + $j, $bg, $fontfile, $lines[$lineno]);
                        }
                    }
                }
                if ($args['font'] == 'system') {
                    imagestring($canvas, $fontsize, 2 * $padding + $indent, $padding + $lineno * ($lineheight + $linespacing), $lines[$lineno], $fg);
                } else {
                    imagettftext($canvas, $fontsize, 0, 2 * $padding + $indent, $padding + ($lineno + 1) * $lineheight + $lineno * $linespacing, $fg, $fontfile, $lines[$lineno]);
                }
                break;
            case 'blackonwhite':
            case 'whiteonblack':
            case 'white':
            case 'black':
                $lft = $padding + $indent;
                $rht = 3 * $padding + $indent + $lengths[$lineno];
                $top = $lineno * ($lineheight + $linespacing) + $padding;
                $bot = ($lineno + 1) * ($lineheight + $linespacing) + $padding;
                imagefilledrectangle($canvas, $lft, $top + 1, $rht, $bot, $bg);
                //				imagerectangle( $canvas, $lft, $top, $rht, $bot, $fg );	// debug
                $top = $padding + $lineno * ($lineheight + $linespacing) + floor($linespacing / 2);
                $lft = 2 * $padding + $indent;
                $bot = $padding + ($lineno + 1) * ($lineheight + $linespacing) - ceil($linespacing / 2);
                if ($args['font'] == 'system') {
                    imagestring($canvas, $fontsize, $lft, $top, $lines[$lineno], $fg);
                } else {
                    imagettftext($canvas, $fontsize, 0, $lft, $bot - 1, $fg, $fontfile, $lines[$lineno]);
                }
                break;
        }
    }
    imagesavealpha($canvas, true);
    imagepng($canvas, $filename);
    imagedestroy($canvas);
    if ($preview || $args['url']) {
        $url = str_replace(WPPA_UPLOAD_PATH, WPPA_UPLOAD_URL, $filename);
        return $url;
    } else {
        return $filename;
    }
}
function wppa_delete_from_cloudinary($id)
{
    global $wppa_cloudinary_api;
    $prefix = is_multisite() && !WPPA_MULTISITE_GLOBAL ? $blog_id . '-' : '';
    if (is_array($id)) {
        foreach (array_keys($id) as $key) {
            $id[$key] = $prefix . $id[$key];
        }
        $pub_id = implode(',', $id);
    } else {
        $pub_id = $prefix . $id;
    }
    $result = $wppa_cloudinary_api->delete_derived_resources($pub_id);
    $result = $wppa_cloudinary_api->delete_resources($pub_id);
    //wppa_log('Obs', 'Deleteing from Cloudinary: '.$pub_id);
    //wppa_log('Obs', 'Returned: '.serialize($result));
    //wppa_log('Obs',var_dump($result));
    if (isset($result->rate_limit_allowed)) {
        if ($result->rate_limit_remaining < '10') {
            wppa_log('Observation', 'Running out of Cloudinary API calls');
            echo 'Error: Running out of allowed Cloudinary Api calls. Please try to continue in an hour';
        }
    }
}
function wppa_ajax_callback()
{
    global $wpdb;
    global $wppa_session;
    wppa('ajax', true);
    wppa('error', '0');
    wppa('out', '');
    $wppa_session['page']--;
    $wppa_session['ajax']++;
    wppa_save_session();
    // ALTHOUGH IF WE ARE HERE AS FRONT END VISITOR, is_admin() is true.
    // So, $wppa_opt switches are 'yes' or 'no' and not true or false.
    // So, always use the function wppa_switch( $slug ) to test on a bool setting
    // Globally check query args to prevent php injection
    $wppa_args = array('album', 'photo', 'slide', 'cover', 'occur', 'woccur', 'searchstring', 'topten', 'lasten', 'comten', 'featen', 'single', 'photos-only', 'debug', 'relcount', 'upldr', 'owner', 'rootsearch');
    foreach ($_REQUEST as $arg) {
        if (in_array(str_replace('wppa-', '', $arg), $wppa_args)) {
            if (strpos($arg, '<?') !== false) {
                die('Security check failure #91');
            }
            if (strpos($arg, '?>') !== false) {
                die('Security check failure #92');
            }
        }
    }
    wppa_vfy_arg('wppa-action', true);
    wppa_vfy_arg('photo-id');
    wppa_vfy_arg('comment-id');
    wppa_vfy_arg('moccur');
    wppa_vfy_arg('comemail', true);
    wppa_vfy_arg('comname', true);
    wppa_vfy_arg('tag', true);
    $wppa_action = $_REQUEST['wppa-action'];
    switch ($wppa_action) {
        case 'getssiptclist':
            $tag = str_replace('H', '#', $_REQUEST['tag']);
            $mocc = $_REQUEST['moccur'];
            $oldvalue = '';
            if (strpos($wppa_session['supersearch'], ',') !== false) {
                $ss_data = explode(',', $wppa_session['supersearch']);
                if (count($ss_data) == '4') {
                    if ($ss_data['0'] == 'p') {
                        if ($ss_data['1'] == 'i') {
                            if ($ss_data['2'] == $_REQUEST['tag']) {
                                $oldvalue = $ss_data['3'];
                            }
                        }
                    }
                }
            }
            $iptcdata = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_IPTC . "` WHERE `photo` > '0' AND `tag` = %s ORDER BY `description`", $tag), ARRAY_A);
            $last = '';
            $any = false;
            if (is_array($iptcdata)) {
                foreach ($iptcdata as $item) {
                    $desc = sanitize_text_field($item['description']);
                    $desc = str_replace(array(chr(0), chr(1), chr(2), chr(3), chr(4), chr(5), chr(6), chr(7)), '', $desc);
                    if ($desc != $last) {
                        $sel = $oldvalue && $oldvalue == $desc ? 'selected="selected"' : '';
                        if ($sel) {
                            echo 'selected:' . $oldvalue;
                        }
                        $ddesc = strlen($desc) > '32' ? substr($desc, 0, 30) . '...' : $desc;
                        echo '<option' . ' value="' . esc_attr($desc) . '"' . ' class="wppa-iptclist-' . $mocc . '"' . ' ' . $sel . ' >' . $ddesc . '</option>';
                        $last = $desc;
                        $any = true;
                    }
                }
            }
            if (!$any) {
                $query = $wpdb->prepare("DELETE FROM `" . WPPA_IPTC . "` WHERE `photo` = '0' AND `tag` = %s", $tag);
                $wpdb->query($query);
                //				wppa_log( 'dbg', $query );
            }
            wppa_exit();
            break;
        case 'getssexiflist':
            $tag = str_replace('H', '#', $_REQUEST['tag']);
            $mocc = $_REQUEST['moccur'];
            $oldvalue = '';
            if (strpos($wppa_session['supersearch'], ',') !== false) {
                $ss_data = explode(',', $wppa_session['supersearch']);
                if (count($ss_data) == '4') {
                    if ($ss_data['0'] == 'p') {
                        if ($ss_data['1'] == 'e') {
                            if ($ss_data['2'] == $_REQUEST['tag']) {
                                $oldvalue = $ss_data['3'];
                            }
                        }
                    }
                }
            }
            $exifdata = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_EXIF . "` WHERE `photo` > '0' AND `tag` = %s ORDER BY `description`", $tag), ARRAY_A);
            $last = '';
            $any = false;
            if (is_array($exifdata)) {
                foreach ($exifdata as $item) {
                    $desc = sanitize_text_field($item['description']);
                    $desc = str_replace(array(chr(0), chr(1), chr(2), chr(3), chr(4), chr(5), chr(6), chr(7)), '', $desc);
                    if ($desc != $last) {
                        $sel = $oldvalue && $oldvalue == $desc ? 'selected="selected"' : '';
                        $ddesc = strlen($desc) > '32' ? substr($desc, 0, 30) . '...' : $desc;
                        echo '<option' . ' value="' . esc_attr($desc) . '"' . ' class="wppa-exiflist-' . $mocc . '"' . ' ' . $sel . ' >' . $ddesc . '</option>';
                        $last = $desc;
                        $any = true;
                    }
                }
            }
            if (!$any) {
                $query = $wpdb->prepare("DELETE FROM `" . WPPA_EXIF . "` WHERE `photo` = '0' AND `tag` = %s", $tag);
                $wpdb->query($query);
                //				wppa_log( 'dbg', $query );
            }
            wppa_exit();
            break;
        case 'front-edit':
            if (!isset($_REQUEST['photo-id'])) {
                die('Missing required argument');
            }
            $photo = $_REQUEST['photo-id'];
            $ok = false;
            if (current_user_can('wppa_admin')) {
                $ok = true;
            }
            if (wppa_get_user() == wppa_get_photo_owner($photo) && (current_user_can('wppa_upload') || is_user_logged_in() && wppa_switch('upload_edit'))) {
                $ok = true;
            }
            if (!$ok) {
                die('You do not have sufficient rights to do this');
            }
            require_once 'wppa-photo-admin-autosave.php';
            wppa('front_edit', true);
            echo '	<div style="padding-bottom:4px;height:24px;" >
						<span style="color:#777;" >
							<i>' . __('All modifications are instantly updated on the server. The <b style="color:#070" >Remark</b> field keeps you informed on the actions taken at the background.', 'wp-photo-album-plus') . '</i>
						</span>
						<input id="wppa-fe-exit" type="button" style="float:right;color:red;font-weight:bold;" onclick="window.opener.location.reload( true );window.close();" value="' . __('Exit & Refresh', 'wp-photo-album-plus') . '" />
						<div id="wppa-fe-count" style="float:right;" ></div>
					</div><div style="clear:both;"></div>';
            wppa_album_photos('', $photo);
            wppa_exit();
            break;
        case 'do-comment':
            // Security check
            $mocc = $_REQUEST['moccur'];
            $nonce = $_REQUEST['wppa-nonce'];
            if (!wp_verify_nonce($nonce, 'wppa-nonce-' . $mocc)) {
                _e('Security check failure', 'wp-photo-album-plus');
                wppa_exit();
            }
            // Correct the fact that this is a non-admin operation, if it is only
            if (is_admin()) {
                require_once 'wppa-non-admin.php';
            }
            wppa('mocc', $_REQUEST['moccur']);
            wppa('comment_photo', isset($_REQUEST['photo-id']) ? $_REQUEST['photo-id'] : '0');
            wppa('comment_id', isset($_REQUEST['comment-edit']) ? $_REQUEST['comment-edit'] : '0');
            $comment_allowed = !wppa_switch('comment_login') || is_user_logged_in();
            if (wppa_switch('show_comments') && $comment_allowed) {
                //				if ( wppa_switch( 'search_comments' ) ) wppa_index_remove( 'photo', $_REQUEST['photo-id'] );
                wppa_do_comment($_REQUEST['photo-id']);
                // Process the comment
                if (wppa_switch('search_comments')) {
                    wppa_index_update('photo', $_REQUEST['photo-id']);
                }
            }
            wppa('no_esc', true);
            echo wppa_comment_html($_REQUEST['photo-id'], $comment_allowed);
            // Retrieve the new commentbox content
            wppa_exit();
            break;
        case 'import':
            require_once 'wppa-upload.php';
            _wppa_page_import();
            wppa_exit();
            break;
        case 'approve':
            $iret = '0';
            if (!current_user_can('wppa_moderate') && !current_user_can('wppa_comments')) {
                _e('You do not have the rights to moderate photos this way', 'wp-photo-album-plus');
                wppa_exit();
            }
            if (isset($_REQUEST['photo-id']) && current_user_can('wppa_moderate')) {
                $iret = $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `status` = 'publish' WHERE `id` = %s", $_REQUEST['photo-id']));
                wppa_flush_upldr_cache('photoid', $_REQUEST['photo-id']);
                $alb = $wpdb->get_var($wpdb->prepare("SELECT `album` FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $_REQUEST['photo-id']));
                wppa_clear_taglist();
                wppa_flush_treecounts($alb);
            }
            if (isset($_REQUEST['comment-id'])) {
                $iret = $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_COMMENTS . "` SET `status` = 'approved' WHERE `id` = %s", $_REQUEST['comment-id']));
            }
            if ($iret) {
                echo 'OK';
            } else {
                if (isset($_REQUEST['photo-id'])) {
                    if (current_user_can('wppa_moderate')) {
                        echo sprintf(__('Failed to update stutus of photo %s', 'wp-photo-album-plus'), $_REQUEST['photo-id']) . "\n" . __('Please refresh the page', 'wp-photo-album-plus');
                    } else {
                        _e('Security check failure', 'wp-photo-album-plus');
                    }
                }
                if (isset($_REQUEST['comment-id'])) {
                    echo sprintf(__('Failed to update stutus of comment %s', 'wp-photo-album-plus'), $_REQUEST['comment-id']) . "\n" . __('Please refresh the page', 'wp-photo-album-plus');
                }
            }
            wppa_exit();
        case 'remove':
            if (isset($_REQUEST['photo-id'])) {
                // Remove photo
                if (wppa_user_is('administrator') || current_user_can('wppa_moderate') || wppa_get_user() == wppa_get_photo_owner($_REQUEST['photo-id']) && wppa_switch('upload_edit')) {
                    // Frontend delete?
                    wppa_delete_photo($_REQUEST['photo-id']);
                    echo 'OK||' . __('Photo removed', 'wp-photo-album-plus');
                    wppa_exit();
                }
            }
            if (!current_user_can('wppa_moderate') && !current_user_can('wppa_comments')) {
                _e('You do not have the rights to moderate photos this way', 'wp-photo-album-plus');
                wppa_exit();
            }
            if (isset($_REQUEST['photo-id'])) {
                // Remove photo
                if (!current_user_can('wppa_moderate')) {
                    _e('Security check failure', 'wp-photo-album-plus');
                    wppa_exit();
                }
                wppa_delete_photo($_REQUEST['photo-id']);
                echo 'OK||' . __('Photo removed', 'wp-photo-album-plus');
                wppa_exit();
            }
            if (isset($_REQUEST['comment-id'])) {
                // Remove comment
                $iret = $wpdb->query($wpdb->prepare("DELETE FROM `" . WPPA_COMMENTS . "` WHERE `id`= %s", $_REQUEST['comment-id']));
                if ($iret) {
                    echo 'OK||' . __('Comment removed', 'wp-photo-album-plus');
                } else {
                    _e('Could not remove comment', 'wp-photo-album-plus');
                }
                wppa_exit();
            }
            _e('Unexpected error', 'wp-photo-album-plus');
            wppa_exit();
        case 'downloadalbum':
            // Feature enabled?
            if (!wppa_switch('allow_download_album')) {
                echo '||ER||' . __('This feature is not enabled on this website', 'wp-photo-album-plus');
                wppa_exit();
            }
            // Validate args
            $alb = $_REQUEST['album-id'];
            $status = "`status` <> 'pending' AND `status` <> 'scheduled'";
            if (!is_user_logged_in()) {
                $status .= " AND `status` <> 'private'";
            }
            $photos = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s AND ( ( " . $status . " ) OR owner = %s ) " . wppa_get_photo_order($alb), $alb, wppa_get_user()), ARRAY_A);
            if (!$photos) {
                echo '||ER||' . __('The album is empty', 'wp-photo-album-plus');
                wppa_exit();
            }
            // Remove obsolete files
            wppa_delete_obsolete_tempfiles();
            // Open zipfile
            if (!class_exists('ZipArchive')) {
                echo '||ER||' . __('Unable to create zip archive', 'wp-photo-album-plus');
                wppa_exit();
            }
            $zipfilename = wppa_get_album_name($alb);
            $zipfilename = wppa_sanitize_file_name($zipfilename . '.zip');
            // Remove illegal chars
            $zipfilepath = WPPA_UPLOAD_PATH . '/temp/' . $zipfilename;
            if (is_file($zipfilepath)) {
                //		unlink( $zipfilepath );	// Debug
            }
            $wppa_zip = new ZipArchive();
            $iret = $wppa_zip->open($zipfilepath, 1);
            if ($iret !== true) {
                echo '||ER||' . sprintf(__('Unable to create zip archive. code = %s', 'wp-photo-album-plus'), $iret);
                wppa_exit();
            }
            // Add photos to zip
            $stop = false;
            foreach ($photos as $p) {
                if (wppa_is_time_up()) {
                    wppa_log('obs', 'Time up during album to zip creation');
                    $stop = true;
                } else {
                    $id = $p['id'];
                    if (!wppa_is_multi($id)) {
                        $source = wppa_switch('download_album_source') && is_file(wppa_get_source_path($id)) ? wppa_get_source_path($id) : wppa_get_photo_path($id);
                        if (is_file($source)) {
                            $dest = $p['filename'] ? wppa_sanitize_file_name($p['filename']) : wppa_sanitize_file_name(wppa_strip_ext($p['name']) . '.' . $p['ext']);
                            $dest = wppa_fix_poster_ext($dest, $id);
                            $iret = $wppa_zip->addFile($source, $dest);
                            // To prevent too may files open, and to have at least a file when there are too many photos, close and re-open
                            $wppa_zip->close();
                            $wppa_zip->open($zipfilepath);
                            // wppa_log( 'dbg', 'Added ' . basename($source) . ' to ' . basename($zipfilepath));
                        }
                    }
                }
                if ($stop) {
                    break;
                }
            }
            // Close zip and return
            $zipcount = $wppa_zip->numFiles;
            $wppa_zip->close();
            // A zip is created
            $desturl = WPPA_UPLOAD_URL . '/temp/' . $zipfilename;
            echo $desturl . '||OK||';
            if ($zipcount != count($photos)) {
                echo sprintf(__('Only %s out of %s photos could be added to the zipfile', 'wp-photo-album-plus'), $zipcount, count($photos));
            }
            wppa_exit();
            break;
        case 'getalbumzipurl':
            $alb = $_REQUEST['album-id'];
            $zipfilename = wppa_get_album_name($alb);
            $zipfilename = wppa_sanitize_file_name($zipfilename . '.zip');
            // Remove illegal chars
            $zipfilepath = WPPA_UPLOAD_PATH . '/temp/' . $zipfilename;
            $zipfileurl = WPPA_UPLOAD_URL . '/temp/' . $zipfilename;
            if (is_file($zipfilepath)) {
                echo $zipfileurl;
            } else {
                echo 'ER';
            }
            wppa_exit();
            break;
        case 'makeorigname':
            $photo = $_REQUEST['photo-id'];
            $from = $_REQUEST['from'];
            if ($from == 'fsname') {
                $type = wppa_opt('art_monkey_link');
            } elseif ($from == 'popup') {
                $type = wppa_opt('art_monkey_popup_link');
            } else {
                echo '||7||' . __('Unknown source of request', 'wp-photo-album-plus');
                wppa_exit();
            }
            $data = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $photo), ARRAY_A);
            if ($data) {
                // The photo is supposed to exist
                // Make the name
                if ($data['filename']) {
                    $name = $data['filename'];
                } else {
                    $name = __($data['name'], 'wp-photo-album-plus');
                }
                $name = wppa_sanitize_file_name($name);
                // Remove illegal chars
                $name = preg_replace('/\\.[^.]*$/', '', $name);
                // Remove file extension
                if (strlen($name) == '0') {
                    echo '||1||' . __('Empty filename', 'wp-photo-album-plus');
                    wppa_exit();
                }
                // Make the file
                if (wppa_switch('artmonkey_use_source')) {
                    if (is_file(wppa_get_source_path($photo))) {
                        $source = wppa_get_source_path($photo);
                    } else {
                        $source = wppa_get_photo_path($photo);
                    }
                } else {
                    $source = wppa_get_photo_path($photo);
                }
                $source = wppa_fix_poster_ext($source, $photo);
                // Fix the extension for mm items.
                if ($data['ext'] == 'xxx') {
                    $data['ext'] = wppa_get_ext($source);
                }
                $dest = WPPA_UPLOAD_PATH . '/temp/' . $name . '.' . $data['ext'];
                $zipfile = WPPA_UPLOAD_PATH . '/temp/' . $name . '.zip';
                $tempdir = WPPA_UPLOAD_PATH . '/temp';
                if (!is_dir($tempdir)) {
                    @mkdir($tempdir);
                }
                if (!is_dir($tempdir)) {
                    echo '||2||' . __('Unable to create tempdir', 'wp-photo-album-plus');
                    wppa_exit();
                }
                // Remove obsolete files
                wppa_delete_obsolete_tempfiles();
                // Make the files
                if ($type == 'file') {
                    copy($source, $dest);
                    $ext = $data['ext'];
                } elseif ($type == 'zip') {
                    if (!class_exists('ZipArchive')) {
                        echo '||8||' . __('Unable to create zip archive', 'wp-photo-album-plus');
                        wppa_exit();
                    }
                    $ext = 'zip';
                    $wppa_zip = new ZipArchive();
                    $wppa_zip->open($zipfile, 1);
                    $wppa_zip->addFile($source, basename($dest));
                    $wppa_zip->close();
                } else {
                    echo '||6||' . __('Unknown type', 'wp-photo-album-plus');
                    wppa_exit();
                }
                $desturl = WPPA_UPLOAD_URL . '/temp/' . $name . '.' . $ext;
                echo '||0||' . $desturl;
                // No error: return url
                wppa_exit();
            } else {
                echo '||9||' . __('The photo does no longer exist', 'wp-photo-album-plus');
                wppa_exit();
            }
            wppa_exit();
            break;
        case 'tinymcedialog':
            $result = wppa_make_tinymce_dialog();
            echo $result;
            wppa_exit();
            break;
        case 'bumpviewcount':
            $nonce = $_REQUEST['wppa-nonce'];
            if (wp_verify_nonce($nonce, 'wppa-check')) {
                wppa_bump_viewcount('photo', $_REQUEST['wppa-photo']);
            } else {
                _e('Security check failure', 'wp-photo-album-plus');
            }
            wppa_exit();
            break;
        case 'rate':
            // Get commandline args
            $photo = $_REQUEST['wppa-rating-id'];
            $rating = $_REQUEST['wppa-rating'];
            $occur = $_REQUEST['wppa-occur'];
            $index = $_REQUEST['wppa-index'];
            $nonce = $_REQUEST['wppa-nonce'];
            // Make errortext
            $errtxt = __('An error occurred while processing you rating request.', 'wp-photo-album-plus');
            $errtxt .= "\n" . __('Maybe you opened the page too long ago to recognize you.', 'wp-photo-album-plus');
            $errtxt .= "\n" . __('You may refresh the page and try again.', 'wp-photo-album-plus');
            $wartxt = __('Althoug an error occurred while processing your rating, your vote has been registered.', 'wp-photo-album-plus');
            $wartxt .= "\n" . __('However, this may not be reflected in the current pageview', 'wp-photo-album-plus');
            // Check on validity
            if (!wp_verify_nonce($nonce, 'wppa-check')) {
                echo '0||100||' . $errtxt;
                wppa_exit();
                // Nonce check failed
            }
            if (wppa_opt('rating_max') == '1' && $rating != '1') {
                echo '0||106||' . $errtxt . ':' . $rating;
                wppa_exit();
                // Value out of range
            } elseif (wppa_opt('rating_max') == '5' && !in_array($rating, array('-1', '1', '2', '3', '4', '5'))) {
                echo '0||106||' . $errtxt . ':' . $rating;
                wppa_exit();
                // Value out of range
            } elseif (wppa_opt('rating_max') == '10' && !in_array($rating, array('-1', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'))) {
                echo '0||106||' . $errtxt . ':' . $rating;
                wppa_exit();
                // Value out of range
            }
            // Get other data
            if (!$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $photo))) {
                echo '0||999||' . __('Photo has been removed.', 'wp-photo-album-plus');
                wppa_exit();
            }
            $user = wppa_get_user();
            $mylast = $wpdb->get_row($wpdb->prepare('SELECT * FROM `' . WPPA_RATING . '` WHERE `photo` = %s AND `user` = %s ORDER BY `id` DESC LIMIT 1', $photo, $user), ARRAY_A);
            $myavgrat = '0';
            // Init
            // Rate own photo?
            if (wppa_get_photo_item($photo, 'owner') == $user && !wppa_switch('allow_owner_votes')) {
                echo '0||900||' . __('Sorry, you can not rate your own photos', 'wp-photo-album-plus');
                wppa_exit();
            }
            // Already a pending one?
            $pending = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_RATING . "` WHERE `photo` = %s AND `user` = %s AND `status` = %s", $photo, $user, 'pending'));
            // Has user motivated his vote?
            $hascommented = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_COMMENTS . "` WHERE `photo` = %s AND `user` = %s", $photo, wppa_get_user('display')));
            if ($pending) {
                if (!$hascommented) {
                    echo '0||900||' . __('Please enter a comment.', 'wp-photo-album-plus');
                    wppa_exit();
                } else {
                    $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_RATING . "` SET `status` = 'publish' WHERE `photo` = %s AND `user` = %s", $photo, $user));
                }
            }
            if (wppa_switch('vote_needs_comment')) {
                $ratingstatus = $hascommented ? 'publish' : 'pending';
            } else {
                $ratingstatus = 'publish';
            }
            // When done, we have to echo $occur.'||'.$photo.'||'.$index.'||'.$myavgrat.'||'.$allavgrat.'||'.$discount.||.$hascommented.||.$message;
            // So we have to do: process rating and find new $myavgrat, $allavgrat and $discount ( $occur, $photo and $index are known )
            // Case 0: Illegal second vote. Frontend takes care of this, but a hacker could enter an ajaxlink manually
            if ($mylast && (!(wppa_switch('rating_change') || wppa_switch('rating_multi')) || $mylast['value'] < '0' || $mylast['value'] > '0' && $rating == '-1')) {
                echo '0||109||' . __('Security check failure.', 'wp-photo-album-plus');
                wppa_exit();
            }
            // Case 1: value = -1 this is a legal dislike vote
            if ($rating == '-1') {
                // Add my dislike
                $iret = wppa_create_rating_entry(array('photo' => $photo, 'value' => $rating, 'user' => $user, 'status' => $ratingstatus));
                if (!$iret) {
                    echo '0||101||' . $errtxt;
                    wppa_exit();
                    // Fail on storing vote
                }
                // Add points
                wppa_add_credit_points(wppa_opt('cp_points_rating'), __('Photo rated', 'wp-photo-album-plus'), $photo, $rating);
                wppa_dislike_check($photo);
                // Check for email to be sent every .. dislikes
                if (!is_file(wppa_get_thumb_path($photo))) {
                    // Photo is removed
                    echo $occur . '||' . $photo . '||' . $index . '||-1||-1|0||' . wppa_opt('dislike_delete');
                    wppa_exit();
                }
            } elseif (!$mylast) {
                // Add my vote
                $iret = wppa_create_rating_entry(array('photo' => $photo, 'value' => $rating, 'user' => $user, 'status' => $ratingstatus));
                if (!$iret) {
                    echo '0||102||' . $errtxt;
                    wppa_exit();
                    // Fail on storing vote
                }
                // Add points
                wppa_add_credit_points(wppa_opt('cp_points_rating'), __('Photo rated', 'wp-photo-album-plus'), $photo, $rating);
            } elseif (wppa_switch('rating_change')) {
                // Votechanging is allowed
                $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_RATING . '` SET `value` = %s WHERE `photo` = %s AND `user` = %s LIMIT 1', $rating, $photo, $user));
                if ($iret === false) {
                    echo '0||103||' . $errtxt;
                    wppa_exit();
                    // Fail on update
                }
            } elseif (wppa_switch('rating_multi')) {
                // Rating multi is allowed
                $iret = wppa_create_rating_entry(array('photo' => $photo, 'value' => $rating, 'user' => $user, 'status' => $ratingstatus));
                if (!$iret) {
                    echo '0||104||' . $errtxt;
                    wppa_exit();
                    // Fail on storing vote
                }
            } else {
                // Should never get here....
                echo '0||110||' . __('Unexpected error', 'wp-photo-album-plus');
                wppa_exit();
            }
            // Compute my avg rating
            $myrats = $wpdb->get_results($wpdb->prepare('SELECT * FROM `' . WPPA_RATING . '`  WHERE `photo` = %s AND `user` = %s AND `status` = %s ', $photo, $user, 'publish'), ARRAY_A);
            if ($myrats) {
                $sum = 0;
                $cnt = 0;
                foreach ($myrats as $rat) {
                    if ($rat['value'] == '-1') {
                        $sum += wppa_opt('dislike_value');
                    } else {
                        $sum += $rat['value'];
                    }
                    $cnt++;
                }
                $myavgrat = $sum / $cnt;
                $i = wppa_opt('rating_prec');
                $j = $i + '1';
                $myavgrat = sprintf('%' . $j . '.' . $i . 'f', $myavgrat);
            } else {
                $myavgrat = '0';
            }
            // Compute new allavgrat
            $ratings = $wpdb->get_results($wpdb->prepare('SELECT * FROM ' . WPPA_RATING . ' WHERE `photo` = %s AND `status` = %s', $photo, 'publish'), ARRAY_A);
            if ($ratings) {
                $sum = 0;
                $cnt = 0;
                foreach ($ratings as $rat) {
                    if ($rat['value'] == '-1') {
                        $sum += wppa_opt('dislike_value');
                    } else {
                        $sum += $rat['value'];
                    }
                    $cnt++;
                }
                $allavgrat = $sum / $cnt;
                if ($allavgrat == '10') {
                    $allavgrat = '9.99999999';
                }
                // For sort order reasons text field
            } else {
                $allavgrat = '0';
            }
            // Store it in the photo info
            $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `mean_rating` = %s WHERE `id` = %s', $allavgrat, $photo));
            if ($iret === false) {
                echo '0||106||' . $wartxt;
                wppa_exit();
                // Fail on save
            }
            // Compute rating_count and store in the photo info
            $ratcount = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_RATING . "` WHERE `photo` = %s", $photo));
            if ($ratcount !== false) {
                $iret = $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `rating_count` = %s WHERE `id` = %s", $ratcount, $photo));
                if ($iret === false) {
                    echo '0||107||' . $wartxt;
                    wppa_exit();
                    // Fail on save
                }
            }
            // Format $allavgrat for output
            $allavgratcombi = $allavgrat . '|' . $ratcount;
            // Compute dsilike count
            $discount = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_RATING . "` WHERE `photo` = %s AND `value` = -1 AND `status` = %s", $photo, 'publish'));
            if ($discount === false) {
                echo '0||108||' . $wartxt;
                wppa_exit();
                // Fail on save
            }
            // Test for possible medal
            wppa_test_for_medal($photo);
            // Success!
            wppa_clear_cache();
            if (wppa_switch('vote_needs_comment') && !$hascommented) {
                $message = __("Please explain your vote in a comment.\nYour vote will be discarded if you don't.\n\nAfter completing your comment,\nyou can refresh the page to see\nyour vote became effective.", 'wp-photo-album-plus');
            } else {
                $message = '';
            }
            echo $occur . '||' . $photo . '||' . $index . '||' . $myavgrat . '||' . $allavgratcombi . '||' . $discount . '||' . $hascommented . '||' . $message;
            break;
        case 'render':
            $tim_1 = microtime(true);
            $nq_1 = get_num_queries();
            // Correct the fact that this is a non-admin operation, if it is
            if (is_admin()) {
                require_once 'wppa-non-admin.php';
            }
            wppa_load_theme();
            // Register geo shortcode if google-maps-gpx-vieuwer is on board. GPX does it in wp_head(), what is not done in an ajax call
            //			if ( function_exists( 'gmapv3' ) ) add_shortcode( 'map', 'gmapv3' );
            // Get the post we are working for
            if (isset($_REQUEST['wppa-fromp'])) {
                $p = $_REQUEST['wppa-fromp'];
                if (wppa_is_int($p)) {
                    $GLOBALS['post'] = get_post($p);
                }
            }
            // Render
            echo wppa_albums();
            $tim_2 = microtime(true);
            $nq_2 = get_num_queries();
            $mem = memory_get_peak_usage(true) / 1024 / 1024;
            $msg = sprintf('WPPA Ajax render: db queries: WP:%d, WPPA+: %d in %4.2f seconds, using %4.2f MB memory max', $nq_1, $nq_2 - $nq_1, $tim_2 - $tim_1, $mem);
            echo '<script type="text/javascript">wppaConsoleLog( \'' . $msg . '\', \'force\' )</script>';
            break;
        case 'delete-photo':
            $photo = $_REQUEST['photo-id'];
            $nonce = $_REQUEST['wppa-nonce'];
            // Check validity
            if (!wp_verify_nonce($nonce, 'wppa_nonce_' . $photo)) {
                echo '||0||' . __('You do not have the rights to delete a photo', 'wp-photo-album-plus');
                wppa_exit();
                // Nonce check failed
            }
            if (!is_numeric($photo)) {
                echo '||0||' . __('Security check failure', 'wp-photo-album-plus');
                wppa_exit();
                // Nonce check failed
            }
            $album = $wpdb->get_var($wpdb->prepare('SELECT `album` FROM `' . WPPA_PHOTOS . '` WHERE `id` = %s', $photo));
            wppa_delete_photo($photo);
            wppa_clear_cache();
            echo '||1||<span style="color:red" >' . sprintf(__('Photo %s has been deleted', 'wp-photo-album-plus'), $photo) . '</span>';
            echo '||';
            $a = wppa_allow_uploads($album);
            if (!$a) {
                echo 'full';
            } else {
                echo 'notfull||' . $a;
            }
            break;
        case 'update-album':
            $album = $_REQUEST['album-id'];
            $nonce = $_REQUEST['wppa-nonce'];
            $item = $_REQUEST['item'];
            $value = $_REQUEST['value'];
            $value = wppa_decode($value);
            // Check validity
            if (!wp_verify_nonce($nonce, 'wppa_nonce_' . $album)) {
                echo '||0||' . __('You do not have the rights to update album information', 'wp-photo-album-plus') . $nonce;
                wppa_exit();
                // Nonce check failed
            }
            switch ($item) {
                case 'clear_ratings':
                    $photos = $wpdb->get_results($wpdb->prepare('SELECT * FROM `' . WPPA_PHOTOS . '` WHERE `album` = %s', $album), ARRAY_A);
                    if ($photos) {
                        foreach ($photos as $photo) {
                            $iret1 = $wpdb->query($wpdb->prepare('DELETE FROM `' . WPPA_RATING . '` WHERE `photo` = %s', $photo['id']));
                            $iret2 = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `mean_rating` = %s WHERE `id` = %s', '', $photo['id']));
                        }
                    }
                    if ($photos && $iret1 !== false && $iret2 !== false) {
                        echo '||97||' . __('<b>Ratings cleared</b>', 'wp-photo-album-plus') . '||' . __('No ratings for this photo.', 'wp-photo-album-plus');
                    } elseif ($photos) {
                        echo '||1||' . __('An error occurred while clearing ratings', 'wp-photo-album-plus');
                    } else {
                        echo '||97||' . __('<b>No photos in this album</b>', 'wp-photo-album-plus') . '||' . __('No ratings for this photo.', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'set_deftags':
                    // to be changed for large albums
                    $photos = $wpdb->get_results($wpdb->prepare('SELECT * FROM `' . WPPA_PHOTOS . '` WHERE `album` = %s', $album), ARRAY_A);
                    $deftag = $wpdb->get_var($wpdb->prepare('SELECT `default_tags` FROM `' . WPPA_ALBUMS . '` WHERE `id` = %s', $album));
                    if (is_array($photos)) {
                        foreach ($photos as $photo) {
                            $tags = wppa_sanitize_tags(wppa_filter_iptc(wppa_filter_exif($deftag, $photo['id']), $photo['id']));
                            $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `tags` = %s WHERE `id` = %s', $tags, $photo['id']));
                            wppa_index_update('photo', $photo['id']);
                        }
                    }
                    if ($photos && $iret !== false) {
                        echo '||97||' . __('<b>Tags set to defaults</b> (reload)', 'wp-photo-album-plus');
                    } elseif ($photos) {
                        echo '||1||' . __('An error occurred while setting tags', 'wp-photo-album-plus');
                    } else {
                        echo '||97||' . __('<b>No photos in this album</b>', 'wp-photo-album-plus');
                    }
                    wppa_clear_taglist();
                    wppa_exit();
                    break;
                case 'add_deftags':
                    $photos = $wpdb->get_results($wpdb->prepare('SELECT * FROM `' . WPPA_PHOTOS . '` WHERE `album` = %s', $album), ARRAY_A);
                    $deftag = $wpdb->get_var($wpdb->prepare('SELECT `default_tags` FROM `' . WPPA_ALBUMS . '` WHERE `id` = %s', $album));
                    if (is_array($photos)) {
                        foreach ($photos as $photo) {
                            $tags = wppa_sanitize_tags(wppa_filter_iptc(wppa_filter_exif($photo['tags'] . ',' . $deftag, $photo['id']), $photo['id']));
                            $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `tags` = %s WHERE `id` = %s', $tags, $photo['id']));
                            wppa_index_update('photo', $photo['id']);
                        }
                    }
                    if ($photos && $iret !== false) {
                        echo '||97||' . __('<b>Tags added width defaults</b> (reload)', 'wp-photo-album-plus');
                    } elseif ($photos) {
                        echo '||1||' . __('An error occurred while adding tags', 'wp-photo-album-plus');
                    } else {
                        echo '||97||' . __('<b>No photos in this album</b>', 'wp-photo-album-plus');
                    }
                    wppa_clear_taglist();
                    wppa_exit();
                    break;
                case 'name':
                    $value = trim(strip_tags($value));
                    if (!wppa_sanitize_file_name($value)) {
                        // Empty album name is not allowed
                        $value = 'Album-#' . $album;
                        echo '||5||' . sprintf(__('Album name may not be empty.<br />Reset to <b>%s</b>', 'wp-photo-album-plus'), $value);
                    }
                    $itemname = __('Name', 'wp-photo-album-plus');
                    break;
                case 'description':
                    $itemname = __('Description', 'wp-photo-album-plus');
                    if (wppa_switch('check_balance')) {
                        $value = str_replace(array('<br/>', '<br>'), '<br />', $value);
                        if (balanceTags($value, true) != $value) {
                            echo '||3||' . __('Unbalanced tags in album description!', 'wp-photo-album-plus');
                            wppa_exit();
                        }
                    }
                    $value = trim($value);
                    break;
                case 'a_order':
                    $itemname = __('Album order #', 'wp-photo-album-plus');
                    break;
                case 'main_photo':
                    $itemname = __('Cover photo', 'wp-photo-album-plus');
                    break;
                case 'a_parent':
                    $itemname = __('Parent album', 'wp-photo-album-plus');
                    wppa_flush_treecounts($album);
                    // Myself and my parents
                    wppa_flush_treecounts($value);
                    // My new parent
                    break;
                case 'p_order_by':
                    $itemname = __('Photo order', 'wp-photo-album-plus');
                    break;
                case 'alt_thumbsize':
                    $itemname = __('Use Alt thumbsize', 'wp-photo-album-plus');
                    break;
                case 'cover_type':
                    $itemname = __('Cover Type', 'wp-photo-album-plus');
                    break;
                case 'cover_linktype':
                    $itemname = __('Link type', 'wp-photo-album-plus');
                    break;
                case 'cover_linkpage':
                    $itemname = __('Link to', 'wp-photo-album-plus');
                    break;
                case 'owner':
                    $itemname = __('Owner', 'wp-photo-album-plus');
                    if ($value != '--- public ---' && !get_user_by('login', $value)) {
                        echo '||4||' . sprintf(__('User %s does not exist', 'wp-photo-album-plus'), $value);
                        wppa_exit();
                    }
                    break;
                case 'upload_limit_count':
                    wppa_ajax_check_range($value, false, '0', false, __('Upload limit count', 'wp-photo-album-plus'));
                    if (wppa('error')) {
                        wppa_exit();
                    }
                    $oldval = $wpdb->get_var($wpdb->prepare('SELECT `upload_limit` FROM ' . WPPA_ALBUMS . ' WHERE `id` = %s', $album));
                    $temp = explode('/', $oldval);
                    $value = $value . '/' . $temp[1];
                    $item = 'upload_limit';
                    $itemname = __('Upload limit count', 'wp-photo-album-plus');
                    break;
                case 'upload_limit_time':
                    $oldval = $wpdb->get_var($wpdb->prepare('SELECT `upload_limit` FROM ' . WPPA_ALBUMS . ' WHERE `id` = %s', $album));
                    $temp = explode('/', $oldval);
                    $value = $temp[0] . '/' . $value;
                    $item = 'upload_limit';
                    $itemname = __('Upload limit time', 'wp-photo-album-plus');
                    break;
                case 'default_tags':
                    $value = wppa_sanitize_tags($value, false, true);
                    $itemname = __('Default tags', 'wp-photo-album-plus');
                    break;
                case 'cats':
                    $value = wppa_sanitize_cats($value);
                    wppa_clear_catlist();
                    $itemname = __('Categories', 'wp-photo-album-plus');
                    break;
                case 'suba_order_by':
                    $itemname = __('Sub albums sort order', 'wp-photo-album-plus');
                    break;
                case 'year':
                case 'month':
                case 'day':
                case 'hour':
                case 'min':
                    $itemname = __('Schedule date/time', 'wp-photo-album-plus');
                    $scheduledtm = $wpdb->get_var($wpdb->prepare("SELECT `scheduledtm` FROM`" . WPPA_ALBUMS . "` WHERE `id` = %s", $album));
                    if (!$scheduledtm) {
                        $scheduledtm = wppa_get_default_scheduledtm();
                    }
                    $temp = explode(',', $scheduledtm);
                    if ($item == 'year') {
                        $temp[0] = $value;
                    }
                    if ($item == 'month') {
                        $temp[1] = $value;
                    }
                    if ($item == 'day') {
                        $temp[2] = $value;
                    }
                    if ($item == 'hour') {
                        $temp[3] = $value;
                    }
                    if ($item == 'min') {
                        $temp[4] = $value;
                    }
                    $scheduledtm = implode(',', $temp);
                    wppa_update_album(array('id' => $album, 'scheduledtm' => $scheduledtm));
                    echo '||0||' . sprintf(__('<b>%s</b> of album %s updated', 'wp-photo-album-plus'), $itemname, $album);
                    wppa_exit();
                    break;
                case 'setallscheduled':
                    $scheduledtm = $wpdb->get_var($wpdb->prepare("SELECT `scheduledtm` FROM `" . WPPA_ALBUMS . "` WHERE `id` = %s", $album));
                    if ($scheduledtm) {
                        $iret = $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `status` = 'scheduled', `scheduledtm` = %s WHERE `album` = %s", $scheduledtm, $album));
                        echo '||0||' . __('All photos set to scheduled per date', 'wp-photo-album-plus') . ' ( ' . $iret . ' ) ' . wppa_format_scheduledtm($scheduledtm);
                    }
                    wppa_exit();
                    break;
                default:
                    $itemname = $item;
            }
            $query = $wpdb->prepare('UPDATE ' . WPPA_ALBUMS . ' SET `' . $item . '` = %s WHERE `id` = %s', $value, $album);
            $iret = $wpdb->query($query);
            if ($iret !== false) {
                if ($item == 'name' || $item == 'description' || $item == 'cats') {
                    wppa_index_update('album', $album);
                }
                if ($item == 'name') {
                    wppa_create_pl_htaccess();
                }
                echo '||0||' . sprintf(__('<b>%s</b> of album %s updated', 'wp-photo-album-plus'), $itemname, $album);
                if ($item == 'upload_limit') {
                    echo '||';
                    $a = wppa_allow_uploads($album);
                    if (!$a) {
                        echo 'full';
                    } else {
                        echo 'notfull||' . $a;
                    }
                }
            } else {
                echo '||2||' . sprintf(__('An error occurred while trying to update <b>%s</b> of album %s', 'wp-photo-album-plus'), $itemname, $album);
                echo '<br>' . __('Press CTRL+F5 and try again.', 'wp-photo-album-plus');
            }
            wppa_clear_cache();
            wppa_exit();
            break;
        case 'update-comment-status':
            $photo = $_REQUEST['wppa-photo-id'];
            $nonce = $_REQUEST['wppa-nonce'];
            $comid = $_REQUEST['wppa-comment-id'];
            $comstat = $_REQUEST['wppa-comment-status'];
            // Check validity
            if (!wp_verify_nonce($nonce, 'wppa_nonce_' . $photo)) {
                echo '||0||' . __('You do not have the rights to update comment status', 'wp-photo-album-plus') . $nonce;
                wppa_exit();
                // Nonce check failed
            }
            //			if ( wppa_switch( 'search_comments' ) ) wppa_index_remove( 'photo', $photo );
            $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_COMMENTS . '` SET `status` = %s WHERE `id` = %s', $comstat, $comid));
            if (wppa_switch('search_comments')) {
                wppa_index_update('photo', $photo);
            }
            if ($iret !== false) {
                echo '||0||' . sprintf(__('Status of comment #%s updated', 'wp-photo-album-plus'), $comid);
            } else {
                echo '||1||' . sprintf(__('Error updating status comment #%s', 'wp-photo-album-plus'), $comid);
            }
            wppa_exit();
            break;
        case 'watermark-photo':
            $photo = $_REQUEST['photo-id'];
            $nonce = $_REQUEST['wppa-nonce'];
            // Check validity
            if (!wp_verify_nonce($nonce, 'wppa_nonce_' . $photo)) {
                echo '||1||' . __('You do not have the rights to change photos', 'wp-photo-album-plus');
                wppa_exit();
                // Nonce check failed
            }
            wppa_cache_thumb($photo);
            if (wppa_add_watermark($photo)) {
                if (wppa_switch('watermark_thumbs')) {
                    wppa_create_thumbnail($photo);
                    // create new thumb
                }
                echo '||0||' . __('Watermark applied', 'wp-photo-album-plus');
                wppa_exit();
            } else {
                echo '||1||' . __('An error occured while trying to apply a watermark', 'wp-photo-album-plus');
                wppa_exit();
            }
        case 'update-photo':
            $photo = $_REQUEST['photo-id'];
            $nonce = $_REQUEST['wppa-nonce'];
            $item = $_REQUEST['item'];
            $value = isset($_REQUEST['value']) ? $_REQUEST['value'] : '';
            $value = wppa_decode($value);
            // Check validity
            if (!wp_verify_nonce($nonce, 'wppa_nonce_' . $photo)) {
                echo '||0||' . __('You do not have the rights to update photo information', 'wp-photo-album-plus');
                wppa_exit();
                // Nonce check failed
            }
            if (substr($item, 0, 20) == 'wppa_watermark_file_' || substr($item, 0, 19) == 'wppa_watermark_pos_') {
                wppa_update_option($item, $value);
                echo '||0||' . sprintf(__('%s updated to %s.', 'wp-photo-album-plus'), $item, $value);
                wppa_exit();
            }
            switch ($item) {
                case 'exifdtm':
                    $format = '0000:00:00 00:00:00';
                    $err = '0';
                    // Length ok?
                    if (strlen($value) != 19) {
                        $err = '1';
                    }
                    // Check on digits, colons and space
                    for ($i = 0; $i < 19; $i++) {
                        $d = substr($value, $i, 1);
                        $f = substr($format, $i, 1);
                        switch ($f) {
                            case '0':
                                if (!in_array($d, array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))) {
                                    $err = '2';
                                }
                                break;
                            case ':':
                            case ' ':
                                if ($d != $f) {
                                    $err = '3';
                                }
                                break;
                        }
                    }
                    // Check on values if format correct, report first error only
                    if (!$err) {
                        $temp = explode(':', str_replace(' ', ':', $value));
                        if ($temp['0'] < '1970') {
                            $err = '11';
                        }
                        // Before UNIX epoch
                        if (!$err && $temp['0'] > date('Y')) {
                            $err = '12';
                        }
                        // Future
                        if (!$err && $temp['1'] < '1') {
                            $err = '13';
                        }
                        // Before january
                        if (!$err && $temp['1'] > '12') {
                            $err = '14';
                        }
                        // After december
                        if (!$err && $temp['2'] < '1') {
                            $err = '15';
                        }
                        // Before first of month
                        if (!$err && $temp['2'] > '31') {
                            $err = '17';
                        }
                        // After 31st ( forget about feb and months with 30 days )
                        if (!$err && $temp['3'] < '1') {
                            $err = '18';
                        }
                        // Before first hour
                        if (!$err && $temp['3'] > '24') {
                            $err = '19';
                        }
                        // Hour > 24
                        if (!$err && $temp['4'] < '1') {
                            $err = '20';
                        }
                        // Min < 1
                        if (!$err && $temp['4'] > '59') {
                            $err = '21';
                        }
                        // Min > 59
                        if (!$err && $temp['5'] < '1') {
                            $err = '22';
                        }
                        // Sec < 1
                        if (!$err && $temp['5'] > '59') {
                            $err = '23';
                        }
                        // Sec > 59
                    }
                    if ($err) {
                        echo '||1||' . sprintf(__('Format error %s. Must be yyyy:mm:dd hh:mm:ss', 'wp-photo-album-plus'), $err);
                    } else {
                        wppa_update_photo(array('id' => $photo, 'exifdtm' => $value));
                        echo '||0||' . __('Exif date/time updated', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'lat':
                    if (!is_numeric($value) || $value < '-90.0' || $value > '90.0') {
                        echo '||1||' . __('Enter a value > -90 and < 90', 'wp-photo-album-plus');
                        wppa_exit();
                    }
                    $photodata = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . WPPA_PHOTOS . ' WHERE `id` = %s', $photo), ARRAY_A);
                    $geo = $photodata['location'] ? $photodata['location'] : '///';
                    $geo = explode('/', $geo);
                    $geo = wppa_format_geo($value, $geo['3']);
                    $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `location` = %s WHERE `id` = %s', $geo, $photo));
                    if ($iret) {
                        echo '||0||' . __('Lattitude updated', 'wp-photo-album-plus');
                    } else {
                        echo '||1||' . __('Could not update lattitude', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'lon':
                    if (!is_numeric($value) || $value < '-180.0' || $value > '180.0') {
                        echo '||1||' . __('Enter a value > -180 and < 180', 'wp-photo-album-plus');
                        wppa_exit();
                    }
                    $photodata = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . WPPA_PHOTOS . ' WHERE `id` = %s', $photo), ARRAY_A);
                    $geo = $photodata['location'] ? $photodata['location'] : '///';
                    $geo = explode('/', $geo);
                    $geo = wppa_format_geo($geo['2'], $value);
                    $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `location` = %s WHERE `id` = %s', $geo, $photo));
                    if ($iret) {
                        echo '||0||' . __('Longitude updated', 'wp-photo-album-plus');
                    } else {
                        echo '||1||' . __('Could not update longitude', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'remake':
                    if (wppa_remake_files('', $photo)) {
                        wppa_bump_photo_rev();
                        wppa_bump_thumb_rev();
                        echo '||0||' . __('Photo files remade', 'wp-photo-album-plus');
                    } else {
                        echo '||2||' . __('Could not remake files', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'remakethumb':
                    if (wppa_create_thumbnail($photo)) {
                        echo '||0||' . __('Thumbnail remade', 'wp-photo-album-plus');
                    } else {
                        echo '||0||' . __('Could not remake thumbnail', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'rotright':
                case 'rot180':
                case 'rotleft':
                    switch ($item) {
                        case 'rotleft':
                            $angle = '90';
                            $dir = __('left', 'wp-photo-album-plus');
                            break;
                        case 'rot180':
                            $angle = '180';
                            $dir = __('180&deg;', 'wp-photo-album-plus');
                            break;
                        case 'rotright':
                            $angle = '270';
                            $dir = __('right', 'wp-photo-album-plus');
                            break;
                    }
                    wppa('error', wppa_rotate($photo, $angle));
                    if (!wppa('error')) {
                        wppa_update_modified($photo);
                        wppa_bump_photo_rev();
                        wppa_bump_thumb_rev();
                        echo '||0||' . sprintf(__('Photo %s rotated %s', 'wp-photo-album-plus'), $photo, $dir);
                    } else {
                        echo '||' . wppa('error') . '||' . sprintf(__('An error occurred while trying to rotate photo %s', 'wp-photo-album-plus'), $photo);
                    }
                    wppa_exit();
                    break;
                case 'moveto':
                    $photodata = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . WPPA_PHOTOS . ' WHERE `id` = %s', $photo), ARRAY_A);
                    if (wppa_switch('void_dups')) {
                        // Check for already exists
                        $exists = wppa_file_is_in_album($photodata['filename'], $value);
                        if ($exists) {
                            // Already exists
                            echo '||3||' . sprintf(__('A photo with filename %s already exists in album %s.', 'wp-photo-album-plus'), $photodata['filename'], $value);
                            wppa_exit();
                            break;
                        }
                    }
                    wppa_flush_treecounts($photodata['album']);
                    // Current album
                    wppa_flush_treecounts($value);
                    // New album
                    $iret = $wpdb->query($wpdb->prepare('UPDATE ' . WPPA_PHOTOS . ' SET `album` = %s WHERE `id` = %s', $value, $photo));
                    if ($iret !== false) {
                        wppa_move_source($photodata['filename'], $photodata['album'], $value);
                        echo '||99||' . sprintf(__('Photo %s has been moved to album %s (%s)', 'wp-photo-album-plus'), $photo, wppa_get_album_name($value), $value);
                    } else {
                        echo '||3||' . sprintf(__('An error occurred while trying to move photo %s', 'wp-photo-album-plus'), $photo);
                    }
                    wppa_exit();
                    break;
                case 'copyto':
                    $photodata = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . WPPA_PHOTOS . ' WHERE `id` = %s', $photo), ARRAY_A);
                    if (wppa_switch('void_dups')) {
                        // Check for already exists
                        $exists = wppa_file_is_in_album($photodata['filename'], $value);
                        if ($exists) {
                            // Already exists
                            echo '||4||' . sprintf(__('A photo with filename %s already exists in album %s.', 'wp-photo-album-plus'), $photodata['filename'], $value);
                            wppa_exit();
                            break;
                        }
                    }
                    wppa('error', wppa_copy_photo($photo, $value));
                    wppa_flush_treecounts($value);
                    // New album
                    if (!wppa('error')) {
                        echo '||0||' . sprintf(__('Photo %s copied to album %s (%s)', 'wp-photo-album-plus'), $photo, wppa_get_album_name($value), $value);
                    } else {
                        echo '||4||' . sprintf(__('An error occurred while trying to copy photo %s', 'wp-photo-album-plus'), $photo);
                        echo '<br>' . __('Press CTRL+F5 and try again.', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'status':
                    if (!current_user_can('wppa_moderate') && !current_user_can('wppa_admin')) {
                        die('Security check failure #78');
                    }
                    wppa_flush_treecounts(wppa_get_photo_item($photo, 'album'));
                    // $wpdb->get_var( $wpdb->prepare( "SELECT `album` FROM `".WPPA_PHOTOS."` WHERE `id` = %s", $photo ) ) );
                // $wpdb->get_var( $wpdb->prepare( "SELECT `album` FROM `".WPPA_PHOTOS."` WHERE `id` = %s", $photo ) ) );
                case 'owner':
                case 'name':
                case 'description':
                case 'p_order':
                case 'linkurl':
                case 'linktitle':
                case 'linktarget':
                case 'tags':
                case 'alt':
                case 'videox':
                case 'videoy':
                    switch ($item) {
                        case 'name':
                            $value = strip_tags($value);
                            $itemname = __('Name', 'wp-photo-album-plus');
                            break;
                        case 'description':
                            $itemname = __('Description', 'wp-photo-album-plus');
                            if (wppa_switch('check_balance')) {
                                $value = str_replace(array('<br/>', '<br>'), '<br />', $value);
                                if (balanceTags($value, true) != $value) {
                                    echo '||3||' . __('Unbalanced tags in photo description!', 'wp-photo-album-plus');
                                    wppa_exit();
                                }
                            }
                            break;
                        case 'p_order':
                            $itemname = __('Photo order #', 'wp-photo-album-plus');
                            break;
                        case 'owner':
                            $usr = get_user_by('login', $value);
                            if (!$usr) {
                                echo '||4||' . sprintf(__('User %s does not exists', 'wp-photo-album-plus'), $value);
                                wppa_exit();
                            }
                            $value = $usr->user_login;
                            // Correct possible case mismatch
                            wppa_flush_upldr_cache('photoid', $photo);
                            // Current owner
                            wppa_flush_upldr_cache('username', $value);
                            // New owner
                            $itemname = __('Owner', 'wp-photo-album-plus');
                            break;
                        case 'linkurl':
                            $itemname = __('Link url', 'wp-photo-album-plus');
                            break;
                        case 'linktitle':
                            $itemname = __('Link title', 'wp-photo-album-plus');
                            break;
                        case 'linktarget':
                            $itemname = __('Link target', 'wp-photo-album-plus');
                            break;
                        case 'tags':
                            $value = wppa_sanitize_tags($value, false, true);
                            $value = wppa_sanitize_tags(wppa_filter_iptc(wppa_filter_exif($value, $photo), $photo));
                            wppa_clear_taglist();
                            $itemname = __('Photo Tags', 'wp-photo-album-plus');
                            break;
                        case 'status':
                            wppa_clear_taglist();
                            wppa_flush_upldr_cache('photoid', $photo);
                            $itemname = __('Status', 'wp-photo-album-plus');
                            break;
                        case 'alt':
                            $itemname = __('HTML Alt', 'wp-photo-album-plus');
                            $value = strip_tags(stripslashes($value));
                            break;
                        case 'videox':
                            $itemname = __('Video width', 'wp-photo-album-plus');
                            if (!wppa_is_int($value) || $value < '0') {
                                echo '||3||' . __('Please enter an integer value >= 0', 'wp-photo-album-plus');
                                wppa_exit();
                            }
                            break;
                        case 'videoy':
                            $itemname = __('Video height', 'wp-photo-album-plus');
                            if (!wppa_is_int($value) || $value < '0') {
                                echo '||3||' . __('Please enter an integer value >= 0', 'wp-photo-album-plus');
                                wppa_exit();
                            }
                            break;
                        default:
                            $itemname = $item;
                    }
                    //				if ( $item == 'name' || $item == 'description' || $item == 'tags' ) wppa_index_quick_remove( 'photo', $photo );
                    $iret = $wpdb->query($wpdb->prepare('UPDATE ' . WPPA_PHOTOS . ' SET `' . $item . '` = %s WHERE `id` = %s', $value, $photo));
                    if ($item == 'name' || $item == 'description' || $item == 'tags') {
                        wppa_index_update('photo', $photo);
                    }
                    if ($item == 'status' && $value != 'scheduled') {
                        wppa_update_photo(array('id' => $photo, 'scheduledtm' => ''));
                    }
                    if ($item == 'status') {
                        wppa_flush_treecounts(wppa_get_photo_item($photo, 'album'));
                    }
                    if ($iret !== false) {
                        wppa_update_modified($photo);
                        if (wppa_is_video($photo)) {
                            echo '||0||' . sprintf(__('<b>%s</b> of video %s updated', 'wp-photo-album-plus'), $itemname, $photo);
                        } else {
                            echo '||0||' . sprintf(__('<b>%s</b> of photo %s updated', 'wp-photo-album-plus'), $itemname, $photo);
                        }
                    } else {
                        echo '||2||' . sprintf(__('An error occurred while trying to update <b>%s</b> of photo %s', 'wp-photo-album-plus'), $itemname, $photo);
                        echo '<br>' . __('Press CTRL+F5 and try again.', 'wp-photo-album-plus');
                        wppa_exit();
                    }
                    break;
                case 'year':
                case 'month':
                case 'day':
                case 'hour':
                case 'min':
                    $itemname = __('Schedule date/time', 'wp-photo-album-plus');
                    $scheduledtm = $wpdb->get_var($wpdb->prepare("SELECT `scheduledtm` FROM`" . WPPA_PHOTOS . "` WHERE `id` = %s", $photo));
                    if (!$scheduledtm) {
                        $scheduledtm = wppa_get_default_scheduledtm();
                    }
                    $temp = explode(',', $scheduledtm);
                    if ($item == 'year') {
                        $temp[0] = $value;
                    }
                    if ($item == 'month') {
                        $temp[1] = $value;
                    }
                    if ($item == 'day') {
                        $temp[2] = $value;
                    }
                    if ($item == 'hour') {
                        $temp[3] = $value;
                    }
                    if ($item == 'min') {
                        $temp[4] = $value;
                    }
                    $scheduledtm = implode(',', $temp);
                    wppa_update_photo(array('id' => $photo, 'scheduledtm' => $scheduledtm, 'status' => 'scheduled'));
                    wppa_flush_treecounts($wpdb->get_var($wpdb->prepare("SELECT `album` FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $photo)));
                    wppa_flush_upldr_cache('photoid', $photo);
                    if (wppa_is_video($photo)) {
                        echo '||0||' . sprintf(__('<b>%s</b> of video %s updated', 'wp-photo-album-plus'), $itemname, $photo);
                    } else {
                        echo '||0||' . sprintf(__('<b>%s</b> of photo %s updated', 'wp-photo-album-plus'), $itemname, $photo);
                    }
                    break;
                case 'custom_0':
                case 'custom_1':
                case 'custom_2':
                case 'custom_3':
                case 'custom_4':
                case 'custom_5':
                case 'custom_6':
                case 'custom_7':
                case 'custom_8':
                case 'custom_9':
                    $index = substr($item, -1);
                    $custom = wppa_get_photo_item($photo, 'custom');
                    if ($custom) {
                        $custom_data = unserialize($custom);
                    } else {
                        $custom_data = array('', '', '', '', '', '', '', '', '', '');
                    }
                    $custom_data[$index] = strip_tags($value);
                    $custom = serialize($custom_data);
                    wppa_update_photo(array('id' => $photo, 'custom' => $custom, 'modified' => time()));
                    wppa_index_update('photo', $photo);
                    echo '||0||' . sprintf(__('<b>Custom field %s</b> of photo %s updated', 'wp-photo-album-plus'), wppa_opt('custom_caption_' . $index), $photo);
                    break;
                case 'file':
                    // Check on upload error
                    if ($_FILES['photo']['error']) {
                        echo '||' . $_FILES['photo']['error'] . '||' . __('<b>Error during upload.</b>', 'wp-photo-album-plus');
                        wppa_exit();
                    }
                    // Save new source
                    wppa_save_source($_FILES['photo']['tmp_name'], wppa_get_photo_item($photo, 'filename'), wppa_get_photo_item($photo, 'album'));
                    // Make the files
                    $bret = wppa_make_the_photo_files($_FILES['photo']['tmp_name'], $photo, strtolower(wppa_get_ext($_FILES['photo']['name'])));
                    if ($bret) {
                        // Update timestamps and sizes
                        $alb = wppa_get_photo_item($photo, 'album');
                        wppa_update_album(array('id' => $alb, 'modified' => time()));
                        wppa_update_photo(array('id' => $photo, 'modified' => time(), 'thumbx' => '0', 'thumby' => '0', 'photox' => '0', 'photoy' => '0'));
                        // Report success
                        echo '||0||' . __('Photo files updated.', 'wp-photo-album-plus');
                    } else {
                        // Report fail
                        echo '||1||' . __('Could not update files.', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'stereo':
                    $t = microtime(true);
                    wppa_update_photo(array('id' => $photo, 'stereo' => $value));
                    wppa_create_stereo_images($photo);
                    wppa_create_thumbnail($photo);
                    $t = microtime(true) - $t;
                    echo '||0||' . sprintf(__('Stereo mode updated in %d milliseconds', 'wp-photo-album-plus'), floor($t * 1000));
                    wppa_exit();
                    break;
                default:
                    echo '||98||This update action is not implemented yet( ' . $item . ' )';
                    wppa_exit();
            }
            wppa_clear_cache();
            break;
            // The wppa-settings page calls ajax with $wppa_action == 'update-option';
        // The wppa-settings page calls ajax with $wppa_action == 'update-option';
        case 'update-option':
            // Verify that we are legally here
            $nonce = $_REQUEST['wppa-nonce'];
            if (!wp_verify_nonce($nonce, 'wppa-nonce')) {
                echo '||1||' . __('You do not have the rights to update settings', 'wp-photo-album-plus');
                wppa_exit();
                // Nonce check failed
            }
            // Initialize
            $old_minisize = wppa_get_minisize();
            // Remember for later, maybe we do something that requires regen
            $option = $_REQUEST['wppa-option'];
            // The option to be processed
            $value = isset($_REQUEST['value']) ? wppa_decode($_REQUEST['value']) : '';
            // The new value, may also contain & # and +
            $value = stripslashes($value);
            $value = trim($value);
            // Remaove surrounding spaces
            $alert = '';
            // Init the return string data
            wppa('error', '0');
            //
            $title = '';
            //
            // If it is a font family, change all double quotes into single quotes as this destroys much more than you would like
            if (strpos($option, 'wppa_fontfamily_') !== false) {
                $value = str_replace('"', "'", $value);
            }
            $option = wppa_decode($option);
            // Dispatch on option
            if (substr($option, 0, 16) == 'wppa_iptc_label_') {
                $tag = substr($option, 16);
                $q = $wpdb->prepare("UPDATE `" . WPPA_IPTC . "` SET `description`=%s WHERE `tag`=%s AND `photo`='0'", $value, $tag);
                $bret = $wpdb->query($q);
                // Produce the response text
                if ($bret) {
                    $output = '||0||' . $tag . ' updated to ' . $value . '||';
                } else {
                    $output = '||1||Failed to update ' . $tag . '||';
                }
                echo $output;
                wppa_exit();
            } elseif (substr($option, 0, 17) == 'wppa_iptc_status_') {
                $tag = substr($option, 17);
                $q = $wpdb->prepare("UPDATE `" . WPPA_IPTC . "` SET `status`=%s WHERE `tag`=%s AND `photo`='0'", $value, $tag);
                $bret = $wpdb->query($q);
                // Produce the response text
                if ($bret) {
                    $output = '||0||' . $tag . ' updated to ' . $value . '||';
                } else {
                    $output = '||1||Failed to update ' . $tag . '||';
                }
                echo $output;
                wppa_exit();
            } elseif (substr($option, 0, 16) == 'wppa_exif_label_') {
                $tag = substr($option, 16);
                $q = $wpdb->prepare("UPDATE `" . WPPA_EXIF . "` SET `description`=%s WHERE `tag`=%s AND `photo`='0'", $value, $tag);
                $bret = $wpdb->query($q);
                // Produce the response text
                if ($bret) {
                    $output = '||0||' . $tag . ' updated to ' . $value . '||';
                } else {
                    $output = '||1||Failed to update ' . $tag . '||';
                }
                echo $output;
                wppa_exit();
            } elseif (substr($option, 0, 17) == 'wppa_exif_status_') {
                $tag = substr($option, 17);
                $q = $wpdb->prepare("UPDATE `" . WPPA_EXIF . "` SET `status`=%s WHERE `tag`=%s AND `photo`='0'", $value, $tag);
                $bret = $wpdb->query($q);
                // Produce the response text
                if ($bret) {
                    $output = '||0||' . $tag . ' updated to ' . $value . '||';
                } else {
                    $output = '||1||Failed to update ' . $tag . '||';
                }
                echo $output;
                wppa_exit();
            } elseif (substr($option, 0, 5) == 'caps-') {
                // Is capability setting
                global $wp_roles;
                //$R = new WP_Roles;
                $setting = explode('-', $option);
                if ($value == 'yes') {
                    $wp_roles->add_cap($setting[2], $setting[1]);
                    echo '||0||' . __('Capability granted', 'wp-photo-album-plus') . '||';
                    wppa_exit();
                } elseif ($value == 'no') {
                    $wp_roles->remove_cap($setting[2], $setting[1]);
                    echo '||0||' . __('Capability withdrawn', 'wp-photo-album-plus') . '||';
                    wppa_exit();
                } else {
                    echo '||1||Invalid value: ' . $value . '||';
                    wppa_exit();
                }
            } else {
                switch ($option) {
                    case 'wppa_colwidth':
                        //	 ??	  fixed   low	high	title
                        wppa_ajax_check_range($value, 'auto', '100', false, __('Column width.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_initial_colwidth':
                        wppa_ajax_check_range($value, false, '100', false, __('Initial width.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_fullsize':
                        wppa_ajax_check_range($value, false, '100', false, __('Full size.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_maxheight':
                        wppa_ajax_check_range($value, false, '100', false, __('Max height.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_thumbsize':
                        wppa_ajax_check_range($value, false, '50', false, __('Thumbnail size.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_tf_width':
                        wppa_ajax_check_range($value, false, '50', false, __('Thumbnail frame width', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_tf_height':
                        wppa_ajax_check_range($value, false, '50', false, __('Thumbnail frame height', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_tn_margin':
                        wppa_ajax_check_range($value, false, '0', false, __('Thumbnail Spacing', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_min_thumbs':
                        wppa_ajax_check_range($value, false, '0', false, __('Photocount treshold.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_thumb_page_size':
                        wppa_ajax_check_range($value, false, '0', false, __('Thumb page size.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_smallsize':
                        wppa_ajax_check_range($value, false, '50', false, __('Cover photo size.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_album_page_size':
                        wppa_ajax_check_range($value, false, '0', false, __('Album page size.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_topten_count':
                        wppa_ajax_check_range($value, false, '2', false, __('Number of TopTen photos', 'wp-photo-album-plus'), '40');
                        break;
                    case 'wppa_topten_size':
                        wppa_ajax_check_range($value, false, '32', false, __('Widget image thumbnail size', 'wp-photo-album-plus'), wppa_get_minisize());
                        break;
                    case 'wppa_max_cover_width':
                        wppa_ajax_check_range($value, false, '150', false, __('Max Cover width', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_text_frame_height':
                        wppa_ajax_check_range($value, false, '0', false, __('Minimal description height', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_cover_minheight':
                        wppa_ajax_check_range($value, false, '0', false, __('Minimal cover height', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_head_and_text_frame_height':
                        wppa_ajax_check_range($value, false, '0', false, __('Minimal text frame height', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_bwidth':
                        wppa_ajax_check_range($value, '', '0', false, __('Border width', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_bradius':
                        wppa_ajax_check_range($value, '', '0', false, __('Border radius', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_box_spacing':
                        wppa_ajax_check_range($value, '', '-20', '100', __('Box spacing', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_popupsize':
                        $floor = wppa_opt('thumbsize');
                        $temp = wppa_opt('smallsize');
                        if ($temp > $floor) {
                            $floor = $temp;
                        }
                        wppa_ajax_check_range($value, false, $floor, wppa_opt('fullsize'), __('Popup size', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_fullimage_border_width':
                        wppa_ajax_check_range($value, '', '0', false, __('Fullsize border width', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_lightbox_bordersize':
                        wppa_ajax_check_range($value, false, '0', false, __('Lightbox Bordersize', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_ovl_border_width':
                        wppa_ajax_check_range($value, false, '0', '16', __('Lightbox Borderwidth', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_ovl_border_radius':
                        wppa_ajax_check_range($value, false, '0', '16', __('Lightbox Borderradius', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_comment_count':
                        wppa_ajax_check_range($value, false, '2', '40', __('Number of Comment widget entries', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_comment_size':
                        wppa_ajax_check_range($value, false, '32', wppa_get_minisize(), __('Comment Widget image thumbnail size', 'wp-photo-album-plus'), wppa_get_minisize());
                        break;
                    case 'wppa_thumb_opacity':
                        wppa_ajax_check_range($value, false, '0', '100', __('Opacity.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_cover_opacity':
                        wppa_ajax_check_range($value, false, '0', '100', __('Opacity.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_star_opacity':
                        wppa_ajax_check_range($value, false, '0', '50', __('Opacity.', 'wp-photo-album-plus'));
                        break;
                        //				case 'wppa_filter_priority':
                        //					wppa_ajax_check_range( $value, false, wppa_opt( 'shortcode_priority' ), false, __( 'Filter priority' ,'wp-photo-album-plus' ) );
                        //					break;
                        //				case 'wppa_shortcode_priority':
                        //					wppa_ajax_check_range( $value, false, '0', wppa_opt( 'filter_priority' ) - '1', __( 'Shortcode_priority', 'wp-photo-album-plus' ) );
                        //					break;
                    //				case 'wppa_filter_priority':
                    //					wppa_ajax_check_range( $value, false, wppa_opt( 'shortcode_priority' ), false, __( 'Filter priority' ,'wp-photo-album-plus' ) );
                    //					break;
                    //				case 'wppa_shortcode_priority':
                    //					wppa_ajax_check_range( $value, false, '0', wppa_opt( 'filter_priority' ) - '1', __( 'Shortcode_priority', 'wp-photo-album-plus' ) );
                    //					break;
                    case 'wppa_gravatar_size':
                        wppa_ajax_check_range($value, false, '10', '256', __('Avatar size', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_watermark_opacity':
                        wppa_ajax_check_range($value, false, '0', '100', __('Watermark opacity', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_watermark_opacity_text':
                        wppa_ajax_check_range($value, false, '0', '100', __('Watermark opacity', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_ovl_txt_lines':
                        wppa_ajax_check_range($value, 'auto', '0', '24', __('Number of text lines', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_ovl_opacity':
                        wppa_ajax_check_range($value, false, '0', '100', __('Overlay opacity', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_upload_limit_count':
                        wppa_ajax_check_range($value, false, '0', false, __('Upload limit', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_dislike_mail_every':
                        wppa_ajax_check_range($value, false, '0', false, __('Notify inappropriate', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_dislike_set_pending':
                        wppa_ajax_check_range($value, false, '0', false, __('Dislike pending', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_dislike_delete':
                        wppa_ajax_check_range($value, false, '0', false, __('Dislike delete', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_max_execution_time':
                        wppa_ajax_check_range($value, false, '0', '900', __('Max execution time', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_cp_points_comment':
                    case 'wppa_cp_points_rating':
                    case 'wppa_cp_points_upload':
                        wppa_ajax_check_range($value, false, '0', false, __('Cube Points points', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_jpeg_quality':
                        wppa_ajax_check_range($value, false, '20', '100', __('JPG Image quality', 'wp-photo-album-plus'));
                        if (wppa_cdn('admin') == 'cloudinary' && !wppa('out')) {
                            wppa_delete_derived_from_cloudinary();
                        }
                        break;
                    case 'wppa_imgfact_count':
                        wppa_ajax_check_range($value, false, '1', '24', __('Number of coverphotos', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_dislike_value':
                        wppa_ajax_check_range($value, false, '-10', '0', __('Dislike value', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_slideshow_pagesize':
                        wppa_ajax_check_range($value, false, '0', false, __('Slideshow pagesize', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_pagelinks_max':
                        wppa_ajax_check_range($value, false, '0', false, __('Max Pagelinks', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_start_pause_symbol_size':
                        wppa_ajax_check_range($value, false, '0', false, __('Start/pause symbol size', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_start_pause_symbol_bradius':
                        wppa_ajax_check_range($value, false, '0', false, __('Start/pause symbol border radius', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_stop_symbol_size':
                        wppa_ajax_check_range($value, false, '0', false, __('Stop symbol size', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_stop_symbol_bradius':
                        wppa_ajax_check_range($value, false, '0', false, __('Stop symbol border radius', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_rating_clear':
                        $iret1 = $wpdb->query('TRUNCATE TABLE ' . WPPA_RATING);
                        $iret2 = $wpdb->query('UPDATE ' . WPPA_PHOTOS . ' SET mean_rating="0", rating_count="0" WHERE id > -1');
                        if ($iret1 !== false && $iret2 !== false) {
                            delete_option('wppa_' . WPPA_RATING . '_lastkey');
                            $title = __('Ratings cleared', 'wp-photo-album-plus');
                        } else {
                            $title = __('Could not clear ratings', 'wp-photo-album-plus');
                            $alert = $title;
                            wppa('error', '1');
                        }
                        break;
                    case 'wppa_viewcount_clear':
                        $iret = $wpdb->query("UPDATE `" . WPPA_PHOTOS . "` SET `views` = '0'") && $wpdb->query("UPDATE `" . WPPA_ALBUMS . "` SET `views` = '0'");
                        if ($iret !== false) {
                            $title = __('Viewcounts cleared', 'wp-photo-album-plus');
                        } else {
                            $title = __('Could not clear viewcounts', 'wp-photo-album-plus');
                            $alert = $title;
                            wppa('error', '1');
                        }
                        break;
                    case 'wppa_iptc_clear':
                        $iret = $wpdb->query('TRUNCATE TABLE ' . WPPA_IPTC);
                        if ($iret !== false) {
                            delete_option('wppa_' . WPPA_IPTC . '_lastkey');
                            $title = __('IPTC data cleared', 'wp-photo-album-plus');
                            $alert = __('Refresh this page to clear table X', 'wp-photo-album-plus');
                            update_option('wppa_index_need_remake', 'yes');
                        } else {
                            $title = __('Could not clear IPTC data', 'wp-photo-album-plus');
                            $alert = $title;
                            wppa('error', '1');
                        }
                        break;
                    case 'wppa_exif_clear':
                        $iret = $wpdb->query('TRUNCATE TABLE ' . WPPA_EXIF);
                        if ($iret !== false) {
                            delete_option('wppa_' . WPPA_EXIF . '_lastkey');
                            $title = __('EXIF data cleared', 'wp-photo-album-plus');
                            $alert = __('Refresh this page to clear table XI', 'wp-photo-album-plus');
                            update_option('wppa_index_need_remake', 'yes');
                        } else {
                            $title = __('Could not clear EXIF data', 'wp-photo-album-plus');
                            $alert = $title;
                            wppa('error', '1');
                        }
                        break;
                    case 'wppa_recup':
                        $result = wppa_recuperate_iptc_exif();
                        echo '||0||' . __('Recuperation performed', 'wp-photo-album-plus') . '||' . $result;
                        wppa_exit();
                        break;
                    case 'wppa_bgcolor_thumbnail':
                        $value = trim(strtolower($value));
                        if (strlen($value) != '7' || substr($value, 0, 1) != '#') {
                            wppa('error', '1');
                        } else {
                            for ($i = 1; $i < 7; $i++) {
                                if (!in_array(substr($value, $i, 1), array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'))) {
                                    wppa('error', '1');
                                }
                            }
                        }
                        if (!wppa('error')) {
                            $old_minisize--;
                        } else {
                            $alert = __('Illegal format. Please enter a 6 digit hexadecimal color value. Example: #77bbff', 'wp-photo-album-plus');
                        }
                        break;
                    case 'wppa_thumb_aspect':
                        $old_minisize--;
                        // Trigger regen message
                        break;
                    case 'wppa_rating_max':
                        if ($value == '5' && wppa_opt('rating_max') == '10') {
                            $rats = $wpdb->get_results('SELECT `id`, `value` FROM `' . WPPA_RATING . '`', ARRAY_A);
                            if ($rats) {
                                foreach ($rats as $rat) {
                                    $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_RATING . '` SET `value` = %s WHERE `id` = %s', $rat['value'] / 2, $rat['id']));
                                }
                            }
                        }
                        if ($value == '10' && wppa_opt('rating_max') == '5') {
                            $rats = $wpdb->get_results('SELECT `id`, `value` FROM `' . WPPA_RATING . '`', ARRAY_A);
                            if ($rats) {
                                foreach ($rats as $rat) {
                                    $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_RATING . '` SET `value` = %s WHERE `id` = %s', $rat['value'] * 2, $rat['id']));
                                }
                            }
                        }
                        update_option('wppa_rerate_status', 'Required');
                        $alert .= __('You just changed a setting that requires the recalculation of ratings.', 'wp-photo-album-plus');
                        $alert .= ' ' . __('Please run the appropriate action in Table VIII.', 'wp-photo-album-plus');
                        wppa_update_option($option, $value);
                        wppa('error', '0');
                        break;
                    case 'wppa_newphoto_description':
                        if (wppa_switch('check_balance') && balanceTags($value, true) != $value) {
                            $alert = __('Unbalanced tags in photo description!', 'wp-photo-album-plus');
                            wppa('error', '1');
                        } else {
                            wppa_update_option($option, $value);
                            wppa('error', '0');
                            $alert = '';
                            wppa_index_compute_skips();
                        }
                        break;
                    case 'wppa_keep_source':
                        $dir = wppa_opt('source_dir');
                        if (!is_dir($dir)) {
                            @mkdir($dir);
                        }
                        if (!is_dir($dir) || !is_writable($dir)) {
                            wppa('error', '1');
                            $alert = sprintf(__('Unable to create or write to %s', 'wp-photo-album-plus'), $dir);
                        }
                        break;
                    case 'wppa_source_dir':
                        $olddir = wppa_opt('source_dir');
                        $value = rtrim($value, '/');
                        if (strpos($value . '/', WPPA_UPLOAD_PATH . '/') !== false) {
                            wppa('error', '1');
                            $alert = sprintf(__('Source can not be inside the wppa folder.', 'wp-photo-album-plus'));
                        } else {
                            $dir = $value;
                            if (!is_dir($dir)) {
                                @mkdir($dir);
                            }
                            if (!is_dir($dir) || !is_writable($dir)) {
                                wppa('error', '1');
                                $alert = sprintf(__('Unable to create or write to %s', 'wp-photo-album-plus'), $dir);
                            } else {
                                @rmdir($olddir);
                                // try to remove when empty
                            }
                        }
                        break;
                    case 'wppa_newpag_content':
                        if (strpos($value, 'w#album') === false) {
                            $alert = __('The content must contain w#album', 'wp-photo-album-plus');
                            wppa('error', '1');
                        }
                        break;
                    case 'wppa_gpx_shortcode':
                        if (strpos($value, 'w#lat') === false || strpos($value, 'w#lon') === false) {
                            $alert = __('The content must contain w#lat and w#lon', 'wp-photo-album-plus');
                            wppa('error', '1');
                        }
                        break;
                    case 'wppa_i_responsive':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_colwidth', 'auto');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_colwidth', '640');
                        }
                        break;
                    case 'wppa_i_downsize':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_resize_on_upload', 'yes');
                            if (wppa_opt('resize_to') == '0') {
                                wppa_update_option('wppa_resize_to', '1024x768');
                            }
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_resize_on_upload', 'no');
                        }
                        break;
                    case 'wppa_i_source':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_keep_source_admin', 'yes');
                            wppa_update_option('wppa_keep_source_frontend', 'yes');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_keep_source_admin', 'no');
                            wppa_update_option('wppa_keep_source_frontend', 'no');
                        }
                        break;
                    case 'wppa_i_userupload':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_user_upload_on', 'yes');
                            wppa_update_option('wppa_user_upload_login', 'yes');
                            wppa_update_option('wppa_owner_only', 'yes');
                            wppa_update_option('wppa_upload_moderate', 'yes');
                            wppa_update_option('wppa_upload_edit', 'yes');
                            wppa_update_option('wppa_upload_notify', 'yes');
                            wppa_update_option('wppa_grant_an_album', 'yes');
                            $grantparent = wppa_opt('grant_parent');
                            if (!wppa_album_exists($grantparent)) {
                                $id = wppa_create_album_entry(array('name' => __('Members', 'wp-photo-album-plus'), 'description' => __('Parent of the member albums', 'wp-photo-album-plus'), 'a_parent' => '-1', 'upload_limit' => '0/0'));
                                if ($id) {
                                    wppa_index_add('album', $id);
                                    wppa_update_option('wppa_grant_parent', $id);
                                }
                                $my_post = array('post_title' => __('Members', 'wp-photo-album-plus'), 'post_content' => '[wppa type="content" album="' . $id . '"][/wppa]', 'post_status' => 'publish', 'post_type' => 'page');
                                $pagid = wp_insert_post($my_post);
                            }
                            wppa_update_option('wppa_alt_is_restricted', 'yes');
                            wppa_update_option('wppa_link_is_restricted', 'yes');
                            wppa_update_option('wppa_covertype_is_restricted', 'yes');
                            wppa_update_option('wppa_porder_restricted', 'yes');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_user_upload_on', 'no');
                        }
                        break;
                    case 'wppa_i_rating':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_rating_on', 'yes');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_rating_on', 'no');
                        }
                        break;
                    case 'wppa_i_comment':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_show_comments', 'yes');
                            wppa_update_option('wppa_comment_moderation', 'all');
                            wppa_update_option('wppa_comment_notify', 'admin');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_show_comments', 'no');
                        }
                        break;
                    case 'wppa_i_share':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_share_on', 'yes');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_share_on', 'no');
                        }
                        break;
                    case 'wppa_i_iptc':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_show_iptc', 'yes');
                            wppa_update_option('wppa_save_iptc', 'yes');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_show_iptc', 'no');
                            wppa_update_option('wppa_save_iptc', 'no');
                        }
                        break;
                    case 'wppa_i_exif':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_show_exif', 'yes');
                            wppa_update_option('wppa_save_exif', 'yes');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_show_exif', 'no');
                            wppa_update_option('wppa_save_exif', 'no');
                        }
                        break;
                    case 'wppa_i_gpx':
                        if ($value == 'yes') {
                            $custom_content = wppa_opt('custom_content');
                            if (strpos($custom_content, 'w#location') === false) {
                                $custom_content = $custom_content . ' w#location';
                                wppa_update_option('wppa_custom_content', $custom_content);
                            }
                            if (!wppa_switch('custom_on')) {
                                wppa_update_option('wppa_custom_on', 'yes');
                            }
                            if (wppa_opt('gpx_implementation') == 'none') {
                                wppa_update_option('wppa_gpx_implementation', 'wppa-plus-embedded');
                            }
                        }
                        break;
                    case 'wppa_i_fotomoto':
                        if ($value == 'yes') {
                            $custom_content = wppa_opt('custom_content');
                            if (strpos($custom_content, 'w#fotomoto') === false) {
                                $custom_content = 'w#fotomoto ' . $custom_content;
                                wppa_update_option('wppa_custom_content', $custom_content);
                            }
                            if (!wppa_switch('custom_on')) {
                                wppa_update_option('wppa_custom_on', 'yes');
                            }
                            wppa_update_option('wppa_fotomoto_on', 'yes');
                            wppa_update_option('wppa_custom_on', 'yes');
                        }
                        break;
                    case 'wppa_i_video':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_enable_video', 'yes');
                        } else {
                            wppa_update_option('wppa_enable_video', 'no');
                        }
                        break;
                    case 'wppa_i_audio':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_enable_audio', 'yes');
                        } else {
                            wppa_update_option('wppa_enable_audio', 'no');
                        }
                        break;
                    case 'wppa_i_done':
                        $value = 'done';
                        break;
                    case 'wppa_search_tags':
                    case 'wppa_search_cats':
                    case 'wppa_search_comments':
                        update_option('wppa_index_need_remake', 'yes');
                        break;
                    case 'wppa_blacklist_user':
                        // Does user exist?
                        $value = trim($value);
                        $user = get_user_by('login', $value);
                        // seems to be case insensitive
                        if ($user && $user->user_login === $value) {
                            $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `status` = 'pending' WHERE `owner` = %s", $value));
                            $black_listed_users = get_option('wppa_black_listed_users', array());
                            if (!in_array($value, $black_listed_users)) {
                                $black_listed_users[] = $value;
                                update_option('wppa_black_listed_users', $black_listed_users);
                            }
                            $alert = esc_js(sprintf(__('User %s has been blacklisted.', 'wp-photo-album-plus'), $value));
                        } else {
                            $alert = esc_js(sprintf(__('User %s does not exist.', 'wp-photo-album-plus'), $value));
                        }
                        $value = '';
                        break;
                    case 'wppa_un_blacklist_user':
                        $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `status` = 'publish' WHERE `owner` = %s", $value));
                        $black_listed_users = get_option('wppa_black_listed_users', array());
                        if (in_array($value, $black_listed_users)) {
                            foreach (array_keys($black_listed_users) as $usr) {
                                if ($black_listed_users[$usr] == $value) {
                                    unset($black_listed_users[$usr]);
                                }
                            }
                            update_option('wppa_black_listed_users', $black_listed_users);
                        }
                        $value = '0';
                        break;
                    case 'wppa_fotomoto_on':
                        if ($value == 'yes') {
                            $custom_content = wppa_opt('custom_content');
                            if (strpos($custom_content, 'w#fotomoto') === false) {
                                $custom_content = 'w#fotomoto ' . $custom_content;
                                wppa_update_option('wppa_custom_content', $custom_content);
                                $alert = __('The content of the Custom box has been changed to display the Fotomoto toolbar.', 'wp-photo-album-plus') . ' ';
                            }
                            if (!wppa_switch('custom_on')) {
                                wppa_update_option('wppa_custom_on', 'yes');
                                $alert .= __('The display of the custom box has been enabled', 'wp-photo-album-plus');
                            }
                        }
                        break;
                    case 'wppa_gpx_implementation':
                        if ($value != 'none') {
                            $custom_content = wppa_opt('custom_content');
                            if (strpos($custom_content, 'w#location') === false) {
                                $custom_content = $custom_content . ' w#location';
                                wppa_update_option('wppa_custom_content', $custom_content);
                                $alert = __('The content of the Custom box has been changed to display maps.', 'wp-photo-album-plus') . ' ';
                            }
                            if (!wppa_switch('custom_on')) {
                                wppa_update_option('wppa_custom_on', 'yes');
                                $alert .= __('The display of the custom box has been enabled', 'wp-photo-album-plus');
                            }
                        }
                        break;
                    case 'wppa_regen_thumbs_skip_one':
                        $last = get_option('wppa_regen_thumbs_last', '0');
                        $skip = $last + '1';
                        update_option('wppa_regen_thumbs_last', $skip);
                        break;
                    case 'wppa_remake_skip_one':
                        $last = get_option('wppa_remake_last', '0');
                        $skip = $last + '1';
                        update_option('wppa_remake_last', $skip);
                        break;
                    case 'wppa_errorlog_purge':
                        @unlink(WPPA_CONTENT_PATH . '/wppa-depot/admin/error.log');
                        break;
                    case 'wppa_pl_dirname':
                        $value = wppa_sanitize_file_name($value);
                        $value = trim($value, ' /');
                        if (!$value) {
                            wppa('error', '714');
                            wppa_out(__('This value can not be empty', 'wp-photo-album-plus'));
                        } else {
                            wppa_create_pl_htaccess($value);
                        }
                        break;
                    case 'wppa_new_tag_value':
                        $value = wppa_sanitize_tags($value, false, true);
                        break;
                    case 'wppa_up_tagselbox_content_1':
                    case 'wppa_up_tagselbox_content_2':
                    case 'wppa_up_tagselbox_content_3':
                        $value = wppa_sanitize_tags($value);
                        break;
                    case 'wppa_wppa_set_shortcodes':
                        $value = str_replace(' ', '', $value);
                        break;
                    case 'wppa_enable_video':
                        // if off: set all statusses of videos to pending
                        break;
                    default:
                        wppa('error', '0');
                        $alert = '';
                }
            }
            if (wppa('error')) {
                if (!$title) {
                    $title = sprintf(__('Failed to set %s to %s', 'wp-photo-album-plus'), $option, $value);
                }
                if (!$alert) {
                    $alert .= wppa('out');
                }
            } else {
                wppa_update_option($option, $value);
                if (!$title) {
                    $title = sprintf(__('Setting %s updated to %s', 'wp-photo-album-plus'), $option, $value);
                }
            }
            // Save possible error
            $error = wppa('error');
            // Something to do after changing the setting?
            wppa_initialize_runtime(true);
            // force reload new values
            // .htaccess
            wppa_create_wppa_htaccess();
            // Thumbsize
            $new_minisize = wppa_get_minisize();
            if ($old_minisize != $new_minisize) {
                update_option('wppa_regen_thumbs_status', 'Required');
                $alert .= __('You just changed a setting that requires the regeneration of thumbnails.', 'wp-photo-album-plus');
                $alert .= ' ' . __('Please run the appropriate action in Table VIII.', 'wp-photo-album-plus');
            }
            // Produce the response text
            $output = '||' . $error . '||' . esc_attr($title) . '||' . esc_js($alert);
            echo $output;
            wppa_clear_cache();
            wppa_exit();
            break;
            // End update-option
        // End update-option
        case 'maintenance':
            $slug = $_POST['slug'];
            $nonce = $_REQUEST['wppa-nonce'];
            if (!wp_verify_nonce($nonce, 'wppa-nonce')) {
                echo 'Security check failure||' . $slug . '||Error||0';
                wppa_exit();
            }
            echo wppa_do_maintenance_proc($slug);
            wppa_exit();
            break;
        case 'maintenancepopup':
            $slug = $_POST['slug'];
            $nonce = $_REQUEST['wppa-nonce'];
            if (!wp_verify_nonce($nonce, 'wppa-nonce')) {
                echo 'Security check failure||' . $slug . '||Error||0';
                wppa_exit();
            }
            echo wppa_do_maintenance_popup($slug);
            wppa_exit();
            break;
        case 'do-fe-upload':
            if (is_admin()) {
                require_once 'wppa-non-admin.php';
            }
            wppa_user_upload();
            echo wppa('out');
            wppa_exit();
            break;
        case 'sanitizetags':
            $tags = isset($_GET['tags']) ? $_GET['tags'] : '';
            $album = isset($_GET['album']) ? $_GET['album'] : '0';
            $deftags = $album ? wppa_get_album_item($album, 'default_tags') : '';
            $tags = $deftags ? $tags . ',' . $deftags : $tags;
            echo wppa_sanitize_tags($tags, false, true);
            wppa_exit();
            break;
        case 'destroyalbum':
            $album = isset($_GET['album']) ? $_GET['album'] : '0';
            if (!$album) {
                _e('Missing album id', 'wp-photo-album-plus');
                wppa_exit();
            }
            $nonce = isset($_GET['nonce']) ? $_GET['nonce'] : '';
            if (!$nonce || !wp_verify_nonce($nonce, 'wppa_nonce_' . $album)) {
                echo 'Security check failure #798';
                wppa_exit();
            }
            // May I?
            $imay = true;
            if (!wppa_switch('user_destroy_on')) {
                $may = false;
            }
            if (wppa_switch('user_create_login')) {
                if (!is_user_logged_in()) {
                    $may = false;
                }
                // Must login
            }
            if (!wppa_have_access($album)) {
                $may = false;
                // No album access
            }
            if (wppa_is_user_blacklisted()) {
                $may = false;
            }
            if (!$imay) {
                _e('You do not have the rights to delete this album', 'wp-photo-album-plus');
                wppa_exit();
            }
            // I may
            require_once 'wppa-album-admin-autosave.php';
            wppa_del_album($album, '');
            wppa_exit();
            break;
        default:
            // Unimplemented $wppa-action
            die('-1');
    }
    wppa_exit();
}
Example #29
0
function __wcs($class)
{
    global $wppa;
    if (!wppa_switch('wppa_inline_css')) {
        return '';
        // No inline styles
    }
    $opt = '';
    $result = '';
    switch ($class) {
        case 'wppa-box':
            $opt = wppa_opt('wppa_bwidth');
            if ($opt > '0') {
                $result .= 'border-style: solid; border-width:' . $opt . 'px; ';
            }
            $opt = wppa_opt('wppa_bradius');
            if ($opt > '0') {
                $result .= 'border-radius:' . $opt . 'px; ';
                $result .= '-moz-border-radius:' . $opt . 'px; ';
                $result .= '-khtml-border-radius:' . $opt . 'px; ';
                $result .= '-webkit-border-radius:' . $opt . 'px; ';
            }
            $opt = wppa_opt('wppa_box_spacing');
            if ($opt != '') {
                $result .= 'margin-bottom:' . $opt . 'px; ';
            }
            break;
        case 'wppa-mini-box':
            $opt = wppa_opt('wppa_bwidth');
            if ($opt > '0') {
                $opt = floor(($opt + 2) / 3);
                $result .= 'border-style: solid; border-width:' . $opt . 'px; ';
            }
            $opt = wppa_opt('wppa_bradius');
            if ($opt > '0') {
                $opt = floor(($opt + 2) / 3);
                $result .= 'border-radius:' . $opt . 'px; ';
                $result .= '-moz-border-radius:' . $opt . 'px; ';
                $result .= '-khtml-border-radius:' . $opt . 'px; ';
                $result .= '-webkit-border-radius:' . $opt . 'px; ';
            }
            break;
        case 'wppa-cover-box':
            $opt = wppa_opt('wppa_cover_minheight');
            if ($opt) {
                $result .= 'min-height:' . $opt . 'px; ';
            }
            break;
        case 'wppa-cover-text-frame':
            $opt = wppa_opt('wppa_head_and_text_frame_height');
            if ($opt) {
                $result .= 'min-height:' . $opt . 'px; ';
            }
            break;
        case 'wppa-thumb-text':
            $opt = wppa_opt('wppa_fontfamily_thumb');
            if ($opt) {
                $result .= 'font-family:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_fontsize_thumb');
            if ($opt) {
                $ls = floor($opt * 1.29);
                $result .= 'font-size:' . $opt . 'px; line-height:' . $ls . 'px; ';
            }
            $opt = wppa_opt('wppa_fontcolor_thumb');
            if ($opt) {
                $result .= 'color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_fontweight_thumb');
            if ($opt) {
                $result .= 'font-weight:' . $opt . '; ';
            }
            break;
        case 'wppa-box-text':
            $opt = wppa_opt('wppa_fontcolor_box');
            if ($opt) {
                $result .= 'color:' . $opt . '; ';
            }
        case 'wppa-box-text-nocolor':
            $opt = wppa_opt('wppa_fontfamily_box');
            if ($opt) {
                $result .= 'font-family:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_fontsize_box');
            if ($opt) {
                $result .= 'font-size:' . $opt . 'px; ';
            }
            $opt = wppa_opt('wppa_fontweight_box');
            if ($opt) {
                $result .= 'font-weight:' . $opt . '; ';
            }
            break;
        case 'wppa-comments':
            $opt = wppa_opt('wppa_bgcolor_com');
            if ($opt) {
                $result .= 'background-color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_bcolor_com');
            if ($opt) {
                $result .= 'border-color:' . $opt . '; ';
            }
            break;
        case 'wppa-iptc':
            $opt = wppa_opt('wppa_bgcolor_iptc');
            if ($opt) {
                $result .= 'background-color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_bcolor_iptc');
            if ($opt) {
                $result .= 'border-color:' . $opt . '; ';
            }
            break;
        case 'wppa-exif':
            $opt = wppa_opt('wppa_bgcolor_exif');
            if ($opt) {
                $result .= 'background-color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_bcolor_exif');
            if ($opt) {
                $result .= 'border-color:' . $opt . '; ';
            }
            break;
        case 'wppa-share':
            $opt = wppa_opt('wppa_bgcolor_share');
            if ($opt) {
                $result .= 'background-color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_bcolor_share');
            if ($opt) {
                $result .= 'border-color:' . $opt . '; ';
            }
            break;
        case 'wppa-name-desc':
            $opt = wppa_opt('wppa_bgcolor_namedesc');
            if ($opt) {
                $result .= 'background-color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_bcolor_namedesc');
            if ($opt) {
                $result .= 'border-color:' . $opt . '; ';
            }
            break;
        case 'wppa-nav':
            $opt = wppa_opt('wppa_bgcolor_nav');
            if ($opt) {
                $result .= 'background-color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_bcolor_nav');
            if ($opt) {
                $result .= 'border-color:' . $opt . '; ';
            }
            break;
        case 'wppa-nav-text':
            $opt = wppa_opt('wppa_fontfamily_nav');
            if ($opt) {
                $result .= 'font-family:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_fontsize_nav');
            if ($opt) {
                $result .= 'font-size:' . $opt . 'px; ';
            }
            $opt = wppa_opt('wppa_fontcolor_nav');
            if ($opt) {
                $result .= 'color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_fontweight_nav');
            if ($opt) {
                $result .= 'font-weight:' . $opt . '; ';
            }
            break;
        case 'wppa-even':
            $opt = wppa_opt('wppa_bgcolor_even');
            if ($opt) {
                $result .= 'background-color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_bcolor_even');
            if ($opt) {
                $result .= 'border-color:' . $opt . '; ';
            }
            break;
        case 'wppa-alt':
            $opt = wppa_opt('wppa_bgcolor_alt');
            if ($opt) {
                $result .= 'background-color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_bcolor_alt');
            if ($opt) {
                $result .= 'border-color:' . $opt . '; ';
            }
            break;
        case 'wppa-img':
            $opt = wppa_opt('wppa_bgcolor_img');
            if ($opt) {
                $result .= 'background-color:' . $opt . '; ';
            }
            break;
        case 'wppa-title':
            $opt = wppa_opt('wppa_fontfamily_title');
            if ($opt) {
                $result .= 'font-family:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_fontsize_title');
            if ($opt) {
                $result .= 'font-size:' . $opt . 'px; ';
            }
            $opt = wppa_opt('wppa_fontcolor_title');
            if ($opt) {
                $result .= 'color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_fontweight_title');
            if ($opt) {
                $result .= 'font-weight:' . $opt . '; ';
            }
            break;
        case 'wppa-fulldesc':
            $opt = wppa_opt('wppa_fontfamily_fulldesc');
            if ($opt) {
                $result .= 'font-family:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_fontsize_fulldesc');
            if ($opt) {
                $result .= 'font-size:' . $opt . 'px; ';
            }
            $opt = wppa_opt('wppa_fontcolor_fulldesc');
            if ($opt) {
                $result .= 'color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_fontweight_fulldesc');
            if ($opt) {
                $result .= 'font-weight:' . $opt . '; ';
            }
            break;
        case 'wppa-fulltitle':
            $opt = wppa_opt('wppa_fontfamily_fulltitle');
            if ($opt) {
                $result .= 'font-family:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_fontsize_fulltitle');
            if ($opt) {
                $result .= 'font-size:' . $opt . 'px; ';
            }
            $opt = wppa_opt('wppa_fontcolor_fulltitle');
            if ($opt) {
                $result .= 'color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_fontweight_fulltitle');
            if ($opt) {
                $result .= 'font-weight:' . $opt . '; ';
            }
            break;
        case 'wppa-custom':
            $opt = wppa_opt('wppa_bgcolor_cus');
            if ($opt) {
                $result .= 'background-color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_bcolor_cus');
            if ($opt) {
                $result .= 'border-color:' . $opt . '; ';
            }
            break;
        case 'wppa-upload':
            $opt = wppa_opt('wppa_bgcolor_upload');
            if ($opt) {
                $result .= 'background-color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_bcolor_upload');
            if ($opt) {
                $result .= 'border-color:' . $opt . '; ';
            }
            break;
        case 'wppa-multitag':
            $opt = wppa_opt('wppa_bgcolor_multitag');
            if ($opt) {
                $result .= 'background-color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_bcolor_multitag');
            if ($opt) {
                $result .= 'border-color:' . $opt . '; ';
            }
            break;
        case 'wppa-bestof':
            $opt = wppa_opt('wppa_bgcolor_bestof');
            if ($opt) {
                $result .= 'background-color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_bcolor_bestof');
            if ($opt) {
                $result .= 'border-color:' . $opt . '; ';
            }
            break;
        case 'wppa-tagcloud':
            $opt = wppa_opt('wppa_bgcolor_tagcloud');
            if ($opt) {
                $result .= 'background-color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_bcolor_tagcloud');
            if ($opt) {
                $result .= 'border-color:' . $opt . '; ';
            }
            break;
        case 'wppa-superview':
            $opt = wppa_opt('wppa_bgcolor_superview');
            if ($opt) {
                $result .= 'background-color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_bcolor_superview');
            if ($opt) {
                $result .= 'border-color:' . $opt . '; ';
            }
            break;
        case 'wppa-search':
            $opt = wppa_opt('wppa_bgcolor_search');
            if ($opt) {
                $result .= 'background-color:' . $opt . '; ';
            }
            $opt = wppa_opt('wppa_bcolor_search');
            if ($opt) {
                $result .= 'border-color:' . $opt . '; ';
            }
            break;
        case 'wppa-black':
            //			$opt = wppa_opt( 'wppa_black' );
            //			if ( $opt ) $result .= 'color:' . $opt . '; ';
            //			break;
            break;
        case 'wppa-arrow':
            $opt = wppa_opt('wppa_arrow_color');
            if ($opt) {
                $result .= 'color:' . $opt . '; ';
            }
            break;
        case 'wppa-td':
            $result .= 'padding: 3px 2px 3px 0; border: 0';
            break;
        default:
            wppa_dbg_msg('Unexpected error in __wcs, unknown class: ' . $class, 'red');
            wppa_log('Err', 'Unexpected error in __wcs, unknown class: ' . $class);
    }
    return $result;
}
function wppa_decrypt_album($album)
{
    global $wpdb;
    // Feature enabled?
    if (!wppa_switch('use_encrypted_links')) {
        return $album;
    }
    // Yes. Decompose possible album enumeration
    $album_crypts = explode('.', $album);
    $album_ids = array();
    $i = 0;
    // Process all tokens
    while ($i < count($album_crypts)) {
        $crypt = $album_crypts[$i];
        if (!$crypt) {
            $id = '';
        } elseif ($crypt == get_option('wppa_album_crypt_9', false)) {
            $id = '999999';
        } elseif ($crypt == get_option('wppa_album_crypt_0', false)) {
            $id = '0';
        } elseif ($crypt == get_option('wppa_album_crypt_1', false)) {
            $id = '-1';
        } elseif ($crypt == get_option('wppa_album_crypt_2', false)) {
            $id = '-2';
        } elseif ($crypt == get_option('wppa_album_crypt_2', false)) {
            $id = '-3';
        } else {
            // Already decrypted?
            if (strlen($crypt) < 12) {
                $id = $crypt;
                if (wppa_switch('refuse_unencrypted')) {
                    wppa_dbg_msg(__('Invalid album identifier:', 'wp-photo-album-plus') . ' ' . $id, 'red');
                    wppa_log('dbg', 'Decrypted album foud wppa_decrypt_album(). id=' . $id, true);
                    $id = '-9';
                } else {
                    return $album;
                    // Assume everything already decrypted, return original
                }
            } else {
                $id = $wpdb->get_var($wpdb->prepare("SELECT `id` FROM `" . WPPA_ALBUMS . "` WHERE `crypt` = %s", substr($crypt, 0, 12)));
                if (!$id) {
                    wppa_log('Dbg', 'Invalid album identifier: ' . $crypt . ' found in: ' . $album . ' (wppa_decrypt_album)');
                    $id = '-9';
                }
            }
        }
        $album_ids[$i] = $id;
        $i++;
    }
    // Compose result
    $result = implode('.', $album_ids);
    // Remove not found/deleted albums
    $result = str_replace('..-9', '', $result);
    $result = str_replace('.-9', '', $result);
    $result = str_replace('-9..', '', $result);
    $result = str_replace('-9.', '', $result);
    return $result;
}