示例#1
0
 /**
  * Parses the nggMeta data only if needed
  * @param int $image path to a image
  * @param bool $onlyEXIF parse only exif if needed
  * @return
  */
 function __construct($image_or_id, $onlyEXIF = false)
 {
     if (is_int($image_or_id)) {
         //get the path and other data about the image
         $this->image = C_Image_Mapper::get_instance()->find($image_or_id);
     } else {
         $this->image = $image_or_id;
     }
     $imagePath = C_Gallery_Storage::get_instance()->get_image_abspath($this->image);
     if (!file_exists($imagePath)) {
         return false;
     }
     $this->size = @getimagesize($imagePath, $metadata);
     if ($this->size && is_array($metadata)) {
         // get exif - data
         if (is_callable('exif_read_data')) {
             $this->exif_data = @exif_read_data($imagePath, NULL, TRUE);
         }
         // stop here if we didn't need other meta data
         if ($onlyEXIF) {
             return true;
         }
         // get the iptc data - should be in APP13
         if (is_callable('iptcparse') && isset($metadata['APP13'])) {
             $this->iptc_data = @iptcparse($metadata['APP13']);
         }
         // get the xmp data in a XML format
         if (is_callable('xml_parser_create')) {
             $this->xmp_data = $this->extract_XMP($imagePath);
         }
         return true;
     }
     return false;
 }
 function index_action()
 {
     $this->enqueue_static_resources();
     $settings = C_NextGen_Settings::get_instance();
     $retval = $settings->proofing_user_confirmation_not_found;
     if ($proof = C_NextGen_Pro_Proofing_Mapper::get_instance()->find_by_hash($this->param('proof'), TRUE)) {
         $image_mapper = C_Image_Mapper::get_instance();
         $images = array();
         foreach ($proof->proofed_gallery['image_list'] as $image_id) {
             $images[] = $image_mapper->find($image_id);
         }
         $message = $settings->proofing_user_confirmation_template;
         if (preg_match_all('/%%(\\w+)%%/', $settings->proofing_user_confirmation_template, $matches, PREG_SET_ORDER) > 0) {
             foreach ($matches as $match) {
                 switch ($match[1]) {
                     case 'user_name':
                         $message = str_replace('%%user_name%%', $proof->customer_name, $message);
                         break;
                     case 'user_email':
                         $message = str_replace('%%user_email%%', $proof->email, $message);
                         break;
                     case 'proof_link':
                         $message = str_replace('%%proof_link%%', $proof->referer, $message);
                         break;
                     case 'proof_details':
                         $imagehtml = $this->object->render_partial('photocrati-nextgen_pro_proofing#confirmation', array('images' => $images, 'storage' => C_Gallery_Storage::get_instance()), TRUE);
                         $message = str_replace('%%proof_details%%', $imagehtml, $message);
                         break;
                 }
             }
             $retval = $message;
         }
     }
     return $retval;
 }
 /**
  * Gets all digital downloads for the pricelist
  * @param null $image_id
  * @return mixed
  */
 function get_digital_downloads($image_id = NULL)
 {
     // Find digital download items
     $mapper = C_Pricelist_Item_Mapper::get_instance();
     $conditions = array(array("pricelist_id = %d", $this->object->id()), array("source IN %s", array(NGG_PRO_DIGITAL_DOWNLOADS_SOURCE)));
     $items = $mapper->select()->where($conditions)->order_by('ID', 'ASC')->run_query();
     // Filter by image resolutions
     if ($image_id) {
         $image = is_object($image_id) ? $image_id : C_Image_Mapper::get_instance()->find($image_id);
         if ($image) {
             $retval = array();
             $storage = C_Gallery_Storage::get_instance();
             foreach ($items as $item) {
                 $source_width = $image->meta_data['width'];
                 $source_height = $image->meta_data['height'];
                 // the downloads themselves come from the backup as source so if possible only filter images
                 // whose backup file doesn't have sufficient dimensions
                 $backup_abspath = $storage->get_backup_abspath($image);
                 if (@file_exists($backup_abspath)) {
                     $dimensions = @getimagesize($backup_abspath);
                     $source_width = $dimensions[0];
                     $source_height = $dimensions[1];
                 }
                 if (isset($item->resolution) && $item->resolution >= 0 && ($source_height >= $item->resolution or $source_width >= $item->resolution)) {
                     $retval[] = $item;
                 }
             }
             $items = $retval;
         }
     }
     return $items;
 }
示例#4
0
/**
 * Image edit functions via AJAX
 *
 * @author Alex Rabe
 *
 *
 * @return void
 */
function ngg_ajax_operation()
{
    global $wpdb;
    // if nonce is not correct it returns -1
    check_ajax_referer("ngg-ajax");
    // check for correct capability
    if (!is_user_logged_in()) {
        die('-1');
    }
    // check for correct NextGEN capability
    if (!current_user_can('NextGEN Upload images') && !current_user_can('NextGEN Manage gallery')) {
        die('-1');
    }
    // include the ngg function
    include_once dirname(__FILE__) . '/functions.php';
    // Get the image id
    if (isset($_POST['image'])) {
        $id = (int) $_POST['image'];
        // let's get the image data
        $picture = nggdb::find_image($id);
        // what do you want to do ?
        switch ($_POST['operation']) {
            case 'create_thumbnail':
                $result = nggAdmin::create_thumbnail($picture);
                break;
            case 'resize_image':
                $result = nggAdmin::resize_image($picture);
                break;
            case 'rotate_cw':
                $result = nggAdmin::rotate_image($picture, 'CW');
                nggAdmin::create_thumbnail($picture);
                break;
            case 'rotate_ccw':
                $result = nggAdmin::rotate_image($picture, 'CCW');
                nggAdmin::create_thumbnail($picture);
                break;
            case 'set_watermark':
                $result = nggAdmin::set_watermark($picture);
                break;
            case 'recover_image':
                $result = nggAdmin::recover_image($id) ? '1' : '0';
                break;
            case 'import_metadata':
                $result = C_Image_Mapper::get_instance()->reimport_metadata($id) ? '1' : '0';
                break;
            case 'get_image_ids':
                $result = nggAdmin::get_image_ids($id);
                break;
            default:
                do_action('ngg_ajax_' . $_POST['operation']);
                die('-1');
                break;
        }
        // A success should return a '1'
        die($result);
    }
    // The script should never stop here
    die('0');
}
 function cheque_checkout_action()
 {
     $retval = array();
     $items = $this->param('items');
     if (!$items) {
         return array('error' => __('Your cart is empty', 'nggallery'));
     }
     $customer = array('name' => $this->param('customer_name'), 'email' => $this->param('customer_email'), 'address' => $this->param('customer_address'), 'city' => $this->param('customer_city'), 'state' => $this->param('customer_state'), 'postal' => $this->param('customer_postal'), 'country' => $this->param('customer_country'));
     $retval['customer'] = $customer;
     // Presently we only do basic field validation: ensure that each field is filled and that
     // the country selected exists in C_NextGen_Pro_Currencies::$countries
     foreach ($customer as $key => $val) {
         if (empty($val)) {
             $retval['error'] = __('Please fill all fields and try again', 'nggallery');
             break;
         }
     }
     // No error yet?
     if (!isset($retval['error'])) {
         if (empty(C_NextGen_Pro_Currencies::$countries[$customer['country']])) {
             return array('error' => __('Invalid country selected, please try again.', 'nggallery'));
         } else {
             $customer['country'] = C_NextGen_Pro_Currencies::$countries[$customer['country']]['name'];
         }
         $checkout = new C_NextGen_Pro_Checkout();
         $cart = new C_NextGen_Pro_Cart();
         $settings = C_NextGen_Settings::get_instance();
         $currency = C_NextGen_Pro_Currencies::$currencies[$settings->ecommerce_currency];
         foreach ($items as $image_id => $image_items) {
             if ($image = C_Image_Mapper::get_instance()->find($image_id)) {
                 $cart->add_image($image_id, $image);
                 foreach ($image_items as $item_id => $quantity) {
                     if ($item = C_Pricelist_Item_Mapper::get_instance()->find($item_id)) {
                         $item->quantity = $quantity;
                         $cart->add_item($image_id, $item_id, $item);
                     }
                 }
             }
         }
         // Calculate the total
         $use_home_country = intval($this->param('use_home_country'));
         $order_total = $cart->get_total($use_home_country);
         // Create the order
         if (!$cart->has_items()) {
             return array('error' => __('Your cart is empty', 'nggallery'));
         }
         $order = $checkout->create_order($cart->to_array(), $customer['name'], $customer['email'], $order_total, 'cheque', $customer['address'], $customer['city'], $customer['state'], $customer['postal'], $customer['country'], $use_home_country, 'unverified');
         $order->status = 'unverified';
         $order->gateway_admin_note = __('Payment was successfully made via Check. Once you have received payment, you can click “Verify” in the View Orders page and a confirmation email will be sent to the user.');
         C_Order_Mapper::get_instance()->save($order);
         $checkout->send_email_notification($order->hash);
         $retval['order'] = $order->hash;
         $retval['redirect'] = $checkout->get_thank_you_page_url($order->hash, TRUE);
     }
     return $retval;
 }
 function index_action()
 {
     wp_dequeue_script('photocrati_ajax');
     wp_dequeue_script('frame_event_publisher');
     wp_dequeue_script('jquery');
     wp_dequeue_style('nextgen_gallery_related_images');
     $img_mapper = C_Image_Mapper::get_instance();
     $image_id = $this->param('image_id');
     if ($image = $img_mapper->find($image_id)) {
         $displayed_gallery_id = $this->param('displayed_gallery_id');
         // Template parameters
         $params = array('img' => $image);
         // Get the url & dimensions
         $named_size = $this->param('named_size');
         $storage = C_Gallery_Storage::get_instance();
         $dimensions = $storage->get_image_dimensions($image, $named_size);
         $image->url = $storage->get_image_url($image, $named_size, TRUE);
         $image->width = $dimensions['width'];
         $image->height = $dimensions['height'];
         // Generate the lightbox url
         $router = $this->get_router();
         $lightboxes = C_Lightbox_Library_Manager::get_instance();
         $lightbox = $lightboxes->get(NGG_PRO_LIGHTBOX);
         $uri = urldecode($this->param('uri'));
         $lightbox_slug = $lightbox->values['nplModalSettings']['router_slug'];
         $qs = $this->get_querystring();
         if ($qs) {
             $lightbox_url = $router->get_url('/', FALSE, 'root');
             $lightbox_url .= "?" . $qs;
         } else {
             $lightbox_url = $router->get_url($uri, FALSE, 'root');
             $lightbox_url .= '/';
         }
         // widget galleries shouldn't have a url specific to one image
         if (FALSE !== strpos($displayed_gallery_id, 'widget-ngg-images-')) {
             $image_id = '!';
         }
         $params['lightbox_url'] = "{$lightbox_url}#{$lightbox_slug}/{$displayed_gallery_id}/{$image_id}";
         // Add the blog name
         $params['blog_name'] = get_bloginfo('name');
         if ($lightbox->values['nplModalSettings']['enable_twitter_cards']) {
             $params['enable_twitter_cards'] = $lightbox->values['nplModalSettings']['enable_twitter_cards'];
             $params['twitter_username'] = $lightbox->values['nplModalSettings']['twitter_username'];
         }
         // Add routed url
         $protocol = $router->is_https() ? 'https://' : 'http://';
         $params['routed_url'] = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
         // Render the opengraph metadata
         $this->expires('+1 day');
         $this->render_view("photocrati-nextgen_pro_lightbox#opengraph", $params);
     } else {
         header(__('Status: 404 Image not found', 'nextgen-gallery-pro'));
         echo __('Image not found', 'nextgen-gallery-pro');
     }
 }
 function upload_images()
 {
     $storage = C_Gallery_Storage::get_instance();
     $image_mapper = C_Image_Mapper::get_instance();
     $gallery_mapper = C_Gallery_Mapper::get_instance();
     // Get Gallery ID
     $galleryID = absint($_POST['galleryselect']);
     if (0 == $galleryID) {
         $galleryID = get_option('npu_default_gallery');
         if (empty($galleryID)) {
             self::show_error(__('No gallery selected.', 'nextgen-public-uploader'));
             return;
         }
     }
     // Get the Gallery
     $gallery = $gallery_mapper->find($galleryID);
     if (!$gallery->path) {
         self::show_error(__('Failure in database, no gallery path set.', 'nextgen-public-uploader'));
         return;
     }
     // Read Image List
     foreach ($_FILES as $key => $value) {
         if (0 == $_FILES[$key]['error']) {
             try {
                 if ($storage->is_image_file($_FILES[$key]['tmp_name'])) {
                     $image = $storage->object->upload_base64_image($gallery, file_get_contents($_FILES[$key]['tmp_name']), $_FILES[$key]['name']);
                     if (get_option('npu_exclude_select')) {
                         $image->exclude = 1;
                         $image_mapper->save($image);
                     }
                     // Add to Image and Dir List
                     $this->arrImgNames[] = $image->filename;
                     $this->arrImageIds[] = $image->id();
                     $this->strGalleryPath = $gallery->path;
                 } else {
                     unlink($_FILES[$key]['tmp_name']);
                     $error_msg = sprintf(__('<strong>%s</strong> is not a valid file.', 'nextgen-public-uploader'), $_FILES[$key]['name']);
                     self::show_error($error_msg);
                     continue;
                 }
             } catch (E_NggErrorException $ex) {
                 self::show_error('<strong>' . $ex->getMessage() . '</strong>');
                 continue;
             } catch (Exception $ex) {
                 self::show_error('<strong>' . $ex->getMessage() . '</strong>');
                 continue;
             }
         }
     }
 }
 /**
  * Read an image file into memory and display it
  *
  * This is necessary for htaccess or server-side protection that blocks access to filenames ending with "_backup"
  * At the moment it only supports the backup or full size image.
  */
 function get_image_file_action()
 {
     $order_id = $this->param('order_id', FALSE);
     $image_id = $this->param('image_id', FALSE);
     $bail = FALSE;
     if (!$order_id || !$image_id) {
         $bail = TRUE;
     }
     $order = C_Order_Mapper::get_instance()->find_by_hash($order_id);
     if (!in_array($image_id, $order->cart['image_ids'])) {
         $bail = TRUE;
     }
     if ($order->status != 'verified') {
         $bail = TRUE;
     }
     if ($bail) {
         header('HTTP/1.1 404 Not found');
         exit;
     }
     $storage = C_Gallery_Storage::get_instance();
     if (version_compare(NGG_PLUGIN_VERSION, '2.0.66.99') <= 0) {
         // Pre 2.0.67 didn't fallback to the original path if the backup file didn't exist
         $imagemapper = C_Image_Mapper::get_instance();
         $fs = C_Fs::get_instance();
         $image = $imagemapper->find($image_id);
         $gallery_path = $storage->get_gallery_abspath($image->galleryid);
         $abspath = $fs->join_paths($gallery_path, $image->filename . '_backup');
         if (!@file_exists($abspath)) {
             $abspath = $storage->get_image_abspath($image_id, 'full');
         }
     } else {
         $abspath = $storage->get_image_abspath($image_id, 'backup');
     }
     $mimetype = 'application/octet';
     if (function_exists('finfo_buffer')) {
         $finfo = new finfo(FILEINFO_MIME);
         $mimetype = @$finfo->file($abspath);
     } elseif (function_exists('mime_content_type')) {
         $mimetype = @mime_content_type($abspath);
     }
     header('Content-Description: File Transfer');
     header('Content-Disposition: attachment; filename=' . basename($storage->get_image_abspath($image_id, 'full')));
     header("Content-type: " . $mimetype);
     header('Expires: 0');
     header('Cache-Control: must-revalidate');
     header('Pragma: public');
     header('Content-Length: ' . @filesize($abspath));
     readfile($abspath);
     exit;
 }
示例#9
0
 function processor()
 {
     global $wpdb, $ngg, $nggdb;
     // Delete a picture
     if ($this->mode == 'delpic') {
         //TODO:Remove also Tag reference
         check_admin_referer('ngg_delpicture');
         $image = $nggdb->find_image($this->pid);
         if ($image) {
             if ($ngg->options['deleteImg']) {
                 @unlink($image->imagePath);
                 @unlink($image->thumbPath);
                 @unlink($image->imagePath . '_backup');
             }
             $mapper = C_Image_Mapper::get_instance();
             $result = $mapper->destroy($this->pid);
             do_action('ngg_delete_picture', $this->pid);
             if ($result) {
                 nggGallery::show_message(__('Picture', 'nggallery') . ' \'' . $this->pid . '\' ' . __('deleted successfully', 'nggallery'));
             }
         }
         $this->mode = 'edit';
         // show pictures
     }
     // Recover picture from backup
     if ($this->mode == 'recoverpic') {
         check_admin_referer('ngg_recoverpicture');
         $image = $nggdb->find_image($this->pid);
         // bring back the old image
         nggAdmin::recover_image($image);
         nggAdmin::create_thumbnail($image);
         nggGallery::show_message(__('Operation successful. Please clear your browser cache.', "nggallery"));
         $this->mode = 'edit';
         // show pictures
     }
     // will be called after a ajax operation
     if (isset($_POST['ajax_callback'])) {
         if ($_POST['ajax_callback'] == 1) {
             nggGallery::show_message(__('Operation successful. Please clear your browser cache.', "nggallery"));
         }
     }
     // show sort order
     if (isset($_POST['sortGallery'])) {
         $this->mode = 'sort';
     }
     if (isset($_GET['s'])) {
         $this->search_images();
     }
 }
 function set_custom_post_link($post_link, $post)
 {
     if (is_int($post)) {
         $post = get_post($post);
     }
     if ($post->post_type == 'photocrati-comments') {
         if (preg_match("/^http(s)?/", $post->post_excerpt)) {
             $post_link = $post->post_excerpt;
         } else {
             $image_id = intval(str_replace('nextgen-comment-link-image-', '', $post->post_name));
             if ($image = C_Image_Mapper::get_instance()->find($image_id)) {
                 $post_link = wp_nonce_url('admin.php?page=nggallery-manage-gallery&mode=edit&gid=' . $image->galleryid);
             }
         }
     }
     return $post_link;
 }
 function add_item($image_id, $item_id, $item_props = array())
 {
     // Treat an object as if it were an array
     if (is_object($item_props)) {
         $item_props = get_object_vars($item_props);
     }
     // Find the item
     $item = C_Pricelist_Item_Mapper::get_instance()->find($item_id);
     // Find the image
     if ($image = C_Image_Mapper::get_instance()->find($image_id) and $item) {
         // Ensure that the image has been added
         if (!isset($this->_state[$image_id])) {
             $image->items = array();
             $this->_state[$image_id] = $image;
         } else {
             $image = $this->_state[$image_id];
         }
         // Ensure that the image has an items array
         if (!isset($image->items)) {
             $image->items = array();
         }
         // Ensure that the items source key exists as an array
         if (!isset($image->items[$item->source])) {
             $image->items[$item->source] = array();
         }
         // Ensure that the item's pricelist id exists as a key in the array
         if (!isset($image->items[$item->source][$item->pricelist_id])) {
             $image->items[$item->source][$item->pricelist_id] = array();
         }
         // Has the item already been added? If so, increment it's quantity
         if (isset($image->items[$item->source][$item->pricelist_id][$item_id])) {
             $previous_quantity = intval($image->items[$item->source][$item->pricelist_id][$item_id]->quantity);
             $image->items[$item->source][$item->pricelist_id][$item_id]->quantity = $previous_quantity + intval($item_props['quantity']);
         } else {
             $item->quantity = isset($item_props['quantity']) ? intval($item_props['quantity']) : 1;
             $image->items[$item->source][$item->pricelist_id][$item_id] = $item;
         }
     } else {
         unset($this->_state[$image_id]);
     }
 }
示例#12
0
 /**
  * Parse the gallery/imagebrowser/slideshow shortcode and return all images into an array
  *
  * @param string $atts
  * @return
  */
 function add_gallery($atts)
 {
     global $wpdb;
     extract(shortcode_atts(array('id' => 0), $atts));
     $gallery_mapper = C_Gallery_Mapper::get_instance();
     if (!is_numeric($id)) {
         if ($gallery = array_shift($gallery_mapper->select()->where(array('name = %s', $id))->limit(1)->run_query())) {
             $id = $gallery->{$gallery->id_field};
         } else {
             $id = NULL;
         }
     }
     if ($id) {
         $gallery_storage = C_Gallery_Storage::get_instance();
         $image_mapper = C_Image_Mapper::get_instance();
         foreach ($image_mapper->find_all_for_gallery($id) as $image) {
             $this->images[] = array('src' => $gallery_storage->get_image_url($image), 'title' => $image->title, 'alt' => $image->alttext);
         }
     }
     return '';
 }
 function paypal_standard_order_action()
 {
     $retval = array();
     if ($items = $this->param('items')) {
         $checkout = new C_NextGen_Pro_Checkout();
         $cart = new C_NextGen_Pro_Cart();
         $settings = C_NextGen_Settings::get_instance();
         $currency = C_NextGen_Pro_Currencies::$currencies[$settings->ecommerce_currency];
         foreach ($items as $image_id => $image_items) {
             if ($image = C_Image_Mapper::get_instance()->find($image_id)) {
                 $cart->add_image($image_id, $image);
                 foreach ($image_items as $item_id => $quantity) {
                     if ($item = C_Pricelist_Item_Mapper::get_instance()->find($item_id)) {
                         $item->quantity = $quantity;
                         $cart->add_item($image_id, $item_id, $item);
                     }
                 }
             }
         }
         // Calculate the total
         $use_home_country = intval($this->param('use_home_country'));
         $order_total = $cart->get_total($use_home_country);
         // Create the order
         if ($cart->has_items()) {
             $order = $checkout->create_order($cart->to_array(), __('PayPal Customer', 'nggallery'), 'Unknown', $order_total, 'paypal_standard');
             $order->status = 'unverified';
             $order->use_home_country = $use_home_country;
             $order->gateway_admin_note = __('Payment was successfully made via PayPal Standard, with no further payment action required.');
             C_Order_Mapper::get_instance()->save($order);
             $retval['order'] = $order->hash;
         } else {
             $retval['error'] = __('Your cart is empty', 'nggallery');
         }
     }
     return $retval;
 }
 function _prepare_entities($displayed_gallery, $thumbnail_size_name)
 {
     $current_url = $this->object->get_routed_url(TRUE);
     $storage = C_Gallery_Storage::get_instance();
     $mapper = C_Image_Mapper::get_instance();
     $entities = $displayed_gallery->get_included_entities();
     foreach ($entities as &$entity) {
         $entity_type = intval($entity->is_gallery) ? 'gallery' : 'album';
         // Is the gallery actually a link to a page? Stupid feature...
         if (isset($entity->pageid) && $entity->pageid > 0) {
             $entity->link = get_page_link($entity->pageid);
         } else {
             $page_url = $current_url;
             if (intval($entity->is_gallery) && !$this->param('album')) {
                 $page_url = $this->object->set_param_for($page_url, 'album', 'galleries');
             }
             $entity->link = $this->object->set_param_for($page_url, $entity_type, $entity->slug);
         }
         $preview_img = $mapper->find($entity->previewpic);
         $entity->thumb_size = $storage->get_image_dimensions($preview_img, $thumbnail_size_name);
         $entity->url = $storage->get_image_url($preview_img, $thumbnail_size_name, TRUE);
     }
     return $entities;
 }
function nggallery_manage_gallery_main()
{
    global $ngg, $nggdb, $wp_query;
    //Build the pagination for more than 25 galleries
    $_GET['paged'] = isset($_GET['paged']) && $_GET['paged'] > 0 ? absint($_GET['paged']) : 1;
    $items_per_page = apply_filters('ngg_manage_galleries_items_per_page', 25);
    $start = ($_GET['paged'] - 1) * $items_per_page;
    if (!empty($_GET['order']) && in_array($_GET['order'], array('DESC', 'ASC'))) {
        $order = $_GET['order'];
    } else {
        $order = apply_filters('ngg_manage_galleries_items_order', 'ASC');
    }
    if (!empty($_GET['orderby']) && in_array($_GET['orderby'], array('gid', 'title', 'author'))) {
        $orderby = $_GET['orderby'];
    } else {
        $orderby = apply_filters('ngg_manage_galleries_items_orderby', 'gid');
    }
    $mapper = C_Gallery_Mapper::get_instance();
    $total_number_of_galleries = $mapper->count();
    $gallerylist = $mapper->select()->order_by($orderby, $order)->limit($items_per_page, $start)->run_query();
    // Need for upgrading from 2.0.40 to 2.0.52 or later.
    // For some reason, the installer doesn't always run.
    // TODO: Remove in 2.1
    if (!$gallerylist) {
        global $wpdb;
        if ($wpdb->get_results("SELECT gid FROM {$wpdb->nggallery} LIMIT 1")) {
            $installer = new C_NggLegacy_Installer();
            $installer->install();
            $gallerylist = $mapper->select()->order_by($orderby, $order)->limit($items_per_page, $start)->run_query();
        }
    }
    $wp_list_table = new _NGG_Galleries_List_Table('nggallery-manage-gallery');
    ?>
	<script type="text/javascript">
	<!--

	// Listen for frame events
	jQuery(function($){
		if ($(this).data('ready')) return;

		if (window.Frame_Event_Publisher) {

			// If a new gallery is added, refresh the page
			Frame_Event_Publisher.listen_for('attach_to_post:new_gallery attach_to_post:manage_images attach_to_post:images_added',function(){
				window.location.href = window.location.href;
			});
		}

		$(this).data('ready', true);
	});


	function checkAll(form)
	{
		for (i = 0, n = form.elements.length; i < n; i++) {
			if(form.elements[i].type == "checkbox") {
				if(form.elements[i].name == "doaction[]") {
					if(form.elements[i].checked == true)
						form.elements[i].checked = false;
					else
						form.elements[i].checked = true;
				}
			}
		}
	}

	function getNumChecked(form)
	{
		var num = 0;
		for (i = 0, n = form.elements.length; i < n; i++) {
			if(form.elements[i].type == "checkbox") {
				if(form.elements[i].name == "doaction[]")
					if(form.elements[i].checked == true)
						num++;
			}
		}
		return num;
	}

	// this function check for a the number of selected images, sumbmit false when no one selected
	function checkSelected() {

        if (typeof document.activeElement == "undefined" && document.addEventListener) {
        	document.addEventListener("focus", function (e) {
        		document.activeElement = e.target;
        	}, true);
        }

        if ( document.activeElement.name == 'post_paged' )
            return true;

		var numchecked = getNumChecked(document.getElementById('editgalleries'));

		if(numchecked < 1) {
			alert('<?php 
    echo esc_js(__('No images selected', 'nggallery'));
    ?>
');
			return false;
		}

		actionId = jQuery('#bulkaction').val();

		switch (actionId) {
			case "resize_images":
                showDialog('resize_images', '<?php 
    echo esc_js(__('Resize images', 'nggallery'));
    ?>
');
				return false;
				break;
			case "new_thumbnail":
				showDialog('new_thumbnail', '<?php 
    echo esc_js(__('Create new thumbnails', 'nggallery'));
    ?>
');
				return false;
				break;
		}

		return confirm('<?php 
    echo sprintf(esc_js(__("You are about to start the bulk edit for %s galleries \n \n 'Cancel' to stop, 'OK' to proceed.", 'nggallery')), "' + numchecked + '");
    ?>
');
	}

	function showDialog( windowId, title ) {
		var form = document.getElementById('editgalleries');
		var elementlist = "";
		for (i = 0, n = form.elements.length; i < n; i++) {
			if(form.elements[i].type == "checkbox") {
				if(form.elements[i].name == "doaction[]")
					if(form.elements[i].checked == true)
						if (elementlist == "")
							elementlist = form.elements[i].value;
						else
							elementlist += "," + form.elements[i].value ;
			}
		}
		jQuery("#" + windowId + "_bulkaction").val(jQuery("#bulkaction").val());
		jQuery("#" + windowId + "_imagelist").val(elementlist);
        // now show the dialog
    	jQuery( "#" + windowId ).dialog({
    		width: 640,
            resizable : false,
    		modal: true,
            title: title,
			position: {
				my:		'center',
				at:		'center',
				of:		window.parent
			}
    	});
        jQuery("#" + windowId + ' .dialog-cancel').click(function() { jQuery( "#" + windowId ).dialog("close"); });
	}

	function showAddGallery() {
    	jQuery( "#addGallery").dialog({
    		width: 640,
            resizable : false,
    		modal: true,
            title: '<?php 
    echo esc_js(__('Add new gallery', 'nggallery'));
    ?>
',
			position: {
				my:		'center',
				at:		'center',
				of:		window.parent
			}
    	});
        jQuery("#addGallery .dialog-cancel").click(function() { jQuery( "#addGallery" ).dialog("close"); });
	}
	//-->
	</script>
	<div class="wrap">
		<?php 
    screen_icon('nextgen-gallery');
    ?>
		<h2><?php 
    echo _n('Manage Galleries', 'Manage Galleries', 2, 'nggallery');
    ?>
</h2>
		<form class="search-form" action="" method="get">
		<p class="search-box">
			<label class="hidden" for="media-search-input"><?php 
    _e('Search Images', 'nggallery');
    ?>
:</label>
			<input type="hidden" id="page-name" name="page" value="nggallery-manage-gallery" />
			<input type="text" id="media-search-input" name="s" value="<?php 
    the_search_query();
    ?>
" />
			<input type="submit" value="<?php 
    _e('Search Images', 'nggallery');
    ?>
" class="button" />
		</p>
		</form>
		<form id="editgalleries" class="nggform" method="POST" action="<?php 
    echo $ngg->manage_page->base_page . '&amp;paged=' . esc_attr($_GET['paged']);
    ?>
" accept-charset="utf-8">
		<?php 
    wp_nonce_field('ngg_bulkgallery');
    ?>
		<input type="hidden" name="page" value="manage-galleries" />

		<div class="tablenav top">

			<div class="alignleft actions">
				<?php 
    if (function_exists('json_encode')) {
        ?>
				<select name="bulkaction" id="bulkaction">
					<option value="no_action" ><?php 
        _e("Bulk actions", 'nggallery');
        ?>
</option>
					<option value="delete_gallery" ><?php 
        _e("Delete", 'nggallery');
        ?>
</option>
                    <option value="set_watermark" ><?php 
        _e("Set watermark", 'nggallery');
        ?>
</option>
					<option value="new_thumbnail" ><?php 
        _e("Create new thumbnails", 'nggallery');
        ?>
</option>
					<option value="resize_images" ><?php 
        _e("Resize images", 'nggallery');
        ?>
</option>
					<option value="import_meta" ><?php 
        _e("Import metadata", 'nggallery');
        ?>
</option>
					<option value="recover_images" ><?php 
        _e("Recover from backup", 'nggallery');
        ?>
</option>
				</select>
				<input name="showThickbox" class="button-secondary" type="submit" value="<?php 
        _e('Apply', 'nggallery');
        ?>
" onclick="if ( !checkSelected() ) return false;" />
				<?php 
    }
    ?>
				<?php 
    if (current_user_can('NextGEN Upload images') && nggGallery::current_user_can('NextGEN Add new gallery')) {
        ?>
					<input name="doaction" class="button-secondary action" type="submit" onclick="showAddGallery(); return false;" value="<?php 
        _e('Add new gallery', 'nggallery');
        ?>
"/>
				<?php 
    }
    ?>
			</div>


        <?php 
    $ngg->manage_page->pagination('top', $_GET['paged'], $total_number_of_galleries, $items_per_page);
    ?>

		</div>
		<table class="wp-list-table widefat" cellspacing="0">
			<thead>
			<tr>
<?php 
    $wp_list_table->print_column_headers(true);
    ?>
			</tr>
			</thead>
			<tfoot>
			<tr>
<?php 
    $wp_list_table->print_column_headers(false);
    ?>
			</tr>
			</tfoot>
			<tbody id="the-list">
<?php 
    if ($gallerylist) {
        //get the columns
        $gallery_columns = $wp_list_table->get_columns();
        $hidden_columns = get_hidden_columns('nggallery-manage-gallery');
        $num_columns = count($gallery_columns) - count($hidden_columns);
        $image_mapper = C_Image_Mapper::get_instance();
        foreach ($gallerylist as $gallery) {
            $alternate = !isset($alternate) || $alternate == 'class="alternate"' ? '' : 'class="alternate"';
            $gid = $gallery->gid;
            $name = empty($gallery->title) ? $gallery->name : $gallery->title;
            $author_user = get_userdata((int) $gallery->author);
            ?>
		<tr id="gallery-<?php 
            echo $gid;
            ?>
" <?php 
            echo $alternate;
            ?>
 >
		<?php 
            foreach ($gallery_columns as $gallery_column_key => $column_display_name) {
                $class = "class=\"{$gallery_column_key} column-{$gallery_column_key}\"";
                $style = '';
                if (in_array($gallery_column_key, $hidden_columns)) {
                    $style = ' style="display:none;"';
                }
                $attributes = "{$class}{$style}";
                switch ($gallery_column_key) {
                    case 'cb':
                        ?>
        			<th scope="row" class="column-cb check-column">
        				<?php 
                        if (nggAdmin::can_manage_this_gallery($gallery->author)) {
                            ?>
        					<input name="doaction[]" type="checkbox" value="<?php 
                            echo $gid;
                            ?>
" />
        				<?php 
                        }
                        ?>
        			</th>
        			<?php 
                        break;
                    case 'id':
                        ?>
					<td <?php 
                        echo $attributes;
                        ?>
><?php 
                        echo $gid;
                        ?>
</td>
					<?php 
                        break;
                    case 'title':
                        ?>
        			<td class="title column-title">
        				<?php 
                        if (nggAdmin::can_manage_this_gallery($gallery->author)) {
                            ?>
        					<a href="<?php 
                            echo wp_nonce_url($ngg->manage_page->base_page . '&amp;mode=edit&amp;gid=' . $gid, 'ngg_editgallery');
                            ?>
" class='edit' title="<?php 
                            _e('Edit');
                            ?>
" >
        						<?php 
                            echo esc_html(M_I18N::translate($name));
                            ?>
        					</a>
        				<?php 
                        } else {
                            ?>
        					<?php 
                            echo esc_html(M_I18N::translate($gallery->title));
                            ?>
        				<?php 
                        }
                        ?>
                        <div class="row-actions"></div>
        			</td>
        			<?php 
                        break;
                    case 'description':
                        ?>
					<td <?php 
                        echo $attributes;
                        ?>
><?php 
                        echo esc_html(M_I18N::translate($gallery->galdesc));
                        ?>
&nbsp;</td>
					<?php 
                        break;
                    case 'author':
                        ?>
					<td <?php 
                        echo $attributes;
                        ?>
><?php 
                        echo esc_html($author_user->display_name);
                        ?>
</td>
					<?php 
                        break;
                    case 'page_id':
                        ?>
        			<td <?php 
                        echo $attributes;
                        ?>
><?php 
                        echo $gallery->pageid;
                        ?>
</td>
        			<?php 
                        break;
                    case 'quantity':
                        $gallery->counter = count($image_mapper->select($image_mapper->get_primary_key_column())->where(array("galleryid = %d", $gallery->{$gallery->id_field}))->run_query(FALSE, FALSE, TRUE));
                        ?>
        			<td <?php 
                        echo $attributes;
                        ?>
><?php 
                        echo $gallery->counter;
                        ?>
</td>
        			<?php 
                        break;
                    default:
                        ?>
					<td <?php 
                        echo $attributes;
                        ?>
><?php 
                        do_action('ngg_manage_gallery_custom_column', $gallery_column_key, $gid);
                        ?>
</td>
					<?php 
                        break;
                }
            }
            ?>
		</tr>
		<?php 
        }
    } else {
        echo '<tr><td colspan="7" align="center"><strong>' . __('No entries found', 'nggallery') . '</strong></td></tr>';
    }
    ?>
			</tbody>
		</table>
        <div class="tablenav bottom">
		<?php 
    $ngg->manage_page->pagination('bottom', $_GET['paged'], $total_number_of_galleries, $items_per_page);
    ?>
        </div>
		</form>
	</div>
	<!-- #addGallery -->
	<div id="addGallery" style="display: none;" >
		<form id="form-tags" method="POST" accept-charset="utf-8">
		<?php 
    wp_nonce_field('ngg_addgallery');
    ?>
		<input type="hidden" name="page" value="manage-galleries" />
		<table width="100%" border="0" cellspacing="3" cellpadding="3" >
		  	<tr>
		    	<td>
					<strong><?php 
    _e('New Gallery', 'nggallery');
    ?>
:</strong> <input type="text" size="35" name="galleryname" value="" /><br />
					<?php 
    if (!is_multisite()) {
        ?>
					<?php 
        _e('Create a new , empty gallery below the folder', 'nggallery');
        ?>
  <strong><?php 
        echo $ngg->options['gallerypath'];
        ?>
</strong><br />
					<?php 
    }
    ?>
					<i>( <?php 
    _e('Allowed characters for file and folder names are', 'nggallery');
    ?>
: a-z, A-Z, 0-9, -, _ )</i>
				</td>
		  	</tr>
            <?php 
    do_action('ngg_add_new_gallery_form');
    ?>
		  	<tr align="right">
		    	<td class="submit">
		    		<input class="button-primary" type="submit" name="addgallery" value="<?php 
    _e('OK', 'nggallery');
    ?>
" />
		    		&nbsp;
		    		<input class="button-secondary dialog-cancel" type="reset" value="&nbsp;<?php 
    _e('Cancel', 'nggallery');
    ?>
&nbsp;" />
		    	</td>
			</tr>
		</table>
		</form>
	</div>
	<!-- /#addGallery -->

	<!-- #resize_images -->
	<div id="resize_images" style="display: none;" >
		<form id="form-resize-images" method="POST" accept-charset="utf-8">
		<?php 
    wp_nonce_field('ngg_thickbox_form');
    ?>
		<input type="hidden" id="resize_images_imagelist" name="TB_imagelist" value="" />
		<input type="hidden" id="resize_images_bulkaction" name="TB_bulkaction" value="" />
		<input type="hidden" name="page" value="manage-galleries" />
		<table width="100%" border="0" cellspacing="3" cellpadding="3" >
			<tr valign="top">
				<td>
					<strong><?php 
    _e('Resize Images to', 'nggallery');
    ?>
:</strong>
				</td>
				<td>
					<input type="text" size="5" name="imgWidth" value="<?php 
    echo $ngg->options['imgWidth'];
    ?>
" /> x <input type="text" size="5" name="imgHeight" value="<?php 
    echo $ngg->options['imgHeight'];
    ?>
" />
					<br /><small><?php 
    _e('Width x height (in pixel). NextGEN Gallery will keep ratio size', 'nggallery');
    ?>
</small>
				</td>
			</tr>
		  	<tr align="right">
		    	<td colspan="2" class="submit">
		    		<input class="button-primary" type="submit" name="TB_ResizeImages" value="<?php 
    _e('OK', 'nggallery');
    ?>
" />
		    		&nbsp;
		    		<input class="button-secondary dialog-cancel" type="reset" value="&nbsp;<?php 
    _e('Cancel', 'nggallery');
    ?>
&nbsp;" />
		    	</td>
			</tr>
		</table>
		</form>
	</div>
	<!-- /#resize_images -->

	<!-- #new_thumbnail -->
	<div id="new_thumbnail" style="display: none;" >
		<form id="form-new-thumbnail" method="POST" accept-charset="utf-8">
		<?php 
    wp_nonce_field('ngg_thickbox_form');
    ?>
		<input type="hidden" id="new_thumbnail_imagelist" name="TB_imagelist" value="" />
		<input type="hidden" id="new_thumbnail_bulkaction" name="TB_bulkaction" value="" />
		<input type="hidden" name="page" value="manage-galleries" />
		<table width="100%" border="0" cellspacing="3" cellpadding="3" >
			<tr valign="top">
				<th align="left"><?php 
    _e('Width x height (in pixel)', 'nggallery');
    ?>
</th>
				<td>
				<?php 
    include dirname(__FILE__) . '/thumbnails-template.php';
    ?>
				</td>
			</tr>
			<tr valign="top">
				<th align="left"><?php 
    _e('Set fix dimension', 'nggallery');
    ?>
</th>
				<td><input type="checkbox" name="thumbfix" value="1" <?php 
    checked('1', $ngg->options['thumbfix']);
    ?>
 />
				<br /><small><?php 
    _e('Ignore the aspect ratio, no portrait thumbnails', 'nggallery');
    ?>
</small></td>
			</tr>
		  	<tr align="right">
		    	<td colspan="2" class="submit">
		    		<input class="button-primary" type="submit" name="TB_NewThumbnail" value="<?php 
    _e('OK', 'nggallery');
    ?>
" />
		    		&nbsp;
		    		<input class="button-secondary dialog-cancel" type="reset" value="&nbsp;<?php 
    _e('Cancel', 'nggallery');
    ?>
&nbsp;" />
		    	</td>
			</tr>
		</table>
		</form>
	</div>
	<!-- /#new_thumbnail -->

<?php 
}
示例#16
0
文件: manage.php 项目: vadia007/frg
 function update_pictures()
 {
     $updated = 0;
     if (!$this->can_user_manage_gallery()) {
         $updated;
     }
     if (isset($_POST['images']) && is_array($_POST['images'])) {
         $image_mapper = C_Image_Mapper::get_instance();
         foreach ($_POST['images'] as $pid => $data) {
             if (!isset($data['exclude'])) {
                 $data['exclude'] = 0;
             }
             if ($image = $image_mapper->find($pid)) {
                 // Strip slashes from title/description/alttext fields
                 if (isset($data['description'])) {
                     $data['description'] = stripslashes($data['description']);
                 }
                 if (isset($data['alttext'])) {
                     $data['alttext'] = stripslashes($data['alttext']);
                 }
                 if (isset($data['title'])) {
                     $data['title'] = stripslashes($data['title']);
                 }
                 // Generate new slug if the alttext has changed
                 if (isset($data['alttext']) && $image->alttext != $data['alttext']) {
                     $data['slug'] = NULL;
                     // will cause a new slug to be generated
                 }
                 // Update all fields
                 foreach ($data as $key => $value) {
                     $image->{$key} = $value;
                 }
                 if ($image_mapper->save($image)) {
                     $updated += 1;
                     // Update the tags for the image
                     if (isset($data['tags'])) {
                         $tags = $data['tags'];
                         if (!is_array($tags)) {
                             $tags = explode(',', $tags);
                         }
                         foreach ($tags as &$tag) {
                             $tag = trim($tag);
                         }
                         wp_set_object_terms($image->{$image->id_field}, $tags, 'ngg_tag');
                     }
                     // remove from cache
                     wp_cache_delete($image->pid, 'ngg_image');
                     // hook for other plugins after image is updated
                     do_action('ngg_image_updated', $image);
                 }
             }
         }
     }
     return $updated;
 }
 public function get_name_from_params($params, $only_size_name = false, $id_in_name = true)
 {
     $prefix_list = $this->object->_get_name_prefix_list();
     $id_prefix = $prefix_list['id'];
     $size_prefix = $prefix_list['size'];
     $flags_prefix = $prefix_list['flags'];
     $flags = $prefix_list['flag'];
     $max_value_length = $prefix_list['max_value_length'];
     $params = $this->object->_get_params_sanitized($params);
     $image = isset($params['image']) ? $params['image'] : null;
     $image_width = isset($params['width']) ? $params['width'] : null;
     $image_height = isset($params['height']) ? $params['height'] : null;
     $image_quality = isset($params['quality']) ? $params['quality'] : null;
     $extension = null;
     $name = null;
     // if $only_size_name is false then we include the file name and image id for the image
     if (!$only_size_name) {
         if (is_int($image)) {
             $imap = C_Image_Mapper::get_instance();
             $image = $imap->find($image);
         }
         if ($image != null) {
             // this is used to remove the extension and then add it back at the end of the name
             $extension = M_I18n::mb_pathinfo($image->filename, PATHINFO_EXTENSION);
             if ($extension != null) {
                 $extension = '.' . $extension;
             }
             $name .= M_I18n::mb_basename($image->filename, $extension);
             $name .= '-';
             if ($id_in_name) {
                 $image_id = strval($image->pid);
                 $id_len = min($max_value_length, strlen($image_id));
                 $id_len_hex = dechex($id_len);
                 // sanity check, should never occurr if $max_value_length is not messed up, ensure only 1 character is used to encode length or else skip parameter
                 if (strlen($id_len_hex) == 1) {
                     $name .= $id_prefix . $id_len . substr($image_id, 0, $id_len);
                     $name .= '-';
                 }
             }
         }
     }
     $name .= $size_prefix;
     $name .= strval($image_width) . 'x' . strval($image_height);
     if ($image_quality != null) {
         $name .= 'x' . $image_quality;
     }
     $name .= '-';
     $name .= $flags_prefix;
     foreach ($flags as $flag_prefix => $flag_name) {
         $flag_value = 0;
         if (isset($params[$flag_name])) {
             $flag_value = $params[$flag_name];
             if (!is_string($flag_value)) {
                 // only strings or ints allowed, sprintf is required because intval(0) returns '' and not '0'
                 $flag_value = intval($flag_value);
                 $flag_value = sprintf('%d', $flag_value);
             }
         }
         $flag_value = strval($flag_value);
         $flag_len = min($max_value_length, strlen($flag_value));
         $flag_len_hex = dechex($flag_len);
         // sanity check, should never occurr if $max_value_length is not messed up, ensure only 1 character is used to encode length or else skip parameter
         if (strlen($flag_len_hex) == 1) {
             $name .= $flag_prefix . $flag_len . substr($flag_value, 0, $flag_len);
         }
     }
     $name .= $extension;
     return $name;
 }
 /**
  * Renders the "Edit Proof" main content area
  *
  * @param null $post
  */
 function nextgen_proof_metabox($post = null)
 {
     if ($post != null) {
         $settings = C_NextGen_Settings::get_instance();
         $image_mapper = C_Image_Mapper::get_instance();
         $values = $image_mapper->unserialize($post->post_content);
         $proofed_gallery = $values['proofed_gallery'];
         $image_list = isset($proofed_gallery['image_list']) ? $proofed_gallery['image_list'] : null;
         $confirmation_param = array('proof' => $values['hash']);
         if (!empty($settings->proofing_page_confirmation)) {
             $confirmation_url = self::get_page_url($settings->proofing_page_confirmation, $confirmation_param);
         } else {
             $confirmation_url = self::add_to_querystring(site_url('/?ngg_pro_proofing_page=1'), $confirmation_param);
         }
         if ($image_list != null) {
             $storage = C_Gallery_Storage::get_instance();
             echo '<h4>';
             echo '<a target="_blank" href="' . $confirmation_url . '">' . __('User confirmation', 'nextgen-gallery-pro') . '</a>';
             echo ' | ';
             echo '<a target="_blank" href="' . $values['referer'] . '">' . __('Gallery source url', 'nextgen-gallery-pro') . '</a>';
             echo '</h4>';
             echo '<table style="width: 98%;">';
             echo '<tr><th style="width: 150px; text-align:left;">' . __('Thumbnail', 'nextgen-gallery-pro') . '</th><th style="text-align:left;">' . __('Title', 'nextgen-gallery-pro') . '</th><th style="width: 40%; text-align:left;">' . __('Filename', 'nextgen-gallery-pro') . '</th></tr>';
             foreach ($image_list as $image_id) {
                 $image = $image_mapper->find($image_id);
                 if (!$image) {
                     continue;
                 }
                 echo '<tr>';
                 echo '<td>' . $storage->get_image_html($image, 'thumb') . '</td>';
                 echo '<td>' . esc_html($image->alttext) . '</td>';
                 echo '<td>' . esc_html($image->filename) . '</td>';
                 echo '</tr>';
             }
             echo '</table>';
         }
     }
 }
 function _get_preview_image()
 {
     $registry = $this->object->get_registry();
     $storage = C_Gallery_Storage::get_instance();
     $image = C_Image_Mapper::get_instance()->find_first();
     $imagegen = C_Dynamic_Thumbnails_Manager::get_instance();
     $size = $imagegen->get_size_name(array('height' => 250, 'crop' => FALSE, 'watermark' => TRUE));
     $url = $image ? $storage->get_image_url($image, $size) : NULL;
     $abspath = $image ? $storage->get_image_abspath($image, $size) : NULL;
     return array('url' => $url, 'abspath' => $abspath);
 }
 /**
  * Returns the parameter objects necessary for legacy template rendering (legacy_render())
  *
  * @param $images
  * @param $displayed_gallery
  * @param array $params
  *
  * @return array
  */
 function prepare_legacy_parameters($images, $displayed_gallery, $params = array())
 {
     // setup
     $image_map = C_Image_Mapper::get_instance();
     $gallery_map = C_Gallery_Mapper::get_instance();
     $image_key = $image_map->get_primary_key_column();
     $gallery_key = $gallery_map->get_primary_key_column();
     $gallery_id = $displayed_gallery->id();
     $pid = $this->object->param('pid');
     // because picture_list implements ArrayAccess any array-specific actions must be taken on
     // $picture_list->container or they won't do anything
     $picture_list = new C_Image_Wrapper_Collection();
     $current_pid = NULL;
     // begin processing
     $current_page = @get_the_ID() == FALSE ? 0 : @get_the_ID();
     // determine what the "current image" is; used mostly for carousel
     if (!is_numeric($pid) && !empty($pid)) {
         $picture = $image_map->find_first(array('image_slug = %s', $pid));
         $pid = $picture->{$image_key};
     }
     // create our new wrappers
     foreach ($images as &$image) {
         if ($image && isset($params['effect_code'])) {
             if (is_object($image)) {
                 $image->thumbcode = $params['effect_code'];
             } elseif (is_array($image)) {
                 $image['thumbcode'] = $params['effect_code'];
             }
         }
         $new_image = new C_Image_Wrapper($image, $displayed_gallery);
         if ($pid == $new_image->{$image_key}) {
             $current_pid = $new_image;
         }
         $picture_list[] = $new_image;
     }
     reset($picture_list->container);
     // assign current_pid
     $current_pid = is_null($current_pid) ? current($picture_list->container) : $current_pid;
     foreach ($picture_list as &$image) {
         if (isset($image->hidden) && $image->hidden) {
             $tmp = $displayed_gallery->display_settings['number_of_columns'];
             $image->style = $tmp > 0 ? 'style="width:' . floor(100 / $tmp) . '%;display: none;"' : 'style="display: none;"';
         }
     }
     // find our gallery to build the new one on
     $orig_gallery = $gallery_map->find(current($picture_list->container)->galleryid);
     // create the 'gallery' object
     $gallery = new stdclass();
     $gallery->ID = $displayed_gallery->id();
     $gallery->name = stripslashes($orig_gallery->name);
     $gallery->title = stripslashes($orig_gallery->title);
     $gallery->description = html_entity_decode(stripslashes($orig_gallery->galdesc));
     $gallery->pageid = $orig_gallery->pageid;
     $gallery->anchor = 'ngg-gallery-' . $gallery_id . '-' . $current_page;
     $gallery->displayed_gallery =& $displayed_gallery;
     $gallery->columns = @intval($displayed_gallery->display_settings['number_of_columns']);
     $gallery->imagewidth = $gallery->columns > 0 ? 'style="width:' . floor(100 / $gallery->columns) . '%;"' : '';
     if (!empty($displayed_gallery->display_settings['show_slideshow_link'])) {
         $gallery->show_slideshow = TRUE;
         $gallery->slideshow_link = $params['slideshow_link'];
         $gallery->slideshow_link_text = $displayed_gallery->display_settings['slideshow_link_text'];
     } else {
         $gallery->show_slideshow = FALSE;
     }
     $gallery = apply_filters('ngg_gallery_object', $gallery, 4);
     // build our array of things to return
     $return = array('registry' => C_Component_Registry::get_instance(), 'gallery' => $gallery);
     // single_image is an internally added flag
     if (!empty($params['single_image'])) {
         $return['image'] = $picture_list[0];
     } else {
         $return['current'] = $current_pid;
         $return['images'] = $picture_list->container;
     }
     // this is expected to always exist
     if (!empty($params['pagination'])) {
         $return['pagination'] = $params['pagination'];
     } else {
         $return['pagination'] = NULL;
     }
     if (!empty($params['next'])) {
         $return['next'] = $params['next'];
     } else {
         $return['next'] = FALSE;
     }
     if (!empty($params['prev'])) {
         $return['prev'] = $params['prev'];
     } else {
         $return['prev'] = FALSE;
     }
     return $return;
 }
示例#21
0
function nggallery_picturelist($controller)
{
    // *** show picture list
    global $wpdb, $nggdb, $user_ID, $ngg;
    // Look if its a search result
    $is_search = isset($_GET['s']) ? true : false;
    $counter = 0;
    $wp_list_table = new _NGG_Images_List_Table('nggallery-manage-images');
    if ($is_search) {
        // fetch the imagelist
        $picturelist = $ngg->manage_page->search_result;
        // we didn't set a gallery or a pagination
        $act_gid = 0;
        $_GET['paged'] = 1;
        $page_links = false;
    } else {
        // GET variables
        $act_gid = $ngg->manage_page->gid;
        // Load the gallery metadata
        $mapper = C_Gallery_Mapper::get_instance();
        $gallery = $mapper->find($act_gid);
        if (!$gallery) {
            nggGallery::show_error(__('Gallery not found.', 'nggallery'));
            return;
        }
        // Check if you have the correct capability
        if (!nggAdmin::can_manage_this_gallery($gallery->author)) {
            nggGallery::show_error(__('Sorry, you have no access here', 'nggallery'));
            return;
        }
        // look for pagination
        $_GET['paged'] = isset($_GET['paged']) && $_GET['paged'] > 0 ? absint($_GET['paged']) : 1;
        $items_per_page = 50;
        $start = ($_GET['paged'] - 1) * $items_per_page;
        // get picture values
        $image_mapper = C_Image_Mapper::get_instance();
        $total_number_of_images = count($image_mapper->select($image_mapper->get_primary_key_column())->where(array("galleryid = %d", $act_gid))->run_query(FALSE, TRUE));
        $picturelist = $image_mapper->select()->where(array("galleryid = %d", $act_gid))->order_by($ngg->options['galSort'], $ngg->options['galSortDir'])->limit($items_per_page, $start)->run_query();
        // get the current author
        $act_author_user = get_userdata((int) $gallery->author);
    }
    // list all galleries
    $gallerylist = $nggdb->find_all_galleries();
    //get the columns
    $image_columns = $wp_list_table->get_columns();
    $hidden_columns = get_hidden_columns('nggallery-manage-images');
    $num_columns = count($image_columns) - count($hidden_columns);
    $attr = nggGallery::current_user_can('NextGEN Edit gallery options') ? '' : 'disabled="disabled"';
    ?>
<script type="text/javascript">
<!--
function showDialog( windowId, title ) {
	var form = document.getElementById('updategallery');
	var elementlist = "";
	for (i = 0, n = form.elements.length; i < n; i++) {
		if(form.elements[i].type == "checkbox") {
			if(form.elements[i].name == "doaction[]")
				if(form.elements[i].checked == true)
					if (elementlist == "")
						elementlist = form.elements[i].value;
					else
						elementlist += "," + form.elements[i].value ;
		}
	}
	jQuery("#" + windowId + "_bulkaction").val(jQuery("#bulkaction").val());
	jQuery("#" + windowId + "_imagelist").val(elementlist);
    // now show the dialog
	jQuery( "#" + windowId ).dialog({
		width: 640,
        resizable : false,
		modal: true,
        title: title,
		position: {
			my:		'center',
			at:		'center',
			of:		window.parent
		}
	});
    jQuery("#" + windowId + ' .dialog-cancel').click(function() { jQuery( "#" + windowId ).dialog("close"); });
}

jQuery(function (){

    jQuery('span.tooltip, label.tooltip').tooltip();

    // load a content via ajax
    jQuery('a.ngg-dialog').click(function() {
    	var dialogs = jQuery('.ngg-overlay-dialog:visible');
    	if (dialogs.size() > 0) {
    		return false;
    	}

      if ( jQuery( "#spinner" ).length == 0) {
      	jQuery("body").append('<div id="spinner"></div>');
      }

    	var $this = jQuery(this);
      var results = new RegExp('[\\?&]w=([^&#]*)').exec(this.href);
    	var width  = ( results ) ? results[1] : 600;
      var results = new RegExp('[\\?&]h=([^&#]*)').exec(this.href);
	    var height = ( results ) ? results[1] : 440;
      var container = window;

      if (window.parent) {
      	container = window.parent;
      }

      jQuery('#spinner').fadeIn();
      jQuery('#spinner').position({ my: "center", at: "center", of: container });

      var dialog = jQuery('<div class="ngg-overlay-dialog" style="display:hidden"></div>').appendTo('body');
      // load the remote content
      dialog.load(
          this.href,
          {},
          function () {
              jQuery('#spinner').hide();

              dialog.dialog({
                  title: ($this.attr('title')) ? $this.attr('title') : '',
                  position: { my: "center", at: "center", of: container },
                  width: width,
                  height: height,
                  modal: true,
                  resizable: false,
                  close: function() { dialog.remove(); }
              }).width(width - 30).height(height - 30);
          }
      );

      //prevent the browser to follow the link
      return false;
    });
});

function checkAll(form)
{
	for (i = 0, n = form.elements.length; i < n; i++) {
		if(form.elements[i].type == "checkbox") {
			if(form.elements[i].name == "doaction[]") {
				if(form.elements[i].checked == true)
					form.elements[i].checked = false;
				else
					form.elements[i].checked = true;
			}
		}
	}
}

function getNumChecked(form)
{
	var num = 0;
	for (i = 0, n = form.elements.length; i < n; i++) {
		if(form.elements[i].type == "checkbox") {
			if(form.elements[i].name == "doaction[]")
				if(form.elements[i].checked == true)
					num++;
		}
	}
	return num;
}

// this function check for a the number of selected images, sumbmit false when no one selected
function checkSelected() {

	var numchecked = getNumChecked(document.getElementById('updategallery'));

    if (typeof document.activeElement == "undefined" && document.addEventListener) {
    	document.addEventListener("focus", function (e) {
    		document.activeElement = e.target;
    	}, true);
    }

    if ( document.activeElement.name == 'post_paged' )
        return true;

	if(numchecked < 1) {
		alert('<?php 
    echo esc_js(__('No images selected', 'nggallery'));
    ?>
');
		return false;
	}

	actionId = jQuery('#bulkaction').val();

	switch (actionId) {
		case "copy_to":
			showDialog('selectgallery', '<?php 
    echo esc_js(__('Copy image to...', 'nggallery'));
    ?>
');
			return false;
			break;
		case "move_to":
			showDialog('selectgallery', '<?php 
    echo esc_js(__('Move image to...', 'nggallery'));
    ?>
');
			return false;
			break;
		case "add_tags":
			showDialog('entertags', '<?php 
    echo esc_js(__('Add new tags', 'nggallery'));
    ?>
');
			return false;
			break;
		case "delete_tags":
			showDialog('entertags', '<?php 
    echo esc_js(__('Delete tags', 'nggallery'));
    ?>
');
			return false;
			break;
		case "overwrite_tags":
			showDialog('entertags', '<?php 
    echo esc_js(__('Overwrite', 'nggallery'));
    ?>
');
			return false;
			break;
		case "resize_images":
			showDialog('resize_images', '<?php 
    echo esc_js(__('Resize images', 'nggallery'));
    ?>
');
			return false;
			break;
		case "new_thumbnail":
			showDialog('new_thumbnail', '<?php 
    echo esc_js(__('Create new thumbnails', 'nggallery'));
    ?>
');
			return false;
			break;
	}

	return confirm('<?php 
    echo sprintf(esc_js(__("You are about to start the bulk edit for %s images \n \n 'Cancel' to stop, 'OK' to proceed.", 'nggallery')), "' + numchecked + '");
    ?>
');
}

jQuery(document).ready( function($) {
	if ($(this).data('ready')) return;

	// close postboxes that should be closed
	jQuery('.if-js-closed').removeClass('if-js-closed').addClass('closed');
	postboxes.add_postbox_toggles('ngg-manage-gallery');

	jQuery('.iedit').mouseover(
		function(e){
			jQuery(this).parent().find('.row-actions').css('visibility', 'hidden');
			jQuery(this).next('.row_actions:first').find('.row-actions:first').css('visibility', 'visible');
		}
	);

	$(this).data('ready', true);
});

//-->
</script>
<div class="wrap">
<?php 
    //include('templates/social_media_buttons.php');
    screen_icon('nextgen-gallery');
    if ($is_search) {
        ?>
<h2><?php 
        printf(__('Search results for &#8220;%s&#8221;', 'nggallery'), esc_html(get_search_query()));
        ?>
</h2>
<form class="search-form" action="" method="get">
<p class="search-box">
	<label class="hidden" for="media-search-input"><?php 
        _e('Search Images', 'nggallery');
        ?>
:</label>
	<input type="hidden" id="page-name" name="page" value="nggallery-manage-gallery" />
	<input type="text" id="media-search-input" name="s" value="<?php 
        the_search_query();
        ?>
" />
	<input type="submit" value="<?php 
        _e('Search Images', 'nggallery');
        ?>
" class="button" />
</p>
</form>

<br style="clear: both;" />

<form id="updategallery" class="nggform" method="POST" action="<?php 
        echo $ngg->manage_page->base_page . '&amp;mode=edit&amp;s=' . get_search_query();
        ?>
" accept-charset="utf-8">
<?php 
        wp_nonce_field('ngg_updategallery');
        ?>
<input type="hidden" name="page" value="manage-images" />

<?php 
    } else {
        ?>
<h2><?php 
        echo _n('Gallery', 'Galleries', 1, 'nggallery');
        ?>
 : <?php 
        echo esc_html(nggGallery::i18n($gallery->title));
        ?>
</h2>

<br style="clear: both;" />

<form id="updategallery" class="nggform" method="POST" action="<?php 
        echo $ngg->manage_page->base_page . '&amp;mode=edit&amp;gid=' . $act_gid . '&amp;paged=' . esc_attr($_GET['paged']);
        ?>
" accept-charset="utf-8">
<?php 
        wp_nonce_field('ngg_updategallery');
        ?>
<input type="hidden" name="page" value="manage-images" />

<?php 
        if (nggGallery::current_user_can('NextGEN Edit gallery options')) {
            ?>
<div id="poststuff">
	<?php 
            wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false);
            ?>
	<div id="gallerydiv" class="postbox <?php 
            echo postbox_classes('gallerydiv', 'ngg-manage-gallery');
            ?>
" >
		<h3><?php 
            _e('Gallery settings', 'nggallery');
            ?>
<small> (<?php 
            _e('Click here for more settings', 'nggallery');
            ?>
)</small></h3>
		<div class="inside">
			<?php 
            $controller->render_gallery_fields();
            ?>

			<div class="submit">
				<?php 
            if (wpmu_enable_function('wpmuImportFolder') && nggGallery::current_user_can('NextGEN Import image folder')) {
                ?>
				<input type="submit" class="button-secondary" name="scanfolder" value="<?php 
                _e("Scan Folder for new images", 'nggallery');
                ?>
 " />
				<?php 
            }
            ?>
				<input type="submit" class="button-primary action" name="updatepictures" value="<?php 
            _e("Save Changes", 'nggallery');
            ?>
" />
			</div>

		</div>
	</div>
</div> <!-- poststuff -->
<?php 
        }
        ?>

<?php 
    }
    ?>

<div class="tablenav top ngg-tablenav">
    <?php 
    $ngg->manage_page->pagination('top', $_GET['paged'], $total_number_of_images, $items_per_page);
    ?>
	<div class="alignleft actions">
	<select id="bulkaction" name="bulkaction">
		<option value="no_action" ><?php 
    _e("Bulk actions", 'nggallery');
    ?>
</option>
		<option value="set_watermark" ><?php 
    _e("Set watermark", 'nggallery');
    ?>
</option>
		<option value="new_thumbnail" ><?php 
    _e("Create new thumbnails", 'nggallery');
    ?>
</option>
		<option value="resize_images" ><?php 
    _e("Resize images", 'nggallery');
    ?>
</option>
		<option value="recover_images" ><?php 
    _e("Recover from backup", 'nggallery');
    ?>
</option>
		<option value="delete_images" ><?php 
    _e("Delete images", 'nggallery');
    ?>
</option>
		<option value="import_meta" ><?php 
    _e("Import metadata", 'nggallery');
    ?>
</option>
		<option value="rotate_cw" ><?php 
    _e("Rotate images clockwise", 'nggallery');
    ?>
</option>
		<option value="rotate_ccw" ><?php 
    _e("Rotate images counter-clockwise", 'nggallery');
    ?>
</option>
		<option value="copy_to" ><?php 
    _e("Copy to...", 'nggallery');
    ?>
</option>
		<option value="move_to"><?php 
    _e("Move to...", 'nggallery');
    ?>
</option>
		<option value="add_tags" ><?php 
    _e("Add tags", 'nggallery');
    ?>
</option>
		<option value="delete_tags" ><?php 
    _e("Delete tags", 'nggallery');
    ?>
</option>
		<option value="overwrite_tags" ><?php 
    _e("Overwrite tags", 'nggallery');
    ?>
</option>
	</select>
	<input class="button-secondary" type="submit" name="showThickbox" value="<?php 
    _e('Apply', 'nggallery');
    ?>
" onclick="if ( !checkSelected() ) return false;" />

	<?php 
    if ($ngg->options['galSort'] == "sortorder" && !$is_search) {
        ?>
		<input class="button-secondary" type="submit" name="sortGallery" value="<?php 
        _e('Sort gallery', 'nggallery');
        ?>
" />
	<?php 
    }
    ?>

	<input type="submit" name="updatepictures" class="button-primary action"  value="<?php 
    _e('Save Changes', 'nggallery');
    ?>
" />
	</div>
</div>
<table id="ngg-listimages" class="widefat fixed" cellspacing="0" >

	<thead>
		<?php 
    $controller->render_image_row_header();
    ?>
	</thead>
	<tfoot>
		<?php 
    $controller->render_image_row_header();
    ?>
	</tfoot>
	<tbody id="the-list">
<?php 
    if ($picturelist) {
        $thumbsize = '';
        $storage = C_Gallery_Storage::get_instance();
        if ($ngg->options['thumbfix']) {
            $thumbsize = 'width="' . $ngg->options['thumbwidth'] . '" height="' . $ngg->options['thumbheight'] . '"';
        }
        foreach ($picturelist as $picture) {
            //for search result we need to check the capatibiliy
            if (!nggAdmin::can_manage_this_gallery($gallery->author) && $is_search) {
                continue;
            }
            $counter++;
            $picture->imageURL = $storage->get_image_url($picture);
            $picture->thumbURL = $storage->get_thumb_url($picture);
            $picture->imagePath = $storage->get_image_abspath($picture);
            $picture->thumbPath = $storage->get_thumb_abspath($picture);
            echo apply_filters('ngg_manage_images_row', $picture, $counter);
        }
    }
    // In the case you have no capaptibility to see the search result
    if ($counter == 0) {
        echo '<tr><td colspan="' . $num_columns . '" align="center"><strong>' . __('No entries found', 'nggallery') . '</strong></td></tr>';
    }
    ?>

		</tbody>
	</table>
    <div class="tablenav bottom">
    <input type="submit" class="button-primary action" name="updatepictures" value="<?php 
    _e('Save Changes', 'nggallery');
    ?>
" />
    <?php 
    $ngg->manage_page->pagination('bottom', $_GET['paged'], $total_number_of_images, $items_per_page);
    ?>
    </div>
	</form>
	<br class="clear"/>
	</div><!-- /#wrap -->

	<!-- #entertags -->
	<div id="entertags" style="display: none;" >
		<form id="form-tags" method="POST" accept-charset="utf-8">
		<?php 
    wp_nonce_field('ngg_thickbox_form');
    ?>
		<input type="hidden" id="entertags_imagelist" name="TB_imagelist" value="" />
		<input type="hidden" id="entertags_bulkaction" name="TB_bulkaction" value="" />
		<input type="hidden" name="page" value="manage-images" />
		<table width="100%" border="0" cellspacing="3" cellpadding="3" >
		  	<tr>
		    	<th><?php 
    _e("Enter the tags", 'nggallery');
    ?>
 : <input name="taglist" type="text" style="width:90%" value="" /></th>
		  	</tr>
		  	<tr align="right">
		    	<td class="submit">
		    		<input class="button-primary" type="submit" name="TB_EditTags" value="<?php 
    _e("OK", 'nggallery');
    ?>
" />
		    		&nbsp;
		    		<input class="button-secondary dialog-cancel" type="reset" value="&nbsp;<?php 
    _e("Cancel", 'nggallery');
    ?>
&nbsp;" />
		    	</td>
			</tr>
		</table>
		</form>
	</div>
	<!-- /#entertags -->

	<!-- #selectgallery -->
	<div id="selectgallery" style="display: none;" >
		<form id="form-select-gallery" method="POST" accept-charset="utf-8">
		<?php 
    wp_nonce_field('ngg_thickbox_form');
    ?>
		<input type="hidden" id="selectgallery_imagelist" name="TB_imagelist" value="" />
		<input type="hidden" id="selectgallery_bulkaction" name="TB_bulkaction" value="" />
		<input type="hidden" name="page" value="manage-images" />
		<table width="100%" border="0" cellspacing="3" cellpadding="3" >
		  	<tr>
		    	<th>
		    		<?php 
    _e('Select the destination gallery:', 'nggallery');
    ?>
&nbsp;
		    		<select name="dest_gid" style="width:90%" >
		    			<?php 
    foreach ($gallerylist as $gallery) {
        if ($gallery->gid != $act_gid) {
            ?>
						<option value="<?php 
            echo $gallery->gid;
            ?>
" ><?php 
            echo $gallery->gid;
            ?>
 - <?php 
            echo esc_attr(stripslashes($gallery->title));
            ?>
</option>
						<?php 
        }
    }
    ?>
		    		</select>
		    	</th>
		  	</tr>
		  	<tr align="right">
		    	<td class="submit">
		    		<input type="submit" class="button-primary" name="TB_SelectGallery" value="<?php 
    _e("OK", 'nggallery');
    ?>
" />
		    		&nbsp;
		    		<input class="button-secondary dialog-cancel" type="reset" value="<?php 
    _e("Cancel", 'nggallery');
    ?>
" />
		    	</td>
			</tr>
		</table>
		</form>
	</div>
	<!-- /#selectgallery -->

	<!-- #resize_images -->
	<div id="resize_images" style="display: none;" >
		<form id="form-resize-images" method="POST" accept-charset="utf-8">
		<?php 
    wp_nonce_field('ngg_thickbox_form');
    ?>
		<input type="hidden" id="resize_images_imagelist" name="TB_imagelist" value="" />
		<input type="hidden" id="resize_images_bulkaction" name="TB_bulkaction" value="" />
		<input type="hidden" name="page" value="manage-images" />
		<table width="100%" border="0" cellspacing="3" cellpadding="3" >
			<tr valign="top">
				<td>
					<strong><?php 
    _e('Resize Images to', 'nggallery');
    ?>
:</strong>
				</td>
				<td>
					<input type="text" size="5" name="imgWidth" value="<?php 
    echo $ngg->options['imgWidth'];
    ?>
" /> x <input type="text" size="5" name="imgHeight" value="<?php 
    echo $ngg->options['imgHeight'];
    ?>
" />
					<br /><small><?php 
    _e('Width x height (in pixel). NextGEN Gallery will keep ratio size', 'nggallery');
    ?>
</small>
				</td>
			</tr>
		  	<tr align="right">
		    	<td colspan="2" class="submit">
		    		<input class="button-primary" type="submit" name="TB_ResizeImages" value="<?php 
    _e('OK', 'nggallery');
    ?>
" />
		    		&nbsp;
		    		<input class="button-secondary dialog-cancel" type="reset" value="&nbsp;<?php 
    _e('Cancel', 'nggallery');
    ?>
&nbsp;" />
		    	</td>
			</tr>
		</table>
		</form>
	</div>
	<!-- /#resize_images -->

	<!-- #new_thumbnail -->
	<div id="new_thumbnail" style="display: none;" >
		<form id="form-new-thumbnail" method="POST" accept-charset="utf-8">
		<?php 
    wp_nonce_field('ngg_thickbox_form');
    ?>
		<input type="hidden" id="new_thumbnail_imagelist" name="TB_imagelist" value="" />
		<input type="hidden" id="new_thumbnail_bulkaction" name="TB_bulkaction" value="" />
		<input type="hidden" name="page" value="manage-images" />
    <table width="100%" border="0" cellspacing="3" cellpadding="3" >
			<tr valign="top">
				<th align="left"><?php 
    _e('Width x height (in pixel)', 'nggallery');
    ?>
</th>
				<td>
				<?php 
    include dirname(__FILE__) . '/thumbnails-template.php';
    ?>
				</td>
			</tr>
			<tr valign="top">
				<th align="left"><?php 
    _e('Set fix dimension', 'nggallery');
    ?>
</th>
				<td><input type="checkbox" name="thumbfix" value="1" <?php 
    checked('1', $ngg->options['thumbfix']);
    ?>
 />
				<br /><small><?php 
    _e('Ignore the aspect ratio, no portrait thumbnails', 'nggallery');
    ?>
</small></td>
			</tr>
		  	<tr align="right">
		    	<td colspan="2" class="submit">
		    		<input class="button-primary" type="submit" name="TB_NewThumbnail" value="<?php 
    _e('OK', 'nggallery');
    ?>
" />
		    		&nbsp;
		    		<input class="button-secondary dialog-cancel" type="reset" value="&nbsp;<?php 
    _e('Cancel', 'nggallery');
    ?>
&nbsp;" />
		    	</td>
			</tr>
		</table>
		</form>
	</div>
	<!-- /#new_thumbnail -->

	<script type="text/javascript">
	/* <![CDATA[ */
	jQuery(document).ready(function(){columns.init('nggallery-manage-images');});
	/* ]]> */
	</script>
	<?php 
}
 public function import_media_library_action()
 {
     $retval = array();
     $created_gallery = FALSE;
     $gallery_id = intval($this->param('gallery_id'));
     $gallery_name = urldecode($this->param('gallery_name'));
     $gallery_mapper = C_Gallery_Mapper::get_instance();
     $image_mapper = C_Image_Mapper::get_instance();
     $attachment_ids = $this->param('attachment_ids');
     if ($this->validate_ajax_request('nextgen_upload_image', TRUE)) {
         if (empty($attachment_ids) || !is_array($attachment_ids)) {
             $retval['error'] = __('An unexpected error occured.', 'nggallery');
         }
         if (empty($retval['error']) && $gallery_id == 0) {
             if (strlen($gallery_name) > 0) {
                 $gallery = $gallery_mapper->create(array('title' => $gallery_name));
                 if (!$gallery->save()) {
                     $retval['error'] = $gallery->get_errors();
                 } else {
                     $created_gallery = TRUE;
                     $gallery_id = $gallery->id();
                 }
             } else {
                 $retval['error'] = __('No gallery name specified', 'nggallery');
             }
         }
         if (empty($retval['error'])) {
             $retval['gallery_id'] = $gallery_id;
             $storage = C_Gallery_Storage::get_instance();
             foreach ($attachment_ids as $id) {
                 try {
                     $abspath = get_attached_file($id);
                     $file_data = @file_get_contents($abspath);
                     $file_name = M_I18n::mb_basename($abspath);
                     $attachment = get_post($id);
                     if (empty($file_data)) {
                         $retval['error'] = __('Image generation failed', 'nggallery');
                         break;
                     }
                     $image = $storage->upload_base64_image($gallery_id, $file_data, $file_name);
                     if ($image) {
                         // Potentially import metadata from WordPress
                         $image = $image_mapper->find($image->id());
                         if (!empty($attachment->post_excerpt)) {
                             $image->alttext = $attachment->post_excerpt;
                         }
                         if (!empty($attachment->post_content)) {
                             $image->description = $attachment->post_content;
                         }
                         $image = apply_filters('ngg_medialibrary_imported_image', $image, $attachment);
                         $image_mapper->save($image);
                     } else {
                         $retval['error'] = __('Image generation failed', 'nggallery');
                         break;
                     }
                     $retval['image_ids'][] = $image->{$image->id_field};
                 } catch (E_NggErrorException $ex) {
                     $retval['error'] = $ex->getMessage();
                     if ($created_gallery) {
                         $gallery_mapper->destroy($gallery_id);
                     }
                 } catch (Exception $ex) {
                     $retval['error'] = __('An unexpected error occured.', 'nggallery');
                     $retval['error_details'] = $ex->getMessage();
                 }
             }
         }
     } else {
         $retval['error'] = __('No permissions to upload images. Try refreshing the page or ensuring that your user account has sufficient roles/privileges.', 'nggallery');
     }
     if (!empty($retval['error'])) {
         return $retval;
     } else {
         $retval['gallery_name'] = esc_html($gallery_name);
     }
     return $retval;
 }
 /**
  * Displays a preview image for the displayed gallery
  */
 public function preview_action()
 {
     $found_preview_pic = FALSE;
     $dyn_thumbs = C_Dynamic_Thumbnails_Manager::get_instance();
     $storage = C_Gallery_Storage::get_instance();
     $image_mapper = C_Image_Mapper::get_instance();
     // Get the first entity from the displayed gallery. We will use this
     // for a preview pic
     $entity = array_pop($this->object->_displayed_gallery->get_included_entities(1));
     $image = FALSE;
     if ($entity) {
         // This is an album or gallery
         if (isset($entity->previewpic)) {
             $image = (int) $entity->previewpic;
             if ($image = $image_mapper->find($image)) {
                 $found_preview_pic = TRUE;
             }
         } else {
             if (isset($entity->galleryid)) {
                 $image = $entity;
                 $found_preview_pic = TRUE;
             }
         }
     }
     // Were we able to find a preview pic? If so, then render it
     $image_size = $dyn_thumbs->get_size_name(array('width' => 200, 'height' => 200, 'quality' => 90, 'type' => 'jpg'));
     $found_preview_pic = $storage->render_image($image, $image_size, TRUE);
     // Render invalid image if no preview pic is found
     if (!$found_preview_pic) {
         $filename = $this->object->get_static_abspath('photocrati-attach_to_post#invalid_image.png');
         $this->set_content_type('image/png');
         readfile($filename);
         $this->render();
     }
 }
示例#24
0
 /**
  * Get the last images registered in the database with a maximum number of $limit results
  *
  * @param integer $page start offset as page number (0,1,2,3,4...)
  * @param integer $limit the number of result
  * @param bool $exclude do not show exluded images
  * @param int $galleryId Only look for images with this gallery id, or in all galleries if id is 0
  * @param string $orderby is one of "id" (default, order by pid), "date" (order by exif date), sort (order by user sort order)
  * @deprecated
  * @return
  */
 static function find_last_images($page = 0, $limit = 30, $exclude = true, $galleryId = 0, $orderby = "pid")
 {
     // Determine ordering
     $order_field = $orderby;
     $order_direction = 'DESC';
     switch ($orderby) {
         case 'date':
         case 'imagedate':
         case 'time':
         case 'datetime':
             $order_field = 'imagedate';
             $order_direction = 'DESC';
             break;
         case 'sort':
         case 'sortorder':
             $order_field = 'sortorder';
             $order_direction = 'ASC';
             break;
     }
     // Start query
     $mapper = C_Image_Mapper::get_instance();
     $mapper->select()->order_by($order_field, $order_direction);
     // Calculate limit and offset
     if (!$limit) {
         $limit = 30;
     }
     $offset = $page * $limit;
     if ($offset && $limit) {
         $mapper->limit($limit, $offset);
     }
     // Add exclusion clause
     if ($exclude) {
         $mapper->where(array("exclude = %d", 0));
     }
     // Add gallery clause
     if ($galleryId) {
         $mapper->where(array("galleryid = %d", $galleryId));
     }
     return $mapper->run_query();
 }
 /**
  * Returns a single image object
  * @param $args (blog_id, username, password, pid)
  */
 function get_image($args, $return_model = FALSE)
 {
     $retval = new IXR_Error(403, 'Invalid username or password');
     $blog_id = intval($args[0]);
     $username = strval($args[1]);
     $password = strval($args[2]);
     $image_id = intval($args[3]);
     // Authenticate the user
     if ($this->_login($username, $password, $blog_id)) {
         // Try to find the image
         $image_mapper = C_Image_Mapper::get_instance();
         if ($image = $image_mapper->find($image_id, TRUE)) {
             // Try to find the gallery that the image belongs to
             $gallery_mapper = C_Gallery_Mapper::get_instance();
             if ($gallery = $gallery_mapper->find($image->galleryid)) {
                 // Does the user have sufficient capabilities?
                 if ($this->_can_manage_gallery($gallery)) {
                     $storage = C_Gallery_Storage::get_instance();
                     $image->imageURL = $storage->get_image_url($image, 'full', TRUE);
                     $image->thumbURL = $storage->get_thumb_url($image, TRUE);
                     $image->imagePath = $storage->get_image_abspath($image);
                     $image->thumbPath = $storage->get_thumb_abspath($image);
                     $retval = $return_model ? $image : $image->get_entity();
                 } else {
                     $retval = new IXR_Error(403, "You don't have permission to manage gallery #{$image->galleryid}");
                 }
             } else {
                 $retval = new IXR_Error(404, "Gallery not found (with id #{$image->gallerid}");
             }
         } else {
             $retval = FALSE;
         }
     }
     return $retval;
 }
 /**
  * Returns the rendered template of an image browser display
  *
  * @param C_Displayed_Gallery
  * @param array $picture_list
  * @return string Rendered HTML (probably)
  */
 function render_image_browser($displayed_gallery, $picture_list)
 {
     $display_settings = $displayed_gallery->display_settings;
     $storage = C_Gallery_Storage::get_instance();
     $imap = C_Image_Mapper::get_instance();
     $application = C_Router::get_instance()->get_routed_app();
     // the pid may be a slug so we must track it & the slug target's database id
     $pid = $this->object->param('pid');
     $numeric_pid = NULL;
     // makes the upcoming which-image-am-I loop easier
     $picture_array = array();
     foreach ($picture_list as $picture) {
         $picture_array[] = $picture->{$imap->get_primary_key_column()};
     }
     // Determine which image in the list we need to display
     if (!empty($pid)) {
         if (is_numeric($pid) && !empty($picture_list[$pid])) {
             $numeric_pid = intval($pid);
         } else {
             // in the case it's a slug we need to search for the pid
             foreach ($picture_list as $key => $picture) {
                 if ($picture->image_slug == $pid) {
                     $numeric_pid = $key;
                     break;
                 }
             }
         }
     } else {
         reset($picture_array);
         $numeric_pid = current($picture_array);
     }
     // get ids to the next and previous images
     $total = count($picture_array);
     $key = array_search($numeric_pid, $picture_array);
     if (!$key) {
         $numeric_pid = reset($picture_array);
         $key = key($picture_array);
     }
     // for "viewing image #13 of $total"
     $picture_list_pos = $key + 1;
     // our image to display
     $picture = new C_Image_Wrapper($imap->find($numeric_pid), $displayed_gallery, TRUE);
     $picture = apply_filters('ngg_image_object', $picture, $numeric_pid);
     // determine URI to the next & previous images
     $back_pid = $key >= 1 ? $picture_array[$key - 1] : end($picture_array);
     // 'show' is set when using the imagebrowser as an alternate view to a thumbnail or slideshow
     // for which the basic-gallery module will rewrite the show parameter into existence as long as 'image'
     // is set. We remove 'show' here so navigation appears fluid.
     $current_url = $application->get_routed_url(TRUE);
     if ($this->object->param('ajax_pagination_referrer')) {
         $current_url = $this->object->param('ajax_pagination_referrer');
     }
     $prev_image_link = $this->object->set_param_for($current_url, 'pid', $picture_list[$back_pid]->image_slug);
     $prev_image_link = $this->object->remove_param_for($prev_image_link, 'show', $displayed_gallery->id());
     $next_pid = $key < $total - 1 ? $picture_array[$key + 1] : reset($picture_array);
     $next_image_link = $this->object->set_param_for($current_url, 'pid', $picture_list[$next_pid]->image_slug);
     $next_image_link = $this->object->remove_param_for($next_image_link, 'show', $displayed_gallery->id());
     // css class
     $anchor = 'ngg-imagebrowser-' . $displayed_gallery->id() . '-' . (get_the_ID() == false ? 0 : get_the_ID());
     // try to read EXIF data, but fallback to the db presets
     $meta = new C_NextGen_Metadata($picture);
     $meta->sanitize();
     $meta_results = array('exif' => $meta->get_EXIF(), 'iptc' => $meta->get_IPTC(), 'xmp' => $meta->get_XMP(), 'db' => $meta->get_saved_meta());
     $meta_results['exif'] = $meta_results['exif'] == false ? $meta_results['db'] : $meta_results['exif'];
     // disable triggers IF we're rendering inside of an ajax-pagination request; var set in common.js
     if (!empty($_POST['ajax_referrer'])) {
         $displayed_gallery->display_settings['ngg_triggers_display'] = 'never';
     }
     if (!empty($display_settings['template']) && $display_settings['template'] != 'default') {
         $this->object->add_mixin('Mixin_NextGen_Basic_Templates');
         $picture->href_link = $picture->get_href_link();
         $picture->previous_image_link = $prev_image_link;
         $picture->previous_pid = $back_pid;
         $picture->next_image_link = $next_image_link;
         $picture->next_pid = $next_pid;
         $picture->number = $picture_list_pos;
         $picture->total = $total;
         $picture->anchor = $anchor;
         return $this->object->legacy_render($display_settings['template'], array('image' => $picture, 'meta' => $meta, 'exif' => $meta_results['exif'], 'iptc' => $meta_results['iptc'], 'xmp' => $meta_results['xmp'], 'db' => $meta_results['db'], 'displayed_gallery' => $displayed_gallery), TRUE, 'imagebrowser');
     } else {
         $params = $display_settings;
         $params['anchor'] = $anchor;
         $params['image'] = $picture;
         $params['storage'] =& $storage;
         $params['previous_pid'] = $back_pid;
         $params['next_pid'] = $next_pid;
         $params['number'] = $picture_list_pos;
         $params['total'] = $total;
         $params['previous_image_link'] = $prev_image_link;
         $params['next_image_link'] = $next_image_link;
         $params['effect_code'] = $this->object->get_effect_code($displayed_gallery);
         $params = $this->object->prepare_display_parameters($displayed_gallery, $params);
         return $this->object->render_partial('photocrati-nextgen_basic_imagebrowser#nextgen_basic_imagebrowser', $params, TRUE);
     }
 }
示例#27
0
 /**
  * nggAdmin::set_gallery_preview() - define a preview pic after the first upload, can be changed in the gallery settings
  *
  * @class nggAdmin
  * @param int $galleryID
  * @return void
  */
 static function set_gallery_preview($galleryID)
 {
     $gallery_mapper = C_Gallery_Mapper::get_instance();
     if ($gallery = $gallery_mapper->find($galleryID)) {
         if (!$gallery->previewpic) {
             $image_mapper = C_Image_Mapper::get_instance();
             if ($image = $image_mapper->select()->where(array('galleryid = %d', $galleryID))->where(array('exclude != 1'))->order_by($image_mapper->get_primary_key_column())->limit(1)->run_query()) {
                 $gallery->previewpic = $image->{$image->id_field};
                 $gallery_mapper->save($gallery);
             }
         }
     }
 }
示例#28
0
 /**
  * Lazy-loader for image variables.
  *
  * @param string $name Parameter name
  * @return mixed
  */
 public function __get($name)
 {
     if (isset($this->_cache_overrides[$name])) {
         return $this->_cache_overrides[$name];
     }
     // at the bottom we default to returning $this->_cache[$name].
     switch ($name) {
         case 'alttext':
             $this->_cache['alttext'] = empty($this->_cache['alttext']) ? ' ' : html_entity_decode(stripslashes(nggGallery::i18n($this->_cache['alttext'], 'pic_' . $this->__get('id') . '_alttext')));
             return $this->_cache['alttext'];
         case 'author':
             if ($this->_legacy) {
                 $gallery = $this->get_legacy_gallery($this->__get('galleryid'));
             } else {
                 $gallery_map = $this->get_gallery($this->__get('galleryid'));
                 $gallery = $gallery_map->find($this->__get('galleryid'));
             }
             $this->_cache['author'] = $gallery->name;
             return $this->_cache['author'];
         case 'caption':
             $caption = html_entity_decode(stripslashes(nggGallery::i18n($this->__get('description'), 'pic_' . $this->__get('id') . '_description')));
             if (empty($caption)) {
                 $caption = '&nbsp;';
             }
             $this->_cache['caption'] = $caption;
             return $this->_cache['caption'];
         case 'description':
             $this->_cache['description'] = empty($this->_cache['description']) ? ' ' : html_entity_decode(stripslashes(nggGallery::i18n($this->_cache['description'], 'pic_' . $this->__get('id') . '_description')));
             return $this->_cache['description'];
         case 'galdesc':
             if ($this->_legacy) {
                 $gallery = $this->get_legacy_gallery($this->__get('galleryid'));
             } else {
                 $gallery_map = $this->get_gallery($this->__get('galleryid'));
                 $gallery = $gallery_map->find($this->__get('galleryid'));
             }
             $this->_cache['galdesc'] = $gallery->name;
             return $this->_cache['galdesc'];
         case 'gid':
             if ($this->_legacy) {
                 $gallery = $this->get_legacy_gallery($this->__get('galleryid'));
             } else {
                 $gallery_map = $this->get_gallery($this->__get('galleryid'));
                 $gallery = $gallery_map->find($this->__get('galleryid'));
             }
             $this->_cache['gid'] = $gallery->name;
             return $this->_cache['gid'];
         case 'href':
             return $this->__get('imageHTML');
         case 'id':
             return $this->_orig_image_id;
         case 'imageHTML':
             $tmp = '<a href="' . $this->__get('imageURL') . '" title="' . htmlspecialchars(stripslashes(nggGallery::i18n($this->__get('description'), 'pic_' . $this->__get('id') . '_description'))) . '" ' . $this->get_thumbcode($this->__get('name')) . '>' . '<img alt="' . $this->__get('alttext') . '" src="' . $this->__get('imageURL') . '"/>' . '</a>';
             $this->_cache['href'] = $tmp;
             $this->_cache['imageHTML'] = $tmp;
             return $this->_cache['imageHTML'];
         case 'imagePath':
             $storage = $this->get_storage();
             $this->_cache['imagePath'] = $storage->get_image_abspath($this->_orig_image, 'full');
             return $this->_cache['imagePath'];
         case 'imageURL':
             $storage = $this->get_storage();
             $this->_cache['imageURL'] = $storage->get_image_url($this->_orig_image, 'full');
             return $this->_cache['imageURL'];
         case 'linktitle':
             $this->_cache['linktitle'] = htmlspecialchars(stripslashes(nggGallery::i18n($this->__get('description'), 'pic_' . $this->__get('id') . '_description')));
             return $this->_cache['linktitle'];
         case 'name':
             if ($this->_legacy) {
                 $gallery = $this->get_legacy_gallery($this->__get('galleryid'));
             } else {
                 $gallery_map = $this->get_gallery($this->__get('galleryid'));
                 $gallery = $gallery_map->find($this->__get('galleryid'));
             }
             $this->_cache['name'] = $gallery->name;
             return $this->_cache['name'];
         case 'pageid':
             if ($this->_legacy) {
                 $gallery = $this->get_legacy_gallery($this->__get('galleryid'));
             } else {
                 $gallery_map = $this->get_gallery($this->__get('galleryid'));
                 $gallery = $gallery_map->find($this->__get('galleryid'));
             }
             $this->_cache['pageid'] = $gallery->name;
             return $this->_cache['pageid'];
         case 'path':
             if ($this->_legacy) {
                 $gallery = $this->get_legacy_gallery($this->__get('galleryid'));
             } else {
                 $gallery_map = $this->get_gallery($this->__get('galleryid'));
                 $gallery = $gallery_map->find($this->__get('galleryid'));
             }
             $this->_cache['path'] = $gallery->name;
             return $this->_cache['path'];
         case 'permalink':
             $this->_cache['permalink'] = $this->__get('imageURL');
             return $this->_cache['permalink'];
         case 'pid':
             return $this->_orig_image_id;
         case 'pidlink':
             $application = C_Component_Registry::get_instance()->get_utility('I_Router')->get_routed_app();
             $controller = C_Component_Registry::get_instance()->get_utility('I_Display_Type_Controller');
             $this->_cache['pidlink'] = $controller->set_param_for($application->get_routed_url(TRUE), 'pid', $this->__get('image_slug'));
             return $this->_cache['pidlink'];
         case 'previewpic':
             if ($this->_legacy) {
                 $gallery = $this->get_legacy_gallery($this->__get('galleryid'));
             } else {
                 $gallery_map = $this->get_gallery($this->__get('galleryid'));
                 $gallery = $gallery_map->find($this->__get('galleryid'));
             }
             $this->_cache['previewpic'] = $gallery->name;
             return $this->_cache['previewpic'];
         case 'size':
             if (is_string($this->_orig_image->meta_data)) {
                 $this->_orig_image = C_Image_Mapper::get_instance()->unserialize($this->_orig_image->meta_data);
             }
             $w = $this->_orig_image->meta_data['thumbnail']['width'];
             $h = $this->_orig_image->meta_data['thumbnail']['height'];
             return "width='{$w}' height='{$h}'";
         case 'slug':
             if ($this->_legacy) {
                 $gallery = $this->get_legacy_gallery($this->__get('galleryid'));
             } else {
                 $gallery_map = $this->get_gallery($this->__get('galleryid'));
                 $gallery = $gallery_map->find($this->__get('galleryid'));
             }
             $this->_cache['slug'] = $gallery->name;
             return $this->_cache['slug'];
         case 'tags':
             $this->_cache['tags'] = wp_get_object_terms($this->__get('id'), 'ngg_tag', 'fields=all');
             return $this->_cache['tags'];
         case 'thumbHTML':
             $tmp = '<a href="' . $this->__get('imageURL') . '" title="' . htmlspecialchars(stripslashes(nggGallery::i18n($this->__get('description'), 'pic_' . $this->__get('id') . '_description'))) . '" ' . $this->get_thumbcode($this->__get('name')) . '>' . '<img alt="' . $this->__get('alttext') . '" src="' . $this->thumbURL . '"/>' . '</a>';
             $this->_cache['href'] = $tmp;
             $this->_cache['thumbHTML'] = $tmp;
             return $this->_cache['thumbHTML'];
         case 'thumbPath':
             $storage = $this->get_storage();
             $this->_cache['thumbPath'] = $storage->get_image_abspath($this->_orig_image, 'thumbnail');
             return $this->_cache['thumbPath'];
         case 'thumbnailURL':
             $storage = $this->get_storage();
             $this->_cache['thumbnailURL'] = $storage->get_thumb_url($this->_orig_image);
             return $this->_cache['thumbnailURL'];
         case 'thumbcode':
             $this->_cache['thumbcode'] = $this->get_thumbcode($this->__get('name'));
             return $this->_cache['thumbcode'];
         case 'thumbURL':
             return $this->__get('thumbnailURL');
         case 'title':
             $this->_cache['title'] = stripslashes($this->__get('name'));
             return $this->_cache['title'];
         case 'url':
             $storage = $this->get_storage();
             $this->_cache['url'] = $storage->get_image_url($this->_orig_image, 'full');
             return $this->_cache['url'];
         default:
             return $this->_cache[$name];
     }
 }
 public function prepare_legacy_album_params($displayed_gallery, $params)
 {
     $image_mapper = C_Image_Mapper::get_instance();
     $storage = C_Gallery_Storage::get_instance();
     $image_gen = C_Dynamic_Thumbnails_Manager::get_instance();
     if (empty($displayed_gallery->display_settings['override_thumbnail_settings'])) {
         // legacy templates expect these dimensions
         $image_gen_params = array('width' => 91, 'height' => 68, 'crop' => TRUE);
     } else {
         // use settings requested by user
         $image_gen_params = array('width' => $displayed_gallery->display_settings['thumbnail_width'], 'height' => $displayed_gallery->display_settings['thumbnail_height'], 'quality' => isset($displayed_gallery->display_settings['thumbnail_quality']) ? $displayed_gallery->display_settings['thumbnail_quality'] : 100, 'crop' => isset($displayed_gallery->display_settings['thumbnail_crop']) ? $displayed_gallery->display_settings['thumbnail_crop'] : NULL, 'watermark' => isset($displayed_gallery->display_settings['thumbnail_watermark']) ? $displayed_gallery->display_settings['thumbnail_watermark'] : NULL);
     }
     // so user templates can know how big the images are expected to be
     $params['image_gen_params'] = $image_gen_params;
     // Transform entities
     $params['galleries'] = $params['entities'];
     unset($params['entities']);
     foreach ($params['galleries'] as &$gallery) {
         // Get the preview image url
         $gallery->previewurl = '';
         if ($gallery->previewpic && $gallery->previewpic > 0) {
             if ($image = $image_mapper->find(intval($gallery->previewpic))) {
                 $gallery->previewurl = $storage->get_image_url($image, $image_gen->get_size_name($image_gen_params), TRUE);
                 $gallery->previewname = $gallery->name;
             }
         }
         // Get the page link. If the entity is an album, then the url will
         // look like /nggallery/album--slug.
         $id_field = $gallery->id_field;
         if ($gallery->is_album) {
             if ($gallery->pageid > 0) {
                 $gallery->pagelink = @get_page_link($gallery->pageid);
             } else {
                 $gallery->pagelink = $this->object->set_param_for($this->object->get_routed_url(TRUE), 'album', $gallery->slug);
             }
         } else {
             if ($gallery->pageid > 0) {
                 $gallery->pagelink = @get_page_link($gallery->pageid);
             }
             if (empty($gallery->pagelink)) {
                 $pagelink = $this->object->get_routed_url(TRUE);
                 $parent_album = $this->object->get_parent_album_for($gallery->{$id_field});
                 if ($parent_album) {
                     $pagelink = $this->object->set_param_for($pagelink, 'album', $parent_album->slug);
                 } else {
                     if ($displayed_gallery->container_ids === array('0') || $displayed_gallery->container_ids === array('')) {
                         $pagelink = $this->object->set_param_for($pagelink, 'album', 'all');
                     } else {
                         $pagelink = $this->object->set_param_for($pagelink, 'album', 'album');
                     }
                 }
                 $gallery->pagelink = $this->object->set_param_for($pagelink, 'gallery', $gallery->slug);
             }
         }
         // Let plugins modify the gallery
         $gallery = apply_filters('ngg_album_galleryobject', $gallery);
     }
     $params['album'] = reset($this->albums);
     $params['albums'] = $this->albums;
     // Clean up
     unset($storage);
     unset($image_mapper);
     unset($image_gen);
     unset($image_gen_params);
     return $params;
 }
 public function set_post_thumbnail($post, $image)
 {
     $attachment_id = null;
     // Get the post id
     $post_id = $post;
     if (is_object($post)) {
         if (property_exists($post, 'ID')) {
             $post_id = $post->ID;
         } elseif (property_exists($post, 'post_id')) {
             $post_id = $post->post_id;
         }
     } elseif (is_array($post)) {
         if (isset($post['ID'])) {
             $post_id = $post['ID'];
         } elseif (isset($post['post_id'])) {
             $post_id = $post['post_id'];
         }
     }
     // Get the image object
     if (is_int($image)) {
         $image = C_Image_Mapper::get_instance()->find($image);
     }
     // Do we have what we need?
     if ($image && is_int($post_id)) {
         $args = array('post_type' => 'attachment', 'meta_key' => '_ngg_image_id', 'meta_compare' => '==', 'meta_value' => $image->{$image->id_field});
         $upload_dir = wp_upload_dir();
         $basedir = $upload_dir['basedir'];
         $thumbs_dir = implode(DIRECTORY_SEPARATOR, array($basedir, 'ngg_featured'));
         $gallery_abspath = $this->object->get_gallery_abspath($image->galleryid);
         $image_abspath = $this->object->get_full_abspath($image);
         $target_path = null;
         $copy_image = TRUE;
         // Have we previously set the post thumbnail?
         if ($posts = get_posts($args)) {
             $attachment_id = $posts[0]->ID;
             $attachment_file = get_attached_file($attachment_id);
             $target_path = $attachment_file;
             if (filemtime($image_abspath) > filemtime($target_path)) {
                 $copy_image = TRUE;
             }
         } else {
             $url = $this->object->get_full_url($image);
             $target_relpath = null;
             $target_basename = M_I18n::mb_basename($image_abspath);
             if (strpos($image_abspath, $gallery_abspath) === 0) {
                 $target_relpath = substr($image_abspath, strlen($gallery_abspath));
             } else {
                 if ($image->galleryid) {
                     $target_relpath = path_join(strval($image->galleryid), $target_basename);
                 } else {
                     $target_relpath = $target_basename;
                 }
             }
             $target_relpath = trim($target_relpath, '\\/');
             $target_path = path_join($thumbs_dir, $target_relpath);
             $max_count = 100;
             $count = 0;
             while (file_exists($target_path) && $count <= $max_count) {
                 $count++;
                 $pathinfo = M_I18n::mb_pathinfo($target_path);
                 $dirname = $pathinfo['dirname'];
                 $filename = $pathinfo['filename'];
                 $extension = $pathinfo['extension'];
                 $rand = mt_rand(1, 9999);
                 $basename = $filename . '_' . sprintf('%04d', $rand) . '.' . $extension;
                 $target_path = path_join($dirname, $basename);
             }
             if (file_exists($target_path)) {
             }
             $target_dir = dirname($target_path);
             wp_mkdir_p($target_dir);
         }
         if ($copy_image) {
             @copy($image_abspath, $target_path);
             if (!$attachment_id) {
                 $size = @getimagesize($target_path);
                 $image_type = $size ? $size['mime'] : 'image/jpeg';
                 $title = sanitize_file_name($image->alttext);
                 $caption = sanitize_file_name($image->description);
                 $attachment = array('post_title' => $title, 'post_content' => $caption, 'post_status' => 'attachment', 'post_parent' => 0, 'post_mime_type' => $image_type, 'guid' => $url);
                 $attachment_id = wp_insert_attachment($attachment, $target_path);
             }
             update_post_meta($attachment_id, '_ngg_image_id', $image->{$image->id_field});
             wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $target_path));
             set_post_thumbnail($post_id, $attachment_id);
         }
     }
     return $attachment_id;
 }