function wppa_do_frontend_file_upload($file, $alb)
{
    global $wpdb;
    // Log upload attempt
    wppa_log('Upl', 'FE Upload attempt of file ' . $file['name'] . ', size=' . filesize($file['tmp_name']));
    $album = wppa_cache_album($alb);
    if (!wppa_allow_uploads($alb) || !wppa_allow_user_uploads()) {
        wppa_alert(__('Max uploads reached', 'wp-photo-album-plus'));
        return false;
    }
    if ($file['error'] != '0') {
        wppa_alert(__('Error during upload', 'wp-photo-album-plus'));
        return false;
    }
    $imgsize = getimagesize($file['tmp_name']);
    if (!is_array($imgsize)) {
        wppa_alert(__('Uploaded file is not an image', 'wp-photo-album-plus'));
        return false;
    }
    if ($imgsize[2] < 1 || $imgsize[2] > 3) {
        wppa_alert(sprintf(__('Only gif, jpg and png image files are supported. Returned filetype = %d.', 'wp-photo-album-plus'), $imagesize[2]));
        return false;
    }
    $ms = wppa_opt('upload_fronend_maxsize');
    if ($ms) {
        // Max size configured
        if ($imgsize[0] > $ms || $imgsize[0] > $ms) {
            wppa_alert(sprintf(__('Uploaded file is larger than the allowed maximum of %d x %d pixels.', 'wp-photo-album-plus'), $ms, $ms));
            return false;
        }
    }
    if (wppa_switch('void_dups')) {
        // Check for already exists
        if (wppa_file_is_in_album(wppa_sanitize_file_name($file['name']), $alb)) {
            wppa_alert(sprintf(__('Uploaded file %s already exists in this album.', 'wp-photo-album-plus'), wppa_sanitize_file_name($file['name'])));
            return false;
        }
    }
    $mayupload = wppa_check_memory_limit('', $imgsize[0], $imgsize[1]);
    if ($mayupload === false) {
        $maxsize = wppa_check_memory_limit(false);
        if (is_array($maxsize)) {
            wppa_alert(sprintf(__('The image is too big. Max photo size: %d x %d (%2.1f MegaPixel)', 'wp-photo-album-plus'), $maxsize['maxx'], $maxsize['maxy'], $maxsize['maxp'] / (1024 * 1024)));
            return false;
        }
    }
    switch ($imgsize[2]) {
        // mime type
        case 1:
            $ext = 'gif';
            break;
        case 2:
            $ext = 'jpg';
            break;
        case 3:
            $ext = 'png';
            break;
    }
    if (wppa_get_post('user-name')) {
        $name = wppa_get_post('user-name');
    } else {
        $name = $file['name'];
    }
    $name = wppa_sanitize_photo_name($name);
    $desc = balanceTags(wppa_get_post('user-desc'), true);
    $linktarget = '_self';
    $status = wppa_switch('upload_moderate') && !current_user_can('wppa_admin') ? 'pending' : 'publish';
    $filename = wppa_sanitize_file_name($file['name']);
    $id = wppa_create_photo_entry(array('album' => $alb, 'ext' => $ext, 'name' => $name, 'description' => $desc, 'status' => $status, 'filename' => $filename));
    if (!$id) {
        wppa_alert(__('Could not insert photo into db.', 'wp-photo-album-plus'));
        return false;
    } else {
        wppa_save_source($file['tmp_name'], $filename, $alb);
        wppa_update_album(array('id' => $alb, 'modified' => time()));
        wppa_flush_treecounts($alb);
        wppa_flush_upldr_cache('photoid', $id);
    }
    if (wppa_make_the_photo_files($file['tmp_name'], $id, $ext)) {
        // Repair photoname if not standard
        if (!wppa_get_post('user-name')) {
            wppa_set_default_name($id, $file['name']);
        }
        // Custom data
        if (wppa_switch('fe_custom_fields')) {
            $custom_data = array('', '', '', '', '', '', '', '', '', '');
            for ($i = '0'; $i < '10'; $i++) {
                if (isset($_POST['wppa-user-custom-' . $i])) {
                    $custom_data[$i] = strip_tags($_POST['wppa-user-custom-' . $i]);
                }
            }
            wppa_update_photo(array('id' => $id, 'custom' => serialize($custom_data)));
        }
        // Default tags
        wppa_set_default_tags($id);
        // Custom tags
        $tags = wppa_get_photo_item($id, 'tags');
        $oldt = $tags;
        for ($i = '1'; $i < '4'; $i++) {
            if (isset($_POST['wppa-user-tags-' . $i])) {
                // Existing tags
                $tags .= ',' . implode(',', $_POST['wppa-user-tags-' . $i]);
            }
        }
        if (isset($_POST['wppa-new-tags'])) {
            // New tags
            $newt = $_POST['wppa-new-tags'];
            $tags .= ',' . $newt;
        } else {
            $newt = '';
        }
        $tags = wppa_sanitize_tags(str_replace(array('\'', '"'), ',', wppa_filter_iptc(wppa_filter_exif($tags, $id), $id)));
        if ($tags != $oldt) {
            // Added tag(s)
            wppa_update_photo(array('id' => $id, 'tags' => $tags));
        }
        // Index
        wppa_index_add('photo', $id);
        // Tags
        if ($tags) {
            wppa_clear_taglist();
            // Forces recreation
        }
        // and add watermark ( optionally ) to fullsize image only
        wppa_add_watermark($id);
        // Also to thumbnail?
        if (wppa_switch('watermark_thumbs')) {
            wppa_create_thumbnail($id);
            // create new thumb
        }
        // Is it a default coverimage?
        wppa_check_coverimage($id);
        // Mail
        if (wppa_switch('upload_notify')) {
            $to = get_bloginfo('admin_email');
            $subj = sprintf(__('New photo uploaded: %s', 'wp-photo-album-plus'), $name);
            $cont['0'] = sprintf(__('User %1$s uploaded photo %2$s into album %3$s', 'wp-photo-album-plus'), wppa_get_user(), $id, wppa_get_album_name($alb));
            if (wppa_switch('upload_moderate') && !current_user_can('wppa_admin')) {
                $cont['1'] = __('This upload requires moderation', 'wp-photo-album-plus');
                $cont['2'] = '<a href="' . get_admin_url() . 'admin.php?page=wppa_admin_menu&tab=pmod&photo=' . $id . '" >' . __('Moderate manage photo', 'wp-photo-album-plus') . '</a>';
            } else {
                $cont['1'] = __('Details:', 'wp-photo-album-plus');
                $cont['1'] .= ' <a href="' . get_admin_url() . 'admin.php?page=wppa_admin_menu&tab=pmod&photo=' . $id . '" >' . __('Manage photo', 'wp-photo-album-plus') . '</a>';
            }
            wppa_send_mail($to, $subj, $cont, $id);
        }
        return true;
    } else {
        return false;
    }
}
function wppa_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_do_frontend_file_upload($file, $alb)
{
    global $wpdb;
    global $wppa_supported_video_extensions;
    global $wppa_supported_audio_extensions;
    // Log upload attempt
    wppa_log('Upl', 'FE Upload attempt of file ' . $file['name'] . ', size=' . filesize($file['tmp_name']));
    $album = wppa_cache_album($alb);
    // Legal here?
    if (!wppa_allow_uploads($alb) || !wppa_allow_user_uploads()) {
        wppa_alert(__('Max uploads reached', 'wp-photo-album-plus'));
        return false;
    }
    // No error during upload?
    if ($file['error'] != '0') {
        wppa_alert(__('Error during upload', 'wp-photo-album-plus'));
        return false;
    }
    // Find the filename
    $filename = wppa_sanitize_file_name($file['name']);
    $filename = wppa_strip_ext($filename);
    // See if this filename with any extension already exists in this album
    $id = $wpdb->get_var("SELECT `id` FROM `" . WPPA_PHOTOS . "` WHERE `filename` LIKE '" . $filename . ".%' AND `album` = " . $alb);
    // Addition to an av item?
    if ($id) {
        $is_av = wppa_get_photo_item($id, 'ext') == 'xxx';
    } else {
        $is_av = false;
    }
    // see if audio / video and process
    if (wppa_switch('enable_video') && wppa_switch('user_upload_video_on') && in_array(strtolower(wppa_get_ext($file['name'])), $wppa_supported_video_extensions) || wppa_switch('enable_audio') && wppa_switch('user_upload_audio_on') && in_array(strtolower(wppa_get_ext($file['name'])), $wppa_supported_audio_extensions)) {
        $is_av = true;
        // Find the name
        if (wppa_get_post('user-name')) {
            $name = wppa_get_post('user-name');
        } else {
            $name = $file['name'];
        }
        $name = wppa_sanitize_photo_name($name);
        $filename .= '.xxx';
        // update entry
        if ($id) {
            wppa_update_photo(array('id' => $id, 'ext' => 'xxx', 'filename' => $filename));
        }
        // Add new entry
        if (!$id) {
            $id = wppa_create_photo_entry(array('album' => $alb, 'filename' => $filename, 'ext' => 'xxx', 'name' => $name, 'description' => balanceTags(wppa_get_post('user-desc'), true)));
            if (!$id) {
                wppa_alert(__('Could not insert media into db.', 'wp-photo-album-plus'));
                return false;
            }
        }
        // Housekeeping
        wppa_update_album(array('id' => $alb, 'modified' => time()));
        wppa_flush_treecounts($alb);
        wppa_flush_upldr_cache('photoid', $id);
        // Add video filetype
        $ext = strtolower(wppa_get_ext($file['name']));
        $newpath = wppa_strip_ext(wppa_get_photo_path($id)) . '.' . $ext;
        copy($file['tmp_name'], $newpath);
        // Repair name if not standard
        if (!wppa_get_post('user-name')) {
            wppa_set_default_name($id, $file['name']);
        }
        // tags
        wppa_fe_add_tags($id);
        // custom
        wppa_fe_add_custom($id);
        // Done!
        return $id;
    }
    // If not already an existing audio / video; Forget the id from a previously found item with the same filename.
    if (!$is_av) {
        $id = false;
    }
    // Is it an image?
    $imgsize = getimagesize($file['tmp_name']);
    if (!is_array($imgsize)) {
        wppa_alert(__('Uploaded file is not an image', 'wp-photo-album-plus'));
        return false;
    }
    // Is it a supported image filetype?
    if ($imgsize[2] != IMAGETYPE_GIF && $imgsize[2] != IMAGETYPE_JPEG && $imgsize[2] != IMAGETYPE_PNG) {
        wppa_alert(sprintf(__('Only gif, jpg and png image files are supported. Returned info = %s.', 'wp-photo-album-plus'), wppa_serialize($imgsize)), false, false);
        return false;
    }
    // Is it not too big?
    $ms = wppa_opt('upload_fronend_maxsize');
    if ($ms) {
        // Max size configured
        if ($imgsize[0] > $ms || $imgsize[1] > $ms) {
            wppa_alert(sprintf(__('Uploaded file is larger than the allowed maximum of %d x %d pixels.', 'wp-photo-album-plus'), $ms, $ms));
            return false;
        }
    }
    // Check for already exists
    if (wppa_switch('void_dups')) {
        if (wppa_file_is_in_album(wppa_sanitize_file_name($file['name']), $alb)) {
            wppa_alert(sprintf(__('Uploaded file %s already exists in this album.', 'wp-photo-album-plus'), wppa_sanitize_file_name($file['name'])));
            return false;
        }
    }
    // Check for max memory needed to rocess image?
    $mayupload = wppa_check_memory_limit('', $imgsize[0], $imgsize[1]);
    if ($mayupload === false) {
        $maxsize = wppa_check_memory_limit(false);
        if (is_array($maxsize)) {
            wppa_alert(sprintf(__('The image is too big. Max photo size: %d x %d (%2.1f MegaPixel)', 'wp-photo-album-plus'), $maxsize['maxx'], $maxsize['maxy'], $maxsize['maxp'] / (1024 * 1024)));
            return false;
        }
    }
    // Find extension from mimetype
    switch ($imgsize[2]) {
        // mime type
        case 1:
            $ext = 'gif';
            break;
        case 2:
            $ext = 'jpg';
            break;
        case 3:
            $ext = 'png';
            break;
    }
    // Did the user supply a photoname?
    if (wppa_get_post('user-name')) {
        $name = wppa_get_post('user-name');
    } else {
        $name = $file['name'];
    }
    // Sanitize input
    $name = wppa_sanitize_photo_name($name);
    $desc = balanceTags(wppa_get_post('user-desc'), true);
    // If BlogIt! and no descrption given, use name field - this is for the shortcode used: typ"mphoto"
    if (!$desc && isset($_POST['wppa-blogit'])) {
        $desc = 'w#name';
    }
    // Find status and other needed data
    $linktarget = '_self';
    $status = wppa_switch('upload_moderate') && !current_user_can('wppa_admin') ? 'pending' : 'publish';
    if (wppa_switch('fe_upload_private')) {
        $status = 'private';
    }
    $filename = wppa_sanitize_file_name($file['name']);
    // Create new entry if this is not a posterfile
    if (!$is_av) {
        $id = wppa_create_photo_entry(array('album' => $alb, 'ext' => $ext, 'name' => $name, 'description' => $desc, 'status' => $status, 'filename' => $filename));
    }
    if (!$id) {
        wppa_alert(__('Could not insert photo into db.', 'wp-photo-album-plus'));
        return false;
    } else {
        wppa_save_source($file['tmp_name'], $filename, $alb);
        wppa_make_o1_source($id);
        wppa_update_album(array('id' => $alb, 'modified' => time()));
        wppa_flush_treecounts($alb);
        wppa_flush_upldr_cache('photoid', $id);
    }
    if (wppa_make_the_photo_files($file['tmp_name'], $id, $ext)) {
        // Repair photoname if not standard
        if (!wppa_get_post('user-name')) {
            wppa_set_default_name($id, $file['name']);
        }
        // Custom data
        wppa_fe_add_custom($id);
        // Add tags
        wppa_fe_add_tags($id);
        // and add watermark ( optionally ) to fullsize image only
        wppa_add_watermark($id);
        // Also to thumbnail?
        if (wppa_switch('watermark_thumbs')) {
            wppa_create_thumbnail($id);
            // create new thumb
        }
        // Is it a default coverimage?
        wppa_check_coverimage($id);
        // Mail
        if (wppa_switch('upload_notify')) {
            $to = get_bloginfo('admin_email');
            $subj = sprintf(__('New photo uploaded: %s', 'wp-photo-album-plus'), $name);
            $cont['0'] = sprintf(__('User %1$s uploaded photo %2$s into album %3$s', 'wp-photo-album-plus'), wppa_get_user(), $id, wppa_get_album_name($alb));
            if (wppa_switch('upload_moderate') && !current_user_can('wppa_admin')) {
                $cont['1'] = __('This upload requires moderation', 'wp-photo-album-plus');
                $cont['2'] = '<a href="' . get_admin_url() . 'admin.php?page=wppa_admin_menu&tab=pmod&photo=' . $id . '" >' . __('Moderate manage photo', 'wp-photo-album-plus') . '</a>';
            } else {
                $cont['1'] = __('Details:', 'wp-photo-album-plus');
                $cont['1'] .= ' <a href="' . get_admin_url() . 'admin.php?page=wppa_admin_menu&tab=pmod&photo=' . $id . '" >' . __('Manage photo', 'wp-photo-album-plus') . '</a>';
            }
            wppa_send_mail($to, $subj, $cont, $id);
        }
        return $id;
    }
    return false;
}