function wppa_get_photo_count($id = '0', $use_treecounts = false)
{
    global $wpdb;
    if ($use_treecounts) {
        $treecounts = wppa_treecount_a($id);
        if (current_user_can('wppa_moderate')) {
            $count = $treecounts['selfphotos'] + $treecounts['pendphotos'] + $treecounts['scheduledphotos'];
        } else {
            $count = $treecounts['selfphotos'];
        }
    } elseif (!$id) {
        if (current_user_can('wppa_moderate')) {
            $count = $wpdb->get_var("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` ");
        } else {
            $count = $wpdb->get_var("SELECT COUNT(*) FROM `" . WPPA_PHOTOS, "` WHERE ( ( `status` <> 'pending' AND `status` <> 'scheduled' ) OR owner = %s )", wppa_get_user());
        }
    } else {
        if (current_user_can('wppa_moderate')) {
            $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM " . WPPA_PHOTOS . " WHERE album = %s", $id));
        } else {
            $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM " . WPPA_PHOTOS . " WHERE `album` = %s AND ( ( `status` <> 'pending' AND `status` <> 'scheduled' ) OR owner = %s )", $id, wppa_get_user()));
        }
        wppa_dbg_q('Q-gpc');
    }
    // Substract private photos if not logged in and album given
    if ($id && !is_user_logged_in()) {
        $count -= $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s AND `status` = 'private' ", $id));
    }
    return $count;
}
 /** @see WP_Widget::widget */
 function widget($args, $instance)
 {
     global $wpdb;
     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();
     wppa('in_widget', 'albnav');
     wppa_bump_mocc();
     extract($args);
     $instance = wp_parse_args((array) $instance, array('title' => '', 'parent' => '0', 'skip' => 'yes'));
     $widget_title = apply_filters('widget_title', $instance['title']);
     $page = wppa_get_the_landing_page('album_navigator_widget_linkpage', __('Photo Albums', 'wp-photo-album-plus'));
     $parent = $instance['parent'];
     $skip = $instance['skip'];
     $widget_content = "\n" . '<!-- WPPA+ Album Navigator Widget start -->';
     $widget_content .= '<div style="width:100%; overflow:hidden; position:relative; left: -12px;" >';
     if ($parent == 'all') {
         $widget_content .= $this->do_album_navigator('0', $page, $skip, '');
         $widget_content .= $this->do_album_navigator('-1', $page, $skip, '');
     } elseif ($parent == 'owner') {
         $widget_content .= $this->do_album_navigator('0', $page, $skip, '', " AND ( `owner` = '--- public ---' OR `owner` = '" . wppa_get_user() . "' ) ");
         $widget_content .= $this->do_album_navigator('-1', $page, $skip, '', " AND ( `owner` = '--- public ---' OR `owner` = '" . wppa_get_user() . "' ) ");
     } else {
         $widget_content .= $this->do_album_navigator($parent, $page, $skip, '');
     }
     $widget_content .= '</div>';
     $widget_content .= '<div style="clear:both"></div>';
     $widget_content .= "\n" . '<!-- WPPA+ Album Navigator 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_get_edit_search_photos($limit = '', $count_only = false)
{
    global $wpdb;
    global $wppa_search_stats;
    $doit = false;
    //	if ( wppa_user_is( 'administrator' ) ) $doit = true;
    if (current_user_can('wppa_admin') && current_user_can('wppa_moderate')) {
        $doit = true;
    }
    if (wppa_switch('upload_edit')) {
        $doit = true;
    }
    if (!$doit) {
        // Should never get here. Only when url is manipulted manually.
        die('Security check failure #309');
    }
    $words = explode(',', wppa_sanitize_searchstring($_REQUEST['wppa-searchstring']));
    $wppa_search_stats = array();
    $first = true;
    foreach ($words as $word) {
        // Find lines in index db table
        if (wppa_switch('wild_front')) {
            $pidxs = $wpdb->get_results("SELECT `slug`, `photos` FROM `" . WPPA_INDEX . "` WHERE `slug` LIKE '%" . $word . "%'", ARRAY_A);
        } else {
            $pidxs = $wpdb->get_results("SELECT `slug`, `photos` FROM `" . WPPA_INDEX . "` WHERE `slug` LIKE '" . $word . "%'", ARRAY_A);
        }
        $photos = '';
        foreach ($pidxs as $pi) {
            $photos .= $pi['photos'] . ',';
        }
        if ($first) {
            $photo_array = wppa_index_array_remove_dups(wppa_index_string_to_array(trim($photos, ',')));
            $count = empty($photo_array) ? '0' : count($photo_array);
            $list = implode(',', $photo_array);
            if (!$list) {
                $list = '0';
            }
            //			if ( wppa_user_is( 'administrator' ) ) {
            if (current_user_can('wppa_admin') && current_user_can('wppa_moderate')) {
                $real_count = $wpdb->get_var("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `id` IN (" . $list . ") ");
                if ($count != $real_count) {
                    update_option('wppa_remake_index_photos_status', __('Required', 'wp-photo-album-plus'));
                    // 					echo 'realcount mismatch:1';
                    //					echo ' count='.$count.', realcount='.$real_count.'<br/>';
                }
            } else {
                // Not admin, can edit own photos only
                $real_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `id` IN (" . $list . ") AND `owner` = %s", wppa_get_user()));
            }
            $wppa_search_stats[] = array('word' => $word, 'count' => $real_count);
            $first = false;
        } else {
            $temp_array = wppa_index_array_remove_dups(wppa_index_string_to_array(trim($photos, ',')));
            $count = empty($temp_array) ? '0' : count($temp_array);
            $list = implode(',', $temp_array);
            //			if ( wppa_user_is( 'administrator' ) ) {
            if (current_user_can('wppa_admin') && current_user_can('wppa_moderate')) {
                $real_count = $wpdb->get_var("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `id` IN (" . $list . ") ");
                if ($count != $real_count) {
                    update_option('wppa_remake_index_photos_status', __('Required', 'wp-photo-album-plus'));
                    //					echo 'realcount mismatch:2';
                    //					echo ' count='.$count.', realcount='.$real_count.'<br/>';
                }
            } else {
                // Not admin, can edit own photos only
                $real_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `id` IN (" . $list . ") AND `owner` = %s", wppa_get_user()));
            }
            $wppa_search_stats[] = array('word' => $word, 'count' => $real_count);
            $photo_array = array_intersect($photo_array, $temp_array);
        }
    }
    if (!empty($photo_array)) {
        $list = implode(',', $photo_array);
        //		if ( wppa_user_is( 'administrator' ) ) {
        if (current_user_can('wppa_admin') && current_user_can('wppa_moderate')) {
            $totcount = $wpdb->get_var("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `id` IN (" . $list . ") ");
        } else {
            // Not admin, can edit own photos only
            $totcount = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `id` IN (" . $list . ") AND `owner` = %s", wppa_get_user()));
        }
        $wppa_search_stats[] = array('word' => __('Combined', 'wp-photo-album-plus'), 'count' => $totcount);
        //		if ( wppa_user_is( 'administrator' ) ) {
        if (current_user_can('wppa_admin') && current_user_can('wppa_moderate')) {
            $photos = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `id` IN (" . $list . ") " . wppa_get_photo_order('0', 'norandom') . $limit, ARRAY_A);
        } else {
            // Not admin, can edit own photos only
            $photos = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `id` IN (" . $list . ") AND `owner` = %s" . wppa_get_photo_order('0', 'norandom') . $limit, wppa_get_user()), ARRAY_A);
        }
    } else {
        $photos = false;
    }
    if ($count_only) {
        if (is_array($photos)) {
            return count($photos);
        } else {
            return '0';
        }
    } else {
        return $photos;
    }
}
function wppa_insert_photo($file = '', $alb = '', $name = '', $desc = '', $porder = '0', $id = '0', $linkurl = '', $linktitle = '')
{
    global $wpdb;
    global $warning_given_small;
    $album = wppa_cache_album($alb);
    if (!wppa_allow_uploads($alb)) {
        if (is_admin() && !wppa('ajax')) {
            wppa_error_message(sprintf(__('Album %s is full', 'wp-photo-album-plus'), wppa_get_album_name($alb)));
        } else {
            wppa_alert(sprintf(__('Album %s is full', 'wp-photo-album-plus'), wppa_get_album_name($alb)));
        }
        return false;
    }
    if ($file != '' && $alb != '') {
        // Get the name if not given
        if ($name == '') {
            $name = basename($file);
        }
        // Sanitize name
        $filename = wppa_sanitize_file_name($name);
        $name = wppa_sanitize_photo_name($name);
        // If not dups allowed and its already here, quit
        if (isset($_POST['wppa-nodups']) || wppa_switch('void_dups')) {
            $exists = wppa_file_is_in_album($filename, $alb);
            if ($exists) {
                if (isset($_POST['del-after-p'])) {
                    unlink($file);
                    $msg = __('Photo %s already exists in album number %s. Removed from depot.', 'wp-photo-album-plus');
                } else {
                    $msg = __('Photo %s already exists in album number %s.', 'wp-photo-album-plus');
                }
                wppa_warning_message(sprintf($msg, $name, $alb));
                return false;
            }
        }
        // Verify file exists
        if (!wppa('is_remote') && !file_exists($file)) {
            if (!is_dir(dirname($file))) {
                wppa_error_message('Error: Directory ' . dirname($file) . ' does not exist.');
                return false;
            }
            if (!is_writable(dirname($file))) {
                wppa_error_message('Error: Directory ' . dirname($file) . ' is not writable.');
                return false;
            }
            wppa_error_message('Error: File ' . $file . ' does not exist.');
            return false;
        }
        //		else {
        //			wppa_ok_message( 'Good: File '.$file.' exists.' );
        //		}
        // Get and verify the size
        $img_size = getimagesize($file);
        if ($img_size) {
            if (wppa_check_memory_limit('', $img_size['0'], $img_size['1']) === false) {
                wppa_error_message(sprintf(__('ERROR: Attempt to upload a photo that is too large to process (%s).', 'wp-photo-album-plus'), $name) . wppa_check_memory_limit());
                wppa('ajax_import_files_error', __('Too big', 'wp-photo-album-plus'));
                return false;
            }
            if (!$warning_given_small && ($img_size['0'] < wppa_get_minisize() && $img_size['1'] < wppa_get_minisize())) {
                wppa_warning_message(__('WARNING: You are uploading photos that are too small. Photos must be larger than the thumbnail size and larger than the coverphotosize.', 'wp-photo-album-plus'));
                wppa('ajax_import_files_error', __('Too small', 'wp-photo-album-plus'));
                $warning_given_small = true;
            }
        } else {
            wppa_error_message(__('ERROR: Unable to retrieve image size of', 'wp-photo-album-plus') . ' ' . $name . ' ' . __('Are you sure it is a photo?', 'wp-photo-album-plus'));
            wppa('ajax_import_files_error', __('No imagesize', 'wp-photo-album-plus'));
            return false;
        }
        // Get ext based on mimetype, regardless of ext
        switch ($img_size[2]) {
            // mime type
            case 1:
                $ext = 'gif';
                break;
            case 2:
                $ext = 'jpg';
                break;
            case 3:
                $ext = 'png';
                break;
            default:
                wppa_error_message(__('Unsupported mime type encountered:', 'wp-photo-album-plus') . ' ' . $img_size[2] . '.');
                return false;
        }
        // Get an id if not yet there
        if ($id == '0') {
            $id = wppa_nextkey(WPPA_PHOTOS);
        }
        // Get opt deflt desc if empty
        if ($desc == '' && wppa_switch('apply_newphoto_desc')) {
            $desc = stripslashes(wppa_opt('newphoto_description'));
        }
        // Reset rating
        $mrat = '0';
        // Find ( new ) owner
        $owner = wppa_get_user();
        // Validate album
        if (!is_numeric($alb) || $alb < '1') {
            wppa_error_message(__('Album not known while trying to add a photo', 'wp-photo-album-plus'));
            return false;
        }
        if (!wppa_have_access($alb)) {
            wppa_error_message(sprintf(__('Album %s does not exist or is not accessable while trying to add a photo', 'wp-photo-album-plus'), $alb));
            return false;
        }
        $status = wppa_switch('upload_moderate') && !current_user_can('wppa_admin') ? 'pending' : 'publish';
        // Add photo to db
        $id = wppa_create_photo_entry(array('id' => $id, 'album' => $alb, 'ext' => $ext, 'name' => $name, 'p_order' => $porder, 'description' => $desc, 'linkurl' => $linkurl, 'linktitle' => $linktitle, 'owner' => $owner, 'status' => $status, 'filename' => $filename));
        if (!$id) {
            wppa_error_message(__('Could not insert photo.', 'wp-photo-album-plus'));
        } else {
            // Save the source
            wppa_save_source($file, $filename, $alb);
            wppa_flush_treecounts($alb);
            wppa_update_album(array('id' => $alb, 'modified' => time()));
            wppa_flush_upldr_cache('photoid', $id);
        }
        // Make the photo files
        if (wppa_make_the_photo_files($file, $id, $ext)) {
            // Repair photoname if not supplied and not standard
            wppa_set_default_name($id, $name);
            // Tags
            wppa_set_default_tags($id);
            // Index
            wppa_index_add('photo', $id);
            // and add watermark ( optionally ) to fullsize image only
            wppa_add_watermark($id);
            // also to thumbnail?
            if (wppa_switch('watermark_thumbs')) {
                wppa_create_thumbnail($id);
            }
            // Is it a default coverimage?
            wppa_check_coverimage($id);
            return $id;
        }
    } else {
        wppa_error_message(__('ERROR: Unknown file or album.', 'wp-photo-album-plus'));
        return false;
    }
}
function wppa_album_select_a($args)
{
    global $wpdb;
    $args = wp_parse_args($args, array('exclude' => '', 'selected' => '', 'disabled' => '', 'addpleaseselect' => false, 'addnone' => false, 'addall' => false, 'addgeneric' => false, 'addblank' => false, 'addselected' => false, 'addseparate' => false, 'addselbox' => false, 'disableancestors' => false, 'checkaccess' => false, 'checkowner' => false, 'checkupload' => false, 'addmultiple' => false, 'addnumbers' => false, 'path' => false, 'root' => false, 'content' => false, 'sort' => true));
    // Provide default selection if no selected given
    if ($args['selected'] === '') {
        $args['selected'] = wppa_get_last_album();
    }
    // See if selection is valid
    if ($args['selected'] == $args['exclude'] || $args['checkupload'] && !wppa_allow_uploads($args['selected']) || $args['disableancestors'] && wppa_is_ancestor($args['exclude'], $args['selected'])) {
        $args['selected'] = '0';
    }
    $albums = $wpdb->get_results("SELECT * FROM `" . WPPA_ALBUMS . "` " . wppa_get_album_order($args['root']), ARRAY_A);
    // Add to secondary cache
    if ($albums) {
        wppa_cache_album('add', $albums);
    }
    if ($albums) {
        // Filter for root
        if ($args['root']) {
            $root = $args['root'];
            switch ($root) {
                // case '0': all, will be skipped as it returns false in 'if ( $args['root'] )'
                case '-2':
                    // Generic only
                    foreach (array_keys($albums) as $albidx) {
                        if (wppa_is_separate($albums[$albidx]['id'])) {
                            unset($albums[$albidx]);
                        }
                    }
                    break;
                case '-1':
                    // Separate only
                    foreach (array_keys($albums) as $albidx) {
                        if (!wppa_is_separate($albums[$albidx]['id'])) {
                            unset($albums[$albidx]);
                        }
                    }
                    break;
                default:
                    foreach (array_keys($albums) as $albidx) {
                        if (!wppa_is_ancestor($root, $albums[$albidx]['id'])) {
                            unset($albums[$albidx]);
                        }
                    }
                    break;
            }
        }
        // Filter for must have content
        if ($args['content']) {
            foreach (array_keys($albums) as $albidx) {
                if (wppa_get_photo_count($albums[$albidx]['id']) <= wppa_get_mincount()) {
                    unset($albums[$albidx]);
                }
            }
        }
        // Add paths
        if ($args['path']) {
            $albums = wppa_add_paths($albums);
        } else {
            foreach (array_keys($albums) as $index) {
                $albums[$index]['name'] = __(stripslashes($albums[$index]['name']));
            }
        }
        // Sort
        if ($args['sort']) {
            $albums = wppa_array_sort($albums, 'name');
        }
    }
    // Output
    $result = '';
    $selected = $args['selected'] == '0' ? ' selected="selected"' : '';
    if ($args['addpleaseselect']) {
        $result .= '<option value="0" disabled="disabled" ' . $selected . ' >' . (is_admin() ? __('- select an album -', 'wppa') : __a('- select an album -')) . '</option>';
    }
    $selected = $args['selected'] == '0' ? ' selected="selected"' : '';
    if ($args['addnone']) {
        $result .= '<option value="0"' . $selected . ' >' . (is_admin() ? __('--- none ---', 'wppa') : __a('--- none ---')) . '</option>';
    }
    $selected = $args['selected'] == '0' ? ' selected="selected"' : '';
    if ($args['addall']) {
        $result .= '<option value="0"' . $selected . ' >' . (is_admin() ? __('--- all ---', 'wppa') : __a('--- all ---')) . '</option>';
    }
    $selected = $args['selected'] == '-2' ? ' selected="selected"' : '';
    if ($args['addall']) {
        $result .= '<option value="-2"' . $selected . ' >' . (is_admin() ? __('--- generic ---', 'wppa') : __a('--- generic ---')) . '</option>';
    }
    $selected = $args['selected'] == '0' ? ' selected="selected"' : '';
    if ($args['addblank']) {
        $result .= '<option value="0"' . $selected . ' >' . '</option>';
    }
    $selected = $args['selected'] == '-99' ? ' selected="selected"' : '';
    if ($args['addmultiple']) {
        $result .= '<option value="-99"' . $selected . ' >' . (is_admin() ? __('--- multiple see below ---', 'wppa') : __a('--- multiple see below ---')) . '</option>';
    }
    $selected = $args['selected'] == '0' ? ' selected="selected"' : '';
    if ($args['addselbox']) {
        $result .= '<option value="0"' . $selected . ' >' . (is_admin() ? __('--- a selection box ---', 'wppa') : __a('--- a selection box ---')) . '</option>';
    }
    if ($albums) {
        foreach ($albums as $album) {
            if ($args['disabled'] == $album['id'] || $args['exclude'] == $album['id'] || $args['checkupload'] && !wppa_allow_uploads($album['id']) || $args['disableancestors'] && wppa_is_ancestor($args['exclude'], $album['id'])) {
                $disabled = ' disabled="disabled"';
            } else {
                $disabled = '';
            }
            if ($args['selected'] == $album['id'] && !$disabled) {
                $selected = ' selected="selected"';
            } else {
                $selected = '';
            }
            $ok = true;
            // Assume this will be in the list
            if ($args['checkaccess'] && !wppa_have_access($album['id'])) {
                $ok = false;
            }
            if ($args['checkowner'] && wppa_switch('upload_owner_only')) {
                // Need to check
                if ($album['owner'] != wppa_get_user() && $album['owner'] != '--- public ---') {
                    // Not 'mine'
                    if (!wppa_user_is('administrator')) {
                        // No admin
                        $ok = false;
                    }
                }
            }
            if ($selected && $args['addselected']) {
                $ok = true;
            }
            if ($ok) {
                if ($args['addnumbers']) {
                    $number = ' ( ' . $album['id'] . ' )';
                } else {
                    $number = '';
                }
                $result .= '<option value="' . $album['id'] . '" ' . $selected . $disabled . '>' . $album['name'] . $number . '</option>';
            }
        }
    }
    $selected = $args['selected'] == '-1' ? ' selected="selected"' : '';
    if ($args['addseparate']) {
        $result .= '<option value="-1"' . $selected . '>' . (is_admin() ? __('--- separate ---', 'wppa') : __a('--- separate ---')) . '</option>';
    }
    return $result;
}
function wppa_import_photos($delp = false, $dela = false, $delz = false, $delv = false, $delu = false, $delc = false, $delf = false)
{
    global $wpdb;
    global $warning_given;
    global $wppa_supported_photo_extensions;
    global $wppa_supported_video_extensions;
    global $wppa_supported_audio_extensions;
    $warning_given = false;
    // Get this users current source directory setting
    $user = wppa_get_user();
    $source_type = get_option('wppa_import_source_type_' . $user, 'local');
    if ($source_type == 'remote') {
        wppa('is_remote', true);
    }
    $source = get_option('wppa_import_source_' . $user, WPPA_DEPOT_PATH);
    $depot = WPPA_ABSPATH . $source;
    // Filesystem
    $depoturl = get_bloginfo('wpurl') . '/' . $source;
    // url
    // See what's in there
    $files = wppa_get_import_files();
    // First extract zips if our php version is ok
    $idx = '0';
    $zcount = 0;
    if (PHP_VERSION_ID >= 50207) {
        foreach ($files as $zipfile) {
            if (isset($_POST['file-' . $idx])) {
                $ext = strtolower(substr(strrchr($zipfile, "."), 1));
                if ($ext == 'zip') {
                    $err = wppa_extract($zipfile, $delz);
                    if ($err == '0') {
                        $zcount++;
                    }
                }
                // if ext = zip
            }
            // if isset
            $idx++;
        }
        // foreach
    }
    // Now see if albums must be created
    $idx = '0';
    $acount = 0;
    foreach ($files as $album) {
        if (isset($_POST['file-' . $idx])) {
            $ext = strtolower(substr(strrchr($album, "."), 1));
            if ($ext == 'amf') {
                $name = '';
                $desc = '';
                $aord = '0';
                $parent = '0';
                $porder = '0';
                $owner = '';
                $handle = fopen($album, "r");
                if ($handle) {
                    $buffer = fgets($handle, 4096);
                    while (!feof($handle)) {
                        $tag = substr($buffer, 0, 5);
                        $len = strlen($buffer) - 6;
                        // substract 5 for label and one for eol
                        $data = substr($buffer, 5, $len);
                        switch ($tag) {
                            case 'name=':
                                $name = $data;
                                break;
                            case 'desc=':
                                $desc = wppa_txt_to_nl($data);
                                break;
                            case 'aord=':
                                if (is_numeric($data)) {
                                    $aord = $data;
                                }
                                break;
                            case 'prnt=':
                                if ($data == __('--- none ---', 'wp-photo-album-plus')) {
                                    $parent = '0';
                                } elseif ($data == __('--- separate ---', 'wp-photo-album-plus')) {
                                    $parent = '-1';
                                } else {
                                    $prnt = wppa_get_album_id($data);
                                    if ($prnt != '') {
                                        $parent = $prnt;
                                    } else {
                                        $parent = '0';
                                        wppa_warning_message(__('Unknown parent album:', 'wp-photo-album-plus') . ' ' . $data . ' ' . __('--- none --- used.', 'wp-photo-album-plus'));
                                    }
                                }
                                break;
                            case 'pord=':
                                if (is_numeric($data)) {
                                    $porder = $data;
                                }
                                break;
                            case 'ownr=':
                                $owner = $data;
                                break;
                        }
                        $buffer = fgets($handle, 4096);
                    }
                    // while !foef
                    fclose($handle);
                    if (wppa_get_album_id($name) != '') {
                        wppa_warning_message('Album already exists ' . stripslashes($name));
                        if ($dela) {
                            unlink($album);
                        }
                    } else {
                        $id = basename($album);
                        $id = substr($id, 0, strpos($id, '.'));
                        $id = wppa_create_album_entry(array('id' => $id, 'name' => stripslashes($name), 'description' => stripslashes($desc), 'a_order' => $aord, 'a_parent' => $parent, 'p_order_by' => $porder, 'owner' => $owner));
                        if ($id === false) {
                            wppa_error_message(__('Could not create album.', 'wp-photo-album-plus'));
                        } else {
                            //$id = wppa_get_album_id( $name );
                            wppa_set_last_album($id);
                            wppa_index_add('album', $id);
                            wppa_ok_message(__('Album #', 'wp-photo-album-plus') . ' ' . $id . ': ' . stripslashes($name) . ' ' . __('Added.', 'wp-photo-album-plus'));
                            if ($dela) {
                                unlink($album);
                            }
                            $acount++;
                            wppa_clear_cache();
                            wppa_flush_treecounts($id);
                        }
                        // album added
                    }
                    // album did not exist
                }
                // if handle ( file open )
            }
            // if its an album
        }
        // if isset
        $idx++;
    }
    // foreach file
    // Now the photos
    $idx = '0';
    $pcount = '0';
    $totpcount = '0';
    // find album id
    if (isset($_POST['cre-album'])) {
        // use album ngg gallery name for ngg conversion
        $album = wppa_get_album_id(strip_tags($_POST['cre-album']));
        if (!$album) {
            // the album does not exist yet, create it
            $name = strip_tags($_POST['cre-album']);
            $desc = sprintf(__('This album has been converted from ngg gallery %s', 'wp-photo-album-plus'), $name);
            $uplim = '0/0';
            // Unlimited not to destroy the conversion process!!
            $album = wppa_create_album_entry(array('name' => $name, 'description' => $desc, 'upload_limit' => $uplim));
            if ($album === false) {
                wppa_error_message(__('Could not create album.', 'wp-photo-album-plus') . '<br/>Query = ' . $query);
                wp_die('Sorry, cannot continue');
            }
        }
    } elseif (isset($_POST['wppa-photo-album'])) {
        $album = $_POST['wppa-photo-album'];
    } else {
        $album = '0';
    }
    // Report starting process
    wppa_ok_message(__('Processing files, please wait...', 'wp-photo-album-plus') . ' ' . __('If the line of dots stops growing or your browser reports Ready, your server has given up. In that case: try again', 'wp-photo-album-plus') . ' <a href="' . wppa_dbg_url(get_admin_url() . 'admin.php?page=wppa_import_photos') . '">' . __('here.', 'wp-photo-album-plus') . '</a>');
    // Do them all
    foreach (array_keys($files) as $file_idx) {
        $unsanitized_path_name = $files[$file_idx];
        $file = $files[$file_idx];
        wppa_is_wppa_tree($file);
        // Sets wppa( 'is_wppa_tree' )
        if (isset($_POST['use-backup']) && is_file($file . '_backup')) {
            $file = $file . '_backup';
        }
        $file = wppa_sanitize_file_name($file);
        if (isset($_POST['file-' . $idx]) || wppa('ajax')) {
            if (wppa('is_wppa_tree')) {
                if (wppa('ajax')) {
                    wppa('ajax_import_files', basename(wppa_compress_tree_path($file)));
                }
            } else {
                if (wppa('ajax')) {
                    wppa('ajax_import_files', basename($file));
                }
            }
            $ext = strtolower(substr(strrchr($file, "."), 1));
            $ext = str_replace('_backup', '', $ext);
            if (in_array($ext, $wppa_supported_photo_extensions)) {
                // See if a metafile exists
                //$meta = substr( $file, 0, strlen( $file ) - 3 ).'pmf';
                $meta = wppa_strip_ext($unsanitized_path_name) . '.PMF';
                if (!is_file($meta)) {
                    $meta = wppa_strip_ext($unsanitized_path_name) . '.pmf';
                }
                // find all data: name, desc, porder form metafile
                if (is_file($meta)) {
                    $alb = wppa_get_album_id(wppa_get_meta_album($meta));
                    $name = wppa_get_meta_name($meta);
                    $desc = wppa_txt_to_nl(wppa_get_meta_desc($meta));
                    $porder = wppa_get_meta_porder($meta);
                    $linkurl = wppa_get_meta_linkurl($meta);
                    $linktitle = wppa_get_meta_linktitle($meta);
                } else {
                    $alb = $album;
                    // default album
                    $name = '';
                    // default name
                    $desc = '';
                    // default description
                    $porder = '0';
                    // default p_order
                    $linkurl = '';
                    $linktitle = '';
                }
                // If there is a video or audio with the same name, this is the poster.
                $is_poster = wppa_file_is_in_album(wppa_strip_ext(basename($file)) . '.xxx', $alb);
                if ($is_poster) {
                    // Delete possible poster sourcefile
                    wppa_delete_source(basename($file), $alb);
                    // Remove possible existing posters, the file-extension may be different as before
                    $old_photo = wppa_strip_ext(wppa_get_photo_path($is_poster));
                    $old_thumb = wppa_strip_ext(wppa_get_thumb_path($is_poster));
                    foreach ($wppa_supported_photo_extensions as $pext) {
                        if (is_file($old_photo . '.' . $pext)) {
                            unlink($old_photo . '.' . $pext);
                        }
                        if (is_file($old_thumb . '.' . $pext)) {
                            unlink($old_thumb . '.' . $pext);
                        }
                    }
                    // Clear sizes on db
                    wppa_update_photo(array('thumbx' => '0', 'thumby' => '0', 'photox' => '0', 'photoy' => '0'));
                    // Make new files
                    $bret = wppa_make_the_photo_files($file, $is_poster, strtolower(wppa_get_ext(basename($file))));
                    if ($bret) {
                        // Success
                        if (wppa('ajax')) {
                            wppa('ajax_import_files_done', true);
                        }
                        wppa_save_source($file, basename($file), $alb);
                        wppa_make_o1_source($is_poster);
                        $pcount++;
                        $totpcount += $bret;
                        if ($delp) {
                            unlink($file);
                        }
                    } else {
                        // Failed
                        if (!wppa('ajax')) {
                            wppa_error_message('Failed to add poster for item ' . $is_poster);
                        }
                        if ($delf) {
                            unlink($file);
                        }
                    }
                } elseif (isset($_POST['wppa-update'])) {
                    if (wppa('is_wppa_tree')) {
                        $tmp = explode('/wppa/', $file);
                        $name = str_replace('/', '', $tmp[1]);
                    }
                    $iret = wppa_update_photo_files($unsanitized_path_name, $name);
                    if ($iret) {
                        if (wppa('ajax')) {
                            wppa('ajax_import_files_done', true);
                        }
                        $pcount++;
                        $totpcount += $iret;
                        if ($delp) {
                            unlink($unsanitized_path_name);
                        }
                    } else {
                        if ($delf) {
                            unlink($unsanitized_path_name);
                        }
                    }
                } else {
                    if (is_numeric($alb) && $alb != '0') {
                        if (wppa('is_wppa_tree')) {
                            $tmp = explode('/wppa/', $file);
                            $id = str_replace('/', '', $tmp[1]);
                            $name = $id;
                        } else {
                            $id = basename($file);
                        }
                        if (wppa_switch('void_dups') && wppa_file_is_in_album($id, $alb)) {
                            wppa_warning_message(sprintf(__('Photo %s already exists in album %s. (1)', 'wp-photo-album-plus'), $id, $alb));
                            wppa('ajax_import_files_error', __('Duplicate', 'wp-photo-album-plus'));
                            if ($delf) {
                                unlink($file);
                            }
                        } else {
                            $id = substr($id, 0, strpos($id, '.'));
                            if (!is_numeric($id) || !wppa_is_id_free('photo', $id)) {
                                $id = 0;
                            }
                            if (wppa_insert_photo($unsanitized_path_name, $alb, stripslashes($name), stripslashes($desc), $porder, $id, stripslashes($linkurl), stripslashes($linktitle))) {
                                if (wppa('ajax')) {
                                    wppa('ajax_import_files_done', true);
                                }
                                $pcount++;
                                if ($delp) {
                                    unlink($unsanitized_path_name);
                                    if (is_file($meta)) {
                                        unlink($meta);
                                    }
                                }
                            } else {
                                wppa_error_message(__('Error inserting photo', 'wp-photo-album-plus') . ' ' . basename($file) . '.');
                                if ($delf) {
                                    unlink($unsanitized_path_name);
                                }
                            }
                        }
                    } else {
                        wppa_error_message(sprintf(__('Error inserting photo %s, unknown or non existent album.', 'wp-photo-album-plus'), basename($file)));
                    }
                }
                // Insert
            }
        }
        $idx++;
        if ($source_type == 'remote') {
            unset($files[$file_idx]);
        }
        if (wppa_is_time_up()) {
            wppa_warning_message(sprintf(__('Time out. %s photos imported. Please restart this operation.', 'wp-photo-album-plus'), $pcount));
            wppa_set_last_album($album);
            if ($source_type == 'remote') {
                update_option('wppa_import_source_url_found_' . $user, $files);
            }
            return;
        }
    }
    // foreach $files
    if ($source_type == 'remote') {
        update_option('wppa_import_source_url_found_' . $user, $files);
    }
    // Now the dirs to album imports
    $idx = '0';
    $dircount = '0';
    global $photocount;
    $photocount = '0';
    $iret = true;
    foreach ($files as $file) {
        if (basename($file) != '.' && basename($file) != '..' && (isset($_POST['file-' . $idx]) || isset($_GET['continue']))) {
            if (is_dir($file)) {
                $iret = wppa_import_dir_to_album($file, '0');
                if (wppa_is_time_up() && wppa_switch('auto_continue')) {
                    wppa('continue', 'continue');
                }
                $dircount++;
            }
        }
        $idx++;
        if ($iret == false) {
            break;
        }
        // Time out
    }
    // Now the video files
    $videocount = '0';
    $alb = isset($_POST['wppa-video-album']) ? $_POST['wppa-video-album'] : '0';
    if (wppa('ajax') && !$alb) {
        wppa('ajax_import_files_error', __('Unknown album', 'wp-photo-album-plus'));
    } else {
        foreach (array_keys($files) as $idx) {
            $file = $files[$idx];
            if (isset($_POST['file-' . $idx]) || wppa('ajax')) {
                if (wppa('ajax')) {
                    wppa('ajax_import_files', wppa_sanitize_file_name(basename($file)));
                }
                /* */
                $ext = strtolower(substr(strrchr($file, "."), 1));
                if (in_array($ext, $wppa_supported_video_extensions)) {
                    if (is_numeric($alb) && $alb != '0') {
                        // Do we have this filename with ext xxx in this album?
                        $filename = wppa_strip_ext(basename($file)) . '.xxx';
                        $id = wppa_file_is_in_album($filename, $alb);
                        // Or maybe the poster is already there
                        foreach ($wppa_supported_photo_extensions as $pext) {
                            if (!$id) {
                                $id = wppa_file_is_in_album(str_replace('xxx', $pext, $filename), $alb);
                            }
                        }
                        // This filename already exists: is the poster. Fix the filename in the photo info
                        if ($id) {
                            $fname = wppa_get_photo_item($id, 'filename');
                            $fname = wppa_strip_ext($fname) . '.xxx';
                            // Fix filename and ext in photo info
                            wppa_update_photo(array('id' => $id, 'filename' => $fname, 'ext' => 'xxx'));
                        }
                        // Add new entry
                        if (!$id) {
                            $id = wppa_create_photo_entry(array('album' => $alb, 'filename' => $filename, 'ext' => 'xxx', 'name' => wppa_strip_ext($filename)));
                            wppa_flush_treecounts($alb);
                        }
                        // Add video filetype
                        $newpath = wppa_strip_ext(wppa_get_photo_path($id)) . '.' . $ext;
                        $fs = filesize($file);
                        if ($fs > 1024 * 1024 * 64 || $delv) {
                            // copy fails for files > 64 Mb
                            // Remove old version if already exists
                            if (is_file($newpath)) {
                                unlink($newpath);
                            }
                            rename($file, $newpath);
                        } else {
                            copy($file, $newpath);
                        }
                        if (wppa('ajax')) {
                            wppa('ajax_import_files_done', true);
                        }
                        // Make sure ext is set to xxx after adding video to an existing poster
                        wppa_update_photo(array('id' => $id, 'ext' => 'xxx'));
                        // Book keeping
                        $videocount++;
                    } else {
                        wppa_error_message(sprintf(__('Error inserting video %s, unknown or non existent album.', 'wp-photo-album-plus'), basename($file)));
                    }
                }
            }
        }
    }
    // Now the audio files
    $audiocount = '0';
    $alb = isset($_POST['wppa-audio-album']) ? $_POST['wppa-audio-album'] : '0';
    if (wppa('ajax') && !$alb) {
        wppa('ajax_import_files_error', __('Unknown album', 'wp-photo-album-plus'));
    } else {
        foreach (array_keys($files) as $idx) {
            $file = $files[$idx];
            if (isset($_POST['file-' . $idx]) || wppa('ajax')) {
                if (wppa('ajax')) {
                    wppa('ajax_import_files', wppa_sanitize_file_name(basename($file)));
                }
                $ext = strtolower(substr(strrchr($file, "."), 1));
                if (in_array($ext, $wppa_supported_audio_extensions)) {
                    if (is_numeric($alb) && $alb != '0') {
                        // Do we have this filename with ext xxx in this album?
                        $filename = wppa_strip_ext(basename($file)) . '.xxx';
                        $id = wppa_file_is_in_album($filename, $alb);
                        // Or maybe the poster is already there
                        foreach ($wppa_supported_photo_extensions as $pext) {
                            if (!$id) {
                                $id = wppa_file_is_in_album(str_replace('xxx', $pext, $filename), $alb);
                            }
                        }
                        // This filename already exists: is the poster. Fix the filename in the photo info
                        if ($id) {
                            $fname = wppa_get_photo_item($id, 'filename');
                            $fname = wppa_strip_ext($fname) . '.xxx';
                            // Fix filename and ext in photo info
                            wppa_update_photo(array('id' => $id, 'filename' => $fname, 'ext' => 'xxx'));
                        }
                        // Add new entry
                        if (!$id) {
                            $id = wppa_create_photo_entry(array('album' => $alb, 'filename' => $filename, 'ext' => 'xxx', 'name' => wppa_strip_ext($filename)));
                            wppa_flush_treecounts($alb);
                        }
                        // Add audio filetype
                        $newpath = wppa_strip_ext(wppa_get_photo_path($id)) . '.' . $ext;
                        copy($file, $newpath);
                        if ($delu) {
                            unlink($file);
                        }
                        if (wppa('ajax')) {
                            wppa('ajax_import_files_done', true);
                        }
                        // Make sure ext is set to xxx after adding audio to an existing poster
                        wppa_update_photo(array('id' => $id, 'ext' => 'xxx'));
                        // Book keeping
                        $audiocount++;
                    } else {
                        wppa_error_message(sprintf(__('Error inserting audio %s, unknown or non existent album.', 'wp-photo-album-plus'), basename($file)));
                    }
                }
            }
        }
    }
    // The csv files. NOT with ajax
    $csvcount = wppa_get_csvcount($files);
    if ($csvcount) {
        $csvcount = '0';
        if (!wppa('ajax')) {
            if (is_array($files)) {
                // Make sure the feature is on
                if (!wppa_switch('custom_fields')) {
                    wppa_update_option('wppa_custom_fields', 'yes');
                    echo '<b>' . __('Custom datafields enabled', 'wp-photo-album-plus') . '</b><br />';
                }
                // Get the captions we already have
                $cust_labels = array();
                for ($i = '0'; $i < '10'; $i++) {
                    $cust_labels[$i] = wppa_opt('custom_caption_' . $i);
                }
                // Process the files
                $photos_processed_csv = '0';
                $photos_skipped_csv = '0';
                $is_db_table = false;
                $tables = array(WPPA_ALBUMS, WPPA_PHOTOS, WPPA_RATING, WPPA_COMMENTS, WPPA_IPTC, WPPA_EXIF, WPPA_INDEX, WPPA_SESSION);
                foreach (array_keys($files) as $idx) {
                    $this_skipped = '0';
                    $file = $files[$idx];
                    if (isset($_POST['file-' . $idx]) || isset($_GET['continue'])) {
                        $ext = strtolower(wppa_get_ext($file));
                        if ($ext == 'csv') {
                            // See if it is a db table
                            foreach (array_keys($tables) as $idx) {
                                $table_name = str_replace($wpdb->prefix, '', $tables[$idx]);
                                if (strpos($file, $table_name . '.csv') !== false) {
                                    $is_db_table = $tables[$idx];
                                    // Only administrators may do this
                                    if (!current_user_can('administrator')) {
                                        wppa_error_messgae(__('Only administrators are allowed to import db table data.', 'wp-photo-album-plus'));
                                        return;
                                    }
                                }
                            }
                            if ($is_db_table) {
                                echo '<b>' . __('Processing db table', 'wp-photo-album-plus') . ' ' . $is_db_table . '</b><br />';
                                wppa_log('dbg', __('Processing db table', 'wp-photo-album-plus') . ' ' . $is_db_table);
                            } else {
                                echo '<b>' . __('Processing', 'wp-photo-album-plus') . ' ' . basename($file) . '</b><br />';
                                wppa_log('dbg', __('Processing', 'wp-photo-album-plus') . ' ' . basename($file));
                            }
                            // Copy the file to a temp file
                            $tempfile = dirname($file) . '/temp.csv';
                            copy($file, $tempfile);
                            // Open file
                            $handle = fopen($tempfile, "rt");
                            if (!$handle) {
                                wppa_error_message(__('Can not open file. Can not continue. (1)', 'wp-photo-album-plus'));
                                return;
                            }
                            $write_handle = fopen($file, "wt");
                            if (!$write_handle) {
                                wppa_error_message(__('Can not open file. Can not continue. (2)', 'wp-photo-album-plus'));
                                return;
                            }
                            // Read header
                            $header = fgets($handle, 4096);
                            if (!$header) {
                                wppa_error_message(__('Can not read header. Can not continue.', 'wp-photo-album-plus'));
                                fclose($handle);
                                return;
                            }
                            fputs($write_handle, $header);
                            echo __('Read header:', 'wp-photo-album-plus') . ' ' . $header . '<br />';
                            // Is it a db table?
                            if ($is_db_table) {
                                // Functions for inserting db table data
                                $entry_functions = array(WPPA_ALBUMS => 'wppa_create_album_entry', WPPA_PHOTOS => 'wppa_create_photo_entry', WPPA_RATING => 'wppa_create_rating_entry', WPPA_COMMENTS => 'wppa_create_comments_entry', WPPA_IPTC => 'wppa_create_iptc_entry', WPPA_EXIF => 'wppa_create_exif_entry', WPPA_INDEX => 'wppa_create_index_entry');
                                // Interprete and verify header. All fields from .csv MUST be in table fields, else fail
                                $csv_fields = str_getcsv($header);
                                $db_fields = $wpdb->get_results("DESCRIBE `" . $is_db_table . "`", ARRAY_A);
                                foreach ($csv_fields as $csv_field) {
                                    $ok = false;
                                    foreach ($db_fields as $db_field) {
                                        if ($db_field['Field'] === $csv_field) {
                                            $ok = true;
                                        }
                                    }
                                    if (!$ok) {
                                        wppa_error_message('Field ' . $csv_field . ' not found in db table ' . $is_db_table . ' description');
                                        wppa_error_message(__('Invalid header. Can not continue.', 'wp-photo-album-plus'));
                                        fclose($handle);
                                        return;
                                    }
                                }
                                // Now process the lines
                                while (!feof($handle)) {
                                    $dataline = fgets($handle, 16 * 4096);
                                    if ($dataline) {
                                        $data_arr = str_getcsv($dataline);
                                        // Embedded newlines?
                                        while (count($csv_fields) > count($data_arr) && !feof($handle)) {
                                            // Assume continue after embedded linebreak
                                            $dataline .= "\n" . fgets($handle, 16 * 4096);
                                            $data_arr = str_getcsv($dataline);
                                        }
                                        reset($data_arr);
                                        $id = trim(current($data_arr));
                                        if (wppa_is_int($id) && $id > '0') {
                                            wppa_dbg_msg('Processing id ' . $id);
                                            $existing_data = $wpdb->get_row("SELECT * FROM `" . $is_db_table . "` WHERE `id` = {$id}", ARRAY_A);
                                            // If entry exists:
                                            // 1. save existing data,
                                            // 2. remove entry,
                                            if ($existing_data) {
                                                $data = $existing_data;
                                                $wpdb->query("DELETE FROM `" . $is_db_table . "` WHERE `id` = {$id}");
                                            }
                                            // Entry does not / no longer exist, add csv data to data array
                                            foreach (array_keys($csv_fields) as $key) {
                                                if (isset($data_arr[$key])) {
                                                    $data[$csv_fields[$key]] = $data_arr[$key];
                                                }
                                            }
                                            // Insert 'new' entry
                                            if (isset($entry_functions[$is_db_table])) {
                                                $iret = call_user_func_array($entry_functions[$is_db_table], array($data));
                                                if ($iret) {
                                                    $photos_processed_csv++;
                                                } else {
                                                    // Write back to original file
                                                    fputs($write_handle, $dataline);
                                                    $photos_skipped_csv++;
                                                    $this_skipped++;
                                                }
                                            } else {
                                                wppa_error_message('Table ' . $is_db_table . 'not supported');
                                                return;
                                            }
                                        } else {
                                            wppa_error_message('Id field not positive numeric: ' . $id);
                                            // Write back to original file
                                            fputs($write_handle, $dataline);
                                            $photos_skipped_csv++;
                                            $this_skipped++;
                                        }
                                    }
                                    // Time up?
                                    if (wppa_is_time_up() && wppa_switch('auto_continue')) {
                                        wppa('continue', 'continue');
                                        // Copy rest of file back to original
                                        while (!feof($handle)) {
                                            $temp = fgets($handle, 16 * 4096);
                                            fputs($write_handle, $temp);
                                        }
                                    }
                                }
                            } else {
                                // Interprete header
                                $captions = str_getcsv($header);
                                if (!is_array($captions) || count($captions) < '2') {
                                    wppa_error_message(__('Invalid header. Can not continue.', 'wp-photo-album-plus'));
                                    fclose($handle);
                                    return;
                                }
                                foreach (array_keys($captions) as $key) {
                                    if ($key == '0') {
                                        if (!in_array(strtolower(trim($captions['0'])), array('name', 'photoname', 'filename'))) {
                                            wppa_error_message(__('Invalid header. First item must be \'name\', \'photoname\' or \'filename\'', 'wp-photo-album-plus'));
                                            fclose($handle);
                                            return;
                                        }
                                    } elseif (!in_array($captions[$key], $cust_labels)) {
                                        if (!in_array('', $cust_labels)) {
                                            wppa_error_message(__('All available custom data fields are in use. There is no space for', 'wp-photo-album-plus') . ' ' . $captions[$key]);
                                            fclose($handle);
                                            return;
                                        }
                                        // Add a new caption
                                        $i = '0';
                                        while ($cust_labels[$i]) {
                                            $i++;
                                        }
                                        $cust_labels[$i] = $captions[$key];
                                        wppa_update_option('wppa_custom_caption_' . $i, $cust_labels[$i]);
                                        wppa_update_option('wppa_custom_visible_' . $i, 'yes');
                                        wppa_log('dbg', sprintf(__('New caption %s added.', 'wp-photo-album-plus'), $cust_labels[$i]));
                                    }
                                }
                                // Find the correlation between caption index and custom data index.
                                $pointers = array();
                                for ($i = '1'; $i < count($captions); $i++) {
                                    for ($j = '0'; $j < '10'; $j++) {
                                        if ($captions[$i] == $cust_labels[$j]) {
                                            $pointers[$j] = $i;
                                        }
                                    }
                                }
                                // Now process the lines
                                while (!feof($handle)) {
                                    $dataline = fgets($handle, 4096);
                                    if ($dataline) {
                                        wppa_log('dbg', __('Read data:', 'wp-photo-album-plus') . ' ' . trim($dataline));
                                        $data_arr = str_getcsv($dataline);
                                        foreach (array_keys($data_arr) as $i) {
                                            if (!seems_utf8($data_arr[$i])) {
                                                $data_arr[$i] = utf8_encode($data_arr[$i]);
                                            }
                                        }
                                        $search = $data_arr[0];
                                        switch (strtolower($captions[0])) {
                                            case 'photoname':
                                                $photos = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `name` = %s", $data_arr[0]), ARRAY_A);
                                                break;
                                            case 'filename':
                                                $photos = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `filename` = %s", $data_arr[0]), ARRAY_A);
                                                break;
                                            case 'name':
                                                $photos = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `name` = %s OR `filename` = %s", $data_arr[0], $data_arr[0]), ARRAY_A);
                                                break;
                                        }
                                        if ($photos) {
                                            foreach ($photos as $photo) {
                                                $cust_data = $photo['custom'] ? unserialize($photo['custom']) : array('', '', '', '', '', '', '', '', '', '');
                                                foreach (array_keys($pointers) as $p) {
                                                    $cust_data[$p] = wppa_sanitize_custom_field($data_arr[$pointers[$p]]);
                                                }
                                                wppa_update_photo(array('id' => $photo['id'], 'custom' => serialize($cust_data)));
                                                $photos_processed_csv++;
                                            }
                                            wppa_log('dbg', 'Processed: ' . $data_arr[0]);
                                        } else {
                                            wppa_log('dbg', 'Could not find: ' . $data_arr[0]);
                                            // Write back to original file
                                            fputs($write_handle, $dataline);
                                            $photos_skipped_csv++;
                                            $this_skipped++;
                                        }
                                        echo '.';
                                    }
                                    // Time up?
                                    if (wppa_is_time_up() && wppa_switch('auto_continue')) {
                                        wppa('continue', 'continue');
                                        // Copy rest of file back to original
                                        while (!feof($handle)) {
                                            $temp = fgets($handle, 4096);
                                            fputs($write_handle, $temp);
                                        }
                                    }
                                }
                            }
                            fclose($handle);
                            fclose($write_handle);
                            $csvcount++;
                            // Remove tempfile
                            unlink($tempfile);
                            // Remove orig file
                            if (!$this_skipped && !wppa_is_time_up()) {
                                unlink($file);
                            }
                        }
                    }
                }
            }
        }
    }
    wppa_ok_message(__('Done processing files.', 'wp-photo-album-plus'));
    if ($pcount == '0' && $acount == '0' && $zcount == '0' && $dircount == '0' && $photocount == '0' && $videocount == '0' && $audiocount == '0' && $csvcount == '0') {
        wppa_warning_message(__('No files to import.', 'wp-photo-album-plus'));
    } else {
        $msg = '';
        if ($zcount) {
            $msg .= $zcount . ' ' . __('Zipfiles extracted.', 'wp-photo-album-plus') . ' ';
        }
        if ($acount) {
            $msg .= $acount . ' ' . __('Albums created.', 'wp-photo-album-plus') . ' ';
        }
        if ($dircount) {
            $msg .= $dircount . ' ' . __('Directory to album imports.', 'wp-photo-album-plus') . ' ';
        }
        if ($photocount) {
            $msg .= ' ' . sprintf(__('With total %s photos.', 'wppa', 'wp-photo-album-plus'), $photocount) . ' ';
        }
        if ($pcount) {
            if (isset($_POST['wppa-update'])) {
                $msg .= $pcount . ' ' . __('Photos updated', 'wp-photo-album-plus');
                if ($totpcount != $pcount) {
                    $msg .= ' ' . sprintf(__('to %s locations', 'wp-photo-album-plus'), $totpcount);
                }
                $msg .= '.';
            } else {
                $msg .= $pcount . ' ' . __('single photos imported.', 'wp-photo-album-plus') . ' ';
            }
        }
        if ($videocount) {
            $msg .= $videocount . ' ' . __('Videos imported.', 'wp-photo-album-plus');
        }
        if ($audiocount) {
            $msg .= $audiocount . ' ' . __('Audios imported.', 'wp-photo-album-plus');
        }
        if ($csvcount) {
            $msg .= $csvcount . ' ' . __('CSVs imported,', 'wp-photo-album-plus') . ' ' . $photos_processed_csv . ' ' . __('items processed.', 'wp-photo-album-plus') . ' ' . $photos_skipped_csv . ' ' . __('items skipped.', 'wp-photo-album-plus');
        }
        wppa_ok_message($msg);
        wppa_set_last_album($album);
    }
}
function wppa_backend_upload_mail($id, $alb, $name)
{
    $owner = wppa_get_user();
    if ($owner == 'admin') {
        return;
    }
    // Admin does not send mails to himself
    if (wppa_switch('upload_backend_notify')) {
        $to = get_bloginfo('admin_email');
        $subj = sprintf(__('New photo uploaded: %s', 'wp-photo-album-plus'), wppa_sanitize_file_name($name));
        $cont['0'] = sprintf(__('User %1$s uploaded photo %2$s into album %3$s', 'wp-photo-album-plus'), $owner, $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);
    }
}
示例#8
0
function wppa_get_session_id()
{
    global $wppa_api_version;
    $id = md5($_SERVER['REMOTE_ADDR'] . wppa_get_user() . $_SERVER["HTTP_USER_AGENT"] . $wppa_api_version);
    return $id;
}
示例#9
0
function wppa_log($type, $msg)
{
    // Log debug messages only if WP_DEBUG is defined as true
    if ($type == 'dbg') {
        if (!defined('WP_DEBUG') || !WP_DEBUG) {
            return;
        }
    }
    @wppa_mktree(WPPA_CONTENT_PATH . '/wppa-depot/admin');
    // Just in case...
    $filename = WPPA_CONTENT_PATH . '/wppa-depot/admin/error.log';
    if (is_file($filename)) {
        $filesize = filesize($filename);
        if ($filesize > 102400) {
            // File > 100kB
            $file = fopen($filename, 'rb');
            if ($file) {
                $buffer = @fread($file, $filesize);
                $buffer = substr($buffer, $filesize - 90 * 1024);
                // Take ending 90 kB
                fclose($file);
                $file = fopen($filename, 'wb');
                @fwrite($file, $buffer);
                @fclose($file);
            }
        }
    }
    if (!($file = fopen($filename, 'ab'))) {
        return;
    }
    // Unable to open log file
    @fwrite($file, $type . ': on:' . wppa_local_date(get_option('date_format', "F j, Y,") . ' ' . get_option('time_format', "g:i a"), time()) . ': ' . wppa_get_user() . ' ' . $msg . "\n");
    // To prevent recursive error reporting, do not use wppa_switch!!!
    //if ( wppa_switch( 'wppa_debug_trace_on' ) ) {
    if (get_option('wppa_debug_trace_on') == 'yes') {
        ob_start();
        debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
        $trace = ob_get_contents();
        ob_end_clean();
        @fwrite($file, $trace . "\n");
    }
    @fclose($file);
}
示例#10
0
    /** @see WP_Widget::widget */
    function widget($args, $instance)
    {
        global $wpdb;
        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();
        wppa('in_widget', 'upldr');
        wppa_bump_mocc();
        extract($args);
        $instance = wp_parse_args((array) $instance, array('title' => '', 'sortby' => 'name', 'ignore' => 'admin', 'parent' => ''));
        $widget_title = apply_filters('widget_title', $instance['title']);
        $page = in_array('album', wppa('links_no_page')) ? '' : wppa_get_the_landing_page('wppa_upldr_widget_linkpage', __('User uploaded photos', 'wp-photo-album-plus'));
        $ignorelist = explode(',', $instance['ignore']);
        $upldrcache = wppa_get_upldr_cache();
        $needupdate = false;
        $users = wppa_get_users();
        $workarr = array();
        $selalbs = str_replace('.', ',', wppa_expand_enum(wppa_alb_to_enum_children(wppa_expand_enum($instance['parent']))));
        // Make the data we need
        if ($users) {
            foreach ($users as $user) {
                if (!in_array($user['user_login'], $ignorelist)) {
                    $me = wppa_get_user();
                    if ($user['user_login'] != $me && isset($upldrcache[$this->get_widget_id()][$user['user_login']]['c'])) {
                        $photo_count = $upldrcache[$this->get_widget_id()][$user['user_login']]['c'];
                    } else {
                        if ($instance['parent']) {
                            $query = $wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `owner` = %s AND `album` IN (" . $selalbs . ") AND ( ( `status` <> 'pending' AND `status` <> 'scheduled' ) OR `owner` = %s )", $user['user_login'], $me);
                            //);
                        } else {
                            $query = $wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `owner` = %s AND ( ( `status` <> 'pending' AND `status` <> 'scheduled' ) OR `owner` = %s )", $user['user_login'], $me);
                            //);
                        }
                        $photo_count = $wpdb->get_var($query);
                        if ($user['user_login'] != $me) {
                            $upldrcache[$this->get_widget_id()][$user['user_login']]['c'] = $photo_count;
                            $needupdate = true;
                        }
                    }
                    if ($photo_count) {
                        if ($user['user_login'] != $me && isset($upldrcache[$this->get_widget_id()][$user['user_login']]['d'])) {
                            $last_dtm = $upldrcache[$this->get_widget_id()][$user['user_login']]['d'];
                        } else {
                            if ($instance['parent']) {
                                $last_dtm = $wpdb->get_var($wpdb->prepare("SELECT `timestamp` FROM `" . WPPA_PHOTOS . "` WHERE `owner` = %s AND `album` IN (" . $selalbs . ") AND ( ( `status` <> 'pending' AND `status` <> 'scheduled' ) OR `owner` = %s ) ORDER BY `timestamp` DESC LIMIT 1", $user['user_login'], $me));
                            } else {
                                $last_dtm = $wpdb->get_var($wpdb->prepare("SELECT `timestamp` FROM `" . WPPA_PHOTOS . "` WHERE `owner` = %s AND ( ( `status` <> 'pending' AND `status` <> 'scheduled' ) OR `owner` = %s ) ORDER BY `timestamp` DESC LIMIT 1", $user['user_login'], $me));
                            }
                        }
                        if ($user['user_login'] != $me) {
                            $upldrcache[$this->get_widget_id()][$user['user_login']]['d'] = $last_dtm;
                            $needupdate = true;
                        }
                        $workarr[] = array('login' => $user['user_login'], 'name' => $user['display_name'], 'count' => $photo_count, 'date' => $last_dtm);
                    }
                }
            }
        } else {
            $widget_content = __('There are too many registered users in the system for this widget', 'wp-photo-album-plus');
            echo "\n" . $before_widget;
            if (!empty($widget_title)) {
                echo $before_title . $widget_title . $after_title;
            }
            echo $widget_content . $after_widget;
            return;
        }
        if ($needupdate) {
            update_option('wppa_upldr_cache', $upldrcache);
        }
        // Bring me to top
        $myline = false;
        if (is_user_logged_in()) {
            $me = wppa_get_user();
            foreach (array_keys($workarr) as $key) {
                $user = $workarr[$key];
                if ($user['login'] == $me) {
                    $myline = $workarr[$key];
                    unset($workarr[$key]);
                }
            }
        }
        // Sort workarray
        $ord = $instance['sortby'] == 'name' ? SORT_ASC : SORT_DESC;
        $workarr = wppa_array_sort($workarr, $instance['sortby'], $ord);
        // Create widget content
        $widget_content = "\n" . '<!-- WPPA+ Upldr Widget start -->';
        $widget_content .= '<div class="wppa-upldr" style="max-height:180px; overflow:auto"><table><tbody>';
        $albs = $instance['parent'] ? wppa_alb_to_enum_children(wppa_expand_enum($instance['parent'])) : '';
        $a = $albs ? wppa_trim_wppa_('&amp;wppa-album=' . $albs) : '';
        if ($myline) {
            $user = $myline;
            $widget_content .= '<tr class="wppa-user" >
									<td style="padding: 0 3px;" ><a href="' . wppa_get_upldr_link($user['login']) . $a . '" title="' . __('Photos uploaded by', 'wp-photo-album-plus') . ' ' . $user['name'] . '" ><b>' . $user['name'] . '</b></a></td>
									<td style="padding: 0 3px;" ><b>' . $user['count'] . '</b></td>
									<td style="padding: 0 3px;" ><b>' . wppa_get_time_since($user['date']) . '</b></td>
								</tr>';
        }
        foreach ($workarr as $user) {
            $widget_content .= '<tr class="wppa-user" >
									<td style="padding: 0 3px;" ><a href="' . wppa_get_upldr_link($user['login']) . $a . '" title="' . __('Photos uploaded by', 'wp-photo-album-plus') . ' ' . $user['name'] . '" >' . $user['name'] . '</a></td>
									<td style="padding: 0 3px;" >' . $user['count'] . '</td>
									<td style="padding: 0 3px;" >' . wppa_get_time_since($user['date']) . '</td>
								</tr>';
        }
        $widget_content .= '</tbody></table></div>';
        $widget_content .= '<div style="clear:both"></div>';
        $widget_content .= "\n" . '<!-- WPPA+ Upldr Widget end -->';
        // Output
        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_maintenance_button($slug)
{
    $label = __('Start!', 'wp-photo-album-plus');
    $me = wppa_get_user();
    $user = get_option($slug . '_user', $me);
    if ($user && $user != $me) {
        $label = __('Locked!', 'wp-photo-album-plus');
        $locked = true;
    } else {
        $locked = false;
    }
    $result = '<input id="' . $slug . '_button" type="button" class="button-secundary" style="float:left; border-radius:3px; font-size: 11px; height: 18px; margin: 0 4px; padding: 0px;" value="' . $label . '"';
    if (!$locked) {
        $result .= ' onclick="if ( jQuery(\'#' . $slug . '_status\').html() != \'\' || confirm(\'Are you sure ?\') ) wppaMaintenanceProc(\'' . $slug . '\', false);" />';
    } else {
        $result .= ' onclick="alert(\'Is currently being executed by ' . $user . '.\')" />';
    }
    $result .= '<input id="' . $slug . '_continue" type="hidden" value="no" />';
    return $result;
}
function wppa_get_coverphoto_ids($alb, $count)
{
    global $wpdb;
    if (!$alb) {
        return false;
    }
    // no album, no coverphoto
    // Find cover photo id
    $id = wppa_get_album_item($alb, 'main_photo');
    // main_photo is a positive integer ( photo id )?
    if ($id > '0') {
        // 1 coverphoto explicitly given
        $photo = wppa_cache_photo($id);
        if (!$photo) {
            // Photo gone, set id to 0
            $id = '0';
        } elseif ($photo['album'] != $alb) {
            // Photo moved to other album, set id to 0
            $id = '0';
        } else {
            $temp['0'] = $photo;
            // Found!
        }
    }
    // main_photo is 0? Random
    if ('0' == $id) {
        if (current_user_can('wppa_moderate')) {
            $temp = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s ORDER BY RAND( " . wppa_get_randseed('page') . " ) LIMIT %d", $alb, $count), ARRAY_A);
        } else {
            $temp = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s AND ( ( `status` <> 'pending' AND `status` <> 'scheduled' ) OR `owner` = %s ) ORDER BY RAND( " . wppa_get_randseed('page') . " ) LIMIT %d", $alb, wppa_get_user(), $count), ARRAY_A);
        }
    }
    // main_photo is -2? Last upload
    if ('-2' == $id) {
        if (current_user_can('wppa_moderate')) {
            $temp = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s ORDER BY `timestamp` DESC LIMIT %d", $alb, $count), ARRAY_A);
        } else {
            $temp = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s AND ( ( `status` <> 'pending' AND `status` <> 'scheduled' ) OR `owner` = %s ) ORDER BY `timestamp` DESC LIMIT %d", $alb, wppa_get_user(), $count), ARRAY_A);
        }
    }
    // main_phtot is -1? Random featured
    if ('-1' == $id) {
        $temp = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s AND `status` = 'featured' ORDER BY RAND( " . wppa_get_randseed('page') . " ) LIMIT %d", $alb, $count), ARRAY_A);
    }
    // Random from children
    if ('-3' == $id) {
        $allalb = wppa_expand_enum(wppa_alb_to_enum_children($alb));
        $temp = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` " . "WHERE `album` IN ( " . str_replace('.', ',', $allalb) . " ) " . "AND ( ( `status` <> 'pending' AND `status` <> 'scheduled' ) OR `owner` = %s ) " . "ORDER BY RAND( " . wppa_get_randseed('page') . " ) LIMIT %d", wppa_get_user(), $count), ARRAY_A);
    }
    // Most recent from children
    if ('-4' == $id) {
        $allalb = wppa_expand_enum(wppa_alb_to_enum_children($alb));
        $temp = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` " . "WHERE `album` IN ( " . str_replace('.', ',', $allalb) . " ) " . "AND ( ( `status` <> 'pending' AND `status` <> 'scheduled' ) OR `owner` = %s ) " . "ORDER BY `timestamp` DESC LIMIT %d", wppa_get_user(), $count), ARRAY_A);
    }
    // Report query
    wppa_dbg_q('Q-gcovp');
    // Add to 2nd level cache
    wppa_cache_photo('add', $temp);
    // Extract the ids only
    $ids = array();
    if (is_array($temp)) {
        foreach ($temp as $item) {
            $ids[] = $item['id'];
        }
    }
    return $ids;
}
function wppa_create_album_entry($args)
{
    global $wpdb;
    $args = wp_parse_args((array) $args, array('id' => '0', 'name' => __('New Album', 'wp-photo-album-plus'), 'description' => '', 'a_order' => '0', 'main_photo' => wppa_opt('main_photo'), 'a_parent' => wppa_opt('default_parent'), 'p_order_by' => '0', 'cover_linktype' => wppa_opt('default_album_linktype'), 'cover_linkpage' => '0', 'owner' => wppa_get_user(), 'timestamp' => time(), 'modified' => time(), 'upload_limit' => wppa_opt('upload_limit_count') . '/' . wppa_opt('upload_limit_time'), 'alt_thumbsize' => '0', 'default_tags' => '', 'cover_type' => '', 'suba_order_by' => '', 'views' => '0', 'cats' => '', 'scheduledtm' => ''));
    if (!wppa_is_id_free(WPPA_ALBUMS, $args['id'])) {
        $args['id'] = wppa_nextkey(WPPA_ALBUMS);
    }
    $query = $wpdb->prepare("INSERT INTO `" . WPPA_ALBUMS . "` ( \t`id`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`name`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`description`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`a_order`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`main_photo`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`a_parent`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`p_order_by`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`cover_linktype`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`cover_linkpage`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`owner`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`timestamp`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`modified`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`upload_limit`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`alt_thumbsize`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`default_tags`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`cover_type`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`suba_order_by`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`views`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`cats`,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t`scheduledtm`\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tVALUES ( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s ,%s, %s, %s, %s, %s, %s, %s, %s, %s, %s )", $args['id'], trim($args['name']), trim($args['description']), $args['a_order'], $args['main_photo'], $args['a_parent'], $args['p_order_by'], $args['cover_linktype'], $args['cover_linkpage'], $args['owner'], $args['timestamp'], $args['modified'], $args['upload_limit'], $args['alt_thumbsize'], $args['default_tags'], $args['cover_type'], $args['suba_order_by'], $args['views'], $args['cats'], $args['scheduledtm']);
    $iret = $wpdb->query($query);
    if ($iret) {
        return $args['id'];
    } else {
        return false;
    }
}
 /** @see WP_Widget::widget */
 function widget($args, $instance)
 {
     global $wpdb;
     global $wppa_opt;
     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);
     wppa('in_widget', 'featen');
     $instance = wp_parse_args((array) $instance, array('title' => '', 'album' => ''));
     $widget_title = apply_filters('widget_title', $instance['title']);
     $page = in_array(wppa_opt('featen_widget_linktype'), wppa('links_no_page')) ? '' : wppa_get_the_landing_page('featen_widget_linkpage', __('Featured photos', 'wp-photo-album-plus'));
     $max = wppa_opt('featen_count');
     $album = $instance['album'];
     $generic = $album == '-2';
     //		wppa( 'start_album', $album );
     //		if ( $generic ) {
     //			$album = '0';
     //			$max += '1000';
     //		}
     switch ($album) {
         // owner/public
         case '-3':
             $temp = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `status` = 'featured' ORDER BY RAND(" . wppa_get_randseed() . ") DESC", ARRAY_A);
             if ($temp) {
                 $c = '0';
                 $thumbs = array();
                 while ($c < $max && $c < count($temp)) {
                     $alb = wppa_get_photo_item($temp[$c]['id'], 'album');
                     $own = wppa_get_album_item($alb, 'owner');
                     if ($own == '---public---' || $own == wppa_get_user()) {
                         $thumbs[] = $temp[$c];
                     }
                     $c++;
                 }
             } else {
                 $thumbs = false;
             }
             break;
             // generic
         // generic
         case '-2':
             $temp = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `status` = 'featured' ORDER BY RAND(" . wppa_get_randseed() . ") DESC", ARRAY_A);
             if ($temp) {
                 $c = '0';
                 $thumbs = array();
                 while ($c < $max && $c < count($temp)) {
                     $alb = wppa_get_photo_item($temp[$c]['id'], 'album');
                     if (!wppa_is_separate($alb)) {
                         $thumbs[] = $temp[$c];
                     }
                     $c++;
                 }
             } else {
                 $thumbs = false;
             }
             break;
             // all
         // all
         case '0':
             $thumbs = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `status` = 'featured' ORDER BY RAND(" . wppa_get_randseed() . ") DESC LIMIT " . $max, ARRAY_A);
             break;
             // album spec
         // album spec
         default:
             $thumbs = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `status`= 'featured' AND `album` = %s ORDER BY RAND(" . wppa_get_randseed() . ") DESC LIMIT " . $max, $album), ARRAY_A);
     }
     $widget_content = "\n" . '<!-- WPPA+ FeaTen Widget start -->';
     $maxw = wppa_opt('featen_size');
     $maxh = $maxw;
     $lineheight = wppa_opt('fontsize_widget_thumb') * 1.5;
     $maxh += $lineheight;
     $count = '0';
     if ($thumbs) {
         foreach ($thumbs as $image) {
             $thumb = $image;
             if ($generic && wppa_is_separate($thumb['album'])) {
                 continue;
             }
             // Make the HTML for current picture
             $widget_content .= "\n" . '<div class="wppa-widget" style="width:' . $maxw . 'px; height:' . $maxh . 'px; margin:4px; display:inline; text-align:center; float:left;">';
             if ($image) {
                 $no_album = !$album;
                 if ($no_album) {
                     $tit = __('View the featured photos', 'wp-photo-album-plus');
                 } else {
                     $tit = esc_attr(__(stripslashes($image['description'])));
                 }
                 $link = wppa_get_imglnk_a('featen', $image['id'], '', $tit, '', $no_album, $album);
                 $file = wppa_get_thumb_path($image['id']);
                 $imgstyle_a = wppa_get_imgstyle_a($image['id'], $file, $maxw, 'center', 'ttthumb');
                 $imgstyle = $imgstyle_a['style'];
                 $width = $imgstyle_a['width'];
                 $height = $imgstyle_a['height'];
                 $cursor = $imgstyle_a['cursor'];
                 $imgurl = wppa_get_thumb_url($image['id'], '', $width, $height);
                 $imgevents = wppa_get_imgevents('thumb', $image['id'], true);
                 if ($link) {
                     $title = esc_attr(stripslashes($link['title']));
                 } else {
                     $title = '';
                 }
                 //				$album = '0';
                 $display = 'thumbs';
                 $widget_content .= wppa_get_the_widget_thumb('featen', $image, $album, $display, $link, $title, $imgurl, $imgstyle_a, $imgevents);
             } else {
                 // No image
                 $widget_content .= __('Photo not found', 'wp-photo-album-plus');
             }
             $widget_content .= "\n" . '</div>';
             $count++;
             if ($count == wppa_opt('featen_count')) {
                 break;
             }
         }
     } else {
         $widget_content .= __('There are no featured photos (yet)', 'wp-photo-album-plus');
     }
     $widget_content .= '<div style="clear:both"></div>';
     $widget_content .= "\n" . '<!-- WPPA+ FeaTen 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_may_user_fe_delete($id)
{
    // Superuser?
    if (wppa_is_user_superuser()) {
        return true;
    }
    // Can edit albums?
    if (current_user_can('wppa_admin')) {
        return true;
    }
    // If owner and owners may delete?
    if (wppa_get_user() == wppa_get_photo_owner($id)) {
        if (wppa_switch('upload_delete')) {
            return true;
        }
    }
    return false;
}
function wppa_get_rating_range_html($id = 0, $is_lightbox = false, $class = '')
{
    global $wpdb;
    // Not on a feed
    if (is_feed()) {
        return '';
    }
    // On lightbox: only if in visibility settings set.
    if ($is_lightbox) {
        if (!wppa_switch('ovl_rating')) {
            return '';
        }
    }
    if ($id) {
        $wait_text = wppa_get_rating_wait_text($id, wppa_get_user());
        if ($wait_text) {
            return '<span class="' . $class . '" style="color:red" >' . $wait_text . '</span>';
        }
        if (wppa_get_photo_item($id, 'owner') == wppa_get_user() && !wppa_switch('allow_owner_votes')) {
            return '<span class="' . $class . '" >' . __('Sorry, you can not rate your own photos', 'wp-photo-album-plus') . '</span>';
        }
        $mylast = $wpdb->get_row($wpdb->prepare('SELECT * FROM `' . WPPA_RATING . '` WHERE `photo` = %s AND `user` = %s ORDER BY `id` DESC LIMIT 1', $id, wppa_get_user()), ARRAY_A);
        if ($mylast && !wppa_switch('rating_change') && !wppa_switch('rating_multi')) {
            return '<span class="' . $class . '" >' . __('Sorry, you can rate a photo only once', 'wp-photo-album-plus') . '</span>';
        }
    }
    // Mphoto, xphoto and lightbox use a different js function than slideshow.
    // In slideshow the id is not known and retrieved from _wppaCurIdx[mocc].
    // There is also a difference in css.
    $idorlb = $id || $is_lightbox;
    // If on xphoto, reload after
    $reload = wppa('is_xphoto') ? 'true' : 'false';
    $result = '';
    $fs = wppa_opt('fontsize_nav');
    if ($fs) {
        $fs += 3;
    } else {
        $fs = '15';
    }
    // iconsize = fontsize+3, Default to 15
    $dh = $fs + '6';
    $size = 'font-size:' . $fs . 'px;';
    // Open the rating box
    $result .= '<div' . ' id="wppa-rating-' . wppa('mocc') . '"' . ' class="' . ($idorlb ? $class : 'wppa-box wppa-nav wppa-nav-text') . '"' . ' style="' . ($idorlb ? 'padding:4px;' : __wcs('wppa-box') . __wcs('wppa-nav') . __wcs('wppa-nav-text')) . $size . ' text-align:center;"' . '> ';
    // Graphic display ?
    if (wppa_opt('rating_display_type') == 'graphic') {
        if (wppa_opt('rating_max') == '5') {
            $r['1'] = __('very low', 'wp-photo-album-plus');
            $r['2'] = __('low', 'wp-photo-album-plus');
            $r['3'] = __('average', 'wp-photo-album-plus');
            $r['4'] = __('high', 'wp-photo-album-plus');
            $r['5'] = __('very high', 'wp-photo-album-plus');
        } else {
            for ($i = '1'; $i <= '10'; $i++) {
                $r[$i] = $i;
            }
        }
        $style = 'height:' . $fs . 'px; margin:0 0 -3px 0; padding:0; box-shadow:none; display:inline;background-color:transparent;';
        $icon = 'star.ico';
        // Display avg rating
        if (wppa_switch('show_avg_rating')) {
            if ($id) {
                $avgrat = wppa_get_rating_by_id($id, 'nolabel');
                $opac = array();
                $i = '1';
                while ($i <= wppa_opt('rating_max')) {
                    if ($avgrat >= $i) {
                        $opac[$i] = 'opacity:1;';
                    } else {
                        if ($avgrat <= $i - '1') {
                            $opac[$i] = 'opacity:0.2;';
                        } else {
                            $opac[$i] = 'opacity:' . (0.2 + 0.8 * ($avgrat - $i + '1'));
                        }
                    }
                    $i++;
                }
            }
            $result .= '<span' . ' id="wppa-avg-rat-' . wppa('mocc') . '"' . ' class="wppa-rating-label"' . ' >' . __('Average&nbsp;rating', 'wp-photo-album-plus') . '</span>&nbsp;';
            $i = '1';
            while ($i <= wppa_opt('rating_max')) {
                $result .= '<img' . ' id="wppa-avg-' . wppa('mocc') . '-' . $i . '"' . ' class="wppa-avg-' . wppa('mocc') . '-' . $i . ' wppa-avg-' . wppa('mocc') . ' no-shadow"' . ' style="' . $style . ($id ? $opac[$i] : '') . '"' . ' src="' . wppa_get_imgdir() . $icon . '"' . ' alt=" ' . $i . '"' . ' title="' . __('Average&nbsp;rating', 'wp-photo-album-plus') . ': ' . $r[$i] . '"' . ' />';
                $i++;
            }
        }
        $result .= '<img' . ' id="wppa-filler-' . wppa('mocc') . '"' . ' src="' . wppa_get_imgdir() . 'transp.png"' . ' alt="f"' . ' style="width:' . wppa_opt('ratspacing') . 'px; height:15px; box-shadow:none; padding:0; margin:0; border:none;"' . ' />';
        // Display my rating
        // Logged in or don't care
        if (!wppa_switch('rating_login') || is_user_logged_in()) {
            // Show dislike icon?
            $pad = round((wppa_opt('ratspacing') - $fs) / 2);
            if ($pad < 5) {
                $pad = '5';
            }
            if (wppa_opt('dislike_mail_every')) {
                $confirm = esc_attr(str_replace('"', "'", __('Are you sure you want to mark this image as inappropriate?', 'wp-photo-album-plus')));
                $result .= '<img' . ' id="wppa-dislike-' . wppa('mocc') . '"' . ' title="' . __('Click this if you do NOT like this image!', 'wp-photo-album-plus') . '"' . ' src="' . wppa_get_imgdir() . 'thumbdown.png"' . ' alt="d"' . ' style="height:' . $fs . 'px; margin:0 0 -3px 0; padding:0 ' . $pad . 'px; box-shadow:none; display:inline;"' . ' class="no-shadow"' . ' onmouseover="jQuery(this).stop().fadeTo(100, 1.0)"' . ' onmouseout="jQuery(this).stop().fadeTo(100, wppaStarOpacity)"' . ' onclick="';
                if ($idorlb) {
                    $result .= 'if (confirm(\'' . $confirm . '\')) { wppaOvlRateIt( \'' . wppa_encrypt_photo($id) . '\', -1, ' . ($id ? wppa('mocc') : '0') . ' ); }';
                } else {
                    $result .= 'if (confirm(\'' . $confirm . '\')) { wppaRateIt( ' . wppa('mocc') . ', -1); }';
                }
                $result .= '"' . ' />';
                if ($idorlb) {
                    $mylast = wppa_get_my_last_vote($id);
                    if ($mylast == '-1') {
                        $result .= '<script type="text/javascript" >jQuery(\'#wppa-dislike-' . wppa('mocc') . '\').css(\'display\'. \'none\');</script>';
                    } else {
                        $result .= '<script type="text/javascript" >jQuery(\'#wppa-dislike-' . wppa('mocc') . '\').fadeTo(100,' . wppa_opt('star_opacity') / 100 . ');</script>';
                    }
                }
                if (wppa_switch('dislike_show_count')) {
                    $result .= '<span' . ' id="wppa-discount-' . wppa('mocc') . '"' . ' style="cursor:default"' . ' title="' . __('Number of people who marked this photo as inappropriate', 'wp-photo-album-plus') . '"' . ' >' . '</span>';
                }
            }
            // Text left if no avg rating
            if (!wppa_switch('show_avg_rating')) {
                $result .= __('My&nbsp;rating', 'wp-photo-album-plus') . ':&nbsp;';
            }
            // Display the my rating stars
            if ($id) {
                $myavgrat = wppa_get_my_rating_by_id($id, 'nolabel');
                $opac = array();
                $i = '1';
                while ($i <= wppa_opt('rating_max')) {
                    if ($myavgrat >= $i) {
                        $opac[$i] = 'opacity:1;';
                    } else {
                        if ($myavgrat <= $i - '1') {
                            $opac[$i] = 'opacity:0.2;';
                        } else {
                            $opac[$i] = 'opacity:' . (0.2 + 0.8 * ($myavgrat - $i + '1'));
                        }
                    }
                    $i++;
                }
            }
            $i = '1';
            while ($i <= wppa_opt('rating_max')) {
                $result .= '<img' . ' id="wppa-rate-' . wppa('mocc') . '-' . $i . '"' . ' class="wppa-rate-' . wppa('mocc') . '-' . $i . ' wppa-rate-' . wppa('mocc') . ' no-shadow"' . ' style="' . $style . ($id ? $opac[$i] : '') . '"' . ' src="' . wppa_get_imgdir() . $icon . '"' . ' alt="' . $i . '"' . ' title="' . __('My&nbsp;rating', 'wp-photo-album-plus') . ': ' . $r[$i] . '"' . ($id ? ' onmouseover="wppaOvlFollowMe(' . wppa('mocc') . ', ' . $i . ', ' . $myavgrat . ' )"' . ' onmouseout="wppaOvlLeaveMe(' . wppa('mocc') . ', ' . $i . ', ' . $myavgrat . ' )"' : ' onmouseover="wppaFollowMe(' . wppa('mocc') . ', ' . $i . ')"' . ' onmouseout="wppaLeaveMe(' . wppa('mocc') . ', ' . $i . ')"') . ($idorlb ? ' onclick="wppaOvlRateIt(\'' . wppa_encrypt_photo($id) . '\', ' . $i . ', ' . ($id ? wppa('mocc') : '0') . ', ' . $reload . ' )"' : ' onclick="wppaRateIt(' . wppa('mocc') . ', ' . $i . ')"') . ' />';
                $i++;
            }
            // Text right if avg rating diaplayed
            if (wppa_switch('show_avg_rating')) {
                $result .= '&nbsp;' . '<span' . ' id="wppa-my-rat-' . wppa('mocc') . '" ' . ' class="wppa-rating-label"' . '>' . __('My&nbsp;rating', 'wp-photo-album-plus') . '</span>';
            }
        } else {
            if (wppa_switch('login_links')) {
                $result .= sprintf(__('You must <a href="%s">login</a> to vote', 'wp-photo-album-plus'), site_url('wp-login.php', 'login'));
            } else {
                $result .= __('You must login to vote', 'wp-photo-album-plus');
            }
        }
    } elseif (wppa_opt('rating_display_type') == 'numeric') {
        // Display avg rating
        if (wppa_switch('show_avg_rating')) {
            $result .= __('Average&nbsp;rating', 'wp-photo-album-plus') . ':&nbsp;' . '<span id="wppa-numrate-avg-' . wppa('mocc') . '"></span>' . ' &bull;';
        }
        // Display my rating
        // Logged in or don't care
        if (!wppa_switch('rating_login') || is_user_logged_in()) {
            // Show dislike icon?
            $pad = round((wppa_opt('ratspacing') - $fs) / 2);
            if ($pad < 5) {
                $pad = '5';
            }
            if (wppa_opt('dislike_mail_every')) {
                $result .= '<div' . ' id="wppa-dislike-imgdiv-' . wppa('mocc') . '"' . ' style="display:inline"' . ' >';
                $confirm = esc_attr(str_replace('"', "'", __('Are you sure you want to mark this image as inappropriate?', 'wp-photo-album-plus')));
                $result .= '<img' . ' id="wppa-dislike-' . wppa('mocc') . '"' . ' title="' . __('Click this if you do NOT like this image!', 'wp-photo-album-plus') . '"' . ' src="' . wppa_get_imgdir() . 'thumbdown.png"' . ' alt="d"' . ' style="height:' . $fs . 'px; margin:0 0 -3px 0; padding:0 ' . $pad . 'px; box-shadow:none; display:inline;"' . ' class="no-shadow"' . ' onmouseover="jQuery(this).stop().fadeTo(100, 1.0)"' . ' onmouseout="jQuery(this).stop().fadeTo(100, wppaStarOpacity)"' . ' onclick="';
                if ($idorlb) {
                    $result .= 'if (confirm(\'' . $confirm . '\')) { wppaOvlRateIt( \'' . wppa_encrypt_photo($id) . '\', -1, ' . ($id ? wppa('mocc') : '0') . ' ); }';
                } else {
                    $result .= 'if (confirm(\'' . $confirm . '\')) { wppaRateIt( ' . wppa('mocc') . ', -1); }';
                }
                $result .= '"' . ' />';
                $result .= '</div>';
                if (wppa_switch('dislike_show_count')) {
                    $result .= '<span' . ' id="wppa-discount-' . wppa('mocc') . '"' . ' style="cursor:default"' . ' title="' . __('Number of people who marked this photo as inappropriate', 'wp-photo-album-plus') . '"' . ' >' . '</span>';
                }
            }
            $result .= ' ' . __('My rating:', 'wp-photo-album-plus');
            $result .= '<span id="wppa-numrate-mine-' . wppa('mocc') . '" ></span>';
        } else {
            if (wppa_switch('login_links')) {
                $result .= sprintf(__('You must <a href="%s">login</a> to vote', 'wp-photo-album-plus'), site_url('wp-login.php', 'login'));
            } else {
                $result .= __('You must login to vote', 'wp-photo-album-plus');
            }
        }
    }
    // Close rating box
    $result .= '</div>';
    return $result;
}
function wppa_album_select_a($args)
{
    global $wpdb;
    $args = wp_parse_args($args, array('exclude' => '', 'selected' => '', 'disabled' => '', 'addpleaseselect' => false, 'addnone' => false, 'addall' => false, 'addgeneric' => false, 'addblank' => false, 'addselected' => false, 'addseparate' => false, 'addselbox' => false, 'addowner' => false, 'disableancestors' => false, 'checkaccess' => false, 'checkowner' => false, 'checkupload' => false, 'addmultiple' => false, 'addnumbers' => false, 'path' => false, 'root' => false, 'content' => false, 'sort' => true, 'checkarray' => false, 'array' => array(), 'optionclass' => ''));
    // Provide default selection if no selected given
    if ($args['selected'] === '') {
        $args['selected'] = wppa_get_last_album();
    }
    // See if selection is valid
    if ($args['selected'] == $args['exclude'] || $args['checkupload'] && !wppa_allow_uploads($args['selected']) || $args['disableancestors'] && wppa_is_ancestor($args['exclude'], $args['selected'])) {
        $args['selected'] = '0';
    }
    // Get roughly the albums that might be in the selection
    if ($args['checkarray'] && !empty($args['array'])) {
        $albums = $wpdb->get_results("SELECT `id`, `name` " . "FROM `" . WPPA_ALBUMS . "` " . "WHERE `id` IN (" . implode(',', $args['array']) . ") " . ($args['checkowner'] && wppa_switch('upload_owner_only') && !wppa_user_is('administrator') ? "AND `owner` IN ( '--- public ---', '" . wppa_get_user() . "' ) " : "") . wppa_get_album_order($args['root']), ARRAY_A);
    } else {
        $albums = $wpdb->get_results("SELECT `id`, `name` " . "FROM `" . WPPA_ALBUMS . "` " . ($args['checkowner'] && wppa_switch('upload_owner_only') && !wppa_user_is('administrator') ? "WHERE `owner` IN ( '--- public ---', '" . wppa_get_user() . "' ) " : "") . wppa_get_album_order($args['root']), ARRAY_A);
    }
    /* Can not add to cache because only "SELECT * " can be added
    	// Add to secondary cache
    	if ( $albums ) {
    		wppa_cache_album( 'add', $albums );
    	}
    	*/
    if ($albums) {
        // Filter for root
        if ($args['root']) {
            $root = $args['root'];
            switch ($root) {
                // case '0': all, will be skipped as it returns false in 'if ( $args['root'] )'
                case '-2':
                    // Generic only
                    foreach (array_keys($albums) as $albidx) {
                        if (wppa_is_separate($albums[$albidx]['id'])) {
                            unset($albums[$albidx]);
                        }
                    }
                    break;
                case '-1':
                    // Separate only
                    foreach (array_keys($albums) as $albidx) {
                        if (!wppa_is_separate($albums[$albidx]['id'])) {
                            unset($albums[$albidx]);
                        }
                    }
                    break;
                default:
                    foreach (array_keys($albums) as $albidx) {
                        if (!wppa_is_ancestor($root, $albums[$albidx]['id'])) {
                            unset($albums[$albidx]);
                        }
                    }
                    break;
            }
        }
        // Filter for must have content
        if ($args['content']) {
            foreach (array_keys($albums) as $albidx) {
                if (wppa_get_photo_count($albums[$albidx]['id']) <= wppa_get_mincount()) {
                    unset($albums[$albidx]);
                }
            }
        }
        // Add paths
        if ($args['path']) {
            $albums = wppa_add_paths($albums);
        } else {
            foreach (array_keys($albums) as $index) {
                $albums[$index]['name'] = __(stripslashes($albums[$index]['name']));
            }
        }
        // Sort
        if ($args['sort']) {
            $albums = wppa_array_sort($albums, 'name');
        }
    }
    // Output
    $result = '';
    $selected = $args['selected'] == '0' ? ' selected="selected"' : '';
    if ($args['addpleaseselect']) {
        $result .= '<option value="0" disabled="disabled" ' . $selected . ' >' . __('- select an album -', 'wp-photo-album-plus') . '</option>';
    }
    $selected = $args['selected'] == '0' ? ' selected="selected"' : '';
    if ($args['addnone']) {
        $result .= '<option value="0"' . $selected . ' >' . __('--- none ---', 'wp-photo-album-plus') . '</option>';
    }
    $selected = $args['selected'] == '0' ? ' selected="selected"' : '';
    if ($args['addall']) {
        $result .= '<option value="0"' . $selected . ' >' . __('--- all ---', 'wp-photo-album-plus') . '</option>';
    }
    $selected = $args['selected'] == '-2' ? ' selected="selected"' : '';
    if ($args['addall']) {
        $result .= '<option value="-2"' . $selected . ' >' . __('--- generic ---', 'wp-photo-album-plus') . '</option>';
    }
    $selected = $args['selected'] == '-3' ? ' selected="selected"' : '';
    if ($args['addowner']) {
        $result .= '<option value="-3"' . $selected . ' >' . __('--- owner/public ---', 'wp-photo-album-plus') . '</option>';
    }
    $selected = $args['selected'] == '0' ? ' selected="selected"' : '';
    if ($args['addblank']) {
        $result .= '<option value="0"' . $selected . ' >' . '</option>';
    }
    $selected = $args['selected'] == '-99' ? ' selected="selected"' : '';
    if ($args['addmultiple']) {
        $result .= '<option value="-99"' . $selected . ' >' . __('--- multiple see below ---', 'wp-photo-album-plus') . '</option>';
    }
    $selected = $args['selected'] == '0' ? ' selected="selected"' : '';
    if ($args['addselbox']) {
        $result .= '<option value="0"' . $selected . ' >' . __('--- a selection box ---', 'wp-photo-album-plus') . '</option>';
    }
    // In case multiple
    if (strpos($args['selected'], ',') !== false) {
        $selarr = explode(',', $args['selected']);
    } else {
        $selarr = array($args['selected']);
    }
    if ($albums) {
        foreach ($albums as $album) {
            if ($args['disabled'] == $album['id'] || $args['exclude'] == $album['id'] || $args['checkupload'] && !wppa_allow_uploads($album['id']) || $args['disableancestors'] && wppa_is_ancestor($args['exclude'], $album['id'])) {
                $disabled = ' disabled="disabled"';
            } else {
                $disabled = '';
            }
            if (in_array($album['id'], $selarr, true) && !$disabled) {
                $selected = ' selected="selected"';
            } else {
                $selected = '';
            }
            $ok = true;
            // Assume this will be in the list
            if ($args['checkaccess'] && !wppa_have_access($album['id'])) {
                $ok = false;
            }
            /* This is in the query now
            		if ( $args['checkowner'] && wppa_switch( 'upload_owner_only' ) ) { 							// Need to check
            			if ( $album['owner'] != wppa_get_user() && $album['owner']  != '--- public ---' ) { 	// Not 'mine'
            				if ( ! wppa_user_is( 'administrator' ) ) {											// No admin
            					$ok = false;
            				}
            			}
            		}
            		*/
            /* This is in the query now
            		if ( $args['checkarray'] ) {
            			if ( ! in_array( $album['id'], $args['array'] ) ) {
            				$ok = false;
            			}
            		}
            		*/
            if ($selected && $args['addselected']) {
                $ok = true;
            }
            if ($ok) {
                if ($args['addnumbers']) {
                    $number = ' ( ' . $album['id'] . ' )';
                } else {
                    $number = '';
                }
                $result .= '<option class="' . $args['optionclass'] . '" value="' . $album['id'] . '" ' . $selected . $disabled . '>' . $album['name'] . $number . '</option>';
            }
        }
    }
    $selected = $args['selected'] == '-1' ? ' selected="selected"' : '';
    if ($args['addseparate']) {
        $result .= '<option value="-1"' . $selected . '>' . __('--- separate ---', 'wp-photo-album-plus') . '</option>';
    }
    return $result;
}
示例#18
0
function wppa_watermark_pos_select($default = false)
{
    // Init
    $user = wppa_get_user();
    $result = '';
    $opt = array(__('top - left', 'wppa'), __('top - center', 'wppa'), __('top - right', 'wppa'), __('center - left', 'wppa'), __('center - center', 'wppa'), __('center - right', 'wppa'), __('bottom - left', 'wppa'), __('bottom - center', 'wppa'), __('bottom - right', 'wppa'));
    $val = array('toplft', 'topcen', 'toprht', 'cenlft', 'cencen', 'cenrht', 'botlft', 'botcen', 'botrht');
    $idx = 0;
    // Find current selection
    $select = wppa_opt('wppa_watermark_pos');
    // default
    if (!$default && (wppa_switch('wppa_watermark_user') || current_user_can('wppa_settings')) && get_option('wppa_watermark_pos_' . $user, 'nil') !== 'nil') {
        $select = get_option('wppa_watermark_pos_' . $user);
    }
    // Produce the html
    while ($idx < 9) {
        $sel = $select == $val[$idx] ? 'selected="selected"' : '';
        $result .= '<option value="' . $val[$idx] . '" ' . $sel . '>' . $opt[$idx] . '</option>';
        $idx++;
    }
    return $result;
}
function wppa_do_maintenance_proc($slug)
{
    global $wpdb;
    global $thumb;
    global $wppa_opt;
    global $wppa_session;
    global $wppa_supported_video_extensions;
    global $wppa_supported_audio_extensions;
    // Check for multiple maintenance procs
    if (!wppa_switch('wppa_maint_ignore_concurrency_error')) {
        $all_slugs = array('wppa_remake_index_albums', 'wppa_remove_empty_albums', 'wppa_remake_index_photos', 'wppa_apply_new_photodesc_all', 'wppa_append_to_photodesc', 'wppa_remove_from_photodesc', 'wppa_remove_file_extensions', 'wppa_readd_file_extensions', 'wppa_regen_thumbs', 'wppa_rerate', 'wppa_recup', 'wppa_file_system', 'wppa_cleanup', 'wppa_remake', 'wppa_list_index', 'wppa_blacklist_user', 'wppa_un_blacklist_user', 'wppa_rating_clear', 'wppa_viewcount_clear', 'wppa_iptc_clear', 'wppa_exif_clear', 'wppa_watermark_all', 'wppa_create_all_autopages', 'wppa_leading_zeros', 'wppa_add_gpx_tag', 'wppa_optimize_ewww', 'wppa_comp_sizes', 'wppa_edit_tag');
        foreach (array_keys($all_slugs) as $key) {
            if ($all_slugs[$key] != $slug) {
                if (get_option($all_slugs[$key] . '_togo', '0')) {
                    // Process running
                    return __('You can run only one maintenance procedure at a time', 'wppa') . '||' . $slug . '||' . __('Error', 'wppa') . '||' . '' . '||' . '';
                }
            }
        }
    }
    // Lock this proc
    update_option($slug . '_user', wppa_get_user());
    // Initialize
    $endtime = time() + '5';
    // Allow for 5 seconds
    $chunksize = '1000';
    $lastid = strval(intval(get_option($slug . '_last', '0')));
    $errtxt = '';
    $id = '0';
    $topid = '0';
    $reload = '';
    if (!isset($wppa_session)) {
        $wppa_session = array();
    }
    if (!isset($wppa_session[$slug . '_fixed'])) {
        $wppa_session[$slug . '_fixed'] = '0';
    }
    if (!isset($wppa_session[$slug . '_deleted'])) {
        $wppa_session[$slug . '_deleted'] = '0';
    }
    if (!isset($wppa_session[$slug . '_skipped'])) {
        $wppa_session[$slug . '_skipped'] = '0';
    }
    if ($lastid == '0') {
        $wppa_session[$slug . '_fixed'] = '0';
        $wppa_session[$slug . '_deleted'] = '0';
        $wppa_session[$slug . '_skipped'] = '0';
    }
    // Pre-processing needed?
    if ($lastid == '0') {
        switch ($slug) {
            case 'wppa_remake_index_albums':
                $wpdb->query("UPDATE `" . WPPA_INDEX . "` SET `albums` = ''");
                break;
            case 'wppa_remake_index_photos':
                $wpdb->query("UPDATE `" . WPPA_INDEX . "` SET `photos` = ''");
                wppa_index_compute_skips();
                break;
            case 'wppa_recup':
                $wpdb->query("DELETE FROM `" . WPPA_IPTC . "` WHERE `photo` <> '0'");
                $wpdb->query("DELETE FROM `" . WPPA_EXIF . "` WHERE `photo` <> '0'");
                break;
            case 'wppa_file_system':
                if (get_option('wppa_file_system') == 'flat') {
                    update_option('wppa_file_system', 'to-tree');
                }
                if (get_option('wppa_file_system') == 'tree') {
                    update_option('wppa_file_system', 'to-flat');
                }
                break;
            case 'wppa_cleanup':
                $orphan_album = get_option('wppa_orphan_album', '0');
                $album_exists = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM`" . WPPA_ALBUMS . "` WHERE `id` = %s", $orphan_album));
                if (!$album_exists) {
                    $orphan_album = false;
                }
                if (!$orphan_album) {
                    $orphan_album = wppa_create_album_entry(array('name' => __('Orphan photos', 'wppa'), 'a_parent' => '-1', 'description' => __('This album contains refound lost photos', 'wppa')));
                    update_option('wppa_orphan_album', $orphan_album);
                }
                break;
        }
    }
    // Dispatch on albums / photos / single actions
    switch ($slug) {
        case 'wppa_remake_index_albums':
        case 'wppa_remove_empty_albums':
            // Process albums
            $table = WPPA_ALBUMS;
            $topid = $wpdb->get_var("SELECT `id` FROM `" . WPPA_ALBUMS . "` ORDER BY `id` DESC LIMIT 1");
            $albums = $wpdb->get_results("SELECT * FROM `" . WPPA_ALBUMS . "` WHERE `id` > " . $lastid . " ORDER BY `id` LIMIT 100", ARRAY_A);
            wppa_cache_album('add', $albums);
            if ($albums) {
                foreach ($albums as $album) {
                    $id = $album['id'];
                    switch ($slug) {
                        case 'wppa_remake_index_albums':
                            wppa_index_add('album', $id);
                            break;
                        case 'wppa_remove_empty_albums':
                            $p = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s", $id));
                            $a = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_ALBUMS . "` WHERE `a_parent` = %s", $id));
                            if (!$a && !$p) {
                                $wpdb->query($wpdb->prepare("DELETE FROM `" . WPPA_ALBUMS . "` WHERE `id` = %s", $id));
                                wppa_delete_album_source($id);
                                wppa_flush_treecounts($id);
                                wppa_index_remove('album', $id);
                            }
                            break;
                    }
                    // Test for timeout / ready
                    $lastid = $id;
                    update_option($slug . '_last', $lastid);
                    if (time() > $endtime) {
                        break;
                    }
                    // Time out
                }
            } else {
                // Nothing to do, Done anyway
                $lastid = $topid;
            }
            break;
            // End process albums
        // End process albums
        case 'wppa_remake_index_photos':
            $chunksize = '100';
        case 'wppa_apply_new_photodesc_all':
        case 'wppa_append_to_photodesc':
        case 'wppa_remove_from_photodesc':
        case 'wppa_remove_file_extensions':
        case 'wppa_readd_file_extensions':
        case 'wppa_regen_thumbs':
        case 'wppa_rerate':
        case 'wppa_recup':
        case 'wppa_file_system':
        case 'wppa_cleanup':
        case 'wppa_remake':
        case 'wppa_watermark_all':
        case 'wppa_create_all_autopages':
        case 'wppa_leading_zeros':
        case 'wppa_add_gpx_tag':
        case 'wppa_optimize_ewww':
        case 'wppa_comp_sizes':
        case 'wppa_edit_tag':
            // Process photos
            $table = WPPA_PHOTOS;
            if ($slug == 'wppa_cleanup') {
                $topid = get_option('wppa_' . WPPA_PHOTOS . '_lastkey', '1') * 10;
                $photos = array();
                for ($i = $lastid + '1'; $i <= $topid; $i++) {
                    $photos[]['id'] = $i;
                }
            } else {
                $topid = $wpdb->get_var("SELECT `id` FROM `" . WPPA_PHOTOS . "` ORDER BY `id` DESC LIMIT 1");
                $photos = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `id` > " . $lastid . " ORDER BY `id` LIMIT " . $chunksize, ARRAY_A);
            }
            if ($slug == 'wppa_edit_tag') {
                $edit_tag = get_option('wppa_tag_to_edit');
                $new_tag = get_option('wppa_new_tag_value');
            }
            if (!$photos && $slug == 'wppa_file_system') {
                $fs = get_option('wppa_file_system');
                if ($fs == 'to-tree') {
                    $to = 'tree';
                } elseif ($fs == 'to-flat') {
                    $to = 'flat';
                } else {
                    $to = $fs;
                }
            }
            if ($photos) {
                foreach ($photos as $photo) {
                    $thumb = $photo;
                    // Make globally known
                    $id = $photo['id'];
                    switch ($slug) {
                        case 'wppa_remake_index_photos':
                            wppa_index_add('photo', $id);
                            break;
                        case 'wppa_apply_new_photodesc_all':
                            $value = $wppa_opt['wppa_newphoto_description'];
                            $description = trim($value);
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_append_to_photodesc':
                            $value = trim($wppa_opt['wppa_append_text']);
                            if (!$value) {
                                return 'Unexpected error: missing text to append||' . $slug . '||Error||0';
                            }
                            $description = rtrim($photo['description'] . ' ' . $value);
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_remove_from_photodesc':
                            $value = trim($wppa_opt['wppa_remove_text']);
                            if (!$value) {
                                return 'Unexpected error: missing text to remove||' . $slug . '||Error||0';
                            }
                            $description = rtrim(str_replace($value, '', $photo['description']));
                            if ($description != $photo['description']) {
                                // Modified photo description
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `description` = %s WHERE `id` = %s", $description, $id));
                            }
                            break;
                        case 'wppa_remove_file_extensions':
                            if (!wppa_is_video($id)) {
                                $name = str_replace(array('.jpg', '.png', '.gif', '.JPG', '.PNG', '.GIF'), '', $photo['name']);
                                if ($name != $photo['name']) {
                                    // Modified photo name
                                    $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name, $id));
                                }
                            }
                            break;
                        case 'wppa_readd_file_extensions':
                            if (!wppa_is_video($id)) {
                                $name = str_replace(array('.jpg', '.png', 'gif', '.JPG', '.PNG', '.GIF'), '', $photo['name']);
                                if ($name == $photo['name']) {
                                    // Name had no fileextension
                                    $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name . '.' . $photo['ext'], $id));
                                }
                            }
                            break;
                        case 'wppa_regen_thumbs':
                            if (!wppa_is_video($id) || file_exists(str_replace('xxx', 'jpg', wppa_get_photo_path($id)))) {
                                wppa_create_thumbnail($id);
                            }
                            break;
                        case 'wppa_rerate':
                            wppa_rate_photo($id);
                            break;
                        case 'wppa_recup':
                            $a_ret = wppa_recuperate($id);
                            if ($a_ret['iptcfix']) {
                                $wppa_session[$slug . '_fixed']++;
                            }
                            if ($a_ret['exiffix']) {
                                $wppa_session[$slug . '_fixed']++;
                            }
                            break;
                        case 'wppa_file_system':
                            $fs = get_option('wppa_file_system');
                            if ($fs == 'to-tree' || $fs == 'to-flat') {
                                if ($fs == 'to-tree') {
                                    $from = 'flat';
                                    $to = 'tree';
                                } else {
                                    $from = 'tree';
                                    $to = 'flat';
                                }
                                // Media files
                                if (wppa_is_multi($id)) {
                                    // Can NOT use wppa_has_audio() or wppa_is_video(), they use wppa_get_photo_path() without fs switch!!
                                    $exts = array_merge($wppa_supported_video_extensions, $wppa_supported_audio_extensions);
                                    $pathfrom = wppa_get_photo_path($id, $from);
                                    $pathto = wppa_get_photo_path($id, $to);
                                    //	wppa_log( 'dbg', 'Trying: '.$pathfrom );
                                    foreach ($exts as $ext) {
                                        if (is_file(str_replace('.xxx', '.' . $ext, $pathfrom))) {
                                            //	wppa_log( 'dbg',  str_replace( '.xxx', '.'.$ext, $pathfrom ).' -> '.str_replace( '.xxx', '.'.$ext, $pathto ));
                                            @rename(str_replace('.xxx', '.' . $ext, $pathfrom), str_replace('.xxx', '.' . $ext, $pathto));
                                        }
                                    }
                                }
                                // Poster / photo
                                if (file_exists(wppa_fix_poster_ext(wppa_get_photo_path($id, $from), $id))) {
                                    @rename(wppa_fix_poster_ext(wppa_get_photo_path($id, $from), $id), wppa_fix_poster_ext(wppa_get_photo_path($id, $to), $id));
                                }
                                // Thumbnail
                                if (file_exists(wppa_fix_poster_ext(wppa_get_thumb_path($id, $from), $id))) {
                                    @rename(wppa_fix_poster_ext(wppa_get_thumb_path($id, $from), $id), wppa_fix_poster_ext(wppa_get_thumb_path($id, $to), $id));
                                }
                            }
                            break;
                        case 'wppa_cleanup':
                            $photo_files = glob(WPPA_UPLOAD_PATH . '/' . $id . '.*');
                            // Remove dirs
                            if ($photo_files) {
                                foreach (array_keys($photo_files) as $key) {
                                    if (is_dir($photo_files[$key])) {
                                        unset($photo_files[$key]);
                                    }
                                }
                            }
                            // files left? process
                            if ($photo_files) {
                                foreach ($photo_files as $photo_file) {
                                    $basename = basename($photo_file);
                                    $ext = substr($basename, strpos($basename, '.') + '1');
                                    if (!$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $id))) {
                                        // no db entry for this photo
                                        if (wppa_is_id_free(WPPA_PHOTOS, $id)) {
                                            if (wppa_create_photo_entry(array('id' => $id, 'album' => $orphan_album, 'ext' => $ext, 'filename' => $basename))) {
                                                // Can create entry
                                                $wppa_session[$slug . '_fixed']++;
                                                // Bump counter
                                                wppa_log('Debug', 'Lost photo file ' . $photo_file . ' recovered');
                                            } else {
                                                wppa_log('Debug', 'Unable to recover lost photo file ' . $photo_file . ' Create photo entry failed');
                                            }
                                        } else {
                                            wppa_log('Debug', 'Could not recover lost photo file ' . $photo_file . ' The id is not free');
                                        }
                                    }
                                }
                            }
                            break;
                        case 'wppa_remake':
                            if (wppa_remake_files('', $id)) {
                                $wppa_session[$slug . '_fixed']++;
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_watermark_all':
                            if (!wppa_is_video($id)) {
                                if (wppa_add_watermark($id)) {
                                    wppa_create_thumbnail($id);
                                    // create new thumb
                                    $wppa_session[$slug . '_fixed']++;
                                } else {
                                    $wppa_session[$slug . '_skipped']++;
                                }
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                        case 'wppa_create_all_autopages':
                            wppa_get_the_auto_page($id);
                            break;
                        case 'wppa_leading_zeros':
                            $name = $photo['name'];
                            if (wppa_is_int($name)) {
                                $target_len = wppa_opt('wppa_zero_numbers');
                                $name = strval(intval($name));
                                while (strlen($name) < $target_len) {
                                    $name = '0' . $name;
                                }
                            }
                            if ($name !== $photo['name']) {
                                $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `name` = %s WHERE `id` = %s", $name, $id));
                            }
                            break;
                        case 'wppa_add_gpx_tag':
                            $tags = $photo['tags'];
                            $temp = explode('/', $photo['location']);
                            if (!isset($temp['2'])) {
                                $temp['2'] = false;
                            }
                            if (!isset($temp['3'])) {
                                $temp['3'] = false;
                            }
                            $lat = $temp['2'];
                            $lon = $temp['3'];
                            if ($lat < 0.01 && $lat > -0.01 && $lon < 0.01 && $lon > -0.01) {
                                $lat = false;
                                $lon = false;
                            }
                            if ($photo['location'] && strpos($tags, 'Gpx') === false && $lat && $lon) {
                                // Add it
                                $tags = wppa_sanitize_tags($tags . ',Gpx');
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                wppa_index_update('photo', $photo['id']);
                                wppa_clear_taglist();
                            } elseif (strpos($tags, 'Gpx') !== false && !$lat && !$lon) {
                                // Remove it
                                $tags = wppa_sanitize_tags(str_replace('Gpx', '', $tags));
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                wppa_index_update('photo', $photo['id']);
                                wppa_clear_taglist();
                            }
                            break;
                        case 'wppa_optimize_ewww':
                            $file = wppa_get_photo_path($photo['id']);
                            if (is_file($file)) {
                                ewww_image_optimizer($file, 4, false, false, false);
                            }
                            $file = wppa_get_thumb_path($photo['id']);
                            if (is_file($file)) {
                                ewww_image_optimizer($file, 4, false, false, false);
                            }
                            break;
                        case 'wppa_comp_sizes':
                            $tx = 0;
                            $ty = 0;
                            $px = 0;
                            $py = 0;
                            $file = wppa_get_photo_path($photo['id']);
                            if (is_file($file)) {
                                $temp = getimagesize($file);
                                if (is_array($temp)) {
                                    $px = $temp[0];
                                    $py = $temp[1];
                                }
                            }
                            $file = wppa_get_thumb_path($photo['id']);
                            if (is_file($file)) {
                                $temp = getimagesize($file);
                                if (is_array($temp)) {
                                    $tx = $temp[0];
                                    $ty = $temp[1];
                                }
                            }
                            wppa_update_photo(array('id' => $photo['id'], 'thumbx' => $tx, 'thumby' => $ty, 'photox' => $px, 'photoy' => $py));
                            break;
                        case 'wppa_edit_tag':
                            $phototags = explode(',', wppa_get_photo_item($photo['id'], 'tags'));
                            if (in_array($edit_tag, $phototags)) {
                                foreach (array_keys($phototags) as $key) {
                                    if ($phototags[$key] == $edit_tag) {
                                        $phototags[$key] = $new_tag;
                                    }
                                }
                                $tags = wppa_sanitize_tags(implode(',', $phototags));
                                wppa_update_photo(array('id' => $photo['id'], 'tags' => $tags));
                                $wppa_session[$slug . '_fixed']++;
                            } else {
                                $wppa_session[$slug . '_skipped']++;
                            }
                            break;
                    }
                    // Test for timeout / ready
                    $lastid = $id;
                    update_option($slug . '_last', $lastid);
                    if (time() > $endtime) {
                        break;
                    }
                    // Time out
                }
            } else {
                // Nothing to do, Done anyway
                $lastid = $topid;
                wppa_log('Debug', 'Maintenance proc ' . $slug . ': Done!');
            }
            break;
            // End process photos
            // Single action maintenance modules
            //		case 'wppa_list_index':
            //			break;
            //		case 'wppa_blacklist_user':
            //			break;
            //		case 'wppa_un_blacklist_user':
            //			break;
            //		case 'wppa_rating_clear':
            //			break;
            //		case 'wppa_viewcount_clear':
            //			break;
            //		case 'wppa_iptc_clear':
            //			break;
            //		case 'wppa_exif_clear':
            //			break;
        // End process photos
        // Single action maintenance modules
        //		case 'wppa_list_index':
        //			break;
        //		case 'wppa_blacklist_user':
        //			break;
        //		case 'wppa_un_blacklist_user':
        //			break;
        //		case 'wppa_rating_clear':
        //			break;
        //		case 'wppa_viewcount_clear':
        //			break;
        //		case 'wppa_iptc_clear':
        //			break;
        //		case 'wppa_exif_clear':
        //			break;
        default:
            $errtxt = 'Unimplemented maintenance slug: ' . strip_tags($slug);
    }
    // either $albums / $photos has been exhousted ( for this try ) or time is up
    if ($slug == 'wppa_cleanup') {
        $togo = $topid - $lastid;
    } else {
        $togo = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . $table . "` WHERE `id` > %s ", $lastid));
    }
    $status = $togo ? 'Pending' : 'Ready';
    if ($togo) {
        update_option($slug . '_togo', $togo);
        update_option($slug . '_status', $status);
    } else {
        // Really done
        // Report fixed/skipped/deleted
        if ($wppa_session[$slug . '_fixed']) {
            $status .= ' fixed:' . $wppa_session[$slug . '_fixed'];
            unset($wppa_session[$slug . '_fixed']);
        }
        if ($wppa_session[$slug . '_skipped']) {
            $status .= ' skipped:' . $wppa_session[$slug . '_skipped'];
            unset($wppa_session[$slug . '_skipped']);
        }
        if ($wppa_session[$slug . '_deleted']) {
            $status .= ' deleted:' . $wppa_session[$slug . '_deleted'];
            unset($wppa_session[$slug . '_deleted']);
        }
        // Re-Init options
        delete_option($slug . '_togo', '');
        delete_option($slug . '_status', '');
        delete_option($slug . '_last', '0');
        delete_option($slug . '_user', '');
        // Post-processing needed?
        switch ($slug) {
            case 'wppa_remake_index_albums':
            case 'wppa_remake_index_photos':
                $wpdb->query("DELETE FROM `" . WPPA_INDEX . "` WHERE `albums` = '' AND `photos` = ''");
                // Remove empty entries
                delete_option('wppa_index_need_remake');
                break;
            case 'wppa_apply_new_photodesc_all':
            case 'wppa_append_to_photodesc':
            case 'wppa_remove_from_photodesc':
                update_option('wppa_remake_index_photos_status', __('Required', 'wppa'));
                break;
            case 'wppa_regen_thumbs':
                wppa_bump_thumb_rev();
                break;
            case 'wppa_file_system':
                wppa_update_option('wppa_file_system', $to);
                $reload = 'reload';
                break;
            case 'wppa_remake':
                wppa_bump_photo_rev();
                wppa_bump_thumb_rev();
                break;
            case 'wppa_edit_tag':
                wppa_clear_taglist();
                $reload = 'reload';
                break;
        }
    }
    return $errtxt . '||' . $slug . '||' . $status . '||' . $togo . '||' . $reload;
}
function wppa_ajax_callback()
{
    global $wpdb;
    global $wppa_session;
    wppa('ajax', true);
    wppa('error', '0');
    wppa('out', '');
    $wppa_session['page']--;
    $wppa_session['ajax']++;
    wppa_save_session();
    // ALTHOUGH IF WE ARE HERE AS FRONT END VISITOR, is_admin() is true.
    // So, $wppa_opt switches are 'yes' or 'no' and not true or false.
    // So, always use the function wppa_switch( $slug ) to test on a bool setting
    // Globally check query args to prevent php injection
    $wppa_args = array('album', 'photo', 'slide', 'cover', 'occur', 'woccur', 'searchstring', 'topten', 'lasten', 'comten', 'featen', 'single', 'photos-only', 'debug', 'relcount', 'upldr', 'owner', 'rootsearch');
    foreach ($_REQUEST as $arg) {
        if (in_array(str_replace('wppa-', '', $arg), $wppa_args)) {
            if (strpos($arg, '<?') !== false) {
                die('Security check failure #91');
            }
            if (strpos($arg, '?>') !== false) {
                die('Security check failure #92');
            }
        }
    }
    wppa_vfy_arg('wppa-action', true);
    wppa_vfy_arg('photo-id');
    wppa_vfy_arg('comment-id');
    wppa_vfy_arg('moccur');
    wppa_vfy_arg('comemail', true);
    wppa_vfy_arg('comname', true);
    wppa_vfy_arg('tag', true);
    $wppa_action = $_REQUEST['wppa-action'];
    switch ($wppa_action) {
        case 'getssiptclist':
            $tag = str_replace('H', '#', $_REQUEST['tag']);
            $mocc = $_REQUEST['moccur'];
            $oldvalue = '';
            if (strpos($wppa_session['supersearch'], ',') !== false) {
                $ss_data = explode(',', $wppa_session['supersearch']);
                if (count($ss_data) == '4') {
                    if ($ss_data['0'] == 'p') {
                        if ($ss_data['1'] == 'i') {
                            if ($ss_data['2'] == $_REQUEST['tag']) {
                                $oldvalue = $ss_data['3'];
                            }
                        }
                    }
                }
            }
            $iptcdata = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_IPTC . "` WHERE `photo` > '0' AND `tag` = %s ORDER BY `description`", $tag), ARRAY_A);
            $last = '';
            $any = false;
            if (is_array($iptcdata)) {
                foreach ($iptcdata as $item) {
                    $desc = sanitize_text_field($item['description']);
                    $desc = str_replace(array(chr(0), chr(1), chr(2), chr(3), chr(4), chr(5), chr(6), chr(7)), '', $desc);
                    if ($desc != $last) {
                        $sel = $oldvalue && $oldvalue == $desc ? 'selected="selected"' : '';
                        if ($sel) {
                            echo 'selected:' . $oldvalue;
                        }
                        $ddesc = strlen($desc) > '32' ? substr($desc, 0, 30) . '...' : $desc;
                        echo '<option' . ' value="' . esc_attr($desc) . '"' . ' class="wppa-iptclist-' . $mocc . '"' . ' ' . $sel . ' >' . $ddesc . '</option>';
                        $last = $desc;
                        $any = true;
                    }
                }
            }
            if (!$any) {
                $query = $wpdb->prepare("DELETE FROM `" . WPPA_IPTC . "` WHERE `photo` = '0' AND `tag` = %s", $tag);
                $wpdb->query($query);
                //				wppa_log( 'dbg', $query );
            }
            wppa_exit();
            break;
        case 'getssexiflist':
            $tag = str_replace('H', '#', $_REQUEST['tag']);
            $mocc = $_REQUEST['moccur'];
            $oldvalue = '';
            if (strpos($wppa_session['supersearch'], ',') !== false) {
                $ss_data = explode(',', $wppa_session['supersearch']);
                if (count($ss_data) == '4') {
                    if ($ss_data['0'] == 'p') {
                        if ($ss_data['1'] == 'e') {
                            if ($ss_data['2'] == $_REQUEST['tag']) {
                                $oldvalue = $ss_data['3'];
                            }
                        }
                    }
                }
            }
            $exifdata = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_EXIF . "` WHERE `photo` > '0' AND `tag` = %s ORDER BY `description`", $tag), ARRAY_A);
            $last = '';
            $any = false;
            if (is_array($exifdata)) {
                foreach ($exifdata as $item) {
                    $desc = sanitize_text_field($item['description']);
                    $desc = str_replace(array(chr(0), chr(1), chr(2), chr(3), chr(4), chr(5), chr(6), chr(7)), '', $desc);
                    if ($desc != $last) {
                        $sel = $oldvalue && $oldvalue == $desc ? 'selected="selected"' : '';
                        $ddesc = strlen($desc) > '32' ? substr($desc, 0, 30) . '...' : $desc;
                        echo '<option' . ' value="' . esc_attr($desc) . '"' . ' class="wppa-exiflist-' . $mocc . '"' . ' ' . $sel . ' >' . $ddesc . '</option>';
                        $last = $desc;
                        $any = true;
                    }
                }
            }
            if (!$any) {
                $query = $wpdb->prepare("DELETE FROM `" . WPPA_EXIF . "` WHERE `photo` = '0' AND `tag` = %s", $tag);
                $wpdb->query($query);
                //				wppa_log( 'dbg', $query );
            }
            wppa_exit();
            break;
        case 'front-edit':
            if (!isset($_REQUEST['photo-id'])) {
                die('Missing required argument');
            }
            $photo = $_REQUEST['photo-id'];
            $ok = false;
            if (current_user_can('wppa_admin')) {
                $ok = true;
            }
            if (wppa_get_user() == wppa_get_photo_owner($photo) && (current_user_can('wppa_upload') || is_user_logged_in() && wppa_switch('upload_edit'))) {
                $ok = true;
            }
            if (!$ok) {
                die('You do not have sufficient rights to do this');
            }
            require_once 'wppa-photo-admin-autosave.php';
            wppa('front_edit', true);
            echo '	<div style="padding-bottom:4px;height:24px;" >
						<span style="color:#777;" >
							<i>' . __('All modifications are instantly updated on the server. The <b style="color:#070" >Remark</b> field keeps you informed on the actions taken at the background.', 'wp-photo-album-plus') . '</i>
						</span>
						<input id="wppa-fe-exit" type="button" style="float:right;color:red;font-weight:bold;" onclick="window.opener.location.reload( true );window.close();" value="' . __('Exit & Refresh', 'wp-photo-album-plus') . '" />
						<div id="wppa-fe-count" style="float:right;" ></div>
					</div><div style="clear:both;"></div>';
            wppa_album_photos('', $photo);
            wppa_exit();
            break;
        case 'do-comment':
            // Security check
            $mocc = $_REQUEST['moccur'];
            $nonce = $_REQUEST['wppa-nonce'];
            if (!wp_verify_nonce($nonce, 'wppa-nonce-' . $mocc)) {
                _e('Security check failure', 'wp-photo-album-plus');
                wppa_exit();
            }
            // Correct the fact that this is a non-admin operation, if it is only
            if (is_admin()) {
                require_once 'wppa-non-admin.php';
            }
            wppa('mocc', $_REQUEST['moccur']);
            wppa('comment_photo', isset($_REQUEST['photo-id']) ? $_REQUEST['photo-id'] : '0');
            wppa('comment_id', isset($_REQUEST['comment-edit']) ? $_REQUEST['comment-edit'] : '0');
            $comment_allowed = !wppa_switch('comment_login') || is_user_logged_in();
            if (wppa_switch('show_comments') && $comment_allowed) {
                //				if ( wppa_switch( 'search_comments' ) ) wppa_index_remove( 'photo', $_REQUEST['photo-id'] );
                wppa_do_comment($_REQUEST['photo-id']);
                // Process the comment
                if (wppa_switch('search_comments')) {
                    wppa_index_update('photo', $_REQUEST['photo-id']);
                }
            }
            wppa('no_esc', true);
            echo wppa_comment_html($_REQUEST['photo-id'], $comment_allowed);
            // Retrieve the new commentbox content
            wppa_exit();
            break;
        case 'import':
            require_once 'wppa-upload.php';
            _wppa_page_import();
            wppa_exit();
            break;
        case 'approve':
            $iret = '0';
            if (!current_user_can('wppa_moderate') && !current_user_can('wppa_comments')) {
                _e('You do not have the rights to moderate photos this way', 'wp-photo-album-plus');
                wppa_exit();
            }
            if (isset($_REQUEST['photo-id']) && current_user_can('wppa_moderate')) {
                $iret = $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `status` = 'publish' WHERE `id` = %s", $_REQUEST['photo-id']));
                wppa_flush_upldr_cache('photoid', $_REQUEST['photo-id']);
                $alb = $wpdb->get_var($wpdb->prepare("SELECT `album` FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $_REQUEST['photo-id']));
                wppa_clear_taglist();
                wppa_flush_treecounts($alb);
            }
            if (isset($_REQUEST['comment-id'])) {
                $iret = $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_COMMENTS . "` SET `status` = 'approved' WHERE `id` = %s", $_REQUEST['comment-id']));
            }
            if ($iret) {
                echo 'OK';
            } else {
                if (isset($_REQUEST['photo-id'])) {
                    if (current_user_can('wppa_moderate')) {
                        echo sprintf(__('Failed to update stutus of photo %s', 'wp-photo-album-plus'), $_REQUEST['photo-id']) . "\n" . __('Please refresh the page', 'wp-photo-album-plus');
                    } else {
                        _e('Security check failure', 'wp-photo-album-plus');
                    }
                }
                if (isset($_REQUEST['comment-id'])) {
                    echo sprintf(__('Failed to update stutus of comment %s', 'wp-photo-album-plus'), $_REQUEST['comment-id']) . "\n" . __('Please refresh the page', 'wp-photo-album-plus');
                }
            }
            wppa_exit();
        case 'remove':
            if (isset($_REQUEST['photo-id'])) {
                // Remove photo
                if (wppa_user_is('administrator') || current_user_can('wppa_moderate') || wppa_get_user() == wppa_get_photo_owner($_REQUEST['photo-id']) && wppa_switch('upload_edit')) {
                    // Frontend delete?
                    wppa_delete_photo($_REQUEST['photo-id']);
                    echo 'OK||' . __('Photo removed', 'wp-photo-album-plus');
                    wppa_exit();
                }
            }
            if (!current_user_can('wppa_moderate') && !current_user_can('wppa_comments')) {
                _e('You do not have the rights to moderate photos this way', 'wp-photo-album-plus');
                wppa_exit();
            }
            if (isset($_REQUEST['photo-id'])) {
                // Remove photo
                if (!current_user_can('wppa_moderate')) {
                    _e('Security check failure', 'wp-photo-album-plus');
                    wppa_exit();
                }
                wppa_delete_photo($_REQUEST['photo-id']);
                echo 'OK||' . __('Photo removed', 'wp-photo-album-plus');
                wppa_exit();
            }
            if (isset($_REQUEST['comment-id'])) {
                // Remove comment
                $iret = $wpdb->query($wpdb->prepare("DELETE FROM `" . WPPA_COMMENTS . "` WHERE `id`= %s", $_REQUEST['comment-id']));
                if ($iret) {
                    echo 'OK||' . __('Comment removed', 'wp-photo-album-plus');
                } else {
                    _e('Could not remove comment', 'wp-photo-album-plus');
                }
                wppa_exit();
            }
            _e('Unexpected error', 'wp-photo-album-plus');
            wppa_exit();
        case 'downloadalbum':
            // Feature enabled?
            if (!wppa_switch('allow_download_album')) {
                echo '||ER||' . __('This feature is not enabled on this website', 'wp-photo-album-plus');
                wppa_exit();
            }
            // Validate args
            $alb = $_REQUEST['album-id'];
            $status = "`status` <> 'pending' AND `status` <> 'scheduled'";
            if (!is_user_logged_in()) {
                $status .= " AND `status` <> 'private'";
            }
            $photos = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s AND ( ( " . $status . " ) OR owner = %s ) " . wppa_get_photo_order($alb), $alb, wppa_get_user()), ARRAY_A);
            if (!$photos) {
                echo '||ER||' . __('The album is empty', 'wp-photo-album-plus');
                wppa_exit();
            }
            // Remove obsolete files
            wppa_delete_obsolete_tempfiles();
            // Open zipfile
            if (!class_exists('ZipArchive')) {
                echo '||ER||' . __('Unable to create zip archive', 'wp-photo-album-plus');
                wppa_exit();
            }
            $zipfilename = wppa_get_album_name($alb);
            $zipfilename = wppa_sanitize_file_name($zipfilename . '.zip');
            // Remove illegal chars
            $zipfilepath = WPPA_UPLOAD_PATH . '/temp/' . $zipfilename;
            if (is_file($zipfilepath)) {
                //		unlink( $zipfilepath );	// Debug
            }
            $wppa_zip = new ZipArchive();
            $iret = $wppa_zip->open($zipfilepath, 1);
            if ($iret !== true) {
                echo '||ER||' . sprintf(__('Unable to create zip archive. code = %s', 'wp-photo-album-plus'), $iret);
                wppa_exit();
            }
            // Add photos to zip
            $stop = false;
            foreach ($photos as $p) {
                if (wppa_is_time_up()) {
                    wppa_log('obs', 'Time up during album to zip creation');
                    $stop = true;
                } else {
                    $id = $p['id'];
                    if (!wppa_is_multi($id)) {
                        $source = wppa_switch('download_album_source') && is_file(wppa_get_source_path($id)) ? wppa_get_source_path($id) : wppa_get_photo_path($id);
                        if (is_file($source)) {
                            $dest = $p['filename'] ? wppa_sanitize_file_name($p['filename']) : wppa_sanitize_file_name(wppa_strip_ext($p['name']) . '.' . $p['ext']);
                            $dest = wppa_fix_poster_ext($dest, $id);
                            $iret = $wppa_zip->addFile($source, $dest);
                            // To prevent too may files open, and to have at least a file when there are too many photos, close and re-open
                            $wppa_zip->close();
                            $wppa_zip->open($zipfilepath);
                            // wppa_log( 'dbg', 'Added ' . basename($source) . ' to ' . basename($zipfilepath));
                        }
                    }
                }
                if ($stop) {
                    break;
                }
            }
            // Close zip and return
            $zipcount = $wppa_zip->numFiles;
            $wppa_zip->close();
            // A zip is created
            $desturl = WPPA_UPLOAD_URL . '/temp/' . $zipfilename;
            echo $desturl . '||OK||';
            if ($zipcount != count($photos)) {
                echo sprintf(__('Only %s out of %s photos could be added to the zipfile', 'wp-photo-album-plus'), $zipcount, count($photos));
            }
            wppa_exit();
            break;
        case 'getalbumzipurl':
            $alb = $_REQUEST['album-id'];
            $zipfilename = wppa_get_album_name($alb);
            $zipfilename = wppa_sanitize_file_name($zipfilename . '.zip');
            // Remove illegal chars
            $zipfilepath = WPPA_UPLOAD_PATH . '/temp/' . $zipfilename;
            $zipfileurl = WPPA_UPLOAD_URL . '/temp/' . $zipfilename;
            if (is_file($zipfilepath)) {
                echo $zipfileurl;
            } else {
                echo 'ER';
            }
            wppa_exit();
            break;
        case 'makeorigname':
            $photo = $_REQUEST['photo-id'];
            $from = $_REQUEST['from'];
            if ($from == 'fsname') {
                $type = wppa_opt('art_monkey_link');
            } elseif ($from == 'popup') {
                $type = wppa_opt('art_monkey_popup_link');
            } else {
                echo '||7||' . __('Unknown source of request', 'wp-photo-album-plus');
                wppa_exit();
            }
            $data = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $photo), ARRAY_A);
            if ($data) {
                // The photo is supposed to exist
                // Make the name
                if ($data['filename']) {
                    $name = $data['filename'];
                } else {
                    $name = __($data['name'], 'wp-photo-album-plus');
                }
                $name = wppa_sanitize_file_name($name);
                // Remove illegal chars
                $name = preg_replace('/\\.[^.]*$/', '', $name);
                // Remove file extension
                if (strlen($name) == '0') {
                    echo '||1||' . __('Empty filename', 'wp-photo-album-plus');
                    wppa_exit();
                }
                // Make the file
                if (wppa_switch('artmonkey_use_source')) {
                    if (is_file(wppa_get_source_path($photo))) {
                        $source = wppa_get_source_path($photo);
                    } else {
                        $source = wppa_get_photo_path($photo);
                    }
                } else {
                    $source = wppa_get_photo_path($photo);
                }
                $source = wppa_fix_poster_ext($source, $photo);
                // Fix the extension for mm items.
                if ($data['ext'] == 'xxx') {
                    $data['ext'] = wppa_get_ext($source);
                }
                $dest = WPPA_UPLOAD_PATH . '/temp/' . $name . '.' . $data['ext'];
                $zipfile = WPPA_UPLOAD_PATH . '/temp/' . $name . '.zip';
                $tempdir = WPPA_UPLOAD_PATH . '/temp';
                if (!is_dir($tempdir)) {
                    @mkdir($tempdir);
                }
                if (!is_dir($tempdir)) {
                    echo '||2||' . __('Unable to create tempdir', 'wp-photo-album-plus');
                    wppa_exit();
                }
                // Remove obsolete files
                wppa_delete_obsolete_tempfiles();
                // Make the files
                if ($type == 'file') {
                    copy($source, $dest);
                    $ext = $data['ext'];
                } elseif ($type == 'zip') {
                    if (!class_exists('ZipArchive')) {
                        echo '||8||' . __('Unable to create zip archive', 'wp-photo-album-plus');
                        wppa_exit();
                    }
                    $ext = 'zip';
                    $wppa_zip = new ZipArchive();
                    $wppa_zip->open($zipfile, 1);
                    $wppa_zip->addFile($source, basename($dest));
                    $wppa_zip->close();
                } else {
                    echo '||6||' . __('Unknown type', 'wp-photo-album-plus');
                    wppa_exit();
                }
                $desturl = WPPA_UPLOAD_URL . '/temp/' . $name . '.' . $ext;
                echo '||0||' . $desturl;
                // No error: return url
                wppa_exit();
            } else {
                echo '||9||' . __('The photo does no longer exist', 'wp-photo-album-plus');
                wppa_exit();
            }
            wppa_exit();
            break;
        case 'tinymcedialog':
            $result = wppa_make_tinymce_dialog();
            echo $result;
            wppa_exit();
            break;
        case 'bumpviewcount':
            $nonce = $_REQUEST['wppa-nonce'];
            if (wp_verify_nonce($nonce, 'wppa-check')) {
                wppa_bump_viewcount('photo', $_REQUEST['wppa-photo']);
            } else {
                _e('Security check failure', 'wp-photo-album-plus');
            }
            wppa_exit();
            break;
        case 'rate':
            // Get commandline args
            $photo = $_REQUEST['wppa-rating-id'];
            $rating = $_REQUEST['wppa-rating'];
            $occur = $_REQUEST['wppa-occur'];
            $index = $_REQUEST['wppa-index'];
            $nonce = $_REQUEST['wppa-nonce'];
            // Make errortext
            $errtxt = __('An error occurred while processing you rating request.', 'wp-photo-album-plus');
            $errtxt .= "\n" . __('Maybe you opened the page too long ago to recognize you.', 'wp-photo-album-plus');
            $errtxt .= "\n" . __('You may refresh the page and try again.', 'wp-photo-album-plus');
            $wartxt = __('Althoug an error occurred while processing your rating, your vote has been registered.', 'wp-photo-album-plus');
            $wartxt .= "\n" . __('However, this may not be reflected in the current pageview', 'wp-photo-album-plus');
            // Check on validity
            if (!wp_verify_nonce($nonce, 'wppa-check')) {
                echo '0||100||' . $errtxt;
                wppa_exit();
                // Nonce check failed
            }
            if (wppa_opt('rating_max') == '1' && $rating != '1') {
                echo '0||106||' . $errtxt . ':' . $rating;
                wppa_exit();
                // Value out of range
            } elseif (wppa_opt('rating_max') == '5' && !in_array($rating, array('-1', '1', '2', '3', '4', '5'))) {
                echo '0||106||' . $errtxt . ':' . $rating;
                wppa_exit();
                // Value out of range
            } elseif (wppa_opt('rating_max') == '10' && !in_array($rating, array('-1', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'))) {
                echo '0||106||' . $errtxt . ':' . $rating;
                wppa_exit();
                // Value out of range
            }
            // Get other data
            if (!$wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $photo))) {
                echo '0||999||' . __('Photo has been removed.', 'wp-photo-album-plus');
                wppa_exit();
            }
            $user = wppa_get_user();
            $mylast = $wpdb->get_row($wpdb->prepare('SELECT * FROM `' . WPPA_RATING . '` WHERE `photo` = %s AND `user` = %s ORDER BY `id` DESC LIMIT 1', $photo, $user), ARRAY_A);
            $myavgrat = '0';
            // Init
            // Rate own photo?
            if (wppa_get_photo_item($photo, 'owner') == $user && !wppa_switch('allow_owner_votes')) {
                echo '0||900||' . __('Sorry, you can not rate your own photos', 'wp-photo-album-plus');
                wppa_exit();
            }
            // Already a pending one?
            $pending = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_RATING . "` WHERE `photo` = %s AND `user` = %s AND `status` = %s", $photo, $user, 'pending'));
            // Has user motivated his vote?
            $hascommented = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_COMMENTS . "` WHERE `photo` = %s AND `user` = %s", $photo, wppa_get_user('display')));
            if ($pending) {
                if (!$hascommented) {
                    echo '0||900||' . __('Please enter a comment.', 'wp-photo-album-plus');
                    wppa_exit();
                } else {
                    $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_RATING . "` SET `status` = 'publish' WHERE `photo` = %s AND `user` = %s", $photo, $user));
                }
            }
            if (wppa_switch('vote_needs_comment')) {
                $ratingstatus = $hascommented ? 'publish' : 'pending';
            } else {
                $ratingstatus = 'publish';
            }
            // When done, we have to echo $occur.'||'.$photo.'||'.$index.'||'.$myavgrat.'||'.$allavgrat.'||'.$discount.||.$hascommented.||.$message;
            // So we have to do: process rating and find new $myavgrat, $allavgrat and $discount ( $occur, $photo and $index are known )
            // Case 0: Illegal second vote. Frontend takes care of this, but a hacker could enter an ajaxlink manually
            if ($mylast && (!(wppa_switch('rating_change') || wppa_switch('rating_multi')) || $mylast['value'] < '0' || $mylast['value'] > '0' && $rating == '-1')) {
                echo '0||109||' . __('Security check failure.', 'wp-photo-album-plus');
                wppa_exit();
            }
            // Case 1: value = -1 this is a legal dislike vote
            if ($rating == '-1') {
                // Add my dislike
                $iret = wppa_create_rating_entry(array('photo' => $photo, 'value' => $rating, 'user' => $user, 'status' => $ratingstatus));
                if (!$iret) {
                    echo '0||101||' . $errtxt;
                    wppa_exit();
                    // Fail on storing vote
                }
                // Add points
                wppa_add_credit_points(wppa_opt('cp_points_rating'), __('Photo rated', 'wp-photo-album-plus'), $photo, $rating);
                wppa_dislike_check($photo);
                // Check for email to be sent every .. dislikes
                if (!is_file(wppa_get_thumb_path($photo))) {
                    // Photo is removed
                    echo $occur . '||' . $photo . '||' . $index . '||-1||-1|0||' . wppa_opt('dislike_delete');
                    wppa_exit();
                }
            } elseif (!$mylast) {
                // Add my vote
                $iret = wppa_create_rating_entry(array('photo' => $photo, 'value' => $rating, 'user' => $user, 'status' => $ratingstatus));
                if (!$iret) {
                    echo '0||102||' . $errtxt;
                    wppa_exit();
                    // Fail on storing vote
                }
                // Add points
                wppa_add_credit_points(wppa_opt('cp_points_rating'), __('Photo rated', 'wp-photo-album-plus'), $photo, $rating);
            } elseif (wppa_switch('rating_change')) {
                // Votechanging is allowed
                $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_RATING . '` SET `value` = %s WHERE `photo` = %s AND `user` = %s LIMIT 1', $rating, $photo, $user));
                if ($iret === false) {
                    echo '0||103||' . $errtxt;
                    wppa_exit();
                    // Fail on update
                }
            } elseif (wppa_switch('rating_multi')) {
                // Rating multi is allowed
                $iret = wppa_create_rating_entry(array('photo' => $photo, 'value' => $rating, 'user' => $user, 'status' => $ratingstatus));
                if (!$iret) {
                    echo '0||104||' . $errtxt;
                    wppa_exit();
                    // Fail on storing vote
                }
            } else {
                // Should never get here....
                echo '0||110||' . __('Unexpected error', 'wp-photo-album-plus');
                wppa_exit();
            }
            // Compute my avg rating
            $myrats = $wpdb->get_results($wpdb->prepare('SELECT * FROM `' . WPPA_RATING . '`  WHERE `photo` = %s AND `user` = %s AND `status` = %s ', $photo, $user, 'publish'), ARRAY_A);
            if ($myrats) {
                $sum = 0;
                $cnt = 0;
                foreach ($myrats as $rat) {
                    if ($rat['value'] == '-1') {
                        $sum += wppa_opt('dislike_value');
                    } else {
                        $sum += $rat['value'];
                    }
                    $cnt++;
                }
                $myavgrat = $sum / $cnt;
                $i = wppa_opt('rating_prec');
                $j = $i + '1';
                $myavgrat = sprintf('%' . $j . '.' . $i . 'f', $myavgrat);
            } else {
                $myavgrat = '0';
            }
            // Compute new allavgrat
            $ratings = $wpdb->get_results($wpdb->prepare('SELECT * FROM ' . WPPA_RATING . ' WHERE `photo` = %s AND `status` = %s', $photo, 'publish'), ARRAY_A);
            if ($ratings) {
                $sum = 0;
                $cnt = 0;
                foreach ($ratings as $rat) {
                    if ($rat['value'] == '-1') {
                        $sum += wppa_opt('dislike_value');
                    } else {
                        $sum += $rat['value'];
                    }
                    $cnt++;
                }
                $allavgrat = $sum / $cnt;
                if ($allavgrat == '10') {
                    $allavgrat = '9.99999999';
                }
                // For sort order reasons text field
            } else {
                $allavgrat = '0';
            }
            // Store it in the photo info
            $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `mean_rating` = %s WHERE `id` = %s', $allavgrat, $photo));
            if ($iret === false) {
                echo '0||106||' . $wartxt;
                wppa_exit();
                // Fail on save
            }
            // Compute rating_count and store in the photo info
            $ratcount = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_RATING . "` WHERE `photo` = %s", $photo));
            if ($ratcount !== false) {
                $iret = $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `rating_count` = %s WHERE `id` = %s", $ratcount, $photo));
                if ($iret === false) {
                    echo '0||107||' . $wartxt;
                    wppa_exit();
                    // Fail on save
                }
            }
            // Format $allavgrat for output
            $allavgratcombi = $allavgrat . '|' . $ratcount;
            // Compute dsilike count
            $discount = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_RATING . "` WHERE `photo` = %s AND `value` = -1 AND `status` = %s", $photo, 'publish'));
            if ($discount === false) {
                echo '0||108||' . $wartxt;
                wppa_exit();
                // Fail on save
            }
            // Test for possible medal
            wppa_test_for_medal($photo);
            // Success!
            wppa_clear_cache();
            if (wppa_switch('vote_needs_comment') && !$hascommented) {
                $message = __("Please explain your vote in a comment.\nYour vote will be discarded if you don't.\n\nAfter completing your comment,\nyou can refresh the page to see\nyour vote became effective.", 'wp-photo-album-plus');
            } else {
                $message = '';
            }
            echo $occur . '||' . $photo . '||' . $index . '||' . $myavgrat . '||' . $allavgratcombi . '||' . $discount . '||' . $hascommented . '||' . $message;
            break;
        case 'render':
            $tim_1 = microtime(true);
            $nq_1 = get_num_queries();
            // Correct the fact that this is a non-admin operation, if it is
            if (is_admin()) {
                require_once 'wppa-non-admin.php';
            }
            wppa_load_theme();
            // Register geo shortcode if google-maps-gpx-vieuwer is on board. GPX does it in wp_head(), what is not done in an ajax call
            //			if ( function_exists( 'gmapv3' ) ) add_shortcode( 'map', 'gmapv3' );
            // Get the post we are working for
            if (isset($_REQUEST['wppa-fromp'])) {
                $p = $_REQUEST['wppa-fromp'];
                if (wppa_is_int($p)) {
                    $GLOBALS['post'] = get_post($p);
                }
            }
            // Render
            echo wppa_albums();
            $tim_2 = microtime(true);
            $nq_2 = get_num_queries();
            $mem = memory_get_peak_usage(true) / 1024 / 1024;
            $msg = sprintf('WPPA Ajax render: db queries: WP:%d, WPPA+: %d in %4.2f seconds, using %4.2f MB memory max', $nq_1, $nq_2 - $nq_1, $tim_2 - $tim_1, $mem);
            echo '<script type="text/javascript">wppaConsoleLog( \'' . $msg . '\', \'force\' )</script>';
            break;
        case 'delete-photo':
            $photo = $_REQUEST['photo-id'];
            $nonce = $_REQUEST['wppa-nonce'];
            // Check validity
            if (!wp_verify_nonce($nonce, 'wppa_nonce_' . $photo)) {
                echo '||0||' . __('You do not have the rights to delete a photo', 'wp-photo-album-plus');
                wppa_exit();
                // Nonce check failed
            }
            if (!is_numeric($photo)) {
                echo '||0||' . __('Security check failure', 'wp-photo-album-plus');
                wppa_exit();
                // Nonce check failed
            }
            $album = $wpdb->get_var($wpdb->prepare('SELECT `album` FROM `' . WPPA_PHOTOS . '` WHERE `id` = %s', $photo));
            wppa_delete_photo($photo);
            wppa_clear_cache();
            echo '||1||<span style="color:red" >' . sprintf(__('Photo %s has been deleted', 'wp-photo-album-plus'), $photo) . '</span>';
            echo '||';
            $a = wppa_allow_uploads($album);
            if (!$a) {
                echo 'full';
            } else {
                echo 'notfull||' . $a;
            }
            break;
        case 'update-album':
            $album = $_REQUEST['album-id'];
            $nonce = $_REQUEST['wppa-nonce'];
            $item = $_REQUEST['item'];
            $value = $_REQUEST['value'];
            $value = wppa_decode($value);
            // Check validity
            if (!wp_verify_nonce($nonce, 'wppa_nonce_' . $album)) {
                echo '||0||' . __('You do not have the rights to update album information', 'wp-photo-album-plus') . $nonce;
                wppa_exit();
                // Nonce check failed
            }
            switch ($item) {
                case 'clear_ratings':
                    $photos = $wpdb->get_results($wpdb->prepare('SELECT * FROM `' . WPPA_PHOTOS . '` WHERE `album` = %s', $album), ARRAY_A);
                    if ($photos) {
                        foreach ($photos as $photo) {
                            $iret1 = $wpdb->query($wpdb->prepare('DELETE FROM `' . WPPA_RATING . '` WHERE `photo` = %s', $photo['id']));
                            $iret2 = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `mean_rating` = %s WHERE `id` = %s', '', $photo['id']));
                        }
                    }
                    if ($photos && $iret1 !== false && $iret2 !== false) {
                        echo '||97||' . __('<b>Ratings cleared</b>', 'wp-photo-album-plus') . '||' . __('No ratings for this photo.', 'wp-photo-album-plus');
                    } elseif ($photos) {
                        echo '||1||' . __('An error occurred while clearing ratings', 'wp-photo-album-plus');
                    } else {
                        echo '||97||' . __('<b>No photos in this album</b>', 'wp-photo-album-plus') . '||' . __('No ratings for this photo.', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'set_deftags':
                    // to be changed for large albums
                    $photos = $wpdb->get_results($wpdb->prepare('SELECT * FROM `' . WPPA_PHOTOS . '` WHERE `album` = %s', $album), ARRAY_A);
                    $deftag = $wpdb->get_var($wpdb->prepare('SELECT `default_tags` FROM `' . WPPA_ALBUMS . '` WHERE `id` = %s', $album));
                    if (is_array($photos)) {
                        foreach ($photos as $photo) {
                            $tags = wppa_sanitize_tags(wppa_filter_iptc(wppa_filter_exif($deftag, $photo['id']), $photo['id']));
                            $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `tags` = %s WHERE `id` = %s', $tags, $photo['id']));
                            wppa_index_update('photo', $photo['id']);
                        }
                    }
                    if ($photos && $iret !== false) {
                        echo '||97||' . __('<b>Tags set to defaults</b> (reload)', 'wp-photo-album-plus');
                    } elseif ($photos) {
                        echo '||1||' . __('An error occurred while setting tags', 'wp-photo-album-plus');
                    } else {
                        echo '||97||' . __('<b>No photos in this album</b>', 'wp-photo-album-plus');
                    }
                    wppa_clear_taglist();
                    wppa_exit();
                    break;
                case 'add_deftags':
                    $photos = $wpdb->get_results($wpdb->prepare('SELECT * FROM `' . WPPA_PHOTOS . '` WHERE `album` = %s', $album), ARRAY_A);
                    $deftag = $wpdb->get_var($wpdb->prepare('SELECT `default_tags` FROM `' . WPPA_ALBUMS . '` WHERE `id` = %s', $album));
                    if (is_array($photos)) {
                        foreach ($photos as $photo) {
                            $tags = wppa_sanitize_tags(wppa_filter_iptc(wppa_filter_exif($photo['tags'] . ',' . $deftag, $photo['id']), $photo['id']));
                            $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `tags` = %s WHERE `id` = %s', $tags, $photo['id']));
                            wppa_index_update('photo', $photo['id']);
                        }
                    }
                    if ($photos && $iret !== false) {
                        echo '||97||' . __('<b>Tags added width defaults</b> (reload)', 'wp-photo-album-plus');
                    } elseif ($photos) {
                        echo '||1||' . __('An error occurred while adding tags', 'wp-photo-album-plus');
                    } else {
                        echo '||97||' . __('<b>No photos in this album</b>', 'wp-photo-album-plus');
                    }
                    wppa_clear_taglist();
                    wppa_exit();
                    break;
                case 'name':
                    $value = trim(strip_tags($value));
                    if (!wppa_sanitize_file_name($value)) {
                        // Empty album name is not allowed
                        $value = 'Album-#' . $album;
                        echo '||5||' . sprintf(__('Album name may not be empty.<br />Reset to <b>%s</b>', 'wp-photo-album-plus'), $value);
                    }
                    $itemname = __('Name', 'wp-photo-album-plus');
                    break;
                case 'description':
                    $itemname = __('Description', 'wp-photo-album-plus');
                    if (wppa_switch('check_balance')) {
                        $value = str_replace(array('<br/>', '<br>'), '<br />', $value);
                        if (balanceTags($value, true) != $value) {
                            echo '||3||' . __('Unbalanced tags in album description!', 'wp-photo-album-plus');
                            wppa_exit();
                        }
                    }
                    $value = trim($value);
                    break;
                case 'a_order':
                    $itemname = __('Album order #', 'wp-photo-album-plus');
                    break;
                case 'main_photo':
                    $itemname = __('Cover photo', 'wp-photo-album-plus');
                    break;
                case 'a_parent':
                    $itemname = __('Parent album', 'wp-photo-album-plus');
                    wppa_flush_treecounts($album);
                    // Myself and my parents
                    wppa_flush_treecounts($value);
                    // My new parent
                    break;
                case 'p_order_by':
                    $itemname = __('Photo order', 'wp-photo-album-plus');
                    break;
                case 'alt_thumbsize':
                    $itemname = __('Use Alt thumbsize', 'wp-photo-album-plus');
                    break;
                case 'cover_type':
                    $itemname = __('Cover Type', 'wp-photo-album-plus');
                    break;
                case 'cover_linktype':
                    $itemname = __('Link type', 'wp-photo-album-plus');
                    break;
                case 'cover_linkpage':
                    $itemname = __('Link to', 'wp-photo-album-plus');
                    break;
                case 'owner':
                    $itemname = __('Owner', 'wp-photo-album-plus');
                    if ($value != '--- public ---' && !get_user_by('login', $value)) {
                        echo '||4||' . sprintf(__('User %s does not exist', 'wp-photo-album-plus'), $value);
                        wppa_exit();
                    }
                    break;
                case 'upload_limit_count':
                    wppa_ajax_check_range($value, false, '0', false, __('Upload limit count', 'wp-photo-album-plus'));
                    if (wppa('error')) {
                        wppa_exit();
                    }
                    $oldval = $wpdb->get_var($wpdb->prepare('SELECT `upload_limit` FROM ' . WPPA_ALBUMS . ' WHERE `id` = %s', $album));
                    $temp = explode('/', $oldval);
                    $value = $value . '/' . $temp[1];
                    $item = 'upload_limit';
                    $itemname = __('Upload limit count', 'wp-photo-album-plus');
                    break;
                case 'upload_limit_time':
                    $oldval = $wpdb->get_var($wpdb->prepare('SELECT `upload_limit` FROM ' . WPPA_ALBUMS . ' WHERE `id` = %s', $album));
                    $temp = explode('/', $oldval);
                    $value = $temp[0] . '/' . $value;
                    $item = 'upload_limit';
                    $itemname = __('Upload limit time', 'wp-photo-album-plus');
                    break;
                case 'default_tags':
                    $value = wppa_sanitize_tags($value, false, true);
                    $itemname = __('Default tags', 'wp-photo-album-plus');
                    break;
                case 'cats':
                    $value = wppa_sanitize_cats($value);
                    wppa_clear_catlist();
                    $itemname = __('Categories', 'wp-photo-album-plus');
                    break;
                case 'suba_order_by':
                    $itemname = __('Sub albums sort order', 'wp-photo-album-plus');
                    break;
                case 'year':
                case 'month':
                case 'day':
                case 'hour':
                case 'min':
                    $itemname = __('Schedule date/time', 'wp-photo-album-plus');
                    $scheduledtm = $wpdb->get_var($wpdb->prepare("SELECT `scheduledtm` FROM`" . WPPA_ALBUMS . "` WHERE `id` = %s", $album));
                    if (!$scheduledtm) {
                        $scheduledtm = wppa_get_default_scheduledtm();
                    }
                    $temp = explode(',', $scheduledtm);
                    if ($item == 'year') {
                        $temp[0] = $value;
                    }
                    if ($item == 'month') {
                        $temp[1] = $value;
                    }
                    if ($item == 'day') {
                        $temp[2] = $value;
                    }
                    if ($item == 'hour') {
                        $temp[3] = $value;
                    }
                    if ($item == 'min') {
                        $temp[4] = $value;
                    }
                    $scheduledtm = implode(',', $temp);
                    wppa_update_album(array('id' => $album, 'scheduledtm' => $scheduledtm));
                    echo '||0||' . sprintf(__('<b>%s</b> of album %s updated', 'wp-photo-album-plus'), $itemname, $album);
                    wppa_exit();
                    break;
                case 'setallscheduled':
                    $scheduledtm = $wpdb->get_var($wpdb->prepare("SELECT `scheduledtm` FROM `" . WPPA_ALBUMS . "` WHERE `id` = %s", $album));
                    if ($scheduledtm) {
                        $iret = $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `status` = 'scheduled', `scheduledtm` = %s WHERE `album` = %s", $scheduledtm, $album));
                        echo '||0||' . __('All photos set to scheduled per date', 'wp-photo-album-plus') . ' ( ' . $iret . ' ) ' . wppa_format_scheduledtm($scheduledtm);
                    }
                    wppa_exit();
                    break;
                default:
                    $itemname = $item;
            }
            $query = $wpdb->prepare('UPDATE ' . WPPA_ALBUMS . ' SET `' . $item . '` = %s WHERE `id` = %s', $value, $album);
            $iret = $wpdb->query($query);
            if ($iret !== false) {
                if ($item == 'name' || $item == 'description' || $item == 'cats') {
                    wppa_index_update('album', $album);
                }
                if ($item == 'name') {
                    wppa_create_pl_htaccess();
                }
                echo '||0||' . sprintf(__('<b>%s</b> of album %s updated', 'wp-photo-album-plus'), $itemname, $album);
                if ($item == 'upload_limit') {
                    echo '||';
                    $a = wppa_allow_uploads($album);
                    if (!$a) {
                        echo 'full';
                    } else {
                        echo 'notfull||' . $a;
                    }
                }
            } else {
                echo '||2||' . sprintf(__('An error occurred while trying to update <b>%s</b> of album %s', 'wp-photo-album-plus'), $itemname, $album);
                echo '<br>' . __('Press CTRL+F5 and try again.', 'wp-photo-album-plus');
            }
            wppa_clear_cache();
            wppa_exit();
            break;
        case 'update-comment-status':
            $photo = $_REQUEST['wppa-photo-id'];
            $nonce = $_REQUEST['wppa-nonce'];
            $comid = $_REQUEST['wppa-comment-id'];
            $comstat = $_REQUEST['wppa-comment-status'];
            // Check validity
            if (!wp_verify_nonce($nonce, 'wppa_nonce_' . $photo)) {
                echo '||0||' . __('You do not have the rights to update comment status', 'wp-photo-album-plus') . $nonce;
                wppa_exit();
                // Nonce check failed
            }
            //			if ( wppa_switch( 'search_comments' ) ) wppa_index_remove( 'photo', $photo );
            $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_COMMENTS . '` SET `status` = %s WHERE `id` = %s', $comstat, $comid));
            if (wppa_switch('search_comments')) {
                wppa_index_update('photo', $photo);
            }
            if ($iret !== false) {
                echo '||0||' . sprintf(__('Status of comment #%s updated', 'wp-photo-album-plus'), $comid);
            } else {
                echo '||1||' . sprintf(__('Error updating status comment #%s', 'wp-photo-album-plus'), $comid);
            }
            wppa_exit();
            break;
        case 'watermark-photo':
            $photo = $_REQUEST['photo-id'];
            $nonce = $_REQUEST['wppa-nonce'];
            // Check validity
            if (!wp_verify_nonce($nonce, 'wppa_nonce_' . $photo)) {
                echo '||1||' . __('You do not have the rights to change photos', 'wp-photo-album-plus');
                wppa_exit();
                // Nonce check failed
            }
            wppa_cache_thumb($photo);
            if (wppa_add_watermark($photo)) {
                if (wppa_switch('watermark_thumbs')) {
                    wppa_create_thumbnail($photo);
                    // create new thumb
                }
                echo '||0||' . __('Watermark applied', 'wp-photo-album-plus');
                wppa_exit();
            } else {
                echo '||1||' . __('An error occured while trying to apply a watermark', 'wp-photo-album-plus');
                wppa_exit();
            }
        case 'update-photo':
            $photo = $_REQUEST['photo-id'];
            $nonce = $_REQUEST['wppa-nonce'];
            $item = $_REQUEST['item'];
            $value = isset($_REQUEST['value']) ? $_REQUEST['value'] : '';
            $value = wppa_decode($value);
            // Check validity
            if (!wp_verify_nonce($nonce, 'wppa_nonce_' . $photo)) {
                echo '||0||' . __('You do not have the rights to update photo information', 'wp-photo-album-plus');
                wppa_exit();
                // Nonce check failed
            }
            if (substr($item, 0, 20) == 'wppa_watermark_file_' || substr($item, 0, 19) == 'wppa_watermark_pos_') {
                wppa_update_option($item, $value);
                echo '||0||' . sprintf(__('%s updated to %s.', 'wp-photo-album-plus'), $item, $value);
                wppa_exit();
            }
            switch ($item) {
                case 'exifdtm':
                    $format = '0000:00:00 00:00:00';
                    $err = '0';
                    // Length ok?
                    if (strlen($value) != 19) {
                        $err = '1';
                    }
                    // Check on digits, colons and space
                    for ($i = 0; $i < 19; $i++) {
                        $d = substr($value, $i, 1);
                        $f = substr($format, $i, 1);
                        switch ($f) {
                            case '0':
                                if (!in_array($d, array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))) {
                                    $err = '2';
                                }
                                break;
                            case ':':
                            case ' ':
                                if ($d != $f) {
                                    $err = '3';
                                }
                                break;
                        }
                    }
                    // Check on values if format correct, report first error only
                    if (!$err) {
                        $temp = explode(':', str_replace(' ', ':', $value));
                        if ($temp['0'] < '1970') {
                            $err = '11';
                        }
                        // Before UNIX epoch
                        if (!$err && $temp['0'] > date('Y')) {
                            $err = '12';
                        }
                        // Future
                        if (!$err && $temp['1'] < '1') {
                            $err = '13';
                        }
                        // Before january
                        if (!$err && $temp['1'] > '12') {
                            $err = '14';
                        }
                        // After december
                        if (!$err && $temp['2'] < '1') {
                            $err = '15';
                        }
                        // Before first of month
                        if (!$err && $temp['2'] > '31') {
                            $err = '17';
                        }
                        // After 31st ( forget about feb and months with 30 days )
                        if (!$err && $temp['3'] < '1') {
                            $err = '18';
                        }
                        // Before first hour
                        if (!$err && $temp['3'] > '24') {
                            $err = '19';
                        }
                        // Hour > 24
                        if (!$err && $temp['4'] < '1') {
                            $err = '20';
                        }
                        // Min < 1
                        if (!$err && $temp['4'] > '59') {
                            $err = '21';
                        }
                        // Min > 59
                        if (!$err && $temp['5'] < '1') {
                            $err = '22';
                        }
                        // Sec < 1
                        if (!$err && $temp['5'] > '59') {
                            $err = '23';
                        }
                        // Sec > 59
                    }
                    if ($err) {
                        echo '||1||' . sprintf(__('Format error %s. Must be yyyy:mm:dd hh:mm:ss', 'wp-photo-album-plus'), $err);
                    } else {
                        wppa_update_photo(array('id' => $photo, 'exifdtm' => $value));
                        echo '||0||' . __('Exif date/time updated', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'lat':
                    if (!is_numeric($value) || $value < '-90.0' || $value > '90.0') {
                        echo '||1||' . __('Enter a value > -90 and < 90', 'wp-photo-album-plus');
                        wppa_exit();
                    }
                    $photodata = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . WPPA_PHOTOS . ' WHERE `id` = %s', $photo), ARRAY_A);
                    $geo = $photodata['location'] ? $photodata['location'] : '///';
                    $geo = explode('/', $geo);
                    $geo = wppa_format_geo($value, $geo['3']);
                    $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `location` = %s WHERE `id` = %s', $geo, $photo));
                    if ($iret) {
                        echo '||0||' . __('Lattitude updated', 'wp-photo-album-plus');
                    } else {
                        echo '||1||' . __('Could not update lattitude', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'lon':
                    if (!is_numeric($value) || $value < '-180.0' || $value > '180.0') {
                        echo '||1||' . __('Enter a value > -180 and < 180', 'wp-photo-album-plus');
                        wppa_exit();
                    }
                    $photodata = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . WPPA_PHOTOS . ' WHERE `id` = %s', $photo), ARRAY_A);
                    $geo = $photodata['location'] ? $photodata['location'] : '///';
                    $geo = explode('/', $geo);
                    $geo = wppa_format_geo($geo['2'], $value);
                    $iret = $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_PHOTOS . '` SET `location` = %s WHERE `id` = %s', $geo, $photo));
                    if ($iret) {
                        echo '||0||' . __('Longitude updated', 'wp-photo-album-plus');
                    } else {
                        echo '||1||' . __('Could not update longitude', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'remake':
                    if (wppa_remake_files('', $photo)) {
                        wppa_bump_photo_rev();
                        wppa_bump_thumb_rev();
                        echo '||0||' . __('Photo files remade', 'wp-photo-album-plus');
                    } else {
                        echo '||2||' . __('Could not remake files', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'remakethumb':
                    if (wppa_create_thumbnail($photo)) {
                        echo '||0||' . __('Thumbnail remade', 'wp-photo-album-plus');
                    } else {
                        echo '||0||' . __('Could not remake thumbnail', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'rotright':
                case 'rot180':
                case 'rotleft':
                    switch ($item) {
                        case 'rotleft':
                            $angle = '90';
                            $dir = __('left', 'wp-photo-album-plus');
                            break;
                        case 'rot180':
                            $angle = '180';
                            $dir = __('180&deg;', 'wp-photo-album-plus');
                            break;
                        case 'rotright':
                            $angle = '270';
                            $dir = __('right', 'wp-photo-album-plus');
                            break;
                    }
                    wppa('error', wppa_rotate($photo, $angle));
                    if (!wppa('error')) {
                        wppa_update_modified($photo);
                        wppa_bump_photo_rev();
                        wppa_bump_thumb_rev();
                        echo '||0||' . sprintf(__('Photo %s rotated %s', 'wp-photo-album-plus'), $photo, $dir);
                    } else {
                        echo '||' . wppa('error') . '||' . sprintf(__('An error occurred while trying to rotate photo %s', 'wp-photo-album-plus'), $photo);
                    }
                    wppa_exit();
                    break;
                case 'moveto':
                    $photodata = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . WPPA_PHOTOS . ' WHERE `id` = %s', $photo), ARRAY_A);
                    if (wppa_switch('void_dups')) {
                        // Check for already exists
                        $exists = wppa_file_is_in_album($photodata['filename'], $value);
                        if ($exists) {
                            // Already exists
                            echo '||3||' . sprintf(__('A photo with filename %s already exists in album %s.', 'wp-photo-album-plus'), $photodata['filename'], $value);
                            wppa_exit();
                            break;
                        }
                    }
                    wppa_flush_treecounts($photodata['album']);
                    // Current album
                    wppa_flush_treecounts($value);
                    // New album
                    $iret = $wpdb->query($wpdb->prepare('UPDATE ' . WPPA_PHOTOS . ' SET `album` = %s WHERE `id` = %s', $value, $photo));
                    if ($iret !== false) {
                        wppa_move_source($photodata['filename'], $photodata['album'], $value);
                        echo '||99||' . sprintf(__('Photo %s has been moved to album %s (%s)', 'wp-photo-album-plus'), $photo, wppa_get_album_name($value), $value);
                    } else {
                        echo '||3||' . sprintf(__('An error occurred while trying to move photo %s', 'wp-photo-album-plus'), $photo);
                    }
                    wppa_exit();
                    break;
                case 'copyto':
                    $photodata = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . WPPA_PHOTOS . ' WHERE `id` = %s', $photo), ARRAY_A);
                    if (wppa_switch('void_dups')) {
                        // Check for already exists
                        $exists = wppa_file_is_in_album($photodata['filename'], $value);
                        if ($exists) {
                            // Already exists
                            echo '||4||' . sprintf(__('A photo with filename %s already exists in album %s.', 'wp-photo-album-plus'), $photodata['filename'], $value);
                            wppa_exit();
                            break;
                        }
                    }
                    wppa('error', wppa_copy_photo($photo, $value));
                    wppa_flush_treecounts($value);
                    // New album
                    if (!wppa('error')) {
                        echo '||0||' . sprintf(__('Photo %s copied to album %s (%s)', 'wp-photo-album-plus'), $photo, wppa_get_album_name($value), $value);
                    } else {
                        echo '||4||' . sprintf(__('An error occurred while trying to copy photo %s', 'wp-photo-album-plus'), $photo);
                        echo '<br>' . __('Press CTRL+F5 and try again.', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'status':
                    if (!current_user_can('wppa_moderate') && !current_user_can('wppa_admin')) {
                        die('Security check failure #78');
                    }
                    wppa_flush_treecounts(wppa_get_photo_item($photo, 'album'));
                    // $wpdb->get_var( $wpdb->prepare( "SELECT `album` FROM `".WPPA_PHOTOS."` WHERE `id` = %s", $photo ) ) );
                // $wpdb->get_var( $wpdb->prepare( "SELECT `album` FROM `".WPPA_PHOTOS."` WHERE `id` = %s", $photo ) ) );
                case 'owner':
                case 'name':
                case 'description':
                case 'p_order':
                case 'linkurl':
                case 'linktitle':
                case 'linktarget':
                case 'tags':
                case 'alt':
                case 'videox':
                case 'videoy':
                    switch ($item) {
                        case 'name':
                            $value = strip_tags($value);
                            $itemname = __('Name', 'wp-photo-album-plus');
                            break;
                        case 'description':
                            $itemname = __('Description', 'wp-photo-album-plus');
                            if (wppa_switch('check_balance')) {
                                $value = str_replace(array('<br/>', '<br>'), '<br />', $value);
                                if (balanceTags($value, true) != $value) {
                                    echo '||3||' . __('Unbalanced tags in photo description!', 'wp-photo-album-plus');
                                    wppa_exit();
                                }
                            }
                            break;
                        case 'p_order':
                            $itemname = __('Photo order #', 'wp-photo-album-plus');
                            break;
                        case 'owner':
                            $usr = get_user_by('login', $value);
                            if (!$usr) {
                                echo '||4||' . sprintf(__('User %s does not exists', 'wp-photo-album-plus'), $value);
                                wppa_exit();
                            }
                            $value = $usr->user_login;
                            // Correct possible case mismatch
                            wppa_flush_upldr_cache('photoid', $photo);
                            // Current owner
                            wppa_flush_upldr_cache('username', $value);
                            // New owner
                            $itemname = __('Owner', 'wp-photo-album-plus');
                            break;
                        case 'linkurl':
                            $itemname = __('Link url', 'wp-photo-album-plus');
                            break;
                        case 'linktitle':
                            $itemname = __('Link title', 'wp-photo-album-plus');
                            break;
                        case 'linktarget':
                            $itemname = __('Link target', 'wp-photo-album-plus');
                            break;
                        case 'tags':
                            $value = wppa_sanitize_tags($value, false, true);
                            $value = wppa_sanitize_tags(wppa_filter_iptc(wppa_filter_exif($value, $photo), $photo));
                            wppa_clear_taglist();
                            $itemname = __('Photo Tags', 'wp-photo-album-plus');
                            break;
                        case 'status':
                            wppa_clear_taglist();
                            wppa_flush_upldr_cache('photoid', $photo);
                            $itemname = __('Status', 'wp-photo-album-plus');
                            break;
                        case 'alt':
                            $itemname = __('HTML Alt', 'wp-photo-album-plus');
                            $value = strip_tags(stripslashes($value));
                            break;
                        case 'videox':
                            $itemname = __('Video width', 'wp-photo-album-plus');
                            if (!wppa_is_int($value) || $value < '0') {
                                echo '||3||' . __('Please enter an integer value >= 0', 'wp-photo-album-plus');
                                wppa_exit();
                            }
                            break;
                        case 'videoy':
                            $itemname = __('Video height', 'wp-photo-album-plus');
                            if (!wppa_is_int($value) || $value < '0') {
                                echo '||3||' . __('Please enter an integer value >= 0', 'wp-photo-album-plus');
                                wppa_exit();
                            }
                            break;
                        default:
                            $itemname = $item;
                    }
                    //				if ( $item == 'name' || $item == 'description' || $item == 'tags' ) wppa_index_quick_remove( 'photo', $photo );
                    $iret = $wpdb->query($wpdb->prepare('UPDATE ' . WPPA_PHOTOS . ' SET `' . $item . '` = %s WHERE `id` = %s', $value, $photo));
                    if ($item == 'name' || $item == 'description' || $item == 'tags') {
                        wppa_index_update('photo', $photo);
                    }
                    if ($item == 'status' && $value != 'scheduled') {
                        wppa_update_photo(array('id' => $photo, 'scheduledtm' => ''));
                    }
                    if ($item == 'status') {
                        wppa_flush_treecounts(wppa_get_photo_item($photo, 'album'));
                    }
                    if ($iret !== false) {
                        wppa_update_modified($photo);
                        if (wppa_is_video($photo)) {
                            echo '||0||' . sprintf(__('<b>%s</b> of video %s updated', 'wp-photo-album-plus'), $itemname, $photo);
                        } else {
                            echo '||0||' . sprintf(__('<b>%s</b> of photo %s updated', 'wp-photo-album-plus'), $itemname, $photo);
                        }
                    } else {
                        echo '||2||' . sprintf(__('An error occurred while trying to update <b>%s</b> of photo %s', 'wp-photo-album-plus'), $itemname, $photo);
                        echo '<br>' . __('Press CTRL+F5 and try again.', 'wp-photo-album-plus');
                        wppa_exit();
                    }
                    break;
                case 'year':
                case 'month':
                case 'day':
                case 'hour':
                case 'min':
                    $itemname = __('Schedule date/time', 'wp-photo-album-plus');
                    $scheduledtm = $wpdb->get_var($wpdb->prepare("SELECT `scheduledtm` FROM`" . WPPA_PHOTOS . "` WHERE `id` = %s", $photo));
                    if (!$scheduledtm) {
                        $scheduledtm = wppa_get_default_scheduledtm();
                    }
                    $temp = explode(',', $scheduledtm);
                    if ($item == 'year') {
                        $temp[0] = $value;
                    }
                    if ($item == 'month') {
                        $temp[1] = $value;
                    }
                    if ($item == 'day') {
                        $temp[2] = $value;
                    }
                    if ($item == 'hour') {
                        $temp[3] = $value;
                    }
                    if ($item == 'min') {
                        $temp[4] = $value;
                    }
                    $scheduledtm = implode(',', $temp);
                    wppa_update_photo(array('id' => $photo, 'scheduledtm' => $scheduledtm, 'status' => 'scheduled'));
                    wppa_flush_treecounts($wpdb->get_var($wpdb->prepare("SELECT `album` FROM `" . WPPA_PHOTOS . "` WHERE `id` = %s", $photo)));
                    wppa_flush_upldr_cache('photoid', $photo);
                    if (wppa_is_video($photo)) {
                        echo '||0||' . sprintf(__('<b>%s</b> of video %s updated', 'wp-photo-album-plus'), $itemname, $photo);
                    } else {
                        echo '||0||' . sprintf(__('<b>%s</b> of photo %s updated', 'wp-photo-album-plus'), $itemname, $photo);
                    }
                    break;
                case 'custom_0':
                case 'custom_1':
                case 'custom_2':
                case 'custom_3':
                case 'custom_4':
                case 'custom_5':
                case 'custom_6':
                case 'custom_7':
                case 'custom_8':
                case 'custom_9':
                    $index = substr($item, -1);
                    $custom = wppa_get_photo_item($photo, 'custom');
                    if ($custom) {
                        $custom_data = unserialize($custom);
                    } else {
                        $custom_data = array('', '', '', '', '', '', '', '', '', '');
                    }
                    $custom_data[$index] = strip_tags($value);
                    $custom = serialize($custom_data);
                    wppa_update_photo(array('id' => $photo, 'custom' => $custom, 'modified' => time()));
                    wppa_index_update('photo', $photo);
                    echo '||0||' . sprintf(__('<b>Custom field %s</b> of photo %s updated', 'wp-photo-album-plus'), wppa_opt('custom_caption_' . $index), $photo);
                    break;
                case 'file':
                    // Check on upload error
                    if ($_FILES['photo']['error']) {
                        echo '||' . $_FILES['photo']['error'] . '||' . __('<b>Error during upload.</b>', 'wp-photo-album-plus');
                        wppa_exit();
                    }
                    // Save new source
                    wppa_save_source($_FILES['photo']['tmp_name'], wppa_get_photo_item($photo, 'filename'), wppa_get_photo_item($photo, 'album'));
                    // Make the files
                    $bret = wppa_make_the_photo_files($_FILES['photo']['tmp_name'], $photo, strtolower(wppa_get_ext($_FILES['photo']['name'])));
                    if ($bret) {
                        // Update timestamps and sizes
                        $alb = wppa_get_photo_item($photo, 'album');
                        wppa_update_album(array('id' => $alb, 'modified' => time()));
                        wppa_update_photo(array('id' => $photo, 'modified' => time(), 'thumbx' => '0', 'thumby' => '0', 'photox' => '0', 'photoy' => '0'));
                        // Report success
                        echo '||0||' . __('Photo files updated.', 'wp-photo-album-plus');
                    } else {
                        // Report fail
                        echo '||1||' . __('Could not update files.', 'wp-photo-album-plus');
                    }
                    wppa_exit();
                    break;
                case 'stereo':
                    $t = microtime(true);
                    wppa_update_photo(array('id' => $photo, 'stereo' => $value));
                    wppa_create_stereo_images($photo);
                    wppa_create_thumbnail($photo);
                    $t = microtime(true) - $t;
                    echo '||0||' . sprintf(__('Stereo mode updated in %d milliseconds', 'wp-photo-album-plus'), floor($t * 1000));
                    wppa_exit();
                    break;
                default:
                    echo '||98||This update action is not implemented yet( ' . $item . ' )';
                    wppa_exit();
            }
            wppa_clear_cache();
            break;
            // The wppa-settings page calls ajax with $wppa_action == 'update-option';
        // The wppa-settings page calls ajax with $wppa_action == 'update-option';
        case 'update-option':
            // Verify that we are legally here
            $nonce = $_REQUEST['wppa-nonce'];
            if (!wp_verify_nonce($nonce, 'wppa-nonce')) {
                echo '||1||' . __('You do not have the rights to update settings', 'wp-photo-album-plus');
                wppa_exit();
                // Nonce check failed
            }
            // Initialize
            $old_minisize = wppa_get_minisize();
            // Remember for later, maybe we do something that requires regen
            $option = $_REQUEST['wppa-option'];
            // The option to be processed
            $value = isset($_REQUEST['value']) ? wppa_decode($_REQUEST['value']) : '';
            // The new value, may also contain & # and +
            $value = stripslashes($value);
            $value = trim($value);
            // Remaove surrounding spaces
            $alert = '';
            // Init the return string data
            wppa('error', '0');
            //
            $title = '';
            //
            // If it is a font family, change all double quotes into single quotes as this destroys much more than you would like
            if (strpos($option, 'wppa_fontfamily_') !== false) {
                $value = str_replace('"', "'", $value);
            }
            $option = wppa_decode($option);
            // Dispatch on option
            if (substr($option, 0, 16) == 'wppa_iptc_label_') {
                $tag = substr($option, 16);
                $q = $wpdb->prepare("UPDATE `" . WPPA_IPTC . "` SET `description`=%s WHERE `tag`=%s AND `photo`='0'", $value, $tag);
                $bret = $wpdb->query($q);
                // Produce the response text
                if ($bret) {
                    $output = '||0||' . $tag . ' updated to ' . $value . '||';
                } else {
                    $output = '||1||Failed to update ' . $tag . '||';
                }
                echo $output;
                wppa_exit();
            } elseif (substr($option, 0, 17) == 'wppa_iptc_status_') {
                $tag = substr($option, 17);
                $q = $wpdb->prepare("UPDATE `" . WPPA_IPTC . "` SET `status`=%s WHERE `tag`=%s AND `photo`='0'", $value, $tag);
                $bret = $wpdb->query($q);
                // Produce the response text
                if ($bret) {
                    $output = '||0||' . $tag . ' updated to ' . $value . '||';
                } else {
                    $output = '||1||Failed to update ' . $tag . '||';
                }
                echo $output;
                wppa_exit();
            } elseif (substr($option, 0, 16) == 'wppa_exif_label_') {
                $tag = substr($option, 16);
                $q = $wpdb->prepare("UPDATE `" . WPPA_EXIF . "` SET `description`=%s WHERE `tag`=%s AND `photo`='0'", $value, $tag);
                $bret = $wpdb->query($q);
                // Produce the response text
                if ($bret) {
                    $output = '||0||' . $tag . ' updated to ' . $value . '||';
                } else {
                    $output = '||1||Failed to update ' . $tag . '||';
                }
                echo $output;
                wppa_exit();
            } elseif (substr($option, 0, 17) == 'wppa_exif_status_') {
                $tag = substr($option, 17);
                $q = $wpdb->prepare("UPDATE `" . WPPA_EXIF . "` SET `status`=%s WHERE `tag`=%s AND `photo`='0'", $value, $tag);
                $bret = $wpdb->query($q);
                // Produce the response text
                if ($bret) {
                    $output = '||0||' . $tag . ' updated to ' . $value . '||';
                } else {
                    $output = '||1||Failed to update ' . $tag . '||';
                }
                echo $output;
                wppa_exit();
            } elseif (substr($option, 0, 5) == 'caps-') {
                // Is capability setting
                global $wp_roles;
                //$R = new WP_Roles;
                $setting = explode('-', $option);
                if ($value == 'yes') {
                    $wp_roles->add_cap($setting[2], $setting[1]);
                    echo '||0||' . __('Capability granted', 'wp-photo-album-plus') . '||';
                    wppa_exit();
                } elseif ($value == 'no') {
                    $wp_roles->remove_cap($setting[2], $setting[1]);
                    echo '||0||' . __('Capability withdrawn', 'wp-photo-album-plus') . '||';
                    wppa_exit();
                } else {
                    echo '||1||Invalid value: ' . $value . '||';
                    wppa_exit();
                }
            } else {
                switch ($option) {
                    case 'wppa_colwidth':
                        //	 ??	  fixed   low	high	title
                        wppa_ajax_check_range($value, 'auto', '100', false, __('Column width.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_initial_colwidth':
                        wppa_ajax_check_range($value, false, '100', false, __('Initial width.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_fullsize':
                        wppa_ajax_check_range($value, false, '100', false, __('Full size.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_maxheight':
                        wppa_ajax_check_range($value, false, '100', false, __('Max height.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_thumbsize':
                        wppa_ajax_check_range($value, false, '50', false, __('Thumbnail size.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_tf_width':
                        wppa_ajax_check_range($value, false, '50', false, __('Thumbnail frame width', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_tf_height':
                        wppa_ajax_check_range($value, false, '50', false, __('Thumbnail frame height', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_tn_margin':
                        wppa_ajax_check_range($value, false, '0', false, __('Thumbnail Spacing', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_min_thumbs':
                        wppa_ajax_check_range($value, false, '0', false, __('Photocount treshold.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_thumb_page_size':
                        wppa_ajax_check_range($value, false, '0', false, __('Thumb page size.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_smallsize':
                        wppa_ajax_check_range($value, false, '50', false, __('Cover photo size.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_album_page_size':
                        wppa_ajax_check_range($value, false, '0', false, __('Album page size.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_topten_count':
                        wppa_ajax_check_range($value, false, '2', false, __('Number of TopTen photos', 'wp-photo-album-plus'), '40');
                        break;
                    case 'wppa_topten_size':
                        wppa_ajax_check_range($value, false, '32', false, __('Widget image thumbnail size', 'wp-photo-album-plus'), wppa_get_minisize());
                        break;
                    case 'wppa_max_cover_width':
                        wppa_ajax_check_range($value, false, '150', false, __('Max Cover width', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_text_frame_height':
                        wppa_ajax_check_range($value, false, '0', false, __('Minimal description height', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_cover_minheight':
                        wppa_ajax_check_range($value, false, '0', false, __('Minimal cover height', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_head_and_text_frame_height':
                        wppa_ajax_check_range($value, false, '0', false, __('Minimal text frame height', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_bwidth':
                        wppa_ajax_check_range($value, '', '0', false, __('Border width', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_bradius':
                        wppa_ajax_check_range($value, '', '0', false, __('Border radius', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_box_spacing':
                        wppa_ajax_check_range($value, '', '-20', '100', __('Box spacing', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_popupsize':
                        $floor = wppa_opt('thumbsize');
                        $temp = wppa_opt('smallsize');
                        if ($temp > $floor) {
                            $floor = $temp;
                        }
                        wppa_ajax_check_range($value, false, $floor, wppa_opt('fullsize'), __('Popup size', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_fullimage_border_width':
                        wppa_ajax_check_range($value, '', '0', false, __('Fullsize border width', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_lightbox_bordersize':
                        wppa_ajax_check_range($value, false, '0', false, __('Lightbox Bordersize', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_ovl_border_width':
                        wppa_ajax_check_range($value, false, '0', '16', __('Lightbox Borderwidth', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_ovl_border_radius':
                        wppa_ajax_check_range($value, false, '0', '16', __('Lightbox Borderradius', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_comment_count':
                        wppa_ajax_check_range($value, false, '2', '40', __('Number of Comment widget entries', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_comment_size':
                        wppa_ajax_check_range($value, false, '32', wppa_get_minisize(), __('Comment Widget image thumbnail size', 'wp-photo-album-plus'), wppa_get_minisize());
                        break;
                    case 'wppa_thumb_opacity':
                        wppa_ajax_check_range($value, false, '0', '100', __('Opacity.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_cover_opacity':
                        wppa_ajax_check_range($value, false, '0', '100', __('Opacity.', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_star_opacity':
                        wppa_ajax_check_range($value, false, '0', '50', __('Opacity.', 'wp-photo-album-plus'));
                        break;
                        //				case 'wppa_filter_priority':
                        //					wppa_ajax_check_range( $value, false, wppa_opt( 'shortcode_priority' ), false, __( 'Filter priority' ,'wp-photo-album-plus' ) );
                        //					break;
                        //				case 'wppa_shortcode_priority':
                        //					wppa_ajax_check_range( $value, false, '0', wppa_opt( 'filter_priority' ) - '1', __( 'Shortcode_priority', 'wp-photo-album-plus' ) );
                        //					break;
                    //				case 'wppa_filter_priority':
                    //					wppa_ajax_check_range( $value, false, wppa_opt( 'shortcode_priority' ), false, __( 'Filter priority' ,'wp-photo-album-plus' ) );
                    //					break;
                    //				case 'wppa_shortcode_priority':
                    //					wppa_ajax_check_range( $value, false, '0', wppa_opt( 'filter_priority' ) - '1', __( 'Shortcode_priority', 'wp-photo-album-plus' ) );
                    //					break;
                    case 'wppa_gravatar_size':
                        wppa_ajax_check_range($value, false, '10', '256', __('Avatar size', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_watermark_opacity':
                        wppa_ajax_check_range($value, false, '0', '100', __('Watermark opacity', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_watermark_opacity_text':
                        wppa_ajax_check_range($value, false, '0', '100', __('Watermark opacity', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_ovl_txt_lines':
                        wppa_ajax_check_range($value, 'auto', '0', '24', __('Number of text lines', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_ovl_opacity':
                        wppa_ajax_check_range($value, false, '0', '100', __('Overlay opacity', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_upload_limit_count':
                        wppa_ajax_check_range($value, false, '0', false, __('Upload limit', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_dislike_mail_every':
                        wppa_ajax_check_range($value, false, '0', false, __('Notify inappropriate', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_dislike_set_pending':
                        wppa_ajax_check_range($value, false, '0', false, __('Dislike pending', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_dislike_delete':
                        wppa_ajax_check_range($value, false, '0', false, __('Dislike delete', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_max_execution_time':
                        wppa_ajax_check_range($value, false, '0', '900', __('Max execution time', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_cp_points_comment':
                    case 'wppa_cp_points_rating':
                    case 'wppa_cp_points_upload':
                        wppa_ajax_check_range($value, false, '0', false, __('Cube Points points', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_jpeg_quality':
                        wppa_ajax_check_range($value, false, '20', '100', __('JPG Image quality', 'wp-photo-album-plus'));
                        if (wppa_cdn('admin') == 'cloudinary' && !wppa('out')) {
                            wppa_delete_derived_from_cloudinary();
                        }
                        break;
                    case 'wppa_imgfact_count':
                        wppa_ajax_check_range($value, false, '1', '24', __('Number of coverphotos', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_dislike_value':
                        wppa_ajax_check_range($value, false, '-10', '0', __('Dislike value', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_slideshow_pagesize':
                        wppa_ajax_check_range($value, false, '0', false, __('Slideshow pagesize', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_pagelinks_max':
                        wppa_ajax_check_range($value, false, '0', false, __('Max Pagelinks', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_start_pause_symbol_size':
                        wppa_ajax_check_range($value, false, '0', false, __('Start/pause symbol size', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_start_pause_symbol_bradius':
                        wppa_ajax_check_range($value, false, '0', false, __('Start/pause symbol border radius', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_stop_symbol_size':
                        wppa_ajax_check_range($value, false, '0', false, __('Stop symbol size', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_stop_symbol_bradius':
                        wppa_ajax_check_range($value, false, '0', false, __('Stop symbol border radius', 'wp-photo-album-plus'));
                        break;
                    case 'wppa_rating_clear':
                        $iret1 = $wpdb->query('TRUNCATE TABLE ' . WPPA_RATING);
                        $iret2 = $wpdb->query('UPDATE ' . WPPA_PHOTOS . ' SET mean_rating="0", rating_count="0" WHERE id > -1');
                        if ($iret1 !== false && $iret2 !== false) {
                            delete_option('wppa_' . WPPA_RATING . '_lastkey');
                            $title = __('Ratings cleared', 'wp-photo-album-plus');
                        } else {
                            $title = __('Could not clear ratings', 'wp-photo-album-plus');
                            $alert = $title;
                            wppa('error', '1');
                        }
                        break;
                    case 'wppa_viewcount_clear':
                        $iret = $wpdb->query("UPDATE `" . WPPA_PHOTOS . "` SET `views` = '0'") && $wpdb->query("UPDATE `" . WPPA_ALBUMS . "` SET `views` = '0'");
                        if ($iret !== false) {
                            $title = __('Viewcounts cleared', 'wp-photo-album-plus');
                        } else {
                            $title = __('Could not clear viewcounts', 'wp-photo-album-plus');
                            $alert = $title;
                            wppa('error', '1');
                        }
                        break;
                    case 'wppa_iptc_clear':
                        $iret = $wpdb->query('TRUNCATE TABLE ' . WPPA_IPTC);
                        if ($iret !== false) {
                            delete_option('wppa_' . WPPA_IPTC . '_lastkey');
                            $title = __('IPTC data cleared', 'wp-photo-album-plus');
                            $alert = __('Refresh this page to clear table X', 'wp-photo-album-plus');
                            update_option('wppa_index_need_remake', 'yes');
                        } else {
                            $title = __('Could not clear IPTC data', 'wp-photo-album-plus');
                            $alert = $title;
                            wppa('error', '1');
                        }
                        break;
                    case 'wppa_exif_clear':
                        $iret = $wpdb->query('TRUNCATE TABLE ' . WPPA_EXIF);
                        if ($iret !== false) {
                            delete_option('wppa_' . WPPA_EXIF . '_lastkey');
                            $title = __('EXIF data cleared', 'wp-photo-album-plus');
                            $alert = __('Refresh this page to clear table XI', 'wp-photo-album-plus');
                            update_option('wppa_index_need_remake', 'yes');
                        } else {
                            $title = __('Could not clear EXIF data', 'wp-photo-album-plus');
                            $alert = $title;
                            wppa('error', '1');
                        }
                        break;
                    case 'wppa_recup':
                        $result = wppa_recuperate_iptc_exif();
                        echo '||0||' . __('Recuperation performed', 'wp-photo-album-plus') . '||' . $result;
                        wppa_exit();
                        break;
                    case 'wppa_bgcolor_thumbnail':
                        $value = trim(strtolower($value));
                        if (strlen($value) != '7' || substr($value, 0, 1) != '#') {
                            wppa('error', '1');
                        } else {
                            for ($i = 1; $i < 7; $i++) {
                                if (!in_array(substr($value, $i, 1), array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'))) {
                                    wppa('error', '1');
                                }
                            }
                        }
                        if (!wppa('error')) {
                            $old_minisize--;
                        } else {
                            $alert = __('Illegal format. Please enter a 6 digit hexadecimal color value. Example: #77bbff', 'wp-photo-album-plus');
                        }
                        break;
                    case 'wppa_thumb_aspect':
                        $old_minisize--;
                        // Trigger regen message
                        break;
                    case 'wppa_rating_max':
                        if ($value == '5' && wppa_opt('rating_max') == '10') {
                            $rats = $wpdb->get_results('SELECT `id`, `value` FROM `' . WPPA_RATING . '`', ARRAY_A);
                            if ($rats) {
                                foreach ($rats as $rat) {
                                    $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_RATING . '` SET `value` = %s WHERE `id` = %s', $rat['value'] / 2, $rat['id']));
                                }
                            }
                        }
                        if ($value == '10' && wppa_opt('rating_max') == '5') {
                            $rats = $wpdb->get_results('SELECT `id`, `value` FROM `' . WPPA_RATING . '`', ARRAY_A);
                            if ($rats) {
                                foreach ($rats as $rat) {
                                    $wpdb->query($wpdb->prepare('UPDATE `' . WPPA_RATING . '` SET `value` = %s WHERE `id` = %s', $rat['value'] * 2, $rat['id']));
                                }
                            }
                        }
                        update_option('wppa_rerate_status', 'Required');
                        $alert .= __('You just changed a setting that requires the recalculation of ratings.', 'wp-photo-album-plus');
                        $alert .= ' ' . __('Please run the appropriate action in Table VIII.', 'wp-photo-album-plus');
                        wppa_update_option($option, $value);
                        wppa('error', '0');
                        break;
                    case 'wppa_newphoto_description':
                        if (wppa_switch('check_balance') && balanceTags($value, true) != $value) {
                            $alert = __('Unbalanced tags in photo description!', 'wp-photo-album-plus');
                            wppa('error', '1');
                        } else {
                            wppa_update_option($option, $value);
                            wppa('error', '0');
                            $alert = '';
                            wppa_index_compute_skips();
                        }
                        break;
                    case 'wppa_keep_source':
                        $dir = wppa_opt('source_dir');
                        if (!is_dir($dir)) {
                            @mkdir($dir);
                        }
                        if (!is_dir($dir) || !is_writable($dir)) {
                            wppa('error', '1');
                            $alert = sprintf(__('Unable to create or write to %s', 'wp-photo-album-plus'), $dir);
                        }
                        break;
                    case 'wppa_source_dir':
                        $olddir = wppa_opt('source_dir');
                        $value = rtrim($value, '/');
                        if (strpos($value . '/', WPPA_UPLOAD_PATH . '/') !== false) {
                            wppa('error', '1');
                            $alert = sprintf(__('Source can not be inside the wppa folder.', 'wp-photo-album-plus'));
                        } else {
                            $dir = $value;
                            if (!is_dir($dir)) {
                                @mkdir($dir);
                            }
                            if (!is_dir($dir) || !is_writable($dir)) {
                                wppa('error', '1');
                                $alert = sprintf(__('Unable to create or write to %s', 'wp-photo-album-plus'), $dir);
                            } else {
                                @rmdir($olddir);
                                // try to remove when empty
                            }
                        }
                        break;
                    case 'wppa_newpag_content':
                        if (strpos($value, 'w#album') === false) {
                            $alert = __('The content must contain w#album', 'wp-photo-album-plus');
                            wppa('error', '1');
                        }
                        break;
                    case 'wppa_gpx_shortcode':
                        if (strpos($value, 'w#lat') === false || strpos($value, 'w#lon') === false) {
                            $alert = __('The content must contain w#lat and w#lon', 'wp-photo-album-plus');
                            wppa('error', '1');
                        }
                        break;
                    case 'wppa_i_responsive':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_colwidth', 'auto');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_colwidth', '640');
                        }
                        break;
                    case 'wppa_i_downsize':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_resize_on_upload', 'yes');
                            if (wppa_opt('resize_to') == '0') {
                                wppa_update_option('wppa_resize_to', '1024x768');
                            }
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_resize_on_upload', 'no');
                        }
                        break;
                    case 'wppa_i_source':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_keep_source_admin', 'yes');
                            wppa_update_option('wppa_keep_source_frontend', 'yes');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_keep_source_admin', 'no');
                            wppa_update_option('wppa_keep_source_frontend', 'no');
                        }
                        break;
                    case 'wppa_i_userupload':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_user_upload_on', 'yes');
                            wppa_update_option('wppa_user_upload_login', 'yes');
                            wppa_update_option('wppa_owner_only', 'yes');
                            wppa_update_option('wppa_upload_moderate', 'yes');
                            wppa_update_option('wppa_upload_edit', 'yes');
                            wppa_update_option('wppa_upload_notify', 'yes');
                            wppa_update_option('wppa_grant_an_album', 'yes');
                            $grantparent = wppa_opt('grant_parent');
                            if (!wppa_album_exists($grantparent)) {
                                $id = wppa_create_album_entry(array('name' => __('Members', 'wp-photo-album-plus'), 'description' => __('Parent of the member albums', 'wp-photo-album-plus'), 'a_parent' => '-1', 'upload_limit' => '0/0'));
                                if ($id) {
                                    wppa_index_add('album', $id);
                                    wppa_update_option('wppa_grant_parent', $id);
                                }
                                $my_post = array('post_title' => __('Members', 'wp-photo-album-plus'), 'post_content' => '[wppa type="content" album="' . $id . '"][/wppa]', 'post_status' => 'publish', 'post_type' => 'page');
                                $pagid = wp_insert_post($my_post);
                            }
                            wppa_update_option('wppa_alt_is_restricted', 'yes');
                            wppa_update_option('wppa_link_is_restricted', 'yes');
                            wppa_update_option('wppa_covertype_is_restricted', 'yes');
                            wppa_update_option('wppa_porder_restricted', 'yes');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_user_upload_on', 'no');
                        }
                        break;
                    case 'wppa_i_rating':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_rating_on', 'yes');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_rating_on', 'no');
                        }
                        break;
                    case 'wppa_i_comment':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_show_comments', 'yes');
                            wppa_update_option('wppa_comment_moderation', 'all');
                            wppa_update_option('wppa_comment_notify', 'admin');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_show_comments', 'no');
                        }
                        break;
                    case 'wppa_i_share':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_share_on', 'yes');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_share_on', 'no');
                        }
                        break;
                    case 'wppa_i_iptc':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_show_iptc', 'yes');
                            wppa_update_option('wppa_save_iptc', 'yes');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_show_iptc', 'no');
                            wppa_update_option('wppa_save_iptc', 'no');
                        }
                        break;
                    case 'wppa_i_exif':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_show_exif', 'yes');
                            wppa_update_option('wppa_save_exif', 'yes');
                        }
                        if ($value == 'no') {
                            wppa_update_option('wppa_show_exif', 'no');
                            wppa_update_option('wppa_save_exif', 'no');
                        }
                        break;
                    case 'wppa_i_gpx':
                        if ($value == 'yes') {
                            $custom_content = wppa_opt('custom_content');
                            if (strpos($custom_content, 'w#location') === false) {
                                $custom_content = $custom_content . ' w#location';
                                wppa_update_option('wppa_custom_content', $custom_content);
                            }
                            if (!wppa_switch('custom_on')) {
                                wppa_update_option('wppa_custom_on', 'yes');
                            }
                            if (wppa_opt('gpx_implementation') == 'none') {
                                wppa_update_option('wppa_gpx_implementation', 'wppa-plus-embedded');
                            }
                        }
                        break;
                    case 'wppa_i_fotomoto':
                        if ($value == 'yes') {
                            $custom_content = wppa_opt('custom_content');
                            if (strpos($custom_content, 'w#fotomoto') === false) {
                                $custom_content = 'w#fotomoto ' . $custom_content;
                                wppa_update_option('wppa_custom_content', $custom_content);
                            }
                            if (!wppa_switch('custom_on')) {
                                wppa_update_option('wppa_custom_on', 'yes');
                            }
                            wppa_update_option('wppa_fotomoto_on', 'yes');
                            wppa_update_option('wppa_custom_on', 'yes');
                        }
                        break;
                    case 'wppa_i_video':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_enable_video', 'yes');
                        } else {
                            wppa_update_option('wppa_enable_video', 'no');
                        }
                        break;
                    case 'wppa_i_audio':
                        if ($value == 'yes') {
                            wppa_update_option('wppa_enable_audio', 'yes');
                        } else {
                            wppa_update_option('wppa_enable_audio', 'no');
                        }
                        break;
                    case 'wppa_i_done':
                        $value = 'done';
                        break;
                    case 'wppa_search_tags':
                    case 'wppa_search_cats':
                    case 'wppa_search_comments':
                        update_option('wppa_index_need_remake', 'yes');
                        break;
                    case 'wppa_blacklist_user':
                        // Does user exist?
                        $value = trim($value);
                        $user = get_user_by('login', $value);
                        // seems to be case insensitive
                        if ($user && $user->user_login === $value) {
                            $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `status` = 'pending' WHERE `owner` = %s", $value));
                            $black_listed_users = get_option('wppa_black_listed_users', array());
                            if (!in_array($value, $black_listed_users)) {
                                $black_listed_users[] = $value;
                                update_option('wppa_black_listed_users', $black_listed_users);
                            }
                            $alert = esc_js(sprintf(__('User %s has been blacklisted.', 'wp-photo-album-plus'), $value));
                        } else {
                            $alert = esc_js(sprintf(__('User %s does not exist.', 'wp-photo-album-plus'), $value));
                        }
                        $value = '';
                        break;
                    case 'wppa_un_blacklist_user':
                        $wpdb->query($wpdb->prepare("UPDATE `" . WPPA_PHOTOS . "` SET `status` = 'publish' WHERE `owner` = %s", $value));
                        $black_listed_users = get_option('wppa_black_listed_users', array());
                        if (in_array($value, $black_listed_users)) {
                            foreach (array_keys($black_listed_users) as $usr) {
                                if ($black_listed_users[$usr] == $value) {
                                    unset($black_listed_users[$usr]);
                                }
                            }
                            update_option('wppa_black_listed_users', $black_listed_users);
                        }
                        $value = '0';
                        break;
                    case 'wppa_fotomoto_on':
                        if ($value == 'yes') {
                            $custom_content = wppa_opt('custom_content');
                            if (strpos($custom_content, 'w#fotomoto') === false) {
                                $custom_content = 'w#fotomoto ' . $custom_content;
                                wppa_update_option('wppa_custom_content', $custom_content);
                                $alert = __('The content of the Custom box has been changed to display the Fotomoto toolbar.', 'wp-photo-album-plus') . ' ';
                            }
                            if (!wppa_switch('custom_on')) {
                                wppa_update_option('wppa_custom_on', 'yes');
                                $alert .= __('The display of the custom box has been enabled', 'wp-photo-album-plus');
                            }
                        }
                        break;
                    case 'wppa_gpx_implementation':
                        if ($value != 'none') {
                            $custom_content = wppa_opt('custom_content');
                            if (strpos($custom_content, 'w#location') === false) {
                                $custom_content = $custom_content . ' w#location';
                                wppa_update_option('wppa_custom_content', $custom_content);
                                $alert = __('The content of the Custom box has been changed to display maps.', 'wp-photo-album-plus') . ' ';
                            }
                            if (!wppa_switch('custom_on')) {
                                wppa_update_option('wppa_custom_on', 'yes');
                                $alert .= __('The display of the custom box has been enabled', 'wp-photo-album-plus');
                            }
                        }
                        break;
                    case 'wppa_regen_thumbs_skip_one':
                        $last = get_option('wppa_regen_thumbs_last', '0');
                        $skip = $last + '1';
                        update_option('wppa_regen_thumbs_last', $skip);
                        break;
                    case 'wppa_remake_skip_one':
                        $last = get_option('wppa_remake_last', '0');
                        $skip = $last + '1';
                        update_option('wppa_remake_last', $skip);
                        break;
                    case 'wppa_errorlog_purge':
                        @unlink(WPPA_CONTENT_PATH . '/wppa-depot/admin/error.log');
                        break;
                    case 'wppa_pl_dirname':
                        $value = wppa_sanitize_file_name($value);
                        $value = trim($value, ' /');
                        if (!$value) {
                            wppa('error', '714');
                            wppa_out(__('This value can not be empty', 'wp-photo-album-plus'));
                        } else {
                            wppa_create_pl_htaccess($value);
                        }
                        break;
                    case 'wppa_new_tag_value':
                        $value = wppa_sanitize_tags($value, false, true);
                        break;
                    case 'wppa_up_tagselbox_content_1':
                    case 'wppa_up_tagselbox_content_2':
                    case 'wppa_up_tagselbox_content_3':
                        $value = wppa_sanitize_tags($value);
                        break;
                    case 'wppa_wppa_set_shortcodes':
                        $value = str_replace(' ', '', $value);
                        break;
                    case 'wppa_enable_video':
                        // if off: set all statusses of videos to pending
                        break;
                    default:
                        wppa('error', '0');
                        $alert = '';
                }
            }
            if (wppa('error')) {
                if (!$title) {
                    $title = sprintf(__('Failed to set %s to %s', 'wp-photo-album-plus'), $option, $value);
                }
                if (!$alert) {
                    $alert .= wppa('out');
                }
            } else {
                wppa_update_option($option, $value);
                if (!$title) {
                    $title = sprintf(__('Setting %s updated to %s', 'wp-photo-album-plus'), $option, $value);
                }
            }
            // Save possible error
            $error = wppa('error');
            // Something to do after changing the setting?
            wppa_initialize_runtime(true);
            // force reload new values
            // .htaccess
            wppa_create_wppa_htaccess();
            // Thumbsize
            $new_minisize = wppa_get_minisize();
            if ($old_minisize != $new_minisize) {
                update_option('wppa_regen_thumbs_status', 'Required');
                $alert .= __('You just changed a setting that requires the regeneration of thumbnails.', 'wp-photo-album-plus');
                $alert .= ' ' . __('Please run the appropriate action in Table VIII.', 'wp-photo-album-plus');
            }
            // Produce the response text
            $output = '||' . $error . '||' . esc_attr($title) . '||' . esc_js($alert);
            echo $output;
            wppa_clear_cache();
            wppa_exit();
            break;
            // End update-option
        // End update-option
        case 'maintenance':
            $slug = $_POST['slug'];
            $nonce = $_REQUEST['wppa-nonce'];
            if (!wp_verify_nonce($nonce, 'wppa-nonce')) {
                echo 'Security check failure||' . $slug . '||Error||0';
                wppa_exit();
            }
            echo wppa_do_maintenance_proc($slug);
            wppa_exit();
            break;
        case 'maintenancepopup':
            $slug = $_POST['slug'];
            $nonce = $_REQUEST['wppa-nonce'];
            if (!wp_verify_nonce($nonce, 'wppa-nonce')) {
                echo 'Security check failure||' . $slug . '||Error||0';
                wppa_exit();
            }
            echo wppa_do_maintenance_popup($slug);
            wppa_exit();
            break;
        case 'do-fe-upload':
            if (is_admin()) {
                require_once 'wppa-non-admin.php';
            }
            wppa_user_upload();
            echo wppa('out');
            wppa_exit();
            break;
        case 'sanitizetags':
            $tags = isset($_GET['tags']) ? $_GET['tags'] : '';
            $album = isset($_GET['album']) ? $_GET['album'] : '0';
            $deftags = $album ? wppa_get_album_item($album, 'default_tags') : '';
            $tags = $deftags ? $tags . ',' . $deftags : $tags;
            echo wppa_sanitize_tags($tags, false, true);
            wppa_exit();
            break;
        case 'destroyalbum':
            $album = isset($_GET['album']) ? $_GET['album'] : '0';
            if (!$album) {
                _e('Missing album id', 'wp-photo-album-plus');
                wppa_exit();
            }
            $nonce = isset($_GET['nonce']) ? $_GET['nonce'] : '';
            if (!$nonce || !wp_verify_nonce($nonce, 'wppa_nonce_' . $album)) {
                echo 'Security check failure #798';
                wppa_exit();
            }
            // May I?
            $imay = true;
            if (!wppa_switch('user_destroy_on')) {
                $may = false;
            }
            if (wppa_switch('user_create_login')) {
                if (!is_user_logged_in()) {
                    $may = false;
                }
                // Must login
            }
            if (!wppa_have_access($album)) {
                $may = false;
                // No album access
            }
            if (wppa_is_user_blacklisted()) {
                $may = false;
            }
            if (!$imay) {
                _e('You do not have the rights to delete this album', 'wp-photo-album-plus');
                wppa_exit();
            }
            // I may
            require_once 'wppa-album-admin-autosave.php';
            wppa_del_album($album, '');
            wppa_exit();
            break;
        default:
            // Unimplemented $wppa-action
            die('-1');
    }
    wppa_exit();
}
function wppa_time_to_wait_html($album, $user = false)
{
    global $wpdb;
    if (!$album && !$user) {
        return '0';
    }
    if ($user) {
        $limits = wppa_get_user_upload_limits();
    } else {
        $limits = $wpdb->get_var($wpdb->prepare("SELECT `upload_limit` FROM `" . WPPA_ALBUMS . "` WHERE `id` = %s", $album));
    }
    wppa_dbg_q('Q62');
    $temp = explode('/', $limits);
    $limit_max = isset($temp[0]) ? $temp[0] : '0';
    $limit_time = isset($temp[1]) ? $temp[1] : '0';
    $result = '';
    if (!$limit_max || !$limit_time) {
        return $result;
    }
    if ($user) {
        $owner = wppa_get_user('login');
        $last_upload_time = $wpdb->get_var($wpdb->prepare("SELECT `timestamp` FROM `" . WPPA_PHOTOS . "` WHERE `owner` = %s ORDER BY `timestamp` DESC LIMIT 1", $owner));
    } else {
        $last_upload_time = $wpdb->get_var($wpdb->prepare("SELECT `timestamp` FROM `" . WPPA_PHOTOS . "` WHERE `album` = %s ORDER BY `timestamp` DESC LIMIT 1", $album));
    }
    wppa_dbg_q('Q63');
    $timnow = time();
    // For simplicity: a year is 364 days = 52 weeks, we skip the months
    $seconds = array('min' => '60', 'hour' => '3600', 'day' => '86400', 'week' => '604800', 'month' => '2592000', 'year' => '31449600');
    $deltatim = $last_upload_time + $limit_time - $timnow;
    $temp = $deltatim;
    //	$months  = floor( $temp / $seconds['month'] );
    //	$temp    = $temp % $seconds['month'];
    $weeks = floor($temp / $seconds['week']);
    $temp = $temp % $seconds['week'];
    $days = floor($temp / $seconds['day']);
    $temp = $temp % $seconds['day'];
    $hours = floor($temp / $seconds['hour']);
    $temp = $temp % $seconds['hour'];
    $mins = floor($temp / $seconds['min']);
    $secs = $temp % $seconds['min'];
    $switch = false;
    $string = __('You can upload after', 'wp-photo-album-plus') . ' ';
    //	if ( $months           ) { $string .= $months.' '.'months'.', '; $switch = true; }
    if ($weeks || $switch) {
        $string .= $weeks . ' ' . __('weeks', 'wp-photo-album-plus') . ', ';
        $switch = true;
    }
    if ($days || $switch) {
        $string .= $days . ' ' . __('days', 'wp-photo-album-plus') . ', ';
        $switch = true;
    }
    if ($hours || $switch) {
        $string .= $hours . ' ' . __('hours', 'wp-photo-album-plus') . ', ';
        $switch = true;
    }
    if ($mins || $switch) {
        $string .= $mins . ' ' . __('minutes', 'wp-photo-album-plus') . ' ' . __('and', 'wp-photo-album-plus') . ' ';
        $switch = true;
    }
    if ($switch) {
        $string .= $secs . ' ' . __('seconds', 'wp-photo-album-plus');
    }
    $string .= '.';
    $result = '<span style="font-size:9px;"> ' . $string . '</span>';
    return $result;
}
示例#22
0
function wppa_get_user_upload_html($alb, $width, $where = '', $mcr = false)
{
    static $seqno;
    // Init
    $result = '';
    $mocc = wppa('mocc');
    $occur = wppa('occur');
    // Using seqno to distinguish from different places within one occurrence because
    // the album no is not known when there is a selection box.
    if ($seqno) {
        $seqno++;
    } else {
        $seqno = '1';
    }
    // Feature enabled?
    if (!wppa_switch('user_upload_on')) {
        return '';
    }
    // Login required?
    if (wppa_switch('user_upload_login')) {
        if (!is_user_logged_in()) {
            return '';
        }
    }
    // I should have access to this album ( $alb > 0 ).
    if ($alb > '0') {
        $album_owner = wppa_get_album_item($alb, 'owner');
        if ($album_owner != wppa_get_user() && $album_owner != '--- public ---' && !wppa_have_access($alb)) {
            return '';
        }
    } else {
        if (!wppa_have_access()) {
            return '';
        }
    }
    // Find max files for the user
    $allow_me = wppa_allow_user_uploads();
    if (!$allow_me) {
        if (wppa_switch('show_album_full')) {
            $result .= '<div style="clear:both"></div>' . '<span style="color:red">' . __('Max uploads reached', 'wp-photo-album-plus') . wppa_time_to_wait_html('0', true) . '</span>';
        }
        return $result;
    }
    // Find max files for the album
    $allow_alb = wppa_allow_uploads($alb);
    if (!$allow_alb) {
        if (wppa_switch('show_album_full')) {
            $result .= '<div style="clear:both"></div>' . '<span style="color:red">' . __('Max uploads reached', 'wp-photo-album-plus') . wppa_time_to_wait_html($alb) . '</span>';
        }
        return $result;
    }
    if (wppa_is_user_blacklisted()) {
        return '';
    }
    // Find max files for the system
    $allow_sys = ini_get('max_file_uploads');
    // THE max
    if ($allow_me == '-1') {
        $allow_me = $allow_sys;
    }
    if ($allow_alb == '-1') {
        $allow_alb = $allow_sys;
    }
    $max = min($allow_me, $allow_alb, $allow_sys);
    // In a widget or multi column responsive?
    $small = wppa_in_widget() == 'upload' || $mcr;
    // Ajax upload?
    $ajax_upload = wppa_switch('ajax_upload') && wppa_browser_can_html5();
    //					&&
    // WINDOWS 10 / Edge bug
    //					! strpos( $_SERVER["HTTP_USER_AGENT"], 'Edge' ) &&
    //					! strpos( $_SERVER["HTTP_USER_AGENT"], 'Windows NT 10.0' );
    // Create the return url
    if ($ajax_upload) {
        $returnurl = wppa_switch('ajax_non_admin') ? WPPA_URL . '/wppa-ajax-front.php' : admin_url('admin-ajax.php');
        $returnurl .= '?action=wppa&amp;wppa-action=do-fe-upload';
    } else {
        $returnurl = wppa_get_permalink();
        if ($where == 'cover') {
            $returnurl .= 'wppa-album=' . $alb . '&amp;wppa-cover=0&amp;wppa-occur=' . $occur;
        } elseif ($where == 'thumb') {
            $returnurl .= 'wppa-album=' . $alb . '&amp;wppa-cover=0&amp;wppa-occur=' . $occur;
        } elseif ($where == 'widget' || $where == 'uploadbox') {
        }
        if (wppa('page')) {
            $returnurl .= '&amp;wppa-page=' . wppa('page');
        }
        $returnurl = trim($returnurl, '?');
        $returnurl = wppa_trim_wppa_($returnurl);
    }
    // Make the HTML
    $t = $mcr ? 'mcr-' : '';
    $result .= '<div style="clear:both"></div>' . '<a' . ' id="wppa-up-' . $alb . '-' . $mocc . '"' . ' class="wppa-upload-' . $where . '"' . ' onclick="' . 'jQuery( \'#wppa-file-' . $t . $alb . '-' . $mocc . '\' ).css( \'display\',\'block\' );' . 'jQuery( \'#wppa-up-' . $alb . '-' . $mocc . '\' ).css( \'display\',\'none\' );' . 'jQuery( \'#wppa-cr-' . $alb . '-' . $mocc . '\' ).css( \'display\',\'none\' );' . 'jQuery( \'#wppa-ea-' . $alb . '-' . $mocc . '\' ).css( \'display\',\'none\' );' . 'jQuery( \'#wppa-cats-' . $alb . '-' . $mocc . '\' ).css( \'display\',\'none\' );' . 'jQuery( \'#_wppa-up-' . $alb . '-' . $mocc . '\' ).css( \'display\',\'block\' );' . '_wppaDoAutocol( ' . $mocc . ' )' . '"' . ' style="float:left; cursor:pointer;' . '" >' . __('Upload Photo', 'wp-photo-album-plus') . '</a>' . '<a' . ' id="_wppa-up-' . $alb . '-' . $mocc . '"' . ' class="wppa-upload-' . $where . '"' . ' onclick="' . 'jQuery( \'#wppa-file-' . $t . $alb . '-' . $mocc . '\' ).css( \'display\',\'none\' );' . 'jQuery( \'#wppa-cr-' . $alb . '-' . $mocc . '\' ).css( \'display\',\'block\' );' . 'jQuery( \'#wppa-up-' . $alb . '-' . $mocc . '\' ).css( \'display\',\'block\' );' . 'jQuery( \'#wppa-ea-' . $alb . '-' . $mocc . '\' ).css( \'display\',\'block\' );' . 'jQuery( \'#wppa-cats-' . $alb . '-' . $mocc . '\' ).css( \'display\',\'block\' );' . 'jQuery( \'#_wppa-up-' . $alb . '-' . $mocc . '\' ).css( \'display\',\'none\' );' . '_wppaDoAutocol( ' . $mocc . ' )' . '"' . ' style="float:right; cursor:pointer;display:none;' . '" >' . __(wppa_opt('close_text'), 'wp-photo-album-plus') . '</a>' . '<div' . ' id="wppa-file-' . $t . $alb . '-' . $mocc . '"' . ' class="wppa-file-' . $t . $mocc . '"' . ' style="width:' . $width . 'px;text-align:center;display:none; clear:both;"' . ' >' . '<form' . ' id="wppa-uplform-' . $alb . '-' . $mocc . '"' . ' action="' . $returnurl . '"' . ' method="post"' . ' enctype="multipart/form-data"' . ' >' . wppa_nonce_field('wppa-check', 'wppa-nonce', false, false, $alb);
    // If no album given: select one
    if (!$alb) {
        $result .= '<select' . ' id="wppa-upload-album-' . $mocc . '-' . $seqno . '"' . ' name="wppa-upload-album"' . ' style="float:left; max-width: ' . $width . 'px;"' . ' onchange="jQuery( \'#wppa-sel-' . $alb . '-' . $mocc . '\' ).trigger( \'onchange\' )"' . ' >' . wppa_album_select_a(array('addpleaseselect' => true, 'checkowner' => true, 'checkupload' => true, 'path' => wppa_switch('hier_albsel'))) . '</select>' . '<br />';
    } else {
        $result .= '<input' . ' type="hidden"' . ' id="wppa-upload-album-' . $mocc . '-' . $seqno . '"' . ' name="wppa-upload-album"' . ' value="' . $alb . '"' . ' />';
    }
    // One only ?
    if (wppa_switch('upload_one_only') && !current_user_can('administrator')) {
        $result .= '<input' . ' type="file"' . ' accept="image/*"' . (wppa_switch('camera_connect') ? ' capture="capture"' : '') . ' class="wppa-user-file"' . ' style="' . 'width:auto;' . 'max-width:' . $width . ';' . 'margin:6px 0;' . 'float:left;' . __wcs('wppa-box-text') . '"' . ' id="wppa-user-upload-' . $alb . '-' . $mocc . '"' . ' name="wppa-user-upload-' . $alb . '-' . $mocc . '[]"' . ' onchange="jQuery( \'#wppa-user-submit-' . $alb . '-' . $mocc . '\' ).css( \'display\', \'block\' )"' . ' />';
    } else {
        $result .= '<input' . ' type="file"' . ' accept="image/*"' . (wppa_switch('camera_connect') ? ' capture="capture"' : '') . ' multiple="multiple"' . ' class="wppa-user-file"' . ' style="' . 'width:auto;' . 'max-width:' . $width . ';' . 'margin:6px 0;' . 'float:left;' . __wcs('wppa-box-text') . '"' . ' id="wppa-user-upload-' . $alb . '-' . $mocc . '"' . ' name="wppa-user-upload-' . $alb . '-' . $mocc . '[]"' . ' onchange="jQuery( \'#wppa-user-submit-' . $alb . '-' . $mocc . '\' ).css( \'display\', \'block\' )"' . ' />';
    }
    // Explanation
    if (!wppa_switch('upload_one_only') && !current_user_can('administrator')) {
        if ($max) {
            $result .= '<span style="font-size:10px;" >' . sprintf(_n('You may upload %d photo', 'You may upload up to %d photos at once if your browser supports HTML-5 multiple file upload', $max, 'wp-photo-album-plus'), $max) . '</span>';
            $maxsize = wppa_check_memory_limit(false);
            if (is_array($maxsize)) {
                $result .= '<br />' . '<span style="font-size:10px;" >' . sprintf(__('Max photo size: %d x %d (%2.1f MegaPixel)', 'wp-photo-album-plus'), $maxsize['maxx'], $maxsize['maxy'], $maxsize['maxp'] / (1024 * 1024)) . '</span>';
            }
        }
    }
    // Copyright notice
    if (wppa_switch('copyright_on')) {
        $result .= '<div style="clear:both;" >' . __(wppa_opt('copyright_notice'), 'wp-photo-album-plus') . '</div>';
    }
    // Watermark
    if (wppa_switch('watermark_on') && wppa_switch('watermark_user')) {
        $result .= '<table' . ' class="wppa-watermark wppa-box-text"' . ' style="margin:0; border:0; ' . __wcs('wppa-box-text') . '"' . ' >' . '<tbody>' . '<tr valign="top" style="border: 0 none; " >' . '<td' . ' class="wppa-box-text wppa-td"' . ' style="' . __wcs('wppa-box-text') . __wcs('wppa-td') . '"' . ' >' . __('Apply watermark file:', 'wp-photo-album-plus') . '</td>' . '</tr>' . '<tr>' . '<td' . ' class="wppa-box-text wppa-td"' . ' style="width: ' . $width . ';' . __wcs('wppa-box-text') . __wcs('wppa-td') . '"' . ' >' . '<select' . ' style="margin:0; padding:0; text-align:left; width:auto; "' . ' name="wppa-watermark-file"' . ' id="wppa-watermark-file"' . ' >' . wppa_watermark_file_select() . '</select>' . '</td>' . '</tr>' . '<tr valign="top" style="border: 0 none; " >' . '<td' . ' class="wppa-box-text wppa-td"' . ' style="width: ' . $width . ';' . __wcs('wppa-box-text') . __wcs('wppa-td') . '"' . ' >' . __('Position:', 'wp-photo-album-plus') . '</td>' . ($small ? '</tr><tr>' : '') . '<td' . ' class="wppa-box-text wppa-td"' . ' style="width: ' . $width . ';' . __wcs('wppa-box-text') . __wcs('wppa-td') . '"' . ' >' . '<select' . ' style="margin:0; padding:0; text-align:left; width:auto; "' . ' name="wppa-watermark-pos"' . ' id="wppa-watermark-pos"' . ' >' . wppa_watermark_pos_select() . '</select>' . '</td>' . '</tr>' . '</tbody>' . '</table>';
    }
    // Name
    if (wppa_switch('name_user')) {
        switch (wppa_opt('newphoto_name_method')) {
            case 'none':
                $expl = '';
                break;
            case '2#005':
                $expl = __('If you leave this blank, iptc tag 005 (Graphic name) will be used as photoname if available, else the original filename will be used as photo name.', 'wp-photo-album-plus');
                break;
            case '2#120':
                $expl = __('If you leave this blank, iptc tag 120 (Caption) will be used as photoname if available, else the original filename will be used as photo name.', 'wp-photo-album-plus');
                break;
            default:
                $expl = __('If you leave this blank, the original filename will be used as photo name.', 'wp-photo-album-plus');
        }
        $result .= '<div' . ' class="wppa-box-text wppa-td"' . ' style="' . 'clear:both;' . 'float:left;' . 'text-align:left;' . __wcs('wppa-box-text') . __wcs('wppa-td') . '"' . ' >' . __('Enter photo name', 'wp-photo-album-plus') . '&nbsp;' . '<span style="font-size:10px;" >' . $expl . '</span>' . '</div>' . '<input' . ' type="text"' . ' class="wppa-box-text wppa-file-' . $t . $mocc . '"' . ' style="padding:0; width:' . ($width - 6) . 'px; ' . __wcs('wppa-box-text') . '"' . ' name="wppa-user-name"' . ' />';
    }
    // Description user fillable ?
    if (wppa_switch('desc_user')) {
        $desc = wppa_switch('apply_newphoto_desc_user') ? stripslashes(wppa_opt('newphoto_description')) : '';
        $result .= '<div' . ' class="wppa-box-text wppa-td"' . ' style="clear:both; float:left; text-align:left; ' . __wcs('wppa-box-text') . __wcs('wppa-td') . '"' . ' >' . __('Enter/modify photo description', 'wp-photo-album-plus') . '</div>' . '<textarea' . ' class="wppa-user-textarea wppa-box-text wppa-file-' . $t . $mocc . '"' . ' style="height:120px; width:' . ($width - 6) . 'px; ' . __wcs('wppa-box-text') . '"' . ' name="wppa-user-desc"' . ' >' . $desc . '</textarea>';
    } elseif (wppa_switch('apply_newphoto_desc_user')) {
        $result .= '<input' . ' type="hidden"' . ' value="' . esc_attr(wppa_opt('newphoto_description')) . '"' . ' name="wppa-user-desc"' . ' />';
    }
    // Custom fields
    if (wppa_switch('fe_custom_fields')) {
        for ($i = '0'; $i < '10'; $i++) {
            if (wppa_opt('custom_caption_' . $i)) {
                $result .= '<div' . ' class="wppa-box-text wppa-td"' . ' style="clear:both; float:left; text-align:left; ' . __wcs('wppa-box-text') . __wcs('wppa-td') . '"' . ' >' . __(wppa_opt('custom_caption_' . $i), 'wp-photo-album-plus') . ': ' . (wppa_switch('custom_visible_' . $i) ? '' : '&nbsp;<small><i>(&nbsp;' . __('hidden', 'wp-photo-album-plus') . '&nbsp;)</i></small>') . '</div>' . '<input' . ' type="text"' . ' class="wppa-box-text wppa-file-' . $t . $mocc . '"' . ' style="padding:0; width:' . ($width - 6) . 'px; ' . __wcs('wppa-box-text') . '"' . ' name="wppa-user-custom-' . $i . '"' . ' />';
            }
        }
    }
    // Tags
    if (wppa_switch('fe_upload_tags')) {
        // Prepare onclick action
        $onc = 'wppaPrevTags(\'wppa-sel-' . $alb . '-' . $mocc . '\', \'wppa-inp-' . $alb . '-' . $mocc . '\', \'wppa-upload-album-' . $mocc . '-' . $seqno . '\', \'wppa-prev-' . $alb . '-' . $mocc . '\')';
        // Open the tag enter area
        $result .= '<div class="wppa-box-text wppa-td" style="clear:both; float:left; text-align:left; ' . __wcs('wppa-box-text') . __wcs('wppa-td') . '" >';
        // Selection boxes 1..3
        for ($i = '1'; $i < '4'; $i++) {
            if (wppa_switch('up_tagselbox_on_' . $i)) {
                $result .= '<div style="float:left; margin-right:4px;" >' . '<small>' . __(wppa_opt('up_tagselbox_title_' . $i), 'wp-photo-album-plus') . '</small><br />' . '<select' . ' id="wppa-sel-' . $alb . '-' . $mocc . '-' . $i . '"' . ' style="float:left; margin-right: 4px;"' . ' name="wppa-user-tags-' . $i . '[]"' . (wppa_switch('up_tagselbox_multi_' . $i) ? ' multiple' : '') . ' onchange="' . $onc . '"' . ' >';
                if (wppa_opt('up_tagselbox_content_' . $i)) {
                    // List of tags supplied
                    $tags = explode(',', wppa_opt('up_tagselbox_content_' . $i));
                    $result .= '<option value="" >&nbsp;</option>';
                    if (is_array($tags)) {
                        foreach ($tags as $tag) {
                            $result .= '<option class="wppa-sel-' . $alb . '-' . $mocc . '" value="' . $tag . '">' . $tag . '</option>';
                        }
                    }
                } else {
                    // All existing tags
                    $tags = wppa_get_taglist();
                    $result .= '<option value="" >&nbsp;</option>';
                    if (is_array($tags)) {
                        foreach ($tags as $tag) {
                            $result .= '<option class="wppa-sel-' . $alb . '-' . $mocc . '" value="' . $tag['tag'] . '">' . $tag['tag'] . '</option>';
                        }
                    }
                }
                $result .= '</select>' . '</div>';
            }
        }
        // New tags
        if (wppa_switch('up_tag_input_on')) {
            $result .= '<div style="float:left; margin-right:4px;" >' . '<small>' . __(wppa_opt('up_tag_input_title'), 'wp-photo-album-plus') . '</small><br />' . '<input' . ' id="wppa-inp-' . $alb . '-' . $mocc . '"' . ' type="text"' . ' class="wppa-box-text"' . ' style="padding:0; width:150px; ' . __wcs('wppa-box-text') . '"' . ' name="wppa-new-tags"' . ' onchange="' . $onc . '"' . ' />' . '</div>';
        }
        // Preview area
        if (wppa_switch('up_tag_preview')) {
            $result .= '<div style="margin:0; clear:both;" >' . __('Preview tags:', 'wp-photo-album-plus') . ' <small id="wppa-prev-' . $alb . '-' . $mocc . '"></small>' . '</div>' . '<script type="text/javascript" >jQuery( document ).ready(function() {' . $onc . '})</script>';
        }
        // Close tag enter area
        $result .= '</div>';
    }
    /* start submit section */
    // Onclick submit verify album is known
    if (!$alb) {
        $onclick = ' onclick="if ( document.getElementById( \'wppa-upload-album-' . $mocc . '-' . $seqno . '\' ).value == 0 )' . ' {alert( \'' . esc_js(__('Please select an album and try again', 'wp-photo-album-plus')) . '\' );return false;}"';
    } else {
        $onclick = '';
    }
    // The submit button
    $result .= '<input' . ' type="submit"' . ' id="wppa-user-submit-' . $alb . '-' . $mocc . '"' . $onclick . ' style="display:none; margin: 6px 0; float:right; ' . __wcs('wppa-box-text') . '"' . ' class="wppa-user-submit"' . ' name="wppa-user-submit-' . $alb . '-' . $mocc . '" value="' . __('Upload photo', 'wp-photo-album-plus') . '"' . ' />' . '<div style="clear:both"></div>';
    // if ajax: progression bar
    if ($ajax_upload) {
        $result .= '<div' . ' id="progress-' . $alb . '-' . $mocc . '"' . ' class="wppa-progress"' . ' style="border-color:' . wppa_opt('bcolor_upload') . '"' . ' >' . '<div id="bar-' . $alb . '-' . $mocc . '" class="wppa-bar" ></div>' . '<div id="percent-' . $alb . '-' . $mocc . '" class="wppa-percent" >0%</div >' . '</div>' . '<div id="message-' . $alb . '-' . $mocc . '" class="wppa-message" ></div>';
    }
    /* End submit section */
    // Done
    $result .= '</form></div>';
    // Ajax upload script
    if ($ajax_upload) {
        $result .= '<script>' . 'jQuery(document).ready(function() {

					var options = {
						beforeSend: function() {
							jQuery("#progress-' . $alb . '-' . $mocc . '").show();
							//clear everything
							jQuery("#bar-' . $alb . '-' . $mocc . '").width(\'0%\');
							jQuery("#message-' . $alb . '-' . $mocc . '").html("");
							jQuery("#percent-' . $alb . '-' . $mocc . '").html("");
						},
						uploadProgress: function(event, position, total, percentComplete) {
							jQuery("#bar-' . $alb . '-' . $mocc . '").width(percentComplete+\'%\');
							if ( percentComplete < 95 ) {
								jQuery("#percent-' . $alb . '-' . $mocc . '").html(percentComplete+\'%\');
							}
							else {
								jQuery("#percent-' . $alb . '-' . $mocc . '").html(\'Processing...\');
							}
						},
						success: function() {
							jQuery("#bar-' . $alb . '-' . $mocc . '").width(\'100%\');
							jQuery("#percent-' . $alb . '-' . $mocc . '").html(\'Done!\');
						},
						complete: function(response) {
							jQuery("#message-' . $alb . '-' . $mocc . '").html( \'<span style="font-size: 10px;" >\'+response.responseText+\'</span>\' );' . ($where == 'thumb' ? 'document.location.reload(true)' : '') . '
						},
						error: function() {
							jQuery("#message-' . $alb . '-' . $mocc . '").html( \'<span style="color: red;" >' . __('ERROR: unable to upload files.', 'wp-photo-album-plus') . '</span>\' );
						}
					};

					jQuery("#wppa-uplform-' . $alb . '-' . $mocc . '").ajaxForm(options);
				});
			</script>';
    }
    return $result;
}
function wppa_get_like_title_a($id)
{
    global $wpdb;
    //static $c;
    //wppa_log('obs', 'wppa_get_like_title_a', true);
    //$c++;
    $me = wppa_get_user();
    $likes = wppa_get_photo_item($id, 'rating_count');
    //$wpdb->get_var( "SELECT COUNT(*) FROM `" . WPPA_RATING . "` WHERE `photo` = $id" );
    $mylike = $wpdb->get_var("SELECT COUNT(*) FROM `" . WPPA_RATING . "` WHERE `photo` = {$id} AND `user` = '{$me}'");
    if ($mylike) {
        if ($likes > 1) {
            $text = sprintf(_n('You and %d other person like this', 'You and %d other people like this', $likes - 1), $likes - 1);
        } else {
            $text = __('You are the first one who likes this', 'wp-photo-album-plus');
        }
        $text .= "\n" . __('Click again if you do no longer like this', 'wp-photo-album-plus');
    } else {
        if ($likes) {
            $text = sprintf(_n('%d person likes this', '%d people like this', $likes, 'wp-photo-album-plus'), $likes);
        } else {
            $text = __('Be the first one to like this', 'wp-photo-album-plus');
        }
    }
    $result['title'] = $text;
    $result['mine'] = $mylike;
    $result['total'] = $likes;
    $result['display'] = sprintf(_n('%d like', '%d likes', $likes), $likes);
    return $result;
}
示例#24
0
function wppa_can_create_album()
{
    global $wpdb;
    global $wp_roles;
    // Test for logged out users
    if (!is_user_logged_in()) {
        // Login required ?
        if (wppa_switch('user_create_login')) {
            return false;
        } else {
            $rmax = get_option('wppa_loggedout_album_limit_count', '0');
            // If logged out max set, check if limit reached
            if ($rmax) {
                $albs = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_ALBUMS . "` WHERE `owner` = %s", wppa_get_user()));
                if ($albs >= $rmax) {
                    return false;
                    // Limit reached
                } else {
                    return true;
                    // Limit not yet reached
                }
            } else {
                return true;
            }
        }
    }
    // Admin can do everything
    if (wppa_user_is('administrator')) {
        return true;
    }
    // A blacklisted user can not create albums
    if (wppa_is_user_blacklisted()) {
        return false;
    }
    // Check for global max albums per user setting
    $albs = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM `" . WPPA_ALBUMS . "` WHERE `owner` = %s", wppa_get_user()));
    $gmax = wppa_opt('wppa_max_albums');
    if ($gmax && $albs >= $gmax) {
        return false;
    }
    // Check for role dependant max albums per user setting
    $user = wp_get_current_user();
    $roles = $wp_roles->roles;
    foreach (array_keys($roles) as $role) {
        // Find firste role the user has
        if (wppa_user_is($role)) {
            $rmax = get_option('wppa_' . $role . '_album_limit_count', '0');
            if (!$rmax || $albs < $rmax) {
                return true;
            } else {
                return false;
            }
        }
    }
    // If a user has no role, deny creation
    return false;
}
示例#25
0
function wppa_init()
{
    global $blog_id;
    // Upload ( .../wp-content/uploads ) is always relative to ABSPATH,
    // see http://codex.wordpress.org/Editing_wp-config.php#Moving_wp-content_folder
    //
    // Assumption: site_url() corresponds with ABSPATH
    // Our version ( WPPA_UPLOAD ) of the relative part of the path/url to the uploads dir
    // is calculated form wp_upload_dir() by substracting ABSPATH from the uploads basedir.
    $wp_uploaddir = wp_upload_dir();
    // Unfortunately $wp_uploaddir['basedir'] does very often not contain the data promised
    // by the docuentation, so it is unreliable.
    $rel_uploads_path = defined('WPPA_REL_UPLOADS_PATH') ? wppa_trims(WPPA_REL_UPLOADS_PATH) : 'wp-content/uploads';
    // The depot dir is also relative to ABSPATH but on the same level as uploads,
    // but without '/wppa-depot'.
    // If you want to change the name of wp-content, you have also to define WPPA_REL_DEPOT_PATH
    // as being the relative path to the parent of wppa-depot.
    $rel_depot_path = defined('WPPA_REL_DEPOT_PATH') ? wppa_trims(WPPA_REL_DEPOT_PATH) : 'wp-content';
    // For multisite the uploads are in /wp-content/blogs.dir/<blogid>/,
    // so we hope still below ABSPATH
    $wp_content_multi = wppa_trims(str_replace(WPPA_ABSPATH, '', WPPA_CONTENT_PATH));
    // To test the multisite paths and urls, set $debug_multi = true
    $debug_multi = false;
    // Define paths and urls
    if ($debug_multi || is_multisite() && !WPPA_MULTISITE_GLOBAL) {
        if (WPPA_MULTISITE_BLOGSDIR) {
            // Old multisite individual
            define('WPPA_UPLOAD', wppa_trims($wp_content_multi . '/blogs.dir/' . $blog_id));
            define('WPPA_UPLOAD_PATH', WPPA_ABSPATH . WPPA_UPLOAD . '/wppa');
            define('WPPA_UPLOAD_URL', site_url() . '/' . WPPA_UPLOAD . '/wppa');
            define('WPPA_DEPOT', wppa_trims($wp_content_multi . '/blogs.dir/' . $blog_id . '/wppa-depot'));
            define('WPPA_DEPOT_PATH', WPPA_ABSPATH . WPPA_DEPOT);
            define('WPPA_DEPOT_URL', site_url() . '/' . WPPA_DEPOT);
        } elseif (WPPA_MULTISITE_INDIVIDUAL) {
            // New multisite individual
            define('WPPA_UPLOAD', $rel_uploads_path . '/sites/' . $blog_id);
            define('WPPA_UPLOAD_PATH', ABSPATH . WPPA_UPLOAD . '/wppa');
            define('WPPA_UPLOAD_URL', get_bloginfo('wpurl') . '/' . WPPA_UPLOAD . '/wppa');
            define('WPPA_DEPOT', $rel_uploads_path . '/sites/' . $blog_id . '/wppa-depot');
            define('WPPA_DEPOT_PATH', ABSPATH . WPPA_DEPOT);
            define('WPPA_DEPOT_URL', get_bloginfo('wpurl') . '/' . WPPA_DEPOT);
        } else {
            // Not working default multisite
            $user = is_user_logged_in() ? '/' . wppa_get_user() : '';
            define('WPPA_UPLOAD', $rel_uploads_path);
            define('WPPA_UPLOAD_PATH', WPPA_ABSPATH . WPPA_UPLOAD . $user . '/wppa');
            define('WPPA_UPLOAD_URL', site_url() . '/' . WPPA_UPLOAD . $user . '/wppa');
            define('WPPA_DEPOT', wppa_trims($rel_depot_path . '/wppa-depot' . $user));
            define('WPPA_DEPOT_PATH', WPPA_ABSPATH . WPPA_DEPOT);
            define('WPPA_DEPOT_URL', site_url() . '/' . WPPA_DEPOT);
        }
    } else {
        // Single site or multisite global
        define('WPPA_UPLOAD', $rel_uploads_path);
        define('WPPA_UPLOAD_PATH', WPPA_ABSPATH . WPPA_UPLOAD . '/wppa');
        define('WPPA_UPLOAD_URL', site_url() . '/' . WPPA_UPLOAD . '/wppa');
        $user = is_user_logged_in() ? '/' . wppa_get_user() : '';
        define('WPPA_DEPOT', wppa_trims($rel_depot_path . '/wppa-depot' . $user));
        define('WPPA_DEPOT_PATH', WPPA_ABSPATH . WPPA_DEPOT);
        define('WPPA_DEPOT_URL', site_url() . '/' . WPPA_DEPOT);
    }
    wppa_mktree(WPPA_UPLOAD_PATH);
    // Whatever (faulty) path has been calculated, it will be
    wppa_mktree(WPPA_UPLOAD_PATH . '/thumbs');
    // Just to make sure the chmod is right ( 755 )
    wppa_mktree(WPPA_DEPOT_PATH);
    // created and not prevent plugin to activate or function
}
function wppa_session_end()
{
    global $wppa_session;
    // May have logged in now
    $wppa_session['user'] = wppa_get_user();
    wppa_save_session();
}
示例#27
0
function wppa_get_thumb_default($id)
{
    global $wpdb;
    // Validate args
    if (!wppa_is_int($id) || $id < '0') {
        wppa_dbg_msg('Please check file wppa-theme.php or any other php file that calls wppa_get_thumb_default(). Argument 1: photo id is missing or illegal!', 'red', 'force');
        die('Please check your configuration');
    }
    // Initialize
    $result = '';
    // Get the photo info
    $thumb = wppa_cache_thumb($id);
    // Get the album info
    $album = wppa_cache_album($thumb['album']);
    wppa('current_album', $album['id']);
    // Get photo info
    $is_video = wppa_is_video($id);
    $has_audio = wppa_has_audio($id);
    $com_alt = wppa('is_comten') && wppa_switch('comten_alt_display') && !wppa_in_widget();
    $frameattr_a = wppa_get_thumb_frame_style_a();
    $framestyle = $frameattr_a['style'];
    $framewidth = $frameattr_a['width'];
    $frameheight = $frameattr_a['height'];
    // Get class depending of comment alt display
    if ($com_alt) {
        $class = 'thumbnail-frame-comalt thumbnail-frame-comalt-' . wppa('mocc') . ' thumbnail-frame-photo-' . $id;
    } else {
        $class = 'thumbnail-frame thumbnail-frame-' . wppa('mocc') . ' thumbnail-frame-photo-' . $id;
    }
    // If no image to display, die gracefully
    $imgsrc = wppa_fix_poster_ext(wppa_get_thumb_path($id), $id);
    if (!wppa_is_video($id) && !is_file($imgsrc) && !wppa_has_audio($id)) {
        $result .= '<div' . ' class="' . $class . '"' . ' style="' . $framestyle . '; color:red;" >' . 'Missing thumbnail image #' . $id . '</div>';
        return $result;
    }
    // Find image attributes
    $alt = $album['alt_thumbsize'] == 'yes' ? '_alt' : '';
    $imgattr_a = wppa_get_imgstyle_a($id, $imgsrc, wppa_opt('thumbsize' . $alt), 'optional', 'thumb');
    $imgstyle = $imgattr_a['style'];
    $imgwidth = $imgattr_a['width'];
    $imgheight = $imgattr_a['height'];
    $imgmargintop = $imgattr_a['margin-top'];
    $imgmarginbottom = $imgattr_a['margin-bottom'];
    // Special case for comment alt display
    if ($com_alt) {
        $imgwidth = wppa_opt('comten_alt_thumbsize');
        $imgheight = round($imgwidth * $imgattr_a['height'] / $imgattr_a['width']);
        $imgstyle .= 'float:left; margin:0 20px 8px 0;width:' . $imgwidth . 'px; height:' . $imgheight . 'px;';
    }
    // Cursor depends on link
    $cursor = $imgattr_a['cursor'];
    // Find the required image sizes
    if (wppa_switch('use_thumb_popup')) {
        // Landscape?
        if ($imgwidth > $imgheight) {
            $popwidth = wppa_opt('popupsize');
            $popheight = round($popwidth * $imgheight / $imgwidth);
        } else {
            $popheight = wppa_opt('popupsize');
            $popwidth = round($popheight * $imgwidth / $imgheight);
        }
    } else {
        $popwidth = $imgwidth;
        $popheight = $imgheight;
    }
    // More image attributes
    $imgurl = wppa_fix_poster_ext(wppa_get_thumb_url($id, '', $popwidth, $popheight), $id);
    $events = wppa_get_imgevents('thumb', $id);
    $imgalt = wppa_get_imgalt($id);
    // returns something like ' alt="Any text" '
    $title = esc_attr(wppa_get_photo_name($id));
    // Feed ?
    if (is_feed()) {
        $imgattr_a = wppa_get_imgstyle_a($id, $imgsrc, '100', '4', 'thumb');
        $style = $imgattr_a['style'];
        $result .= '<a href="' . get_permalink() . '">' . '<img src="' . $imgurl . '" ' . $imgalt . ' title="' . $title . '" style="' . $style . '" />' . '</a>';
        return $result;
    }
    // Open Com alt wrapper
    if ($com_alt) {
        $result .= '<div>';
    }
    // Open the thumbframe
    $result .= '<div' . ' id="thumbnail_frame_' . $id . '_' . wppa('mocc') . '"' . ' class="' . $class . '"' . ' style="' . $framestyle . '"' . ' >';
    // Open the image container
    $imgcontheight = $com_alt ? $imgheight : max($imgwidth, $imgheight);
    if (!is_file($imgsrc)) {
        $imgcontheight = 2 * wppa_get_audio_control_height();
    }
    if ($com_alt) {
        $framewidth = $imgwidth + '4';
    }
    $result .= '<div' . ' class="wppa-tn-img-container"' . ' style="' . 'height:' . $imgcontheight . 'px;' . 'width:' . $framewidth . 'px;' . ($com_alt ? 'float:left;' : '') . 'overflow:hidden;"' . '>';
    // The medals if at the top
    $medalsize = $com_alt ? 'S' : 'M';
    $result .= wppa_get_medal_html_a(array('id' => $id, 'size' => $medalsize, 'where' => 'top'));
    // The audio when no popup
    if (wppa_switch('thumb_audio') && wppa_has_audio($id) && !$com_alt) {
        $result .= '<div style="position:relative;z-index:11;">';
        $is_safari = strpos($_SERVER["HTTP_USER_AGENT"], 'Safari');
        $cont_h = $is_safari ? 16 : 28;
        $audiotop = $imgattr_a['height'] + $imgattr_a['margin-top'] - $cont_h;
        if (!is_file($imgsrc)) {
            // Audio without image
            $audiotop = wppa_get_audio_control_height();
            $imgwidth = wppa_opt('tf_width');
            $imgheight = wppa_get_audio_control_height();
        }
        $result .= wppa_get_audio_html(array('id' => $id, 'width' => $imgwidth, 'height' => $cont_h, 'style' => 'position:absolute;top:' . $audiotop . 'px;left:0;border:none;'));
        $result .= '</div>';
    }
    // Get the image link
    if (wppa('is_topten')) {
        $no_album = !wppa('start_album');
        if ($no_album) {
            $tit = __('View the top rated photos', 'wp-photo-album-plus');
        } else {
            $tit = esc_attr(__(stripslashes($thumb['description'])));
        }
        $link = wppa_get_imglnk_a('thumb', $id, '', $tit, '', $no_album);
    } else {
        $link = wppa_get_imglnk_a('thumb', $id);
    }
    // voor parent uplr
    // See if ajax possible
    if ($link) {
        // Is link an url?
        if ($link['is_url']) {
            if (wppa_switch('allow_ajax') && wppa_opt('thumb_linktype') == 'photo' && wppa_opt('thumb_linkpage') == '0' && !wppa_switch('thumb_blank') && !(wppa_switch('thumb_overrule') && $thumb['linkurl']) && !wppa('is_topten') && !wppa('is_lasten') && !wppa('is_comten') && !wppa('is_featen') && !wppa('is_tag') && !wppa('is_upldr') && !wppa('src') && !wppa('supersearch') && (wppa_is_int(wppa('start_album')) || wppa('start_album') == '')) {
                // Ajax	possible
                // The a img ajax
                $p = wppa('calendar') ? '' : '&amp;wppa-photo=' . $id;
                $onclick = 'wppaDoAjaxRender( ' . wppa('mocc') . ', \'' . wppa_get_slideshow_url_ajax(wppa('start_album'), '0') . '&amp;wppa-photo=' . $id . '\', \'' . wppa_convert_to_pretty(wppa_get_slideshow_url(wppa('start_album'), '0') . $p) . '\' )';
                $result .= '<a style="position:static;" class="thumb-img" id="x-' . $id . '-' . wppa('mocc') . '">';
                // Video?
                if ($is_video) {
                    $result .= wppa_get_video_html(array('id' => $id, 'width' => $imgwidth, 'height' => $imgheight, 'controls' => wppa_switch('thumb_video'), 'margin_top' => '0', 'margin_bottom' => '0', 'tagid' => 'i-' . $id . '-' . wppa('mocc'), 'cursor' => 'cursor:pointer;', 'events' => $events, 'title' => $title, 'preload' => 'metadata', 'onclick' => $onclick, 'lb' => false, 'class' => '', 'style' => $imgstyle));
                } else {
                    $result .= '<img' . ' onclick="' . $onclick . '"' . ' id="i-' . $id . '-' . wppa('mocc') . '"' . ' src="' . $imgurl . '"' . ' ' . $imgalt . ($title ? ' title="' . $title . '"' : '') . ' width="' . $imgwidth . '"' . ' height="' . $imgheight . '"' . ' style="' . $imgstyle . ' cursor:pointer;"' . ' ' . $events . ' />';
                }
                // Close the a img ajax
                $result .= '</a>';
            } else {
                // The a img non ajax
                $result .= '<a style="position:static;" href="' . $link['url'] . '" target="' . $link['target'] . '" class="thumb-img" id="x-' . $id . '-' . wppa('mocc') . '">';
                if ($is_video) {
                    $result .= wppa_get_video_html(array('id' => $id, 'width' => $imgwidth, 'height' => $imgheight, 'controls' => wppa_switch('thumb_video'), 'margin_top' => '0', 'margin_bottom' => '0', 'tagid' => 'i-' . $id . '-' . wppa('mocc'), 'cursor' => 'cursor:pointer;', 'events' => $events, 'title' => $title, 'preload' => 'metadata', 'onclick' => '', 'lb' => false, 'class' => '', 'style' => $imgstyle));
                } else {
                    $result .= '<img' . ' id="i-' . $id . '-' . wppa('mocc') . '"' . ' src="' . $imgurl . '" ' . $imgalt . ($title ? ' title="' . $title . '"' : '') . ' width="' . $imgwidth . '"' . ' height="' . $imgheight . '"' . ' style="' . $imgstyle . ' cursor:pointer;"' . ' ' . $events . ' />';
                }
                // Close the img non ajax
                $result .= '</a>';
            }
        } elseif ($link['is_lightbox']) {
            $title = wppa_get_lbtitle('thumb', $id);
            // The a img
            $result .= '<a href="' . $link['url'] . '" target="' . $link['target'] . '"' . ($is_video ? ' data-videohtml="' . esc_attr(wppa_get_video_body($id)) . '"' . ' data-videonatwidth="' . wppa_get_videox($id) . '"' . ' data-videonatheight="' . wppa_get_videoy($id) . '"' : '') . ($has_audio ? ' data-audiohtml="' . esc_attr(wppa_get_audio_body($id)) . '"' : '') . ' ' . wppa('rel') . '="' . wppa_opt('lightbox_name') . '[occ' . wppa('mocc') . ']"' . ' ' . wppa('lbtitle') . '="' . $title . '" ' . ' class="thumb-img" id="x-' . $id . '-' . wppa('mocc') . '">';
            if ($is_video) {
                $result .= wppa_get_video_html(array('id' => $id, 'width' => $imgwidth, 'height' => $imgheight, 'controls' => wppa_switch('thumb_video'), 'margin_top' => '0', 'margin_bottom' => '0', 'tagid' => 'i-' . $id . '-' . wppa('mocc'), 'cursor' => $cursor, 'events' => $events, 'title' => wppa_zoom_in($id), 'preload' => 'metadata', 'onclick' => '', 'lb' => false, 'class' => '', 'style' => $imgstyle));
            } else {
                $title = wppa_zoom_in($id);
                $result .= '<img' . ' id="i-' . $id . '-' . wppa('mocc') . '"' . ' src="' . $imgurl . '"' . ' ' . $imgalt . ($title ? ' title="' . $title . '"' : '') . ' width="' . $imgwidth . '"' . ' height="' . $imgheight . '"' . ' style="' . $imgstyle . $cursor . '"' . ' ' . $events . ' />';
            }
            // Close the a img
            $result .= '</a>';
        } else {
            // is onclick
            // The div img
            $result .= '<div onclick="' . $link['url'] . '" class="thumb-img" id="x-' . $id . '-' . wppa('mocc') . '">';
            if ($is_video) {
                $result .= wppa_get_video_html(array('id' => $id, 'width' => $imgwidth, 'height' => $imgheight, 'controls' => wppa_switch('thumb_video'), 'margin_top' => '0', 'margin_bottom' => '0', 'tagid' => 'i-' . $id . '-' . wppa('mocc'), 'cursor' => 'cursor:pointer;', 'events' => $events, 'title' => $title, 'preload' => 'metadata', 'onclick' => '', 'lb' => false, 'class' => '', 'style' => $imgstyle));
            } else {
                $result .= '<img' . ' id="i-' . $id . '-' . wppa('mocc') . '"' . ' src="' . $imgurl . '"' . ' ' . $imgalt . ($title ? ' title="' . $title . '"' : '') . ' width="' . $imgwidth . '"' . ' height="' . $imgheight . '"' . ' style="' . $imgstyle . ' cursor:pointer;"' . ' ' . $events . ' />';
            }
            $result .= '</div>';
            $result .= '<script type="text/javascript">';
            $result .= '/* <![CDATA[ */';
            $result .= 'wppaPopupOnclick[' . $id . '] = "' . $link['url'] . '";';
            $result .= '/* ]]> */';
            $result .= '</script>';
        }
    } else {
        // no link
        if (wppa_switch('use_thumb_popup')) {
            $result .= '<div id="x-' . $id . '-' . wppa('mocc') . '">';
            if ($is_video) {
                $result .= wppa_get_video_html(array('id' => $id, 'width' => $imgwidth, 'height' => $imgheight, 'controls' => false, 'margin_top' => '0', 'margin_bottom' => '0', 'tagid' => 'i-' . $id . '-' . wppa('mocc'), 'cursor' => '', 'events' => $events, 'title' => $title, 'preload' => 'metadata', 'onclick' => '', 'lb' => false, 'class' => '', 'style' => $imgstyle));
            } else {
                $result .= '<img' . ' src="' . $imgurl . '"' . ' ' . $imgalt . ($title ? ' title="' . $title . '"' : '') . ' width="' . $imgwidth . '"' . ' height="' . $imgheight . '"' . ' style="' . $imgstyle . '"' . ' ' . $events . ' />';
            }
            $result .= '</div>';
        } else {
            if ($is_video) {
                $result .= wppa_get_video_html(array('id' => $id, 'width' => $imgwidth, 'height' => $imgheight, 'controls' => wppa_switch('thumb_video'), 'margin_top' => '0', 'margin_bottom' => '0', 'tagid' => 'i-' . $id . '-' . wppa('mocc'), 'cursor' => '', 'events' => $events, 'title' => $title, 'preload' => 'metadata', 'onclick' => '', 'lb' => false, 'class' => '', 'style' => $imgstyle));
            } else {
                $result .= '<img' . ' src="' . $imgurl . '"' . ' ' . $imgalt . ($title ? ' title="' . $title . '"' : '') . ' width="' . $imgwidth . '"' . ' height="' . $imgheight . '"' . ' style="' . $imgstyle . '"' . ' ' . $events . ' />';
            }
        }
    }
    // The medals if near the bottom
    $result .= wppa_get_medal_html_a(array('id' => $id, 'size' => $medalsize, 'where' => 'bot'));
    // Close the image container
    $result .= '</div>';
    /*
    	// The audio when popup
    	if ( wppa_switch( 'use_thumb_popup' ) && wppa_switch( 'thumb_audio' ) && wppa_has_audio( $id ) && ! $com_alt ) {
    		$result .= wppa_get_audio_html( array(
    							'id' 		=> $id,
    							'width'		=> $imgwidth
    							));
    	}
    */
    // Comten alt display?
    if ($com_alt) {
        $result .= '<div' . ' class="wppa-com-alt wppa-com-alt-' . wppa('mocc') . '"' . ' style="' . 'height:' . $imgheight . 'px;' . 'overflow:auto;' . 'margin: 0 0 8px 10px;' . 'border:1px solid ' . wppa_opt('bcolor_alt') . ';' . '"' . ' >';
        $comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPPA_COMMENTS . "` WHERE `photo` = %s AND `status` = 'approved' ORDER BY `timestamp` DESC", $id), ARRAY_A);
        $first = true;
        if ($comments) {
            foreach ($comments as $com) {
                $result .= '<h6' . ' style="' . 'font-size:10px;' . 'line-height:12px;' . 'font-weight:bold;' . 'padding:' . ($first ? '0' : '6px') . ' 0 0 6px;' . 'margin:0;float:left;' . '"' . '>' . $com['user'] . ' ' . __('wrote', 'wp-photo-album-plus') . ' ' . wppa_get_time_since($com['timestamp']) . ':' . '</h6>' . '<p' . ' style="' . 'font-size:10px;' . 'line-height:12px;' . 'padding:0 0 0 6px;' . 'text-align:left;' . 'margin:0;' . 'clear:left;' . '"' . '>' . html_entity_decode(convert_smilies(stripslashes($com['comment']))) . '</p>';
                $first = false;
            }
        }
        $result .= '</div>';
    } else {
        // Open the subtext container
        $margtop = wppa_switch('align_thumbtext') ? '' : 'margin-top:' . -$imgmarginbottom . 'px;';
        $subtextcontheight = $frameheight - max($imgwidth, $imgheight);
        if (!wppa_switch('align_thumbtext')) {
            $subtextcontheight += $imgmarginbottom;
        }
        $result .= '<div' . ' style="' . 'height:' . $subtextcontheight . 'px;' . 'width:' . $framewidth . 'px;' . 'position:absolute;' . $margtop . 'overflow:hidden;' . '" >';
        // Single button voting system
        if (wppa_opt('rating_max') == '1' && wppa_switch('vote_thumb')) {
            $mylast = $wpdb->get_row($wpdb->prepare('SELECT * FROM `' . WPPA_RATING . '` WHERE `photo` = %s AND `user` = %s ORDER BY `id` DESC LIMIT 1', $id, wppa_get_user()), ARRAY_A);
            $buttext = $mylast ? __(wppa_opt('voted_button_text'), 'wp-photo-album-plus') : __(wppa_opt('vote_button_text'), 'wp-photo-album-plus');
            $result .= '<input' . ' id="wppa-vote-button-' . wppa('mocc') . '-' . $id . '"' . ' class="wppa-vote-button-thumb"' . ' style="margin:0;"' . ' type="button"' . ' onclick="wppaVoteThumb( ' . wppa('mocc') . ', ' . $id . ' )"' . ' value="' . $buttext . '"' . ' />';
        }
        // Name
        if (wppa_switch('thumb_text_name') || wppa_switch('thumb_text_owner')) {
            $result .= '<div' . ' class="wppa-thumb-text"' . ' style="' . __wcs('wppa-thumb-text') . '"' . ' >' . wppa_get_photo_name($id, wppa_switch('thumb_text_owner'), false, false, wppa_switch('thumb_text_name')) . '</div>';
        }
        // searching, link to album
        //		if ( wppa( 'src' ) || wppa( 'supersearch' ) || ( ( wppa( 'is_comten') || wppa( 'is_topten' ) || wppa( 'is_lasten' ) || wppa( 'is_featen') ) && wppa( 'start_album' ) != $thumb['album'] ) ) {
        if (wppa_switch('thumb_text_virt_album') && wppa_is_virtual() && wppa('start_album') != $thumb['album']) {
            $result .= '<div' . ' class="wppa-thumb-text"' . ' style="' . __wcs('wppa-thumb-text') . '"' . ' >' . '<a' . ' href="' . wppa_get_album_url($thumb['album']) . '"' . ' >' . '<span class="wppa-tnpar" >(</span>' . stripslashes(__(wppa_get_album_name($thumb['album']), 'wp-photo-album-plus')) . '<span class="wppa-tnpar" >)</span>' . '</a>' . '</div>';
        }
        // Share
        if (wppa_switch('share_on_thumbs')) {
            $result .= '<div' . ' class="wppa-thumb-text"' . ' style="' . __wcs('wppa-thumb-text') . '"' . ' >' . wppa_get_share_html($id, 'thumb') . '</div>';
        }
        // Delete and Edit links
        if (wppa_switch('edit_thumb') && !wppa_is_user_blacklisted()) {
            if (wppa_user_is('administrator') || current_user_can('wppa_moderate') || wppa_get_user() == wppa_get_photo_owner($id) && wppa_switch('upload_edit')) {
                $result .= '<div' . ' class="wppa-thumb-text"' . ' style="' . __wcs('wppa-thumb-text') . '"' . ' >' . '<a' . ' style="color:red;cursor:pointer;"' . ' onclick="' . esc_attr('if ( confirm( "' . __('Are you sure you want to remove this photo?', 'wp-photo-album-plus') . '" ) ) wppaAjaxRemovePhoto( ' . wppa('mocc') . ', ' . $id . ', false ); return false;') . '"' . ' >' . __('Delete', 'wp-photo-album-plus') . '</a>' . '&nbsp;' . '<a' . ' style="color:green;cursor:pointer;"' . ' onclick="wppaEditPhoto( ' . wppa('mocc') . ', ' . $id . ' ); return false;"' . ' >' . __('Edit', 'wp-photo-album-plus') . '</a>' . '</div>';
            }
        }
        // Description
        if (wppa_switch('thumb_text_desc') || $thumb['status'] == 'pending' || $thumb['status'] == 'scheduled') {
            $desc = '';
            if ($thumb['status'] == 'pending' || $thumb['status'] == 'scheduled') {
                $desc .= wppa_moderate_links('thumb', $id);
            }
            $desc .= wppa_get_photo_desc($id, wppa_switch('allow_foreign_shortcodes_thumbs'));
            $result .= '<div' . ' class="wppa-thumb-text"' . ' style="' . __wcs('wppa-thumb-text') . '"' . ' >' . $desc . '</div>';
        }
        // Rating
        if (wppa_switch('thumb_text_rating')) {
            $rating = wppa_get_rating_by_id($id);
            if ($rating && wppa_switch('show_rating_count')) {
                $rating .= ' ( ' . wppa_get_rating_count_by_id($id) . ' )';
            }
            $result .= '<div' . ' class="wppa-thumb-text"' . ' style="' . __wcs('wppa-thumb-text') . '"' . ' >' . $rating . '</div>';
        }
        // Comcount
        if (wppa_switch('thumb_text_comcount')) {
            $comcount = $wpdb->get_var("SELECT COUNT(*) FROM `" . WPPA_COMMENTS . "` WHERE `photo` = " . $id);
            if ($comcount) {
                $result .= '<div' . ' class="wppa-thumb-text"' . ' style="' . __wcs('wppa-thumb-text') . '"' . ' >' . sprintf(_n('%d comment', '%d comments', $comcount, 'wp-photo-album-plus'), $comcount) . '</div>';
            }
        }
        // Viewcount
        if (wppa_switch('thumb_text_viewcount')) {
            $result .= '<div' . ' class="wppa-thumb-text"' . ' style="clear:both;' . __wcs('wppa-thumb-text') . '"' . ' >' . sprintf(_n('%d view', '%d views', $thumb['views'], 'wp-photo-album-plus'), $thumb['views']) . '</div>';
        }
        // Close the subtext container
        $result .= '</div>';
    }
    // if ! $com_alt
    // Close the thumbframe
    $result .= '</div>';
    if ($com_alt) {
        $result .= '</div>';
    }
    return $result;
}
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;
}
 /** @see WP_Widget::widget */
 function widget($args, $instance)
 {
     global $wpdb;
     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();
     wppa('in_widget', 'topten');
     wppa_bump_mocc();
     extract($args);
     $instance = wp_parse_args((array) $instance, array('title' => '', 'sortby' => 'mean_rating', 'title' => '', 'album' => '', 'display' => 'thumbs', 'meanrat' => 'yes', 'ratcount' => 'yes', 'viewcount' => 'yes', 'includesubs' => 'yes', 'medalsonly' => 'no', 'showowner' => 'no', 'showalbum' => 'no'));
     $widget_title = apply_filters('widget_title', $instance['title']);
     $page = in_array(wppa_opt('topten_widget_linktype'), wppa('links_no_page')) ? '' : wppa_get_the_landing_page('topten_widget_linkpage', __('Top Ten Photos', 'wp-photo-album-plus'));
     $albumlinkpage = wppa_get_the_landing_page('topten_widget_album_linkpage', __('Top Ten Photo album', 'wp-photo-album-plus'));
     $max = wppa_opt('topten_count');
     $album = $instance['album'];
     switch ($instance['sortby']) {
         case 'mean_rating':
             $sortby = '`mean_rating` DESC, `rating_count` DESC, `views` DESC';
             break;
         case 'rating_count':
             $sortby = '`rating_count` DESC, `mean_rating` DESC, `views` DESC';
             break;
         case 'views':
             $sortby = '`views` DESC, `mean_rating` DESC, `rating_count` DESC';
             break;
     }
     $display = $instance['display'];
     $meanrat = $instance['meanrat'] == 'yes';
     $ratcount = $instance['ratcount'] == 'yes';
     $viewcount = $instance['viewcount'] == 'yes';
     $includesubs = $instance['includesubs'] == 'yes';
     $albenum = '';
     $medalsonly = $instance['medalsonly'] == 'yes';
     $showowner = $instance['showowner'] == 'yes';
     $showalbum = $instance['showalbum'] == 'yes';
     wppa('medals_only', $medalsonly);
     $likes = wppa_opt('rating_display_type') == 'likes';
     // When likes only, mean rating has no meaning, chan to (rating)(like)count
     if ($likes && $instance['sortby'] == 'mean_rating') {
         $instance['sortby'] = 'rating_count';
     }
     // Album specified?
     if ($album) {
         // All albums ?
         if ($album == '-2') {
             $album = '0';
         }
         // Albums of owner is current logged in user or public?
         if ($album == '-3') {
             $temp = $wpdb->get_results("SELECT `id` FROM `" . WPPA_ALBUMS . "` WHERE `owner` = '--- public ---' OR `owner` = '" . wppa_get_user() . "' ORDER BY `id`", ARRAY_A);
             $album = '';
             if ($temp) {
                 foreach ($temp as $t) {
                     $album .= '.' . $t['id'];
                 }
                 $album = ltrim($album, '.');
             }
         }
         // Including subalbums?
         if ($includesubs) {
             $albenum = wppa_alb_to_enum_children($album);
             $albenum = wppa_expand_enum($albenum);
             $album = str_replace('.', ',', $albenum);
         }
         // Doit
         if ($medalsonly) {
             $thumbs = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` " . "WHERE `album` IN (" . $album . ") " . "AND `status` IN ( 'gold', 'silver', 'bronze' ) " . "ORDER BY " . $sortby . " " . "LIMIT " . $max, ARRAY_A);
         } else {
             $thumbs = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` " . "WHERE `album` IN (" . $album . ") " . "ORDER BY " . $sortby . " " . "LIMIT " . $max, ARRAY_A);
         }
     } else {
         if ($medalsonly) {
             $thumbs = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` " . "WHERE `status` IN ( 'gold', 'silver', 'bronze' ) " . "ORDER BY " . $sortby . " " . "LIMIT " . $max, ARRAY_A);
         } else {
             $thumbs = $wpdb->get_results("SELECT * FROM `" . WPPA_PHOTOS . "` " . "ORDER BY " . $sortby . " " . "LIMIT " . $max, ARRAY_A);
         }
     }
     $widget_content = "\n" . '<!-- WPPA+ TopTen Widget start -->';
     $maxw = wppa_opt('topten_size');
     $maxh = $maxw;
     $lineheight = wppa_opt('fontsize_widget_thumb') * 1.5;
     $maxh += $lineheight;
     if ($meanrat) {
         $maxh += $lineheight;
     }
     if ($ratcount) {
         $maxh += $lineheight;
     }
     if ($viewcount) {
         $maxh += $lineheight;
     }
     if ($showowner) {
         $maxh += $lineheight;
     }
     if ($showalbum) {
         $maxh += $lineheight;
     }
     if ($thumbs) {
         foreach ($thumbs as $image) {
             $thumb = $image;
             // Make the HTML for current picture
             if ($display == 'thumbs') {
                 $widget_content .= "\n" . '<div class="wppa-widget" style="width:' . $maxw . 'px; height:' . $maxh . 'px; margin:4px; display:inline; text-align:center; float:left;">';
             } else {
                 $widget_content .= "\n" . '<div class="wppa-widget" >';
             }
             if ($image) {
                 $no_album = !$album;
                 if ($no_album) {
                     $tit = __('View the top rated photos', 'wp-photo-album-plus');
                 } else {
                     $tit = esc_attr(__(stripslashes($image['description'])));
                 }
                 $compressed_albumenum = wppa_compress_enum($albenum);
                 $link = wppa_get_imglnk_a('topten', $image['id'], '', $tit, '', $no_album, $compressed_albumenum);
                 $file = wppa_get_thumb_path($image['id']);
                 $imgstyle_a = wppa_get_imgstyle_a($image['id'], $file, $maxw, 'center', 'ttthumb');
                 $imgurl = wppa_get_thumb_url($image['id'], '', $imgstyle_a['width'], $imgstyle_a['height']);
                 $imgevents = wppa_get_imgevents('thumb', $image['id'], true);
                 $title = $link ? esc_attr(stripslashes($link['title'])) : '';
                 $widget_content .= wppa_get_the_widget_thumb('topten', $image, $album, $display, $link, $title, $imgurl, $imgstyle_a, $imgevents);
                 $widget_content .= "\n\t" . '<div style="font-size:' . wppa_opt('fontsize_widget_thumb') . 'px; line-height:' . $lineheight . 'px;">';
                 // Display (owner) ?
                 if ($showowner) {
                     $widget_content .= '<div>(' . $image['owner'] . ')</div>';
                 }
                 // Display (album) ?
                 if ($showalbum) {
                     $href = wppa_convert_to_pretty(wppa_encrypt_url(wppa_get_album_url($image['album'], $albumlinkpage, 'content', '1')));
                     $widget_content .= '<div>(<a href="' . $href . '" >' . wppa_get_album_name($image['album']) . '</a>)</div>';
                 }
                 // Display the rating
                 if ($likes) {
                     $lt = wppa_get_like_title_a($image['id']);
                 }
                 switch ($instance['sortby']) {
                     case 'mean_rating':
                         if ($meanrat == 'yes') {
                             $widget_content .= '<div>' . wppa_get_rating_by_id($image['id']) . '</div>';
                         }
                         if ($ratcount == 'yes') {
                             $n = wppa_get_rating_count_by_id($image['id']);
                             $widget_content .= '<div>' . sprintf(_n('%d vote', '%d votes', $n, 'wp-photo-album-plus'), $n) . '</div>';
                         }
                         if ($viewcount == 'yes') {
                             $n = $image['views'];
                             $widget_content .= '<div>' . sprintf(_n('%d view', '%d views', $n, 'wp-photo-album-plus'), $n) . '</div>';
                         }
                         break;
                     case 'rating_count':
                         if ($ratcount == 'yes') {
                             $n = wppa_get_rating_count_by_id($image['id']);
                             $widget_content .= '<div>' . ($likes ? $lt['display'] : sprintf(_n('%d vote', '%d votes', $n, 'wp-photo-album-plus'), $n)) . '</div>';
                         }
                         if ($meanrat == 'yes') {
                             $widget_content .= '<div>' . wppa_get_rating_by_id($image['id']) . '</div>';
                         }
                         if ($viewcount == 'yes') {
                             $n = $image['views'];
                             $widget_content .= '<div>' . sprintf(_n('%d view', '%d views', $n, 'wp-photo-album-plus'), $n) . '</div>';
                         }
                         break;
                     case 'views':
                         if ($viewcount == 'yes') {
                             $n = $image['views'];
                             $widget_content .= '<div>' . sprintf(_n('%d view', '%d views', $n, 'wp-photo-album-plus'), $n) . '</div>';
                         }
                         if ($meanrat == 'yes') {
                             $widget_content .= '<div>' . wppa_get_rating_by_id($image['id']) . '</div>';
                         }
                         if ($ratcount == 'yes') {
                             $n = wppa_get_rating_count_by_id($image['id']);
                             $widget_content .= '<div>' . ($likes ? $lt['display'] : sprintf(_n('%d vote', '%d votes', $n, 'wp-photo-album-plus'), $n)) . '</div>';
                         }
                         break;
                 }
                 $widget_content .= '</div>';
             } else {
                 // No image
                 $widget_content .= __('Photo not found', 'wp-photo-album-plus');
             }
             $widget_content .= "\n" . '</div>';
         }
     } else {
         $widget_content .= __('There are no rated photos (yet)', 'wp-photo-album-plus');
     }
     $widget_content .= '<div style="clear:both"></div>';
     $widget_content .= "\n" . '<!-- WPPA+ TopTen 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 );
     wppa_reset_occurrance();
 }
function wppa_admin_albums_collapsable()
{
    global $wpdb;
    // Read the albums
    $albums = $wpdb->get_results("SELECT * FROM `" . WPPA_ALBUMS . "` ORDER BY `id`", ARRAY_A);
    // Find the ordering method
    $reverse = false;
    if (isset($_REQUEST['order_by'])) {
        $order = $_REQUEST['order_by'];
    } else {
        $order = '';
    }
    if (!$order) {
        $order = get_option('wppa_album_order_' . wppa_get_user(), 'id');
        $reverse = get_option('wppa_album_order_' . wppa_get_user() . '_reverse') == 'yes';
    } else {
        $old_order = get_option('wppa_album_order_' . wppa_get_user(), 'id');
        $reverse = get_option('wppa_album_order_' . wppa_get_user() . '_reverse') == 'yes';
        if ($old_order == $order) {
            $reverse = !$reverse;
        } else {
            $reverse = false;
        }
        update_option('wppa_album_order_' . wppa_get_user(), $order);
        if ($reverse) {
            update_option('wppa_album_order_' . wppa_get_user() . '_reverse', 'yes');
        } else {
            update_option('wppa_album_order_' . wppa_get_user() . '_reverse', 'no');
        }
    }
    if (!empty($albums)) {
        // Setup the sequence array
        $seq = false;
        $num = false;
        foreach ($albums as $album) {
            switch ($order) {
                case 'name':
                    $seq[] = strtolower(__(stripslashes($album['name'])));
                    break;
                case 'description':
                    $seq[] = strtolower(__(stripslashes($album['description'])));
                    break;
                case 'owner':
                    $seq[] = strtolower($album['owner']);
                    break;
                case 'a_order':
                    $seq[] = $album['a_order'];
                    $num = true;
                    break;
                case 'a_parent':
                    $seq[] = strtolower(wppa_get_album_name($album['a_parent']), 'extended');
                    break;
                default:
                    $seq[] = $album['id'];
                    $num = true;
                    break;
            }
        }
        // Sort the seq array
        if ($num) {
            asort($seq, SORT_NUMERIC);
        } else {
            asort($seq, SORT_REGULAR);
        }
        // Reverse ?
        if ($reverse) {
            $t = $seq;
            $c = count($t);
            $tmp = array_keys($t);
            $seq = false;
            for ($i = $c - 1; $i >= 0; $i--) {
                $seq[$tmp[$i]] = '0';
            }
        }
        $downimg = '<img src="' . wppa_get_imgdir() . 'down.png" alt="down" style=" height:12px; position:relative; top:2px; " />';
        $upimg = '<img src="' . wppa_get_imgdir() . 'up.png" alt="up" style=" height:12px; position:relative; top:2px; " />';
        ?>
<!--	<div class="table_wrapper">	-->
		<table class="widefat wppa-table wppa-setting-table" style="margin-top:12px;" >
			<thead>
			<tr>
				<td style="min-width:20px;" >
					<img src="<?php 
        echo wppa_get_imgdir() . 'backarrow.gif';
        ?>
" style="height:16px;" title="<?php 
        _e('Collapse subalbums', 'wp-photo-album-plus');
        ?>
" />
					<img src="<?php 
        echo wppa_get_imgdir() . 'arrow.gif';
        ?>
" style="height:16px;" title="<?php 
        _e('Expand subalbums', 'wp-photo-album-plus');
        ?>
" />
				</td>
				<?php 
        $url = get_admin_url() . 'admin.php?page=wppa_admin_menu&amp;order_by=';
        ?>
				<td  colspan="6" style="min-width: 50px;" >
					<a href="<?php 
        echo wppa_dbg_url($url . 'id');
        ?>
">
						<?php 
        _e('ID', 'wp-photo-album-plus');
        if ($order == 'id') {
            if ($reverse) {
                echo $upimg;
            } else {
                echo $downimg;
            }
        }
        ?>
					</a>
				</td>

				<td  style="min-width: 120px;">
					<a href="<?php 
        echo wppa_dbg_url($url . 'name');
        ?>
">
						<?php 
        _e('Name', 'wp-photo-album-plus');
        if ($order == 'name') {
            if ($reverse) {
                echo $upimg;
            } else {
                echo $downimg;
            }
        }
        ?>
					</a>
				</td>
				<td >
					<a href="<?php 
        echo wppa_dbg_url($url . 'description');
        ?>
">
						<?php 
        _e('Description', 'wp-photo-album-plus');
        if ($order == 'description') {
            if ($reverse) {
                echo $upimg;
            } else {
                echo $downimg;
            }
        }
        ?>
					</a>
				</td>
				<?php 
        if (current_user_can('administrator')) {
            ?>
				<td  style="min-width: 100px;">
					<a href="<?php 
            echo wppa_dbg_url($url . 'owner');
            ?>
">
						<?php 
            _e('Owner', 'wp-photo-album-plus');
            if ($order == 'owner') {
                if ($reverse) {
                    echo $upimg;
                } else {
                    echo $downimg;
                }
            }
            ?>
					</a>
				</td>
				<?php 
        }
        ?>
                <td  style="min-width: 100px;" >
					<a href="<?php 
        echo wppa_dbg_url($url . 'a_order');
        ?>
">
						<?php 
        _e('Order', 'wp-photo-album-plus');
        if ($order == 'a_order') {
            if ($reverse) {
                echo $upimg;
            } else {
                echo $downimg;
            }
        }
        ?>
					</a>
				</td>
                <td  style="width: 120px;">
					<a href="<?php 
        echo wppa_dbg_url($url . 'a_parent');
        ?>
">
						<?php 
        _e('Parent', 'wp-photo-album-plus');
        if ($order == 'a_parent') {
            if ($reverse) {
                echo $upimg;
            } else {
                echo $downimg;
            }
        }
        ?>
					</a>
				</td>
				<td  title="<?php 
        _e('Albums/Photos/Moderation required/Scheduled', 'wp-photo-album-plus');
        ?>
" >
					<?php 
        _e('A/P/PM/S', 'wp-photo-album-plus');
        ?>
				</td>
				<td ><?php 
        _e('Edit', 'wp-photo-album-plus');
        ?>
</td>
				<td ><?php 
        _e('Quick', 'wp-photo-album-plus');
        ?>
</td>
				<td ><?php 
        _e('Bulk', 'wp-photo-album-plus');
        ?>
</td>
				<td ><?php 
        _e('Seq', 'wp-photo-album-plus');
        ?>
</td>
				<td ><?php 
        _e('Delete', 'wp-photo-album-plus');
        ?>
</td>
				<?php 
        if (wppa_can_create_album()) {
            echo '<td >' . __('Create', 'wp-photo-album-plus') . '</td>';
        }
        ?>
			</tr>
			</thead>
			<tbody>

			<?php 
        wppa_do_albumlist('0', '0', $albums, $seq);
        ?>
			<?php 
        if ($wpdb->get_var("SELECT COUNT(*) FROM `" . WPPA_ALBUMS . "` WHERE `a_parent` = '-1'") > 0) {
            ?>
				<tr>
					<td colspan="19" ><em><?php 
            _e('The following albums are ---separate--- and do not show up in the generic album display', 'wp-photo-album-plus');
            ?>
</em></td>
				</tr>
				<?php 
            wppa_do_albumlist('-1', '0', $albums, $seq);
            ?>
			<?php 
        }
        wppa_search_edit(true);
        ?>
			</tbody>
			<tfoot>
			<tr>
				<td>
					<img src="<?php 
        echo wppa_get_imgdir() . 'backarrow.gif';
        ?>
" style="height:16px;" />
					<img src="<?php 
        echo wppa_get_imgdir() . 'arrow.gif';
        ?>
" style="height:16px;" />
				</td>
				<?php 
        $url = get_admin_url() . 'admin.php?page=wppa_admin_menu&amp;order_by=';
        ?>
				<td  colspan="6" >
					<a href="<?php 
        echo wppa_dbg_url($url . 'id');
        ?>
">
						<?php 
        _e('ID', 'wp-photo-album-plus');
        if ($order == 'id') {
            if ($reverse) {
                echo $upimg;
            } else {
                echo $downimg;
            }
        }
        ?>
					</a>
				</td>

				<td  style="width: 120px;">
					<a href="<?php 
        echo wppa_dbg_url($url . 'name');
        ?>
">
						<?php 
        _e('Name', 'wp-photo-album-plus');
        if ($order == 'name') {
            if ($reverse) {
                echo $upimg;
            } else {
                echo $downimg;
            }
        }
        ?>
					</a>
				</td>
				<td >
					<a href="<?php 
        echo wppa_dbg_url($url . 'description');
        ?>
">
						<?php 
        _e('Description', 'wp-photo-album-plus');
        if ($order == 'description') {
            if ($reverse) {
                echo $upimg;
            } else {
                echo $downimg;
            }
        }
        ?>
					</a>
				</td>
				<?php 
        if (current_user_can('administrator')) {
            ?>
				<td  style="width: 100px;">
					<a href="<?php 
            echo wppa_dbg_url($url . 'owner');
            ?>
">
						<?php 
            _e('Owner', 'wp-photo-album-plus');
            if ($order == 'owner') {
                if ($reverse) {
                    echo $upimg;
                } else {
                    echo $downimg;
                }
            }
            ?>
					</a>
				</td>
				<?php 
        }
        ?>
                <td >
					<a href="<?php 
        echo wppa_dbg_url($url . 'a_order');
        ?>
">
						<?php 
        _e('Order', 'wp-photo-album-plus');
        if ($order == 'a_order') {
            if ($reverse) {
                echo $upimg;
            } else {
                echo $downimg;
            }
        }
        ?>
					</a>
				</td>
                <td  style="width: 120px;">
					<a href="<?php 
        echo wppa_dbg_url($url . 'a_parent');
        ?>
">
						<?php 
        _e('Parent', 'wp-photo-album-plus');
        if ($order == 'a_parent') {
            if ($reverse) {
                echo $upimg;
            } else {
                echo $downimg;
            }
        }
        ?>
					</a>
				</td>
				<td  title="<?php 
        _e('Albums/Photos/Moderation required/Scheduled', 'wp-photo-album-plus');
        ?>
" >
					<?php 
        _e('A/P/PM/S', 'wp-photo-album-plus');
        ?>
				</td>
				<td ><?php 
        _e('Edit', 'wp-photo-album-plus');
        ?>
</td>
				<td ><?php 
        _e('Quick', 'wp-photo-album-plus');
        ?>
</td>
				<td ><?php 
        _e('Bulk', 'wp-photo-album-plus');
        ?>
</td>
				<td ><?php 
        _e('Seq', 'wp-photo-album-plus');
        ?>
</td>
				<td ><?php 
        _e('Delete', 'wp-photo-album-plus');
        ?>
</td>
				<?php 
        if (wppa_can_create_album()) {
            echo '<td >' . __('Create', 'wp-photo-album-plus') . '</td>';
        }
        ?>
			</tr>
			</tfoot>

		</table>

		<script type="text/javascript" >
			function checkArrows() {
				elms = jQuery('.alb-arrow-off');
				for(i=0;i<elms.length;i++) {
					elm = elms[i];
					if ( elm.parentNode.parentNode.style.display == 'none' ) elm.style.display = 'none';
				}
				elms = jQuery('.alb-arrow-on');
				for(i=0;i<elms.length;i++) {
					elm = elms[i];
					if ( elm.parentNode.parentNode.style.display == 'none' ) elm.style.display = '';
				}
			}
		</script>
<!--	</div> -->
<?php 
        wppa_album_admin_footer();
    } else {
        ?>
	<p><?php 
        _e('No albums yet.', 'wp-photo-album-plus');
        ?>
</p>
<?php 
    }
}