Plugin Directory

Changeset 3823635


Ignore:
Timestamp:
11/25/2026 06:48:05 PM (less than one hour ago)
Author:
alimuzzamanalim
Message:

Release 3.2.0

Location:
author-or-user-image
Files:
6 added
28 edited
1 copied

Legend:

Unmodified
Added
Removed
  • author-or-user-image/tags/3.2.0/assets/css/front-end.css

    r3796032 r3823635  
    2020.zmai-front-end .zmai-status:empty,
    2121.zmai-front-end .zmai-status p:empty { display: none; }
     22.zmai-front-end.zmai-align-left { margin-inline-end: auto; }
     23.zmai-front-end.zmai-align-center { margin-inline: auto; text-align: center; }
     24.zmai-front-end.zmai-align-center .zmai-avatar-preview { margin-inline: auto; }
     25.zmai-front-end.zmai-align-right { margin-inline-start: auto; }
  • author-or-user-image/tags/3.2.0/assets/js/avatar-upload-editor.js

    r3796032 r3823635  
    11/* global wp */
    2 (function (blocks, element, blockEditor, i18n) {
     2(function (blocks, element, blockEditor, components, i18n) {
    33        'use strict';
     4        var el = element.createElement;
     5        var Fragment = element.Fragment;
     6        var InspectorControls = blockEditor.InspectorControls;
     7        var PanelBody = components.PanelBody;
     8        var ToggleControl = components.ToggleControl;
     9        var RangeControl = components.RangeControl;
     10        var SelectControl = components.SelectControl;
     11        var TextControl = components.TextControl;
     12
     13        function cleanLabel(value, maxLen) {
     14                if (typeof value !== 'string') {
     15                        return '';
     16                }
     17                var cleaned = value.replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim();
     18                return cleaned ? cleaned.slice(0, maxLen) : '';
     19        }
     20
    421        blocks.registerBlockType('author-or-user-image/avatar-upload', {
    522                apiVersion: 3,
    … …  
    926                icon: 'admin-users',
    1027                supports: { html: false },
    11                 edit: function () {
    12                         return element.createElement('div', blockEditor.useBlockProps({ className: 'zmai-front-end' }),
    13                                 element.createElement('strong', null, i18n.__('Avatar upload', 'author-or-user-image')),
    14                                 element.createElement('p', null, i18n.__('On the published page, signed-in visitors can manage their own avatar. Other visitors see a login link.', 'author-or-user-image')));
     28                attributes: {
     29                        showPreview: { type: 'boolean', default: true },
     30                        previewSize: { type: 'integer', default: 0 },
     31                        alignment: { type: 'string', default: '' },
     32                        uploadLabel: { type: 'string', default: '' },
     33                        removeLabel: { type: 'string', default: '' },
     34                        loginLabel: { type: 'string', default: '' }
     35                },
     36                edit: function (props) {
     37                        var attrs = props.attributes || {};
     38                        var showPreview = attrs.showPreview !== false;
     39                        var previewSize = typeof attrs.previewSize === 'number' ? attrs.previewSize : 0;
     40                        var effectivePreviewSize = previewSize > 0 ? Math.min(512, Math.max(32, previewSize)) : 0;
     41                        var rawAlignment = typeof attrs.alignment === 'string' ? attrs.alignment : '';
     42                        var alignment = rawAlignment === 'left' || rawAlignment === 'center' || rawAlignment === 'right' ? rawAlignment : '';
     43                        var uploadLabel = typeof attrs.uploadLabel === 'string' ? attrs.uploadLabel : '';
     44                        var removeLabel = typeof attrs.removeLabel === 'string' ? attrs.removeLabel : '';
     45                        var loginLabel = typeof attrs.loginLabel === 'string' ? attrs.loginLabel : '';
     46                        var summaryUpload = cleanLabel(uploadLabel, 80);
     47                        var summaryRemove = cleanLabel(removeLabel, 80);
     48
     49                        var summary = [];
     50                        if (!showPreview) {
     51                                summary.push(i18n.__('Preview hidden', 'author-or-user-image'));
     52                        } else if (effectivePreviewSize > 0) {
     53                                summary.push(i18n.__('Preview size:', 'author-or-user-image') + ' ' + effectivePreviewSize + 'px');
     54                        }
     55                        if (alignment) {
     56                                summary.push(i18n.__('Alignment:', 'author-or-user-image') + ' ' + alignment);
     57                        }
     58                        if (summaryUpload) {
     59                                summary.push(i18n.__('Upload label:', 'author-or-user-image') + ' ' + summaryUpload);
     60                        }
     61                        if (summaryRemove) {
     62                                summary.push(i18n.__('Remove label:', 'author-or-user-image') + ' ' + summaryRemove);
     63                        }
     64
     65                        var className = 'zmai-front-end' + (alignment ? ' zmai-align-' + alignment : '');
     66
     67                        return el(
     68                                Fragment,
     69                                null,
     70                                el(
     71                                        InspectorControls,
     72                                        null,
     73                                        el(
     74                                                PanelBody,
     75                                                { title: i18n.__('Display & labels', 'author-or-user-image'), initialOpen: true },
     76                                                el(ToggleControl, {
     77                                                        label: i18n.__('Show current avatar preview', 'author-or-user-image'),
     78                                                        checked: showPreview,
     79                                                        onChange: function (value) {
     80                                                                props.setAttributes({ showPreview: !!value });
     81                                                        }
     82                                                }),
     83                                                el(RangeControl, {
     84                                                        label: i18n.__('Preview size (px, 0 = site default)', 'author-or-user-image'),
     85                                                        value: effectivePreviewSize,
     86                                                        min: 0,
     87                                                        max: 512,
     88                                                        step: 8,
     89                                                        onChange: function (value) {
     90                                                                var next = typeof value === 'number' && !isNaN(value) ? Math.round(value) : 0;
     91                                                                if (next > 0 && next < 32) {
     92                                                                        next = effectivePreviewSize >= 32 ? 0 : 32;
     93                                                                } else if (next < 0) {
     94                                                                        next = 0;
     95                                                                } else if (next > 512) {
     96                                                                        next = 512;
     97                                                                }
     98                                                                props.setAttributes({ previewSize: next });
     99                                                        }
     100                                                }),
     101                                                el(SelectControl, {
     102                                                        label: i18n.__('Alignment', 'author-or-user-image'),
     103                                                        value: alignment,
     104                                                        options: [
     105                                                                { label: i18n.__('Default', 'author-or-user-image'), value: '' },
     106                                                                { label: i18n.__('Left', 'author-or-user-image'), value: 'left' },
     107                                                                { label: i18n.__('Center', 'author-or-user-image'), value: 'center' },
     108                                                                { label: i18n.__('Right', 'author-or-user-image'), value: 'right' }
     109                                                        ],
     110                                                        onChange: function (value) {
     111                                                                props.setAttributes({ alignment: value || '' });
     112                                                        }
     113                                                }),
     114                                                el(TextControl, {
     115                                                        label: i18n.__('Upload button label', 'author-or-user-image'),
     116                                                        placeholder: i18n.__('Upload image', 'author-or-user-image'),
     117                                                        maxLength: 80,
     118                                                        value: uploadLabel,
     119                                                        onChange: function (value) {
     120                                                                props.setAttributes({ uploadLabel: value });
     121                                                        }
     122                                                }),
     123                                                el(TextControl, {
     124                                                        label: i18n.__('Remove button label', 'author-or-user-image'),
     125                                                        placeholder: i18n.__('Remove image', 'author-or-user-image'),
     126                                                        maxLength: 80,
     127                                                        value: removeLabel,
     128                                                        onChange: function (value) {
     129                                                                props.setAttributes({ removeLabel: value });
     130                                                        }
     131                                                }),
     132                                                el(TextControl, {
     133                                                        label: i18n.__('Logged-out link text', 'author-or-user-image'),
     134                                                        placeholder: i18n.__('Log in to manage your avatar.', 'author-or-user-image'),
     135                                                        maxLength: 120,
     136                                                        value: loginLabel,
     137                                                        onChange: function (value) {
     138                                                                props.setAttributes({ loginLabel: value });
     139                                                        }
     140                                                })
     141                                        )
     142                                ),
     143                                el(
     144                                        'div',
     145                                        blockEditor.useBlockProps({ className: className }),
     146                                        el('strong', null, i18n.__('Avatar upload', 'author-or-user-image')),
     147                                        el('p', null, i18n.__('On the published page, signed-in visitors can manage their own avatar. Other visitors see a login link.', 'author-or-user-image')),
     148                                        summary.length ? el('p', { className: 'description' }, summary.join(' · ')) : null
     149                                )
     150                        );
    15151                },
    16152                save: function () { return null; }
    17153        });
    18 })(wp.blocks, wp.element, wp.blockEditor, wp.i18n);
     154})(wp.blocks, wp.element, wp.blockEditor, wp.components, wp.i18n);
  • author-or-user-image/tags/3.2.0/author_image.php

    r3796032 r3823635  
    33 * Plugin Name: Author or User Image
    44 * Description: Let registered users use a local image as their WordPress avatar.
    5  * Version: 3.1.0
     5 * Version: 3.2.0
    66 * Requires at least: 6.6
    77 * Requires PHP: 7.4
    … …  
    1717defined( 'ABSPATH' ) || exit;
    1818
    19 define( 'ZMAI_VERSION', '3.1.0' );
     19define( 'ZMAI_VERSION', '3.2.0' );
    2020define( 'ZMAI_FILE', __FILE__ );
    2121define( 'ZMAI_PATH', plugin_dir_path( __FILE__ ) );
    … …  
    3333require_once ZMAI_PATH . 'includes/class-privacy.php';
    3434require_once ZMAI_PATH . 'includes/class-admin.php';
     35require_once ZMAI_PATH . 'includes/class-profile-admin.php';
    3536require_once ZMAI_PATH . 'includes/class-front-end.php';
     37require_once ZMAI_PATH . 'includes/class-rest-api.php';
     38require_once ZMAI_PATH . 'includes/class-cli.php';
    3639require_once ZMAI_PATH . 'includes/class-plugin.php';
    3740
  • author-or-user-image/tags/3.2.0/blocks/avatar-upload/block.json

    r3796032 r3823635  
    33  "apiVersion": 3,
    44  "name": "author-or-user-image/avatar-upload",
    5   "version": "1.0.0",
     5  "version": "1.1.0",
    66  "title": "Avatar upload",
    77  "category": "widgets",
    … …  
    1010  "textdomain": "author-or-user-image",
    1111  "supports": { "html": false },
     12  "attributes": {
     13    "showPreview": { "type": "boolean", "default": true },
     14    "previewSize": { "type": "integer", "default": 0 },
     15    "alignment": { "type": "string", "default": "", "enum": ["", "left", "center", "right"] },
     16    "uploadLabel": { "type": "string", "default": "" },
     17    "removeLabel": { "type": "string", "default": "" },
     18    "loginLabel": { "type": "string", "default": "" }
     19  },
    1220  "editorScript": "zmai-avatar-upload-editor",
    1321  "style": "zmai-front-end"
  • author-or-user-image/tags/3.2.0/includes/class-admin-import.php

    r3796032 r3823635  
    6060                add_action( 'load-' . $hook, array( $this, 'set_page_title' ) );
    6161                $job = $this->migration->import_status();
    62                 if ( is_wp_error( $job ) || ( $job && 'complete' !== $job['state'] ) || get_option( Migration::RELEASE_FAILED_OPTION ) ) {
     62                if ( is_wp_error( $job ) || ( $job && 'complete' !== $job['state'] ) || $this->migration->has_release_failure() ) {
    6363                        return;
    6464                }
    … …  
    199199                        echo '<div class="notice notice-error"><p>' . esc_html__( 'Import stopped. Review the stored progress and restore missing files locally before retrying. Retained locks require operator reconciliation.', 'author-or-user-image' ) . '</p></div>';
    200200                }
    201                 if ( is_wp_error( $job ) || get_option( Migration::RELEASE_FAILED_OPTION ) ) {
     201                if ( is_wp_error( $job ) || $this->migration->has_release_failure() ) {
    202202                        echo '<div class="notice notice-error"><p>' . esc_html__( 'Import state is unavailable or needs recovery. Ask the administrator to reconcile its schema and retained locks. No import was started.', 'author-or-user-image' ) . '</p></div></div>';
    203203                        return;
  • author-or-user-image/tags/3.2.0/includes/class-admin.php

    r3796032 r3823635  
    280280         */
    281281        private function reject_oversized_upload() {
    282                 $limit  = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
    283                 $length = isset( $_SERVER['CONTENT_LENGTH'] ) ? sanitize_text_field( wp_unslash( $_SERVER['CONTENT_LENGTH'] ) ) : '';
     282                $post_max = function_exists( 'ini_get' ) ? (string) ini_get( 'post_max_size' ) : '';
     283                $limit    = '' !== $post_max ? wp_convert_hr_to_bytes( $post_max ) : 0;
     284                $length   = isset( $_SERVER['CONTENT_LENGTH'] ) ? sanitize_text_field( wp_unslash( $_SERVER['CONTENT_LENGTH'] ) ) : '';
    284285                // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Only detect PHP's discarded body; no submitted data is processed and no state is changed.
    285286                if ( ! current_user_can( 'read' ) || ! isset( $_SERVER['REQUEST_METHOD'] ) || 'POST' !== $_SERVER['REQUEST_METHOD'] || $_POST || $_FILES || $limit <= 0 || ! ctype_digit( $length ) || (float) $length <= $limit ) {
    … …  
    525526                }
    526527
     528                $blog_id = get_current_blog_id();
    527529                foreach ( $user_ids as $user_id ) {
    528                         if ( ! get_userdata( $user_id ) ) {
     530                        if ( ! get_userdata( $user_id ) || ( is_multisite() && ! is_user_member_of_blog( $user_id, $blog_id ) ) ) {
     531                                continue;
     532                        }
     533                        if ( ! current_user_can( 'edit_user', $user_id ) ) {
    529534                                continue;
    530535                        }
    … …  
    578583                </form>
    579584                <?php
     585                $this->render_lock_diagnostics();
     586        }
     587
     588        /**
     589         * Render read-only lifecycle lock status without exposing lock tokens or unsafe clear actions.
     590         *
     591         * @return void
     592         */
     593        private function render_lock_diagnostics() {
     594                $locks          = $this->store->get_lock()->inspect_locks();
     595                $release_failed = false;
     596                $status_error   = is_wp_error( $locks );
     597                try {
     598                        $release_failed = (bool) $this->store->read_value( 0, '', Migration::RELEASE_FAILED_OPTION );
     599                } catch ( \Throwable $error ) {
     600                        $status_error = true;
     601                }
     602                $scope_labels = array(
     603                        'migration' => __( 'Migration coordinator', 'author-or-user-image' ),
     604                        'blocks'    => __( 'Block list', 'author-or-user-image' ),
     605                        'default'   => __( 'Default avatar', 'author-or-user-image' ),
     606                        'user'      => __( 'User avatar', 'author-or-user-image' ),
     607                        'unknown'   => __( 'Unknown', 'author-or-user-image' ),
     608                );
     609                ?>
     610                <div class="zmai-card">
     611                        <h2><?php esc_html_e( 'Lifecycle lock status', 'author-or-user-image' ); ?></h2>
     612                        <?php if ( $status_error ) : ?>
     613                                <p class="description"><?php esc_html_e( 'Could not read lifecycle lock status from the database.', 'author-or-user-image' ); ?></p>
     614                        <?php elseif ( ! $locks && ! $release_failed ) : ?>
     615                                <p class="description"><?php esc_html_e( 'No active or retained avatar locks were found on this site.', 'author-or-user-image' ); ?></p>
     616                        <?php else : ?>
     617                                <?php if ( $release_failed ) : ?>
     618                                        <div class="notice notice-warning inline">
     619                                                <p><?php esc_html_e( 'A legacy migration lock release previously failed. Verify no migration process is active and follow the lifecycle recovery guide before retrying.', 'author-or-user-image' ); ?></p>
     620                                        </div>
     621                                <?php endif; ?>
     622                                <?php if ( $locks ) : ?>
     623                                        <p class="description"><?php esc_html_e( 'Active locks belong to running requests. Retained locks remain after an interrupted operation; confirm no worker is running and reconcile using the lifecycle recovery guide before removing any row.', 'author-or-user-image' ); ?></p>
     624                                        <table class="widefat striped">
     625                                                <thead>
     626                                                        <tr>
     627                                                                <th scope="col"><?php esc_html_e( 'Lock name', 'author-or-user-image' ); ?></th>
     628                                                                <th scope="col"><?php esc_html_e( 'Scope', 'author-or-user-image' ); ?></th>
     629                                                                <th scope="col"><?php esc_html_e( 'Owner ID', 'author-or-user-image' ); ?></th>
     630                                                        </tr>
     631                                                </thead>
     632                                                <tbody>
     633                                                        <?php foreach ( $locks as $lock ) : ?>
     634                                                                <tr>
     635                                                                        <td><code><?php echo esc_html( $lock['name'] ); ?></code></td>
     636                                                                        <td><?php echo esc_html( $scope_labels[ $lock['scope'] ] ?? $scope_labels['unknown'] ); ?></td>
     637                                                                        <td><?php echo esc_html( $lock['owner_id'] > 0 ? (string) $lock['owner_id'] : '—' ); ?></td>
     638                                                                </tr>
     639                                                        <?php endforeach; ?>
     640                                                </tbody>
     641                                        </table>
     642                                <?php endif; ?>
     643                        <?php endif; ?>
     644                </div>
     645                <?php
    580646        }
    581647
    … …  
    649715                        echo '<div class="notice notice-error"><p>' . esc_html__( 'The requested changes did not all complete. Avatar data may be busy or need administrator recovery. Please retry.', 'author-or-user-image' ) . '</p></div>';
    650716                } elseif ( in_array( $status, array( 'upload-error', 'remove-error' ), true ) ) {
    651                         $errors  = array(
    652                                 'zmai_invalid_image'      => __( 'Choose a JPEG, PNG, or static WebP image.', 'author-or-user-image' ),
    653                                 'zmai_upload_size'        => __( 'The image exceeds this site’s upload limit. Choose a smaller image.', 'author-or-user-image' ),
    654                                 'zmai_rate_limited'       => __( 'Too many avatar uploads. Please wait before trying again.', 'author-or-user-image' ),
    655                                 'zmai_blocked'            => __( 'Local avatar uploads are disabled for this account.', 'author-or-user-image' ),
    656                                 'zmai_metadata_failed'    => __( 'The image metadata could not be removed safely. Choose another image.', 'author-or-user-image' ),
    657                                 'zmai_metadata_cmyk'      => __( 'This server cannot safely normalize this CMYK JPEG. Convert it to RGB and try again.', 'author-or-user-image' ),
    658                                 'zmai_invalid_dimensions' => __( 'Choose an image no larger than 4096 by 4096 pixels.', 'author-or-user-image' ),
    659                         );
    660                         $message = $errors[ $error ] ?? __( 'The image change could not be completed. Please try again or contact an administrator.', 'author-or-user-image' );
    661                         echo '<div class="notice notice-error is-dismissible"><p>' . esc_html( $message ) . '</p></div>';
     717                        echo '<div class="notice notice-error is-dismissible"><p>' . esc_html( self::upload_error_message( $error ) ) . '</p></div>';
    662718                } elseif ( isset( $map[ $status ] ) ) {
    663719                        $class = 'nothing-selected' === $status ? 'notice-warning' : 'notice-success';
    … …  
    718774                exit;
    719775        }
     776
     777        /**
     778         * Map a typed avatar operation error code to a fixed translated message.
     779         *
     780         * @param string $code Typed error code.
     781         * @return string
     782         */
     783        public static function upload_error_message( $code ) {
     784                $errors = array(
     785                        'zmai_invalid_image'           => __( 'Choose a JPEG, PNG, or static WebP image.', 'author-or-user-image' ),
     786                        'zmai_invalid_image_container' => __( 'Choose a JPEG, PNG, or static WebP image.', 'author-or-user-image' ),
     787                        'zmai_animated_image'          => __( 'Animated images are not supported. Choose a static JPEG, PNG, or WebP image.', 'author-or-user-image' ),
     788                        'zmai_upload_size'             => __( 'The image exceeds this site’s upload limit. Choose a smaller image.', 'author-or-user-image' ),
     789                        'zmai_rate_limited'            => __( 'Too many avatar uploads. Please wait before trying again.', 'author-or-user-image' ),
     790                        'zmai_blocked'                 => __( 'Local avatar uploads are disabled for this account.', 'author-or-user-image' ),
     791                        'zmai_forbidden'               => __( 'You are not allowed to do that.', 'author-or-user-image' ),
     792                        'zmai_metadata_failed'         => __( 'The image metadata could not be removed safely. Choose another image.', 'author-or-user-image' ),
     793                        'zmai_metadata_cmyk'           => __( 'This server cannot safely normalize this CMYK JPEG. Convert it to RGB and try again.', 'author-or-user-image' ),
     794                        'zmai_invalid_dimensions'      => __( 'Choose an image no larger than 4096 by 4096 pixels.', 'author-or-user-image' ),
     795                        'zmai_jpeg_exif_unavailable'   => __( 'JPEG processing requires server EXIF support.', 'author-or-user-image' ),
     796                        'zmai_upload_missing'          => __( 'Choose an image file to upload.', 'author-or-user-image' ),
     797                        'zmai_upload_provenance'       => __( 'Choose a newly uploaded image.', 'author-or-user-image' ),
     798                        'zmai_invalid_policy'          => __( 'Choose a valid upload policy and known site roles.', 'author-or-user-image' ),
     799                        'zmai_busy'                    => __( 'Avatar data is busy or unavailable. Please retry.', 'author-or-user-image' ),
     800                        'zmai_invalid_user'            => __( 'The selected user account does not exist.', 'author-or-user-image' ),
     801                        'zmai_user_not_found'          => __( 'The requested user was not found.', 'author-or-user-image' ),
     802                );
     803                return $errors[ $code ] ?? __( 'The image change could not be completed. Please try again or contact an administrator.', 'author-or-user-image' );
     804        }
    720805}
  • author-or-user-image/tags/3.2.0/includes/class-front-end.php

    r3796032 r3823635  
    5151        public function register() {
    5252                wp_register_style( 'zmai-front-end', ZMAI_URL . 'assets/css/front-end.css', array(), ZMAI_VERSION );
    53                 wp_register_script( 'zmai-avatar-upload-editor', ZMAI_URL . 'assets/js/avatar-upload-editor.js', array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-i18n' ), ZMAI_VERSION, true );
     53                wp_register_script( 'zmai-avatar-upload-editor', ZMAI_URL . 'assets/js/avatar-upload-editor.js', array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n' ), ZMAI_VERSION, true );
    5454                wp_set_script_translations( 'zmai-avatar-upload-editor', 'author-or-user-image' );
    5555                register_block_type( ZMAI_PATH . 'blocks/avatar-upload', array( 'render_callback' => array( $this, 'render_form' ) ) );
    … …  
    172172
    173173        /**
    174          * Render for the current visitor; all block/shortcode attributes are ignored.
    175          *
     174         * Render for the current visitor using allowlisted presentation attributes only.
     175         *
     176         * @param mixed $attributes Block or shortcode attributes.
    176177         * @return string Escaped form markup.
    177178         */
    178         public function render_form() {
     179        public function render_form( $attributes = array() ) {
    179180                // Widgets and templates render after the early hook, so the form marks its own page.
    180181                if ( is_user_logged_in() ) {
    … …  
    187188                        wp_print_styles( array( 'zmai-front-end' ) );
    188189                }
    189                 $home   = wp_parse_url( home_url( '/' ) );
    190                 $origin = $home['scheme'] . '://' . $home['host'] . ( isset( $home['port'] ) ? ':' . $home['port'] : '' );
     190                $opts          = $this->normalize_attributes( $attributes );
     191                $wrapper_class = 'zmai-front-end' . ( '' !== $opts['alignment'] ? ' zmai-align-' . $opts['alignment'] : '' );
     192                $home          = wp_parse_url( home_url( '/' ) );
     193                $origin        = $home['scheme'] . '://' . $home['host'] . ( isset( $home['port'] ) ? ':' . $home['port'] : '' );
    191194                // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- The strict origin/path allowlist below validates this URL before use.
    192195                $request = isset( $_SERVER['REQUEST_URI'] ) && is_string( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '/';
    193196                $return  = self::safe_return_url( $origin . $request );
    194197                ?>
    195                 <div class="zmai-front-end">
     198                <div class="<?php echo esc_attr( $wrapper_class ); ?>">
    196199                <?php if ( ! is_user_logged_in() ) : ?>
    197                         <p><a href="<?php echo esc_url( wp_login_url( $return ) ); ?>"><?php esc_html_e( 'Log in to manage your avatar.', 'author-or-user-image' ); ?></a></p>
     200                        <p><a href="<?php echo esc_url( wp_login_url( $return ) ); ?>"><?php echo esc_html( $opts['loginLabel'] ); ?></a></p>
    198201                <?php else : ?>
    199202                        <?php
    200                         $user_id = get_current_user_id();
    201                         $id      = wp_unique_id( 'zmai-avatar-' );
    202                         $url     = $this->store->get_url( $user_id, $this->store->get_size(), false );
    203                         $action  = add_query_arg(
     203                        $user_id      = get_current_user_id();
     204                        $id           = wp_unique_id( 'zmai-avatar-' );
     205                        $preview_size = $opts['previewSize'] > 0 ? $opts['previewSize'] : $this->store->get_size();
     206                        $blocked      = $this->store->is_blocked( $user_id );
     207                        $url          = $blocked ? '' : $this->store->get_url( $user_id, $preview_size, false );
     208                        $action       = add_query_arg(
    204209                                array(
    205210                                        'action'       => 'zmai_save_avatar',
    … …  
    213218                        ?>
    214219                        <div class="zmai-status" role="status" aria-live="polite"><p><?php echo esc_html( self::status_message( $status ) ); ?></p></div>
    215                         <?php if ( $url ) : ?>
    216                                 <img class="zmai-avatar-preview" src="<?php echo esc_url( $url ); ?>" alt="<?php esc_attr_e( 'Your current avatar', 'author-or-user-image' ); ?>" width="<?php echo absint( $this->store->get_size() ); ?>" height="<?php echo absint( $this->store->get_size() ); ?>">
     220                        <?php if ( $url && $opts['showPreview'] ) : ?>
     221                                <img class="zmai-avatar-preview" src="<?php echo esc_url( $url ); ?>" alt="<?php esc_attr_e( 'Your current avatar', 'author-or-user-image' ); ?>" width="<?php echo absint( $preview_size ); ?>" height="<?php echo absint( $preview_size ); ?>">
    217222                        <?php endif; ?>
    218                         <?php if ( $this->store->is_blocked( $user_id ) ) : ?>
     223                        <?php if ( $blocked ) : ?>
    219224                                <p><?php esc_html_e( 'An administrator has disabled local avatar uploads for your account.', 'author-or-user-image' ); ?></p>
    220225                        <?php elseif ( $this->policy->can_upload( $user_id ) ) : ?>
    … …  
    236241                                        ?>
    237242                                        </p>
    238                                         <button type="submit"><?php esc_html_e( 'Upload image', 'author-or-user-image' ); ?></button>
     243                                        <button type="submit"><?php echo esc_html( $opts['uploadLabel'] ); ?></button>
    239244                                </form>
    240245                        <?php else : ?>
    241246                                <p><?php esc_html_e( 'Your role is not allowed to upload a new avatar on this site. You can still remove your avatar.', 'author-or-user-image' ); ?></p>
    242247                        <?php endif; ?>
    243                         <?php if ( $url && current_user_can( 'read' ) ) : ?>
     248                        <?php if ( $url && ! $blocked && current_user_can( 'read' ) ) : ?>
    244249                                <form class="zmai-remove-form" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
    245250                                        <input type="hidden" name="action" value="zmai_remove_avatar">
    … …  
    248253                                        <input type="hidden" name="zmai_return" value="<?php echo esc_url( $return ); ?>">
    249254                                        <input type="hidden" name="_wpnonce" value="<?php echo esc_attr( wp_create_nonce( 'zmai_remove_avatar' ) ); ?>">
    250                                         <button type="submit"><?php esc_html_e( 'Remove image', 'author-or-user-image' ); ?></button>
     255                                        <button type="submit"><?php echo esc_html( $opts['removeLabel'] ); ?></button>
    251256                                </form>
    252257                        <?php endif; ?>
    … …  
    256261                return ob_get_clean();
    257262        }
     263
     264        /**
     265         * Strictly normalize allowlisted presentation attributes for both block and shortcode callers.
     266         *
     267         * @param mixed $attributes Untrusted caller attributes.
     268         * @return array{showPreview:bool,previewSize:int,alignment:string,uploadLabel:string,removeLabel:string,loginLabel:string}
     269         */
     270        private function normalize_attributes( $attributes ) {
     271                $attrs = is_array( $attributes ) ? $attributes : array();
     272
     273                $raw_show     = $this->pick_attribute( $attrs, 'showPreview', 'show_preview', true );
     274                $show_preview = true;
     275                if ( is_bool( $raw_show ) ) {
     276                        $show_preview = $raw_show;
     277                } elseif ( is_int( $raw_show ) ) {
     278                        $show_preview = 0 !== $raw_show;
     279                } elseif ( is_string( $raw_show ) ) {
     280                        $lower = strtolower( trim( $raw_show ) );
     281                        if ( in_array( $lower, array( 'false', '0', 'no' ), true ) ) {
     282                                $show_preview = false;
     283                        } elseif ( in_array( $lower, array( 'true', '1', 'yes' ), true ) ) {
     284                                $show_preview = true;
     285                        }
     286                }
     287
     288                $raw_size     = $this->pick_attribute( $attrs, 'previewSize', 'preview_size', 0 );
     289                $preview_size = 0;
     290                if ( ( is_int( $raw_size ) || ( is_string( $raw_size ) && preg_match( '/^[0-9]+$/D', trim( $raw_size ) ) ) ) && (int) $raw_size > 0 ) {
     291                        $preview_size = min( 512, max( 32, (int) $raw_size ) );
     292                }
     293
     294                $raw_align = $attrs['alignment'] ?? '';
     295                $alignment = is_string( $raw_align ) && in_array( $raw_align, array( 'left', 'center', 'right' ), true ) ? $raw_align : '';
     296
     297                return array(
     298                        'showPreview' => $show_preview,
     299                        'previewSize' => $preview_size,
     300                        'alignment'   => $alignment,
     301                        'uploadLabel' => $this->sanitize_label(
     302                                $this->pick_attribute( $attrs, 'uploadLabel', 'upload_label', '' ),
     303                                80,
     304                                __( 'Upload image', 'author-or-user-image' )
     305                        ),
     306                        'removeLabel' => $this->sanitize_label(
     307                                $this->pick_attribute( $attrs, 'removeLabel', 'remove_label', '' ),
     308                                80,
     309                                __( 'Remove image', 'author-or-user-image' )
     310                        ),
     311                        'loginLabel'  => $this->sanitize_label(
     312                                $this->pick_attribute( $attrs, 'loginLabel', 'login_label', '' ),
     313                                120,
     314                                __( 'Log in to manage your avatar.', 'author-or-user-image' )
     315                        ),
     316                );
     317        }
     318
     319        /**
     320         * Read an attribute supporting block camelCase, shortcode snake_case, and lowercased shortcode keys.
     321         *
     322         * @param array<string,mixed> $attrs   Caller attribute map.
     323         * @param string              $camel   CamelCase attribute key.
     324         * @param string              $snake   Snake_case attribute key.
     325         * @param mixed               $fallback Default value when unset.
     326         * @return mixed
     327         */
     328        private function pick_attribute( array $attrs, $camel, $snake, $fallback ) {
     329                if ( array_key_exists( $camel, $attrs ) ) {
     330                        return $attrs[ $camel ];
     331                }
     332                if ( array_key_exists( $snake, $attrs ) ) {
     333                        return $attrs[ $snake ];
     334                }
     335                $lower = strtolower( $camel );
     336                if ( array_key_exists( $lower, $attrs ) ) {
     337                        return $attrs[ $lower ];
     338                }
     339                return $fallback;
     340        }
     341
     342        /**
     343         * Sanitize and bound a plain-text UI label attribute.
     344         *
     345         * @param mixed  $value    Raw attribute value.
     346         * @param int    $max_len  Maximum length.
     347         * @param string $fallback Default translated label.
     348         * @return string
     349         */
     350        private function sanitize_label( $value, $max_len, $fallback ) {
     351                if ( ! is_string( $value ) ) {
     352                        return $fallback;
     353                }
     354                $clean = trim( sanitize_text_field( $value ) );
     355                if ( '' === $clean ) {
     356                        return $fallback;
     357                }
     358                return function_exists( 'mb_substr' ) ? mb_substr( $clean, 0, $max_len ) : substr( $clean, 0, $max_len );
     359        }
    258360}
  • author-or-user-image/tags/3.2.0/includes/class-image-processor.php

    r3796032 r3823635  
    5858                }
    5959
    60                 $file_stat = @lstat( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Missing or unreadable local paths are a normal validation failure.
    61                 if ( ! is_array( $file_stat ) || ! isset( $file_stat['mode'] ) || 0100000 !== ( $file_stat['mode'] & 0170000 ) ) {
     60                if ( ! self::is_regular_file( $path ) ) {
    6261                        return self::error( 'zmai_invalid_image', __( 'Choose a readable local image file.', 'author-or-user-image' ) );
    6362                }
    … …  
    189188
    190189                        $basename    = 'zmai-avatar-' . str_replace( '-', '', wp_generate_uuid4() ) . '.' . $extension;
    191                         $unique_name = wp_unique_filename( $real_directory, $basename );
    192                         $output_path = trailingslashit( $real_directory ) . $unique_name;
    193                         // Keep this save in its validated format, without changing other media saves.
    194                         $pin_format = static function () {
    195                                 return array();
    196                         };
    197                         add_filter( 'image_editor_output_format', $pin_format, PHP_INT_MAX );
    198                         try {
    199                                 $saved = $editor->save( $output_path, $validated['type'] );
    200                         } finally {
    201                                 remove_filter( 'image_editor_output_format', $pin_format, PHP_INT_MAX );
    202                         }
     190                        $output_path = '';
     191                        $saved       = self::with_unique_filename_file_list(
     192                                static function () use ( $editor, $real_directory, $basename, $validated, &$output_path ) {
     193                                        $unique_name = wp_unique_filename( $real_directory, $basename );
     194                                        $output_path = trailingslashit( $real_directory ) . $unique_name;
     195                                        // Keep this save in its validated format, without changing other media saves.
     196                                        $pin_format = static function () {
     197                                                return array();
     198                                        };
     199                                        add_filter( 'image_editor_output_format', $pin_format, PHP_INT_MAX );
     200                                        try {
     201                                                return $editor->save( $output_path, $validated['type'] );
     202                                        } finally {
     203                                                remove_filter( 'image_editor_output_format', $pin_format, PHP_INT_MAX );
     204                                        }
     205                                }
     206                        );
     207                        $unique_name = basename( $output_path );
    203208                        if ( is_wp_error( $saved ) || ! is_array( $saved ) ) {
    204209                                return self::square_failure( $output_path, __( 'The square image could not be saved.', 'author-or-user-image' ) );
    … …  
    414419
    415420        /**
     421         * Run a core upload or image-save callback with scandir()-safe filename listing.
     422         *
     423         * @internal
     424         * @param callable $callback Operation invoking wp_unique_filename() or media sideloading.
     425         * @return mixed
     426         */
     427        public static function with_unique_filename_file_list( $callback ) {
     428                if ( function_exists( 'scandir' ) ) {
     429                        return $callback();
     430                }
     431                $list_filter = static function ( $files, $dir ) {
     432                        return self::filter_unique_filename_file_list( $files, $dir );
     433                };
     434                add_filter( 'pre_wp_unique_filename_file_list', $list_filter, 10, 2 );
     435                try {
     436                        return $callback();
     437                } finally {
     438                        remove_filter( 'pre_wp_unique_filename_file_list', $list_filter, 10 );
     439                }
     440        }
     441
     442        /**
     443         * Short-circuit core wp_unique_filename() scandir() calls when scandir is disabled.
     444         *
     445         * @internal
     446         * @param array<int,string>|null $files Previously filtered directory list.
     447         * @param string                 $dir   Target uploads directory.
     448         * @return array<int,string>|null
     449         */
     450        public static function filter_unique_filename_file_list( $files, $dir ) {
     451                if ( null !== $files || function_exists( 'scandir' ) ) {
     452                        return $files;
     453                }
     454                $listed = self::list_directory( $dir );
     455                return is_array( $listed ) ? $listed : array();
     456        }
     457
     458        /**
     459         * List directory entries using scandir or safe core fallbacks when disabled.
     460         *
     461         * @internal
     462         * @param string $directory Local directory path.
     463         * @return array<int,string>|false
     464         */
     465        public static function list_directory( $directory ) {
     466                if ( ! is_string( $directory ) || '' === $directory || ! is_dir( $directory ) ) {
     467                        return false;
     468                }
     469                if ( function_exists( 'scandir' ) ) {
     470                        $files = @scandir( $directory ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- A failed listing is handled by recovery inventory callers.
     471                        return is_array( $files ) ? $files : false;
     472                }
     473                if ( class_exists( 'DirectoryIterator' ) ) {
     474                        try {
     475                                $files = array();
     476                                foreach ( new \DirectoryIterator( $directory ) as $item ) {
     477                                        $files[] = $item->getFilename();
     478                                }
     479                                return $files;
     480                        } catch ( \Throwable $error ) {
     481                                return false;
     482                        }
     483                }
     484                if ( function_exists( 'opendir' ) && function_exists( 'readdir' ) && function_exists( 'closedir' ) ) {
     485                        $handle = @opendir( $directory ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Unreadable directories return false cleanly.
     486                        if ( false === $handle ) {
     487                                return false;
     488                        }
     489                        $files = array();
     490                        while ( true ) {
     491                                $entry = readdir( $handle );
     492                                if ( false === $entry ) {
     493                                        break;
     494                                }
     495                                $files[] = $entry;
     496                        }
     497                        closedir( $handle );
     498                        return $files;
     499                }
     500                return false;
     501        }
     502
     503        /**
    416504         * Confirm that a path is a regular file rather than a directory or symlink.
    417505         *
    … …  
    420508         */
    421509        private static function is_regular_file( $path ) {
    422                 $stat = @lstat( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Partial output is treated as a failed save.
    423                 return is_array( $stat ) && isset( $stat['mode'] ) && 0100000 === ( $stat['mode'] & 0170000 );
     510                if ( ! is_string( $path ) || '' === $path ) {
     511                        return false;
     512                }
     513                if ( function_exists( 'lstat' ) ) {
     514                        $stat = @lstat( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Partial output is treated as a failed save.
     515                        return is_array( $stat ) && isset( $stat['mode'] ) && 0100000 === ( $stat['mode'] & 0170000 );
     516                }
     517                return function_exists( 'is_link' ) && ! is_link( $path ) && is_file( $path );
     518        }
     519
     520        /**
     521         * Safely check whether a path is a symbolic link on hosts that may disable is_link().
     522         *
     523         * @internal
     524         * @param string $path Local filesystem path.
     525         * @return bool
     526         */
     527        public static function is_symlink_path( $path ) {
     528                return is_string( $path ) && '' !== $path && function_exists( 'is_link' ) && is_link( $path );
    424529        }
    425530
    … …  
    431536         */
    432537        private static function remove_file( $path ) {
    433                 if ( ! is_string( $path ) || ( ! file_exists( $path ) && ! is_link( $path ) ) ) {
     538                $is_link = self::is_symlink_path( $path );
     539                if ( ! is_string( $path ) || ( ! file_exists( $path ) && ! $is_link ) ) {
    434540                        return true;
    435541                }
    436                 if ( ! is_file( $path ) && ! is_link( $path ) ) {
     542                if ( ! is_file( $path ) && ! $is_link ) {
    437543                        return false;
    438544                }
    439545                wp_delete_file( $path );
    440546                clearstatcache( true, $path );
    441                 return ! file_exists( $path ) && ! is_link( $path );
     547                return ! file_exists( $path ) && ! self::is_symlink_path( $path );
    442548        }
    443549
    … …  
    456562                if ( $path ) {
    457563                        $stem  = pathinfo( $path, PATHINFO_FILENAME );
    458                         $files = @scandir( dirname( $path ) ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- A failed cleanup listing is retained as recovery inventory below.
     564                        $files = self::list_directory( dirname( $path ) );
    459565                        if ( false === $files ) {
    460566                                $inventory_failed = true;
  • author-or-user-image/tags/3.2.0/includes/class-image-store.php

    r3796032 r3823635  
    118118         * Store an uploaded image for a user or as the site default.
    119119         *
    120          * @param string $field   File input name.
    121          * @param int    $user_id User ID, or zero for the default avatar.
     120         * @param string $field    File input name.
     121         * @param int    $user_id  User ID, or zero for the default avatar.
     122         * @param bool   $by_admin Optional. Whether an authorized administrator is uploading for another user.
    122123         * @return int|WP_Error Attachment ID, or busy/storage/cleanup error; errors never mean success.
    123124         */
    124         public function save_upload( $field, $user_id = 0 ) {
     125        public function save_upload( $field, $user_id = 0, $by_admin = false ) {
    125126                if ( ! is_string( $field ) || ! is_scalar( $user_id ) ) {
    126127                        return $this->storage_error();
    127128                }
    128                 $field   = sanitize_key( $field );
    129                 $user_id = absint( $user_id );
     129                $field    = sanitize_key( $field );
     130                $user_id  = absint( $user_id );
     131                $by_admin = (bool) $by_admin;
    130132                return $this->with_owner_lock(
    131133                        $user_id,
    132                         function () use ( $field, $user_id ) {
     134                        function () use ( $field, $user_id, $by_admin ) {
    133135                                $policy = new Upload_Policy( $this );
    134                                 if ( $user_id ? ! $policy->can_upload_fresh( $user_id ) : ! current_user_can( 'manage_options' ) ) {
    135                                         return new WP_Error( 'zmai_blocked', __( 'Local avatar uploads are disabled for this account.', 'author-or-user-image' ) );
    136                                 }
    137                                 if ( $user_id ) {
     136                                if ( 0 === $user_id ) {
     137                                        if ( ! current_user_can( 'manage_options' ) ) {
     138                                                return new WP_Error( 'zmai_forbidden', __( 'You are not allowed to do that.', 'author-or-user-image' ) );
     139                                        }
     140                                } elseif ( $by_admin ) {
     141                                        if ( ! current_user_can( 'manage_options' ) ) {
     142                                                return new WP_Error( 'zmai_forbidden', __( 'You are not allowed to do that.', 'author-or-user-image' ) );
     143                                        }
     144                                        if ( ! $this->user_exists_fresh( $user_id ) || ! $this->user_is_member_fresh( $user_id ) ) {
     145                                                return new WP_Error( 'zmai_invalid_user', __( 'The selected user account does not exist.', 'author-or-user-image' ) );
     146                                        }
     147                                        if ( ! current_user_can( 'edit_user', $user_id ) ) {
     148                                                return new WP_Error( 'zmai_forbidden', __( 'You are not allowed to do that.', 'author-or-user-image' ) );
     149                                        }
     150                                        if ( $this->is_blocked_fresh( $user_id ) ) {
     151                                                return new WP_Error( 'zmai_blocked', __( 'Local avatar uploads are disabled for this account.', 'author-or-user-image' ) );
     152                                        }
     153                                } else {
     154                                        if ( ! $policy->can_upload_fresh( $user_id ) ) {
     155                                                return new WP_Error( 'zmai_blocked', __( 'Local avatar uploads are disabled for this account.', 'author-or-user-image' ) );
     156                                        }
    138157                                        $rate = $this->consume_upload_attempt( $user_id );
    139158                                        if ( is_wp_error( $rate ) ) {
    … …  
    147166                                                return new WP_Error( 'zmai_upload_failed', __( 'The image upload did not complete.', 'author-or-user-image' ) );
    148167                                        }
     168                                }
     169                                if ( in_array( (int) $file['error'], array( UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE ), true ) ) {
     170                                        return new WP_Error( 'zmai_upload_size', __( 'The image exceeds this site’s upload limit.', 'author-or-user-image' ) );
    149171                                }
    150172                                if ( UPLOAD_ERR_OK !== (int) $file['error'] || ! is_string( $file['tmp_name'] ) || ! is_string( $file['name'] ) ) {
    … …  
    204226                                }
    205227                                $ready = $this->prepare_attachment( $attachment_id, $user_id, $validated['type'], $validated );
    206                                 if ( ! is_wp_error( $ready ) && $user_id && ! $policy->can_upload_fresh( $user_id ) ) {
    207                                         $ready = new WP_Error( 'zmai_blocked', __( 'Local avatar uploads are disabled for this account.', 'author-or-user-image' ) );
     228                                if ( ! is_wp_error( $ready ) ) {
     229                                        if ( 0 === $user_id ) {
     230                                                if ( ! current_user_can( 'manage_options' ) ) {
     231                                                        $ready = new WP_Error( 'zmai_forbidden', __( 'You are not allowed to do that.', 'author-or-user-image' ) );
     232                                                }
     233                                        } elseif ( $by_admin ) {
     234                                                if ( ! current_user_can( 'manage_options' ) ) {
     235                                                        $ready = new WP_Error( 'zmai_forbidden', __( 'You are not allowed to do that.', 'author-or-user-image' ) );
     236                                                } elseif ( ! $this->user_exists_fresh( $user_id ) || ! $this->user_is_member_fresh( $user_id ) ) {
     237                                                        $ready = new WP_Error( 'zmai_invalid_user', __( 'The selected user account does not exist.', 'author-or-user-image' ) );
     238                                                } elseif ( ! current_user_can( 'edit_user', $user_id ) ) {
     239                                                        $ready = new WP_Error( 'zmai_forbidden', __( 'You are not allowed to do that.', 'author-or-user-image' ) );
     240                                                } elseif ( $this->is_blocked_fresh( $user_id ) ) {
     241                                                        $ready = new WP_Error( 'zmai_blocked', __( 'Local avatar uploads are disabled for this account.', 'author-or-user-image' ) );
     242                                                }
     243                                        } elseif ( ! $policy->can_upload_fresh( $user_id ) ) {
     244                                                $ready = new WP_Error( 'zmai_blocked', __( 'Local avatar uploads are disabled for this account.', 'author-or-user-image' ) );
     245                                        }
    208246                                }
    209247                                if ( ! is_wp_error( $ready ) ) {
    … …  
    303341                add_action( 'add_attachment', $remember_id, -99999 );
    304342                try {
    305                         $result = $callback();
     343                        $result = Image_Processor::with_unique_filename_file_list( $callback );
    306344                } catch ( \Throwable $error ) {
    307345                        if ( $wpdb->last_error || ! $stage['file'] ) {
    … …  
    329367                // belongs only to this staging call, so its file inventory is still known.
    330368                $stem  = pathinfo( $stage['file'], PATHINFO_FILENAME );
    331                 $files = @scandir( dirname( $stage['file'] ) ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- A failed listing must retain the attachment inventory and owner fence.
     369                $files = Image_Processor::list_directory( dirname( $stage['file'] ) );
    332370                if ( false === $files ) {
    333371                        return $this->storage_error( true );
    … …  
    346384                        wp_delete_file( $file );
    347385                        clearstatcache( true, $file );
    348                         if ( is_file( $file ) || is_link( $file ) ) {
     386                        if ( is_file( $file ) || Image_Processor::is_symlink_path( $file ) ) {
    349387                                // No attachment row remains to retain this file inventory for a retry.
    350388                                return $this->storage_error( true );
    … …  
    497535                        );
    498536                }
    499                 clean_user_cache( $user_id );
    500                 wp_cache_delete( $user_id, 'user_meta' );
    501                 $membership = $this->database_values( $wpdb->prepare( 'SELECT meta_value FROM %i WHERE user_id = %d AND meta_key = %s', $wpdb->usermeta, $user_id, $wpdb->get_blog_prefix() . 'capabilities' ) );
    502                 if ( is_multisite() && ( ! $membership || ! is_array( maybe_unserialize( $membership[0] ) ) || ! maybe_unserialize( $membership[0] ) ) ) {
     537                if ( ! $this->user_is_member_fresh( $user_id ) ) {
    503538                        return array(
    504539                                'status'        => 'gone',
    … …  
    794829                        return self::$attachment_urls[ $key ];
    795830                }
    796                 $square                        = $meta['sizes']['zmai-avatar'] ?? null;
    797                 $width                         = $square['width'] ?? 0;
    798                 $height                        = $square['height'] ?? 0;
    799                 $named                         = '1' === $marker && is_array( $square ) && ! empty( $square['file'] ) && is_string( $square['file'] ) && basename( $square['file'] ) === $square['file'] && is_int( $width ) && $width > 0 && $width === $height;
    800                 $url                           = wp_get_attachment_image_url( $id, $named ? 'zmai-avatar' : array( $size, $size ) );
     831                $square = $meta['sizes']['zmai-avatar'] ?? null;
     832                $width  = $square['width'] ?? 0;
     833                $height = $square['height'] ?? 0;
     834                $named  = '1' === $marker && is_array( $square ) && ! empty( $square['file'] ) && is_string( $square['file'] ) && basename( $square['file'] ) === $square['file'] && is_int( $width ) && $width > 0 && $width === $height;
     835                $url    = wp_get_attachment_image_url( $id, $named ? 'zmai-avatar' : array( $size, $size ) );
     836                if ( count( self::$attachment_urls ) >= 500 ) {
     837                        self::$attachment_urls = array();
     838                }
    801839                self::$attachment_urls[ $key ] = $url ? $url : '';
    802840                return self::$attachment_urls[ $key ];
    … …  
    10351073
    10361074        /**
     1075         * Authoritative current-site membership inside the owner critical section.
     1076         *
     1077         * @param int $user_id User ID.
     1078         * @return bool
     1079         */
     1080        private function user_is_member_fresh( $user_id ) {
     1081                global $wpdb;
     1082                clean_user_cache( $user_id );
     1083                wp_cache_delete( $user_id, 'user_meta' );
     1084                if ( ! is_multisite() ) {
     1085                        return true;
     1086                }
     1087                $membership = $this->database_values( $wpdb->prepare( 'SELECT meta_value FROM %i WHERE user_id = %d AND meta_key = %s', $wpdb->usermeta, $user_id, $wpdb->get_blog_prefix() . 'capabilities' ) );
     1088                if ( ! $membership ) {
     1089                        return false;
     1090                }
     1091                $caps = maybe_unserialize( $membership[0] );
     1092                return is_array( $caps ) && ! empty( $caps );
     1093        }
     1094
     1095        /**
    10371096         * Authoritative block decision inside the owner critical section.
    10381097         *
    … …  
    10451104                        return true;
    10461105                }
    1047                 $user    = get_userdata( $user_id );
     1106                $login   = $this->user_login_fresh( $user_id );
    10481107                $blocked = $this->read_value( 0, '', self::LEGACY_BLOCK_OPTION );
    1049                 return $user && is_array( $blocked ) && in_array( $user->user_login, $blocked, true );
     1108                return '' !== $login && is_array( $blocked ) && in_array( $login, $blocked, true );
     1109        }
     1110
     1111        /**
     1112         * Authoritative user_login inside critical sections without modifying user caches.
     1113         *
     1114         * @param int $user_id User ID.
     1115         * @return string
     1116         */
     1117        private function user_login_fresh( $user_id ) {
     1118                global $wpdb;
     1119                $values = $this->database_values( $wpdb->prepare( 'SELECT user_login FROM %i WHERE ID = %d', $wpdb->users, $user_id ) );
     1120                return $values ? (string) $values[0] : '';
    10501121        }
    10511122
    … …  
    12691340                        return true;
    12701341                }
    1271                 $user   = get_userdata( $user_id );
     1342                $login  = $this->user_login_fresh( $user_id );
    12721343                $legacy = is_array( $legacy ) ? $legacy : array();
    1273                 if ( $user ) {
    1274                         $legacy = array_values( array_diff( $legacy, array( $user->user_login ) ) );
     1344                if ( '' !== $login ) {
     1345                        $legacy = array_values( array_diff( $legacy, array( $login ) ) );
    12751346                }
    12761347                return $this->write_value( 0, '', self::LEGACY_BLOCK_OPTION, array_values( array_unique( array_merge( $legacy, $logins ) ) ) );
  • author-or-user-image/tags/3.2.0/includes/class-lock.php

    r3796032 r3823635  
    160160                return $result;
    161161        }
     162
     163        /**
     164         * Inspect active or retained lifecycle locks directly from the options table.
     165         *
     166         * @return array<int,array{name:string,scope:string,owner_id:int,token:string,table:string}>|WP_Error
     167         */
     168        public function inspect_locks() {
     169                global $wpdb;
     170                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Lock diagnostics must inspect authoritative rows rather than option caches.
     171                $rows = $wpdb->get_results(
     172                        $wpdb->prepare(
     173                                'SELECT option_name, option_value FROM %i WHERE option_name LIKE %s ORDER BY option_name ASC',
     174                                $wpdb->options,
     175                                $wpdb->esc_like( 'zmai_avatar_lock_' ) . '%'
     176                        ),
     177                        ARRAY_A
     178                );
     179                if ( $wpdb->last_error || ! is_array( $rows ) ) {
     180                        return self::storage_error();
     181                }
     182
     183                $locks = array();
     184                foreach ( $rows as $row ) {
     185                        $name     = isset( $row['option_name'] ) ? (string) $row['option_name'] : '';
     186                        $token    = isset( $row['option_value'] ) ? (string) $row['option_value'] : '';
     187                        $scope    = 'unknown';
     188                        $owner_id = 0;
     189
     190                        if ( 'zmai_avatar_lock_migration' === $name ) {
     191                                $scope = 'migration';
     192                        } elseif ( 'zmai_avatar_lock_blocks' === $name ) {
     193                                $scope = 'blocks';
     194                        } elseif ( 'zmai_avatar_lock_default' === $name ) {
     195                                $scope = 'default';
     196                        } elseif ( preg_match( '/^zmai_avatar_lock_user_([1-9][0-9]*)$/', $name, $matches ) ) {
     197                                $scope    = 'user';
     198                                $owner_id = (int) $matches[1];
     199                        }
     200
     201                        $locks[] = array(
     202                                'name'     => $name,
     203                                'scope'    => $scope,
     204                                'owner_id' => $owner_id,
     205                                'token'    => $token,
     206                                'table'    => (string) $wpdb->options,
     207                        );
     208                }
     209
     210                return $locks;
     211        }
    162212}
  • author-or-user-image/tags/3.2.0/includes/class-migration.php

    r3796032 r3823635  
    3838         */
    3939        public function maybe_migrate() {
    40                 if ( get_option( self::RELEASE_FAILED_OPTION ) ) {
     40                if ( $this->has_release_failure() ) {
    4141                        try {
    4242                                if ( null === $this->store->read_value( 0, '', 'zmai_avatar_lock_migration' ) ) {
    … …  
    5656                        }
    5757                );
     58        }
     59
     60        /**
     61         * Authoritatively check whether an interrupted migration lock release requires recovery.
     62         *
     63         * @return bool
     64         */
     65        public function has_release_failure() {
     66                try {
     67                        return (bool) $this->store->read_value( 0, '', self::RELEASE_FAILED_OPTION );
     68                } catch ( \Throwable $error ) {
     69                        return (bool) get_option( self::RELEASE_FAILED_OPTION );
     70                }
    5871        }
    5972
    … …  
    502515         */
    503516        public function migration_notice() {
    504                 if ( current_user_can( 'manage_options' ) && get_option( self::RELEASE_FAILED_OPTION ) ) {
     517                if ( current_user_can( 'manage_options' ) && $this->has_release_failure() ) {
    505518                        echo '<div class="notice notice-error"><p>' . esc_html__( 'Author or User Image: a legacy migration lock could not be released. Ask for administrator recovery before retrying migration. See the lifecycle recovery guide.', 'author-or-user-image' ) . '</p></div>';
    506519                }
    … …  
    514527         */
    515528        private function report_error( WP_Error $error ) {
    516                 // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Persistent migration/release failures need an operator-visible diagnostic; no values or paths are logged.
    517                 error_log( 'Author or User Image: legacy migration storage or lock-release failure.' );
     529                if ( function_exists( 'error_log' ) ) {
     530                        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Persistent migration/release failures need an operator-visible diagnostic; no values or paths are logged.
     531                        error_log( 'Author or User Image: legacy migration storage or lock-release failure.' );
     532                }
    518533                do_action( 'zmai_migration_error', $error );
    519534        }
    … …  
    667682                                                return $clean;
    668683                                        }
    669                                         $id = media_handle_sideload( $file, 0, null, array( 'meta_input' => array( Image_Store::ATTACHMENT_OWNER_META => $this->store->owner_name( $user_id ) ) ) );
     684                                        $owner = $this->store->owner_name( $user_id );
     685                                        $id    = Image_Processor::with_unique_filename_file_list(
     686                                                static function () use ( $file, $owner ) {
     687                                                        return media_handle_sideload( $file, 0, null, array( 'meta_input' => array( Image_Store::ATTACHMENT_OWNER_META => $owner ) ) );
     688                                                }
     689                                        );
    670690                                } finally {
    671691                                        wp_delete_file( $temporary );
  • author-or-user-image/tags/3.2.0/includes/class-plugin.php

    r3796032 r3823635  
    8686                if ( is_admin() ) {
    8787                        new Admin( $this->store );
     88                        if ( ! is_network_admin() && ! is_user_admin() ) {
     89                                new Profile_Admin( $this->store );
     90                        }
    8891                        ( new Import_Admin( $this->migration ) )->register();
    8992                        add_action( 'admin_init', array( $this, 'maybe_migrate' ) );
    … …  
    9396                new Front_End( $this->store );
    9497                new Privacy( $this->store, $this->cleanup );
     98                new REST_API( $this->store );
     99
     100                if ( defined( 'WP_CLI' ) && WP_CLI ) {
     101                        CLI::register( $this->store, $this->migration );
     102                }
    95103        }
    96104
    … …  
    219227        public function finish_user_deletion( $user_id ) {
    220228                $result = $this->cleanup->finish_user_deletion( $user_id );
    221                 if ( is_wp_error( $result ) ) {
     229                if ( is_wp_error( $result ) && function_exists( 'error_log' ) ) {
    222230                        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Core already deleted the user; retain the fence for recovery without aborting bulk deletion.
    223231                        error_log( 'Author or User Image: deletion fence release failed; administrator recovery required.' );
  • author-or-user-image/tags/3.2.0/includes/class-user-cleanup.php

    r3796032 r3823635  
    239239                        $released = $this->store->get_lock()->release_lock( $lock );
    240240                        unset( $this->deleting_users[ $key ] );
    241                         if ( is_wp_error( $released ) ) {
     241                        if ( is_wp_error( $released ) && function_exists( 'error_log' ) ) {
    242242                                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Shutdown cannot return an error to core; log a fixed diagnostic without tokens or user data.
    243243                                error_log( 'Author or User Image: deletion fence release failed; administrator recovery required.' );
  • author-or-user-image/tags/3.2.0/readme.txt

    r3796032 r3823635  
    55Tested up to: 7.1
    66Requires PHP: 7.4
    7 Stable tag: 3.1.0
     7Stable tag: 3.2.0
    88License: GPL-2.0-or-later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    1717Features include:
    1818
    19 * Self-service avatar upload and removal for registered users.
    20 * An Avatar upload block and `[author_or_user_image_upload]` shortcode that let signed-in visitors change their own avatar on a page.
     19* Self-service avatar upload and removal for registered users (`Users > Author or User Image` and standard WordPress Profile / Edit User screens).
     20* An Avatar upload block and `[author_or_user_image_upload]` shortcode with configurable preview visibility, preview size, alignment, and labels for signed-in visitors.
    2121* An upload setting that allows all users who can read, or only selected roles, on each site.
    2222* Center-square avatars for new uploads, with the original image kept uncropped.
    2323* An optional default avatar for registered users without a personal image.
    24 * Administrator controls to remove images or block individual users from local avatar uploads.
    25 * An importer for avatars from Simple Local Avatars, One User Avatar, WP User Avatar, WP User Avatars, and User Profile Picture / Metronet.
     24* Administrator controls to manage or block individual users on Edit User and `Users > Avatar Management`, plus read-only lifecycle lock diagnostics under Settings.
     25* A WordPress REST API (`author-or-user-image/v1`) for authenticated avatar, block-list, bulk, and settings management.
     26* An importer for avatars from Simple Local Avatars, One User Avatar, WP User Avatar, WP User Avatars, and User Profile Picture / Metronet, available in admin and via WP-CLI (`wp zmai import`).
    2627* Media Library storage and WordPress-generated image sizes.
    2728* Personal-data export and erasure integration.
    … …  
    34351. Upload the plugin files to `/wp-content/plugins/author-or-user-image`, or install the plugin through the Plugins screen.
    35362. Activate **Author or User Image**.
    36 3. Open **Users > Author or User Image** to upload your avatar.
    37 4. Administrators can set the site default on that page and manage user images under **Users > Avatar Management**.
     373. Open **Users > Author or User Image** or your WordPress **Profile** screen to upload your avatar.
     384. Administrators can set the site default on **Users > Author or User Image**, manage users under **Users > Avatar Management** or **Edit User**, and inspect lifecycle lock status under **Users > Avatar Management > Settings**.
    38395. To let signed-in visitors upload from a page, add the **Avatar upload** block, or use the `[author_or_user_image_upload]` shortcode on a Classic Editor page.
    39 6. Administrators can import avatars from an older avatar plugin under **Users > Avatar Management > Avatar Migration**.
     406. Administrators can import avatars from an older avatar plugin under **Users > Avatar Management > Avatar Migration** or via WP-CLI (`wp zmai import`).
    4041
    4142== Frequently Asked Questions ==
    … …  
    7879Unchecking every role turns off self-service uploads. Existing avatars stay visible, and users can still remove their own. A user with several roles qualifies if any checked role matches. A deleted role stops matching, and a role created later with the same slug matches again. Roles created after you save the list are not included until you check them.
    7980
    80 An individual block still stops that user from uploading, whatever their role. Only administrators can change the default image or manage other users.
     81An individual block still stops that user from uploading, whatever their role. Only administrators can change the default image or manage other users. On multisite, the Profile screen and REST API self-service endpoints always require membership on that site, while the **All users who can read** setting preserves WordPress's standard `read` capability rule on the dashboard and front-end form.
    8182
    8283= Is there an upload rate limit? =
    8384
    84 Each user can make five authorized self-upload attempts per minute and twenty per hour, shared between the dashboard and front-end form on the same site. Multisite counters are per site, so a member of several sites has a separate allowance on each. Failed image attempts count too. Removal, privacy erasure, administrator moderation, imports and site-default changes do not use this counter.
     85Each user can make five authorized self-upload attempts per minute and twenty per hour, shared across the dashboard, Profile screen, front-end form, and REST API on the same site. Multisite counters are per site, so a member of several sites has a separate allowance on each. Failed image attempts count too. Removal, privacy erasure, administrator moderation, imports and site-default changes do not use this counter.
    8586
    8687= How do I add an upload form to a page? =
    … …  
    8889Insert the **Avatar upload** block in the block editor. On a Classic Editor page, use the `[author_or_user_image_upload]` shortcode instead.
    8990
    90 The form changes only the signed-in visitor's own avatar. Neither the block nor the shortcode accepts attributes that choose a user, an attachment, a source URL, or the default avatar. Logged-out visitors see a log-in link. Blocked users, and users the upload setting excludes, see the reason instead of the form. The form posts directly to WordPress, so uploads and removals work with JavaScript turned off.
     91The form changes only the signed-in visitor's own avatar. Presentation options (`showPreview`, `previewSize`, `alignment`, and button or link labels) are supported, while attributes that choose a user, an attachment, a source URL, or the default avatar are ignored. Logged-out visitors see a log-in link. Blocked users, and users the upload setting excludes, see the reason instead of the form. The form posts directly to WordPress, so uploads and removals work with JavaScript turned off.
    9192
    9293Place the block or shortcode as standalone content. Nesting it inside another form is not supported, and some themes nest content that way.
    … …  
    130131= How do I import avatars from another plugin? =
    131132
    132 Open **Users > Avatar Management > Avatar Migration** and use the import action for the detected source plugin. The tab is always available. A separate **Users > Avatar Migration** menu appears when a supported plugin or saved avatar data is detected, or an unfinished import needs attention. No source selector is needed. Only an administrator can run an import. Competitor imports start only from this screen. The automatic migration of this plugin's older data remains separate. The import runs in pages and reports counts, errors, and completion. Stop pauses the import, and Resume continues it. Closing the page stops further batches, so reopen the page and choose Continue or Resume.
     133Open **Users > Avatar Management > Avatar Migration** and use the import action for the detected source plugin. The tab is always available. A separate **Users > Avatar Migration** menu appears when a supported plugin or saved avatar data is detected, or an unfinished import needs attention. No source selector is needed. Only an administrator can run an import. Competitor imports start only from this screen or via WP-CLI (`wp zmai import`). The automatic migration of this plugin's older data remains separate. The import runs in pages and reports counts, errors, and completion. Stop pauses the import, and Resume continues it. Closing the page stops further batches, so reopen the page and choose Continue or Resume.
    133134
    134135A user who already has an imported avatar is skipped by later runs, so the first source imported for that user wins. A user who removes an avatar stays without one, and removal blocks any later re-import for that user.
    … …  
    169170== Upgrade Notice ==
    170171
     172= 3.2.0 =
     173
     174Adds Profile and Edit User screen avatar management, REST API (`author-or-user-image/v1`), configurable Avatar upload block/shortcode display attributes, WP-CLI importer and lock recovery commands, and read-only lock diagnostics.
     175
    171176= 3.1.0 =
    172177
    … …  
    182187
    183188== Changelog ==
     189
     190= 3.2.0 =
     191
     192* Added WordPress Profile and Edit User (`profile.php` / `user-edit.php`) avatar upload, removal, and administrator block controls.
     193* Added a site-scoped REST API under `author-or-user-image/v1` (`/avatars`, `/avatars/{user_id}`, `/default`, `/blocked`, `/blocked/{user_id}`, `/bulk`, and `/settings`) enforcing capabilities, upload policy, rate limits, and metadata stripping.
     194* Added presentation-only attributes (`showPreview`, `previewSize`, `alignment`, `uploadLabel`, `removeLabel`, `loginLabel`) and inspector controls to the Avatar upload block and `[author_or_user_image_upload]` shortcode.
     195* Added WP-CLI commands (`wp zmai import sources|status|run|pause|resume|retry|finish` and `wp zmai locks list|unlock`) for batch competitor imports and exact-token lock recovery.
     196* Added read-only lifecycle lock diagnostics under **Users > Avatar Management > Settings** without exposing lock tokens in the admin screen.
     197* Hardened directory listing, regular-file checks, upload-size checks, and error logging for hosts that disable PHP functions such as scandir, lstat, ini_get, and error_log.
    184198
    185199= 3.1.0 =
  • author-or-user-image/trunk/assets/css/front-end.css

    r3796032 r3823635  
    2020.zmai-front-end .zmai-status:empty,
    2121.zmai-front-end .zmai-status p:empty { display: none; }
     22.zmai-front-end.zmai-align-left { margin-inline-end: auto; }
     23.zmai-front-end.zmai-align-center { margin-inline: auto; text-align: center; }
     24.zmai-front-end.zmai-align-center .zmai-avatar-preview { margin-inline: auto; }
     25.zmai-front-end.zmai-align-right { margin-inline-start: auto; }
  • author-or-user-image/trunk/assets/js/avatar-upload-editor.js

    r3796032 r3823635  
    11/* global wp */
    2 (function (blocks, element, blockEditor, i18n) {
     2(function (blocks, element, blockEditor, components, i18n) {
    33        'use strict';
     4        var el = element.createElement;
     5        var Fragment = element.Fragment;
     6        var InspectorControls = blockEditor.InspectorControls;
     7        var PanelBody = components.PanelBody;
     8        var ToggleControl = components.ToggleControl;
     9        var RangeControl = components.RangeControl;
     10        var SelectControl = components.SelectControl;
     11        var TextControl = components.TextControl;
     12
     13        function cleanLabel(value, maxLen) {
     14                if (typeof value !== 'string') {
     15                        return '';
     16                }
     17                var cleaned = value.replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim();
     18                return cleaned ? cleaned.slice(0, maxLen) : '';
     19        }
     20
    421        blocks.registerBlockType('author-or-user-image/avatar-upload', {
    522                apiVersion: 3,
    … …  
    926                icon: 'admin-users',
    1027                supports: { html: false },
    11                 edit: function () {
    12                         return element.createElement('div', blockEditor.useBlockProps({ className: 'zmai-front-end' }),
    13                                 element.createElement('strong', null, i18n.__('Avatar upload', 'author-or-user-image')),
    14                                 element.createElement('p', null, i18n.__('On the published page, signed-in visitors can manage their own avatar. Other visitors see a login link.', 'author-or-user-image')));
     28                attributes: {
     29                        showPreview: { type: 'boolean', default: true },
     30                        previewSize: { type: 'integer', default: 0 },
     31                        alignment: { type: 'string', default: '' },
     32                        uploadLabel: { type: 'string', default: '' },
     33                        removeLabel: { type: 'string', default: '' },
     34                        loginLabel: { type: 'string', default: '' }
     35                },
     36                edit: function (props) {
     37                        var attrs = props.attributes || {};
     38                        var showPreview = attrs.showPreview !== false;
     39                        var previewSize = typeof attrs.previewSize === 'number' ? attrs.previewSize : 0;
     40                        var effectivePreviewSize = previewSize > 0 ? Math.min(512, Math.max(32, previewSize)) : 0;
     41                        var rawAlignment = typeof attrs.alignment === 'string' ? attrs.alignment : '';
     42                        var alignment = rawAlignment === 'left' || rawAlignment === 'center' || rawAlignment === 'right' ? rawAlignment : '';
     43                        var uploadLabel = typeof attrs.uploadLabel === 'string' ? attrs.uploadLabel : '';
     44                        var removeLabel = typeof attrs.removeLabel === 'string' ? attrs.removeLabel : '';
     45                        var loginLabel = typeof attrs.loginLabel === 'string' ? attrs.loginLabel : '';
     46                        var summaryUpload = cleanLabel(uploadLabel, 80);
     47                        var summaryRemove = cleanLabel(removeLabel, 80);
     48
     49                        var summary = [];
     50                        if (!showPreview) {
     51                                summary.push(i18n.__('Preview hidden', 'author-or-user-image'));
     52                        } else if (effectivePreviewSize > 0) {
     53                                summary.push(i18n.__('Preview size:', 'author-or-user-image') + ' ' + effectivePreviewSize + 'px');
     54                        }
     55                        if (alignment) {
     56                                summary.push(i18n.__('Alignment:', 'author-or-user-image') + ' ' + alignment);
     57                        }
     58                        if (summaryUpload) {
     59                                summary.push(i18n.__('Upload label:', 'author-or-user-image') + ' ' + summaryUpload);
     60                        }
     61                        if (summaryRemove) {
     62                                summary.push(i18n.__('Remove label:', 'author-or-user-image') + ' ' + summaryRemove);
     63                        }
     64
     65                        var className = 'zmai-front-end' + (alignment ? ' zmai-align-' + alignment : '');
     66
     67                        return el(
     68                                Fragment,
     69                                null,
     70                                el(
     71                                        InspectorControls,
     72                                        null,
     73                                        el(
     74                                                PanelBody,
     75                                                { title: i18n.__('Display & labels', 'author-or-user-image'), initialOpen: true },
     76                                                el(ToggleControl, {
     77                                                        label: i18n.__('Show current avatar preview', 'author-or-user-image'),
     78                                                        checked: showPreview,
     79                                                        onChange: function (value) {
     80                                                                props.setAttributes({ showPreview: !!value });
     81                                                        }
     82                                                }),
     83                                                el(RangeControl, {
     84                                                        label: i18n.__('Preview size (px, 0 = site default)', 'author-or-user-image'),
     85                                                        value: effectivePreviewSize,
     86                                                        min: 0,
     87                                                        max: 512,
     88                                                        step: 8,
     89                                                        onChange: function (value) {
     90                                                                var next = typeof value === 'number' && !isNaN(value) ? Math.round(value) : 0;
     91                                                                if (next > 0 && next < 32) {
     92                                                                        next = effectivePreviewSize >= 32 ? 0 : 32;
     93                                                                } else if (next < 0) {
     94                                                                        next = 0;
     95                                                                } else if (next > 512) {
     96                                                                        next = 512;
     97                                                                }
     98                                                                props.setAttributes({ previewSize: next });
     99                                                        }
     100                                                }),
     101                                                el(SelectControl, {
     102                                                        label: i18n.__('Alignment', 'author-or-user-image'),
     103                                                        value: alignment,
     104                                                        options: [
     105                                                                { label: i18n.__('Default', 'author-or-user-image'), value: '' },
     106                                                                { label: i18n.__('Left', 'author-or-user-image'), value: 'left' },
     107                                                                { label: i18n.__('Center', 'author-or-user-image'), value: 'center' },
     108                                                                { label: i18n.__('Right', 'author-or-user-image'), value: 'right' }
     109                                                        ],
     110                                                        onChange: function (value) {
     111                                                                props.setAttributes({ alignment: value || '' });
     112                                                        }
     113                                                }),
     114                                                el(TextControl, {
     115                                                        label: i18n.__('Upload button label', 'author-or-user-image'),
     116                                                        placeholder: i18n.__('Upload image', 'author-or-user-image'),
     117                                                        maxLength: 80,
     118                                                        value: uploadLabel,
     119                                                        onChange: function (value) {
     120                                                                props.setAttributes({ uploadLabel: value });
     121                                                        }
     122                                                }),
     123                                                el(TextControl, {
     124                                                        label: i18n.__('Remove button label', 'author-or-user-image'),
     125                                                        placeholder: i18n.__('Remove image', 'author-or-user-image'),
     126                                                        maxLength: 80,
     127                                                        value: removeLabel,
     128                                                        onChange: function (value) {
     129                                                                props.setAttributes({ removeLabel: value });
     130                                                        }
     131                                                }),
     132                                                el(TextControl, {
     133                                                        label: i18n.__('Logged-out link text', 'author-or-user-image'),
     134                                                        placeholder: i18n.__('Log in to manage your avatar.', 'author-or-user-image'),
     135                                                        maxLength: 120,
     136                                                        value: loginLabel,
     137                                                        onChange: function (value) {
     138                                                                props.setAttributes({ loginLabel: value });
     139                                                        }
     140                                                })
     141                                        )
     142                                ),
     143                                el(
     144                                        'div',
     145                                        blockEditor.useBlockProps({ className: className }),
     146                                        el('strong', null, i18n.__('Avatar upload', 'author-or-user-image')),
     147                                        el('p', null, i18n.__('On the published page, signed-in visitors can manage their own avatar. Other visitors see a login link.', 'author-or-user-image')),
     148                                        summary.length ? el('p', { className: 'description' }, summary.join(' · ')) : null
     149                                )
     150                        );
    15151                },
    16152                save: function () { return null; }
    17153        });
    18 })(wp.blocks, wp.element, wp.blockEditor, wp.i18n);
     154})(wp.blocks, wp.element, wp.blockEditor, wp.components, wp.i18n);
  • author-or-user-image/trunk/author_image.php

    r3796032 r3823635  
    33 * Plugin Name: Author or User Image
    44 * Description: Let registered users use a local image as their WordPress avatar.
    5  * Version: 3.1.0
     5 * Version: 3.2.0
    66 * Requires at least: 6.6
    77 * Requires PHP: 7.4
    … …  
    1717defined( 'ABSPATH' ) || exit;
    1818
    19 define( 'ZMAI_VERSION', '3.1.0' );
     19define( 'ZMAI_VERSION', '3.2.0' );
    2020define( 'ZMAI_FILE', __FILE__ );
    2121define( 'ZMAI_PATH', plugin_dir_path( __FILE__ ) );
    … …  
    3333require_once ZMAI_PATH . 'includes/class-privacy.php';
    3434require_once ZMAI_PATH . 'includes/class-admin.php';
     35require_once ZMAI_PATH . 'includes/class-profile-admin.php';
    3536require_once ZMAI_PATH . 'includes/class-front-end.php';
     37require_once ZMAI_PATH . 'includes/class-rest-api.php';
     38require_once ZMAI_PATH . 'includes/class-cli.php';
    3639require_once ZMAI_PATH . 'includes/class-plugin.php';
    3740
  • author-or-user-image/trunk/blocks/avatar-upload/block.json

    r3796032 r3823635  
    33  "apiVersion": 3,
    44  "name": "author-or-user-image/avatar-upload",
    5   "version": "1.0.0",
     5  "version": "1.1.0",
    66  "title": "Avatar upload",
    77  "category": "widgets",
    … …  
    1010  "textdomain": "author-or-user-image",
    1111  "supports": { "html": false },
     12  "attributes": {
     13    "showPreview": { "type": "boolean", "default": true },
     14    "previewSize": { "type": "integer", "default": 0 },
     15    "alignment": { "type": "string", "default": "", "enum": ["", "left", "center", "right"] },
     16    "uploadLabel": { "type": "string", "default": "" },
     17    "removeLabel": { "type": "string", "default": "" },
     18    "loginLabel": { "type": "string", "default": "" }
     19  },
    1220  "editorScript": "zmai-avatar-upload-editor",
    1321  "style": "zmai-front-end"
  • author-or-user-image/trunk/includes/class-admin-import.php

    r3796032 r3823635  
    6060                add_action( 'load-' . $hook, array( $this, 'set_page_title' ) );
    6161                $job = $this->migration->import_status();
    62                 if ( is_wp_error( $job ) || ( $job && 'complete' !== $job['state'] ) || get_option( Migration::RELEASE_FAILED_OPTION ) ) {
     62                if ( is_wp_error( $job ) || ( $job && 'complete' !== $job['state'] ) || $this->migration->has_release_failure() ) {
    6363                        return;
    6464                }
    … …  
    199199                        echo '<div class="notice notice-error"><p>' . esc_html__( 'Import stopped. Review the stored progress and restore missing files locally before retrying. Retained locks require operator reconciliation.', 'author-or-user-image' ) . '</p></div>';
    200200                }
    201                 if ( is_wp_error( $job ) || get_option( Migration::RELEASE_FAILED_OPTION ) ) {
     201                if ( is_wp_error( $job ) || $this->migration->has_release_failure() ) {
    202202                        echo '<div class="notice notice-error"><p>' . esc_html__( 'Import state is unavailable or needs recovery. Ask the administrator to reconcile its schema and retained locks. No import was started.', 'author-or-user-image' ) . '</p></div></div>';
    203203                        return;
  • author-or-user-image/trunk/includes/class-admin.php

    r3796032 r3823635  
    280280         */
    281281        private function reject_oversized_upload() {
    282                 $limit  = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
    283                 $length = isset( $_SERVER['CONTENT_LENGTH'] ) ? sanitize_text_field( wp_unslash( $_SERVER['CONTENT_LENGTH'] ) ) : '';
     282                $post_max = function_exists( 'ini_get' ) ? (string) ini_get( 'post_max_size' ) : '';
     283                $limit    = '' !== $post_max ? wp_convert_hr_to_bytes( $post_max ) : 0;
     284                $length   = isset( $_SERVER['CONTENT_LENGTH'] ) ? sanitize_text_field( wp_unslash( $_SERVER['CONTENT_LENGTH'] ) ) : '';
    284285                // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Only detect PHP's discarded body; no submitted data is processed and no state is changed.
    285286                if ( ! current_user_can( 'read' ) || ! isset( $_SERVER['REQUEST_METHOD'] ) || 'POST' !== $_SERVER['REQUEST_METHOD'] || $_POST || $_FILES || $limit <= 0 || ! ctype_digit( $length ) || (float) $length <= $limit ) {
    … …  
    525526                }
    526527
     528                $blog_id = get_current_blog_id();
    527529                foreach ( $user_ids as $user_id ) {
    528                         if ( ! get_userdata( $user_id ) ) {
     530                        if ( ! get_userdata( $user_id ) || ( is_multisite() && ! is_user_member_of_blog( $user_id, $blog_id ) ) ) {
     531                                continue;
     532                        }
     533                        if ( ! current_user_can( 'edit_user', $user_id ) ) {
    529534                                continue;
    530535                        }
    … …  
    578583                </form>
    579584                <?php
     585                $this->render_lock_diagnostics();
     586        }
     587
     588        /**
     589         * Render read-only lifecycle lock status without exposing lock tokens or unsafe clear actions.
     590         *
     591         * @return void
     592         */
     593        private function render_lock_diagnostics() {
     594                $locks          = $this->store->get_lock()->inspect_locks();
     595                $release_failed = false;
     596                $status_error   = is_wp_error( $locks );
     597                try {
     598                        $release_failed = (bool) $this->store->read_value( 0, '', Migration::RELEASE_FAILED_OPTION );
     599                } catch ( \Throwable $error ) {
     600                        $status_error = true;
     601                }
     602                $scope_labels = array(
     603                        'migration' => __( 'Migration coordinator', 'author-or-user-image' ),
     604                        'blocks'    => __( 'Block list', 'author-or-user-image' ),
     605                        'default'   => __( 'Default avatar', 'author-or-user-image' ),
     606                        'user'      => __( 'User avatar', 'author-or-user-image' ),
     607                        'unknown'   => __( 'Unknown', 'author-or-user-image' ),
     608                );
     609                ?>
     610                <div class="zmai-card">
     611                        <h2><?php esc_html_e( 'Lifecycle lock status', 'author-or-user-image' ); ?></h2>
     612                        <?php if ( $status_error ) : ?>
     613                                <p class="description"><?php esc_html_e( 'Could not read lifecycle lock status from the database.', 'author-or-user-image' ); ?></p>
     614                        <?php elseif ( ! $locks && ! $release_failed ) : ?>
     615                                <p class="description"><?php esc_html_e( 'No active or retained avatar locks were found on this site.', 'author-or-user-image' ); ?></p>
     616                        <?php else : ?>
     617                                <?php if ( $release_failed ) : ?>
     618                                        <div class="notice notice-warning inline">
     619                                                <p><?php esc_html_e( 'A legacy migration lock release previously failed. Verify no migration process is active and follow the lifecycle recovery guide before retrying.', 'author-or-user-image' ); ?></p>
     620                                        </div>
     621                                <?php endif; ?>
     622                                <?php if ( $locks ) : ?>
     623                                        <p class="description"><?php esc_html_e( 'Active locks belong to running requests. Retained locks remain after an interrupted operation; confirm no worker is running and reconcile using the lifecycle recovery guide before removing any row.', 'author-or-user-image' ); ?></p>
     624                                        <table class="widefat striped">
     625                                                <thead>
     626                                                        <tr>
     627                                                                <th scope="col"><?php esc_html_e( 'Lock name', 'author-or-user-image' ); ?></th>
     628                                                                <th scope="col"><?php esc_html_e( 'Scope', 'author-or-user-image' ); ?></th>
     629                                                                <th scope="col"><?php esc_html_e( 'Owner ID', 'author-or-user-image' ); ?></th>
     630                                                        </tr>
     631                                                </thead>
     632                                                <tbody>
     633                                                        <?php foreach ( $locks as $lock ) : ?>
     634                                                                <tr>
     635                                                                        <td><code><?php echo esc_html( $lock['name'] ); ?></code></td>
     636                                                                        <td><?php echo esc_html( $scope_labels[ $lock['scope'] ] ?? $scope_labels['unknown'] ); ?></td>
     637                                                                        <td><?php echo esc_html( $lock['owner_id'] > 0 ? (string) $lock['owner_id'] : '—' ); ?></td>
     638                                                                </tr>
     639                                                        <?php endforeach; ?>
     640                                                </tbody>
     641                                        </table>
     642                                <?php endif; ?>
     643                        <?php endif; ?>
     644                </div>
     645                <?php
    580646        }
    581647
    … …  
    649715                        echo '<div class="notice notice-error"><p>' . esc_html__( 'The requested changes did not all complete. Avatar data may be busy or need administrator recovery. Please retry.', 'author-or-user-image' ) . '</p></div>';
    650716                } elseif ( in_array( $status, array( 'upload-error', 'remove-error' ), true ) ) {
    651                         $errors  = array(
    652                                 'zmai_invalid_image'      => __( 'Choose a JPEG, PNG, or static WebP image.', 'author-or-user-image' ),
    653                                 'zmai_upload_size'        => __( 'The image exceeds this site’s upload limit. Choose a smaller image.', 'author-or-user-image' ),
    654                                 'zmai_rate_limited'       => __( 'Too many avatar uploads. Please wait before trying again.', 'author-or-user-image' ),
    655                                 'zmai_blocked'            => __( 'Local avatar uploads are disabled for this account.', 'author-or-user-image' ),
    656                                 'zmai_metadata_failed'    => __( 'The image metadata could not be removed safely. Choose another image.', 'author-or-user-image' ),
    657                                 'zmai_metadata_cmyk'      => __( 'This server cannot safely normalize this CMYK JPEG. Convert it to RGB and try again.', 'author-or-user-image' ),
    658                                 'zmai_invalid_dimensions' => __( 'Choose an image no larger than 4096 by 4096 pixels.', 'author-or-user-image' ),
    659                         );
    660                         $message = $errors[ $error ] ?? __( 'The image change could not be completed. Please try again or contact an administrator.', 'author-or-user-image' );
    661                         echo '<div class="notice notice-error is-dismissible"><p>' . esc_html( $message ) . '</p></div>';
     717                        echo '<div class="notice notice-error is-dismissible"><p>' . esc_html( self::upload_error_message( $error ) ) . '</p></div>';
    662718                } elseif ( isset( $map[ $status ] ) ) {
    663719                        $class = 'nothing-selected' === $status ? 'notice-warning' : 'notice-success';
    … …  
    718774                exit;
    719775        }
     776
     777        /**
     778         * Map a typed avatar operation error code to a fixed translated message.
     779         *
     780         * @param string $code Typed error code.
     781         * @return string
     782         */
     783        public static function upload_error_message( $code ) {
     784                $errors = array(
     785                        'zmai_invalid_image'           => __( 'Choose a JPEG, PNG, or static WebP image.', 'author-or-user-image' ),
     786                        'zmai_invalid_image_container' => __( 'Choose a JPEG, PNG, or static WebP image.', 'author-or-user-image' ),
     787                        'zmai_animated_image'          => __( 'Animated images are not supported. Choose a static JPEG, PNG, or WebP image.', 'author-or-user-image' ),
     788                        'zmai_upload_size'             => __( 'The image exceeds this site’s upload limit. Choose a smaller image.', 'author-or-user-image' ),
     789                        'zmai_rate_limited'            => __( 'Too many avatar uploads. Please wait before trying again.', 'author-or-user-image' ),
     790                        'zmai_blocked'                 => __( 'Local avatar uploads are disabled for this account.', 'author-or-user-image' ),
     791                        'zmai_forbidden'               => __( 'You are not allowed to do that.', 'author-or-user-image' ),
     792                        'zmai_metadata_failed'         => __( 'The image metadata could not be removed safely. Choose another image.', 'author-or-user-image' ),
     793                        'zmai_metadata_cmyk'           => __( 'This server cannot safely normalize this CMYK JPEG. Convert it to RGB and try again.', 'author-or-user-image' ),
     794                        'zmai_invalid_dimensions'      => __( 'Choose an image no larger than 4096 by 4096 pixels.', 'author-or-user-image' ),
     795                        'zmai_jpeg_exif_unavailable'   => __( 'JPEG processing requires server EXIF support.', 'author-or-user-image' ),
     796                        'zmai_upload_missing'          => __( 'Choose an image file to upload.', 'author-or-user-image' ),
     797                        'zmai_upload_provenance'       => __( 'Choose a newly uploaded image.', 'author-or-user-image' ),
     798                        'zmai_invalid_policy'          => __( 'Choose a valid upload policy and known site roles.', 'author-or-user-image' ),
     799                        'zmai_busy'                    => __( 'Avatar data is busy or unavailable. Please retry.', 'author-or-user-image' ),
     800                        'zmai_invalid_user'            => __( 'The selected user account does not exist.', 'author-or-user-image' ),
     801                        'zmai_user_not_found'          => __( 'The requested user was not found.', 'author-or-user-image' ),
     802                );
     803                return $errors[ $code ] ?? __( 'The image change could not be completed. Please try again or contact an administrator.', 'author-or-user-image' );
     804        }
    720805}
  • author-or-user-image/trunk/includes/class-front-end.php

    r3796032 r3823635  
    5151        public function register() {
    5252                wp_register_style( 'zmai-front-end', ZMAI_URL . 'assets/css/front-end.css', array(), ZMAI_VERSION );
    53                 wp_register_script( 'zmai-avatar-upload-editor', ZMAI_URL . 'assets/js/avatar-upload-editor.js', array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-i18n' ), ZMAI_VERSION, true );
     53                wp_register_script( 'zmai-avatar-upload-editor', ZMAI_URL . 'assets/js/avatar-upload-editor.js', array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n' ), ZMAI_VERSION, true );
    5454                wp_set_script_translations( 'zmai-avatar-upload-editor', 'author-or-user-image' );
    5555                register_block_type( ZMAI_PATH . 'blocks/avatar-upload', array( 'render_callback' => array( $this, 'render_form' ) ) );
    … …  
    172172
    173173        /**
    174          * Render for the current visitor; all block/shortcode attributes are ignored.
    175          *
     174         * Render for the current visitor using allowlisted presentation attributes only.
     175         *
     176         * @param mixed $attributes Block or shortcode attributes.
    176177         * @return string Escaped form markup.
    177178         */
    178         public function render_form() {
     179        public function render_form( $attributes = array() ) {
    179180                // Widgets and templates render after the early hook, so the form marks its own page.
    180181                if ( is_user_logged_in() ) {
    … …  
    187188                        wp_print_styles( array( 'zmai-front-end' ) );
    188189                }
    189                 $home   = wp_parse_url( home_url( '/' ) );
    190                 $origin = $home['scheme'] . '://' . $home['host'] . ( isset( $home['port'] ) ? ':' . $home['port'] : '' );
     190                $opts          = $this->normalize_attributes( $attributes );
     191                $wrapper_class = 'zmai-front-end' . ( '' !== $opts['alignment'] ? ' zmai-align-' . $opts['alignment'] : '' );
     192                $home          = wp_parse_url( home_url( '/' ) );
     193                $origin        = $home['scheme'] . '://' . $home['host'] . ( isset( $home['port'] ) ? ':' . $home['port'] : '' );
    191194                // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- The strict origin/path allowlist below validates this URL before use.
    192195                $request = isset( $_SERVER['REQUEST_URI'] ) && is_string( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '/';
    193196                $return  = self::safe_return_url( $origin . $request );
    194197                ?>
    195                 <div class="zmai-front-end">
     198                <div class="<?php echo esc_attr( $wrapper_class ); ?>">
    196199                <?php if ( ! is_user_logged_in() ) : ?>
    197                         <p><a href="<?php echo esc_url( wp_login_url( $return ) ); ?>"><?php esc_html_e( 'Log in to manage your avatar.', 'author-or-user-image' ); ?></a></p>
     200                        <p><a href="<?php echo esc_url( wp_login_url( $return ) ); ?>"><?php echo esc_html( $opts['loginLabel'] ); ?></a></p>
    198201                <?php else : ?>
    199202                        <?php
    200                         $user_id = get_current_user_id();
    201                         $id      = wp_unique_id( 'zmai-avatar-' );
    202                         $url     = $this->store->get_url( $user_id, $this->store->get_size(), false );
    203                         $action  = add_query_arg(
     203                        $user_id      = get_current_user_id();
     204                        $id           = wp_unique_id( 'zmai-avatar-' );
     205                        $preview_size = $opts['previewSize'] > 0 ? $opts['previewSize'] : $this->store->get_size();
     206                        $blocked      = $this->store->is_blocked( $user_id );
     207                        $url          = $blocked ? '' : $this->store->get_url( $user_id, $preview_size, false );
     208                        $action       = add_query_arg(
    204209                                array(
    205210                                        'action'       => 'zmai_save_avatar',
    … …  
    213218                        ?>
    214219                        <div class="zmai-status" role="status" aria-live="polite"><p><?php echo esc_html( self::status_message( $status ) ); ?></p></div>
    215                         <?php if ( $url ) : ?>
    216                                 <img class="zmai-avatar-preview" src="<?php echo esc_url( $url ); ?>" alt="<?php esc_attr_e( 'Your current avatar', 'author-or-user-image' ); ?>" width="<?php echo absint( $this->store->get_size() ); ?>" height="<?php echo absint( $this->store->get_size() ); ?>">
     220                        <?php if ( $url && $opts['showPreview'] ) : ?>
     221                                <img class="zmai-avatar-preview" src="<?php echo esc_url( $url ); ?>" alt="<?php esc_attr_e( 'Your current avatar', 'author-or-user-image' ); ?>" width="<?php echo absint( $preview_size ); ?>" height="<?php echo absint( $preview_size ); ?>">
    217222                        <?php endif; ?>
    218                         <?php if ( $this->store->is_blocked( $user_id ) ) : ?>
     223                        <?php if ( $blocked ) : ?>
    219224                                <p><?php esc_html_e( 'An administrator has disabled local avatar uploads for your account.', 'author-or-user-image' ); ?></p>
    220225                        <?php elseif ( $this->policy->can_upload( $user_id ) ) : ?>
    … …  
    236241                                        ?>
    237242                                        </p>
    238                                         <button type="submit"><?php esc_html_e( 'Upload image', 'author-or-user-image' ); ?></button>
     243                                        <button type="submit"><?php echo esc_html( $opts['uploadLabel'] ); ?></button>
    239244                                </form>
    240245                        <?php else : ?>
    241246                                <p><?php esc_html_e( 'Your role is not allowed to upload a new avatar on this site. You can still remove your avatar.', 'author-or-user-image' ); ?></p>
    242247                        <?php endif; ?>
    243                         <?php if ( $url && current_user_can( 'read' ) ) : ?>
     248                        <?php if ( $url && ! $blocked && current_user_can( 'read' ) ) : ?>
    244249                                <form class="zmai-remove-form" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
    245250                                        <input type="hidden" name="action" value="zmai_remove_avatar">
    … …  
    248253                                        <input type="hidden" name="zmai_return" value="<?php echo esc_url( $return ); ?>">
    249254                                        <input type="hidden" name="_wpnonce" value="<?php echo esc_attr( wp_create_nonce( 'zmai_remove_avatar' ) ); ?>">
    250                                         <button type="submit"><?php esc_html_e( 'Remove image', 'author-or-user-image' ); ?></button>
     255                                        <button type="submit"><?php echo esc_html( $opts['removeLabel'] ); ?></button>
    251256                                </form>
    252257                        <?php endif; ?>
    … …  
    256261                return ob_get_clean();
    257262        }
     263
     264        /**
     265         * Strictly normalize allowlisted presentation attributes for both block and shortcode callers.
     266         *
     267         * @param mixed $attributes Untrusted caller attributes.
     268         * @return array{showPreview:bool,previewSize:int,alignment:string,uploadLabel:string,removeLabel:string,loginLabel:string}
     269         */
     270        private function normalize_attributes( $attributes ) {
     271                $attrs = is_array( $attributes ) ? $attributes : array();
     272
     273                $raw_show     = $this->pick_attribute( $attrs, 'showPreview', 'show_preview', true );
     274                $show_preview = true;
     275                if ( is_bool( $raw_show ) ) {
     276                        $show_preview = $raw_show;
     277                } elseif ( is_int( $raw_show ) ) {
     278                        $show_preview = 0 !== $raw_show;
     279                } elseif ( is_string( $raw_show ) ) {
     280                        $lower = strtolower( trim( $raw_show ) );
     281                        if ( in_array( $lower, array( 'false', '0', 'no' ), true ) ) {
     282                                $show_preview = false;
     283                        } elseif ( in_array( $lower, array( 'true', '1', 'yes' ), true ) ) {
     284                                $show_preview = true;
     285                        }
     286                }
     287
     288                $raw_size     = $this->pick_attribute( $attrs, 'previewSize', 'preview_size', 0 );
     289                $preview_size = 0;
     290                if ( ( is_int( $raw_size ) || ( is_string( $raw_size ) && preg_match( '/^[0-9]+$/D', trim( $raw_size ) ) ) ) && (int) $raw_size > 0 ) {
     291                        $preview_size = min( 512, max( 32, (int) $raw_size ) );
     292                }
     293
     294                $raw_align = $attrs['alignment'] ?? '';
     295                $alignment = is_string( $raw_align ) && in_array( $raw_align, array( 'left', 'center', 'right' ), true ) ? $raw_align : '';
     296
     297                return array(
     298                        'showPreview' => $show_preview,
     299                        'previewSize' => $preview_size,
     300                        'alignment'   => $alignment,
     301                        'uploadLabel' => $this->sanitize_label(
     302                                $this->pick_attribute( $attrs, 'uploadLabel', 'upload_label', '' ),
     303                                80,
     304                                __( 'Upload image', 'author-or-user-image' )
     305                        ),
     306                        'removeLabel' => $this->sanitize_label(
     307                                $this->pick_attribute( $attrs, 'removeLabel', 'remove_label', '' ),
     308                                80,
     309                                __( 'Remove image', 'author-or-user-image' )
     310                        ),
     311                        'loginLabel'  => $this->sanitize_label(
     312                                $this->pick_attribute( $attrs, 'loginLabel', 'login_label', '' ),
     313                                120,
     314                                __( 'Log in to manage your avatar.', 'author-or-user-image' )
     315                        ),
     316                );
     317        }
     318
     319        /**
     320         * Read an attribute supporting block camelCase, shortcode snake_case, and lowercased shortcode keys.
     321         *
     322         * @param array<string,mixed> $attrs   Caller attribute map.
     323         * @param string              $camel   CamelCase attribute key.
     324         * @param string              $snake   Snake_case attribute key.
     325         * @param mixed               $fallback Default value when unset.
     326         * @return mixed
     327         */
     328        private function pick_attribute( array $attrs, $camel, $snake, $fallback ) {
     329                if ( array_key_exists( $camel, $attrs ) ) {
     330                        return $attrs[ $camel ];
     331                }
     332                if ( array_key_exists( $snake, $attrs ) ) {
     333                        return $attrs[ $snake ];
     334                }
     335                $lower = strtolower( $camel );
     336                if ( array_key_exists( $lower, $attrs ) ) {
     337                        return $attrs[ $lower ];
     338                }
     339                return $fallback;
     340        }
     341
     342        /**
     343         * Sanitize and bound a plain-text UI label attribute.
     344         *
     345         * @param mixed  $value    Raw attribute value.
     346         * @param int    $max_len  Maximum length.
     347         * @param string $fallback Default translated label.
     348         * @return string
     349         */
     350        private function sanitize_label( $value, $max_len, $fallback ) {
     351                if ( ! is_string( $value ) ) {
     352                        return $fallback;
     353                }
     354                $clean = trim( sanitize_text_field( $value ) );
     355                if ( '' === $clean ) {
     356                        return $fallback;
     357                }
     358                return function_exists( 'mb_substr' ) ? mb_substr( $clean, 0, $max_len ) : substr( $clean, 0, $max_len );
     359        }
    258360}
  • author-or-user-image/trunk/includes/class-image-processor.php

    r3796032 r3823635  
    5858                }
    5959
    60                 $file_stat = @lstat( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Missing or unreadable local paths are a normal validation failure.
    61                 if ( ! is_array( $file_stat ) || ! isset( $file_stat['mode'] ) || 0100000 !== ( $file_stat['mode'] & 0170000 ) ) {
     60                if ( ! self::is_regular_file( $path ) ) {
    6261                        return self::error( 'zmai_invalid_image', __( 'Choose a readable local image file.', 'author-or-user-image' ) );
    6362                }
    … …  
    189188
    190189                        $basename    = 'zmai-avatar-' . str_replace( '-', '', wp_generate_uuid4() ) . '.' . $extension;
    191                         $unique_name = wp_unique_filename( $real_directory, $basename );
    192                         $output_path = trailingslashit( $real_directory ) . $unique_name;
    193                         // Keep this save in its validated format, without changing other media saves.
    194                         $pin_format = static function () {
    195                                 return array();
    196                         };
    197                         add_filter( 'image_editor_output_format', $pin_format, PHP_INT_MAX );
    198                         try {
    199                                 $saved = $editor->save( $output_path, $validated['type'] );
    200                         } finally {
    201                                 remove_filter( 'image_editor_output_format', $pin_format, PHP_INT_MAX );
    202                         }
     190                        $output_path = '';
     191                        $saved       = self::with_unique_filename_file_list(
     192                                static function () use ( $editor, $real_directory, $basename, $validated, &$output_path ) {
     193                                        $unique_name = wp_unique_filename( $real_directory, $basename );
     194                                        $output_path = trailingslashit( $real_directory ) . $unique_name;
     195                                        // Keep this save in its validated format, without changing other media saves.
     196                                        $pin_format = static function () {
     197                                                return array();
     198                                        };
     199                                        add_filter( 'image_editor_output_format', $pin_format, PHP_INT_MAX );
     200                                        try {
     201                                                return $editor->save( $output_path, $validated['type'] );
     202                                        } finally {
     203                                                remove_filter( 'image_editor_output_format', $pin_format, PHP_INT_MAX );
     204                                        }
     205                                }
     206                        );
     207                        $unique_name = basename( $output_path );
    203208                        if ( is_wp_error( $saved ) || ! is_array( $saved ) ) {
    204209                                return self::square_failure( $output_path, __( 'The square image could not be saved.', 'author-or-user-image' ) );
    … …  
    414419
    415420        /**
     421         * Run a core upload or image-save callback with scandir()-safe filename listing.
     422         *
     423         * @internal
     424         * @param callable $callback Operation invoking wp_unique_filename() or media sideloading.
     425         * @return mixed
     426         */
     427        public static function with_unique_filename_file_list( $callback ) {
     428                if ( function_exists( 'scandir' ) ) {
     429                        return $callback();
     430                }
     431                $list_filter = static function ( $files, $dir ) {
     432                        return self::filter_unique_filename_file_list( $files, $dir );
     433                };
     434                add_filter( 'pre_wp_unique_filename_file_list', $list_filter, 10, 2 );
     435                try {
     436                        return $callback();
     437                } finally {
     438                        remove_filter( 'pre_wp_unique_filename_file_list', $list_filter, 10 );
     439                }
     440        }
     441
     442        /**
     443         * Short-circuit core wp_unique_filename() scandir() calls when scandir is disabled.
     444         *
     445         * @internal
     446         * @param array<int,string>|null $files Previously filtered directory list.
     447         * @param string                 $dir   Target uploads directory.
     448         * @return array<int,string>|null
     449         */
     450        public static function filter_unique_filename_file_list( $files, $dir ) {
     451                if ( null !== $files || function_exists( 'scandir' ) ) {
     452                        return $files;
     453                }
     454                $listed = self::list_directory( $dir );
     455                return is_array( $listed ) ? $listed : array();
     456        }
     457
     458        /**
     459         * List directory entries using scandir or safe core fallbacks when disabled.
     460         *
     461         * @internal
     462         * @param string $directory Local directory path.
     463         * @return array<int,string>|false
     464         */
     465        public static function list_directory( $directory ) {
     466                if ( ! is_string( $directory ) || '' === $directory || ! is_dir( $directory ) ) {
     467                        return false;
     468                }
     469                if ( function_exists( 'scandir' ) ) {
     470                        $files = @scandir( $directory ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- A failed listing is handled by recovery inventory callers.
     471                        return is_array( $files ) ? $files : false;
     472                }
     473                if ( class_exists( 'DirectoryIterator' ) ) {
     474                        try {
     475                                $files = array();
     476                                foreach ( new \DirectoryIterator( $directory ) as $item ) {
     477                                        $files[] = $item->getFilename();
     478                                }
     479                                return $files;
     480                        } catch ( \Throwable $error ) {
     481                                return false;
     482                        }
     483                }
     484                if ( function_exists( 'opendir' ) && function_exists( 'readdir' ) && function_exists( 'closedir' ) ) {
     485                        $handle = @opendir( $directory ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Unreadable directories return false cleanly.
     486                        if ( false === $handle ) {
     487                                return false;
     488                        }
     489                        $files = array();
     490                        while ( true ) {
     491                                $entry = readdir( $handle );
     492                                if ( false === $entry ) {
     493                                        break;
     494                                }
     495                                $files[] = $entry;
     496                        }
     497                        closedir( $handle );
     498                        return $files;
     499                }
     500                return false;
     501        }
     502
     503        /**
    416504         * Confirm that a path is a regular file rather than a directory or symlink.
    417505         *
    … …  
    420508         */
    421509        private static function is_regular_file( $path ) {
    422                 $stat = @lstat( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Partial output is treated as a failed save.
    423                 return is_array( $stat ) && isset( $stat['mode'] ) && 0100000 === ( $stat['mode'] & 0170000 );
     510                if ( ! is_string( $path ) || '' === $path ) {
     511                        return false;
     512                }
     513                if ( function_exists( 'lstat' ) ) {
     514                        $stat = @lstat( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Partial output is treated as a failed save.
     515                        return is_array( $stat ) && isset( $stat['mode'] ) && 0100000 === ( $stat['mode'] & 0170000 );
     516                }
     517                return function_exists( 'is_link' ) && ! is_link( $path ) && is_file( $path );
     518        }
     519
     520        /**
     521         * Safely check whether a path is a symbolic link on hosts that may disable is_link().
     522         *
     523         * @internal
     524         * @param string $path Local filesystem path.
     525         * @return bool
     526         */
     527        public static function is_symlink_path( $path ) {
     528                return is_string( $path ) && '' !== $path && function_exists( 'is_link' ) && is_link( $path );
    424529        }
    425530
    … …  
    431536         */
    432537        private static function remove_file( $path ) {
    433                 if ( ! is_string( $path ) || ( ! file_exists( $path ) && ! is_link( $path ) ) ) {
     538                $is_link = self::is_symlink_path( $path );
     539                if ( ! is_string( $path ) || ( ! file_exists( $path ) && ! $is_link ) ) {
    434540                        return true;
    435541                }
    436                 if ( ! is_file( $path ) && ! is_link( $path ) ) {
     542                if ( ! is_file( $path ) && ! $is_link ) {
    437543                        return false;
    438544                }
    439545                wp_delete_file( $path );
    440546                clearstatcache( true, $path );
    441                 return ! file_exists( $path ) && ! is_link( $path );
     547                return ! file_exists( $path ) && ! self::is_symlink_path( $path );
    442548        }
    443549
    … …  
    456562                if ( $path ) {
    457563                        $stem  = pathinfo( $path, PATHINFO_FILENAME );
    458                         $files = @scandir( dirname( $path ) ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- A failed cleanup listing is retained as recovery inventory below.
     564                        $files = self::list_directory( dirname( $path ) );
    459565                        if ( false === $files ) {
    460566                                $inventory_failed = true;
  • author-or-user-image/trunk/includes/class-image-store.php

    r3796032 r3823635  
    118118         * Store an uploaded image for a user or as the site default.
    119119         *
    120          * @param string $field   File input name.
    121          * @param int    $user_id User ID, or zero for the default avatar.
     120         * @param string $field    File input name.
     121         * @param int    $user_id  User ID, or zero for the default avatar.
     122         * @param bool   $by_admin Optional. Whether an authorized administrator is uploading for another user.
    122123         * @return int|WP_Error Attachment ID, or busy/storage/cleanup error; errors never mean success.
    123124         */
    124         public function save_upload( $field, $user_id = 0 ) {
     125        public function save_upload( $field, $user_id = 0, $by_admin = false ) {
    125126                if ( ! is_string( $field ) || ! is_scalar( $user_id ) ) {
    126127                        return $this->storage_error();
    127128                }
    128                 $field   = sanitize_key( $field );
    129                 $user_id = absint( $user_id );
     129                $field    = sanitize_key( $field );
     130                $user_id  = absint( $user_id );
     131                $by_admin = (bool) $by_admin;
    130132                return $this->with_owner_lock(
    131133                        $user_id,
    132                         function () use ( $field, $user_id ) {
     134                        function () use ( $field, $user_id, $by_admin ) {
    133135                                $policy = new Upload_Policy( $this );
    134                                 if ( $user_id ? ! $policy->can_upload_fresh( $user_id ) : ! current_user_can( 'manage_options' ) ) {
    135                                         return new WP_Error( 'zmai_blocked', __( 'Local avatar uploads are disabled for this account.', 'author-or-user-image' ) );
    136                                 }
    137                                 if ( $user_id ) {
     136                                if ( 0 === $user_id ) {
     137                                        if ( ! current_user_can( 'manage_options' ) ) {
     138                                                return new WP_Error( 'zmai_forbidden', __( 'You are not allowed to do that.', 'author-or-user-image' ) );
     139                                        }
     140                                } elseif ( $by_admin ) {
     141                                        if ( ! current_user_can( 'manage_options' ) ) {
     142                                                return new WP_Error( 'zmai_forbidden', __( 'You are not allowed to do that.', 'author-or-user-image' ) );
     143                                        }
     144                                        if ( ! $this->user_exists_fresh( $user_id ) || ! $this->user_is_member_fresh( $user_id ) ) {
     145                                                return new WP_Error( 'zmai_invalid_user', __( 'The selected user account does not exist.', 'author-or-user-image' ) );
     146                                        }
     147                                        if ( ! current_user_can( 'edit_user', $user_id ) ) {
     148                                                return new WP_Error( 'zmai_forbidden', __( 'You are not allowed to do that.', 'author-or-user-image' ) );
     149                                        }
     150                                        if ( $this->is_blocked_fresh( $user_id ) ) {
     151                                                return new WP_Error( 'zmai_blocked', __( 'Local avatar uploads are disabled for this account.', 'author-or-user-image' ) );
     152                                        }
     153                                } else {
     154                                        if ( ! $policy->can_upload_fresh( $user_id ) ) {
     155                                                return new WP_Error( 'zmai_blocked', __( 'Local avatar uploads are disabled for this account.', 'author-or-user-image' ) );
     156                                        }
    138157                                        $rate = $this->consume_upload_attempt( $user_id );
    139158                                        if ( is_wp_error( $rate ) ) {
    … …  
    147166                                                return new WP_Error( 'zmai_upload_failed', __( 'The image upload did not complete.', 'author-or-user-image' ) );
    148167                                        }
     168                                }
     169                                if ( in_array( (int) $file['error'], array( UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE ), true ) ) {
     170                                        return new WP_Error( 'zmai_upload_size', __( 'The image exceeds this site’s upload limit.', 'author-or-user-image' ) );
    149171                                }
    150172                                if ( UPLOAD_ERR_OK !== (int) $file['error'] || ! is_string( $file['tmp_name'] ) || ! is_string( $file['name'] ) ) {
    … …  
    204226                                }
    205227                                $ready = $this->prepare_attachment( $attachment_id, $user_id, $validated['type'], $validated );
    206                                 if ( ! is_wp_error( $ready ) && $user_id && ! $policy->can_upload_fresh( $user_id ) ) {
    207                                         $ready = new WP_Error( 'zmai_blocked', __( 'Local avatar uploads are disabled for this account.', 'author-or-user-image' ) );
     228                                if ( ! is_wp_error( $ready ) ) {
     229                                        if ( 0 === $user_id ) {
     230                                                if ( ! current_user_can( 'manage_options' ) ) {
     231                                                        $ready = new WP_Error( 'zmai_forbidden', __( 'You are not allowed to do that.', 'author-or-user-image' ) );
     232                                                }
     233                                        } elseif ( $by_admin ) {
     234                                                if ( ! current_user_can( 'manage_options' ) ) {
     235                                                        $ready = new WP_Error( 'zmai_forbidden', __( 'You are not allowed to do that.', 'author-or-user-image' ) );
     236                                                } elseif ( ! $this->user_exists_fresh( $user_id ) || ! $this->user_is_member_fresh( $user_id ) ) {
     237                                                        $ready = new WP_Error( 'zmai_invalid_user', __( 'The selected user account does not exist.', 'author-or-user-image' ) );
     238                                                } elseif ( ! current_user_can( 'edit_user', $user_id ) ) {
     239                                                        $ready = new WP_Error( 'zmai_forbidden', __( 'You are not allowed to do that.', 'author-or-user-image' ) );
     240                                                } elseif ( $this->is_blocked_fresh( $user_id ) ) {
     241                                                        $ready = new WP_Error( 'zmai_blocked', __( 'Local avatar uploads are disabled for this account.', 'author-or-user-image' ) );
     242                                                }
     243                                        } elseif ( ! $policy->can_upload_fresh( $user_id ) ) {
     244                                                $ready = new WP_Error( 'zmai_blocked', __( 'Local avatar uploads are disabled for this account.', 'author-or-user-image' ) );
     245                                        }
    208246                                }
    209247                                if ( ! is_wp_error( $ready ) ) {
    … …  
    303341                add_action( 'add_attachment', $remember_id, -99999 );
    304342                try {
    305                         $result = $callback();
     343                        $result = Image_Processor::with_unique_filename_file_list( $callback );
    306344                } catch ( \Throwable $error ) {
    307345                        if ( $wpdb->last_error || ! $stage['file'] ) {
    … …  
    329367                // belongs only to this staging call, so its file inventory is still known.
    330368                $stem  = pathinfo( $stage['file'], PATHINFO_FILENAME );
    331                 $files = @scandir( dirname( $stage['file'] ) ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- A failed listing must retain the attachment inventory and owner fence.
     369                $files = Image_Processor::list_directory( dirname( $stage['file'] ) );
    332370                if ( false === $files ) {
    333371                        return $this->storage_error( true );
    … …  
    346384                        wp_delete_file( $file );
    347385                        clearstatcache( true, $file );
    348                         if ( is_file( $file ) || is_link( $file ) ) {
     386                        if ( is_file( $file ) || Image_Processor::is_symlink_path( $file ) ) {
    349387                                // No attachment row remains to retain this file inventory for a retry.
    350388                                return $this->storage_error( true );
    … …  
    497535                        );
    498536                }
    499                 clean_user_cache( $user_id );
    500                 wp_cache_delete( $user_id, 'user_meta' );
    501                 $membership = $this->database_values( $wpdb->prepare( 'SELECT meta_value FROM %i WHERE user_id = %d AND meta_key = %s', $wpdb->usermeta, $user_id, $wpdb->get_blog_prefix() . 'capabilities' ) );
    502                 if ( is_multisite() && ( ! $membership || ! is_array( maybe_unserialize( $membership[0] ) ) || ! maybe_unserialize( $membership[0] ) ) ) {
     537                if ( ! $this->user_is_member_fresh( $user_id ) ) {
    503538                        return array(
    504539                                'status'        => 'gone',
    … …  
    794829                        return self::$attachment_urls[ $key ];
    795830                }
    796                 $square                        = $meta['sizes']['zmai-avatar'] ?? null;
    797                 $width                         = $square['width'] ?? 0;
    798                 $height                        = $square['height'] ?? 0;
    799                 $named                         = '1' === $marker && is_array( $square ) && ! empty( $square['file'] ) && is_string( $square['file'] ) && basename( $square['file'] ) === $square['file'] && is_int( $width ) && $width > 0 && $width === $height;
    800                 $url                           = wp_get_attachment_image_url( $id, $named ? 'zmai-avatar' : array( $size, $size ) );
     831                $square = $meta['sizes']['zmai-avatar'] ?? null;
     832                $width  = $square['width'] ?? 0;
     833                $height = $square['height'] ?? 0;
     834                $named  = '1' === $marker && is_array( $square ) && ! empty( $square['file'] ) && is_string( $square['file'] ) && basename( $square['file'] ) === $square['file'] && is_int( $width ) && $width > 0 && $width === $height;
     835                $url    = wp_get_attachment_image_url( $id, $named ? 'zmai-avatar' : array( $size, $size ) );
     836                if ( count( self::$attachment_urls ) >= 500 ) {
     837                        self::$attachment_urls = array();
     838                }
    801839                self::$attachment_urls[ $key ] = $url ? $url : '';
    802840                return self::$attachment_urls[ $key ];
    … …  
    10351073
    10361074        /**
     1075         * Authoritative current-site membership inside the owner critical section.
     1076         *
     1077         * @param int $user_id User ID.
     1078         * @return bool
     1079         */
     1080        private function user_is_member_fresh( $user_id ) {
     1081                global $wpdb;
     1082                clean_user_cache( $user_id );
     1083                wp_cache_delete( $user_id, 'user_meta' );
     1084                if ( ! is_multisite() ) {
     1085                        return true;
     1086                }
     1087                $membership = $this->database_values( $wpdb->prepare( 'SELECT meta_value FROM %i WHERE user_id = %d AND meta_key = %s', $wpdb->usermeta, $user_id, $wpdb->get_blog_prefix() . 'capabilities' ) );
     1088                if ( ! $membership ) {
     1089                        return false;
     1090                }
     1091                $caps = maybe_unserialize( $membership[0] );
     1092                return is_array( $caps ) && ! empty( $caps );
     1093        }
     1094
     1095        /**
    10371096         * Authoritative block decision inside the owner critical section.
    10381097         *
    … …  
    10451104                        return true;
    10461105                }
    1047                 $user    = get_userdata( $user_id );
     1106                $login   = $this->user_login_fresh( $user_id );
    10481107                $blocked = $this->read_value( 0, '', self::LEGACY_BLOCK_OPTION );
    1049                 return $user && is_array( $blocked ) && in_array( $user->user_login, $blocked, true );
     1108                return '' !== $login && is_array( $blocked ) && in_array( $login, $blocked, true );
     1109        }
     1110
     1111        /**
     1112         * Authoritative user_login inside critical sections without modifying user caches.
     1113         *
     1114         * @param int $user_id User ID.
     1115         * @return string
     1116         */
     1117        private function user_login_fresh( $user_id ) {
     1118                global $wpdb;
     1119                $values = $this->database_values( $wpdb->prepare( 'SELECT user_login FROM %i WHERE ID = %d', $wpdb->users, $user_id ) );
     1120                return $values ? (string) $values[0] : '';
    10501121        }
    10511122
    … …  
    12691340                        return true;
    12701341                }
    1271                 $user   = get_userdata( $user_id );
     1342                $login  = $this->user_login_fresh( $user_id );
    12721343                $legacy = is_array( $legacy ) ? $legacy : array();
    1273                 if ( $user ) {
    1274                         $legacy = array_values( array_diff( $legacy, array( $user->user_login ) ) );
     1344                if ( '' !== $login ) {
     1345                        $legacy = array_values( array_diff( $legacy, array( $login ) ) );
    12751346                }
    12761347                return $this->write_value( 0, '', self::LEGACY_BLOCK_OPTION, array_values( array_unique( array_merge( $legacy, $logins ) ) ) );
  • author-or-user-image/trunk/includes/class-lock.php

    r3796032 r3823635  
    160160                return $result;
    161161        }
     162
     163        /**
     164         * Inspect active or retained lifecycle locks directly from the options table.
     165         *
     166         * @return array<int,array{name:string,scope:string,owner_id:int,token:string,table:string}>|WP_Error
     167         */
     168        public function inspect_locks() {
     169                global $wpdb;
     170                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Lock diagnostics must inspect authoritative rows rather than option caches.
     171                $rows = $wpdb->get_results(
     172                        $wpdb->prepare(
     173                                'SELECT option_name, option_value FROM %i WHERE option_name LIKE %s ORDER BY option_name ASC',
     174                                $wpdb->options,
     175                                $wpdb->esc_like( 'zmai_avatar_lock_' ) . '%'
     176                        ),
     177                        ARRAY_A
     178                );
     179                if ( $wpdb->last_error || ! is_array( $rows ) ) {
     180                        return self::storage_error();
     181                }
     182
     183                $locks = array();
     184                foreach ( $rows as $row ) {
     185                        $name     = isset( $row['option_name'] ) ? (string) $row['option_name'] : '';
     186                        $token    = isset( $row['option_value'] ) ? (string) $row['option_value'] : '';
     187                        $scope    = 'unknown';
     188                        $owner_id = 0;
     189
     190                        if ( 'zmai_avatar_lock_migration' === $name ) {
     191                                $scope = 'migration';
     192                        } elseif ( 'zmai_avatar_lock_blocks' === $name ) {
     193                                $scope = 'blocks';
     194                        } elseif ( 'zmai_avatar_lock_default' === $name ) {
     195                                $scope = 'default';
     196                        } elseif ( preg_match( '/^zmai_avatar_lock_user_([1-9][0-9]*)$/', $name, $matches ) ) {
     197                                $scope    = 'user';
     198                                $owner_id = (int) $matches[1];
     199                        }
     200
     201                        $locks[] = array(
     202                                'name'     => $name,
     203                                'scope'    => $scope,
     204                                'owner_id' => $owner_id,
     205                                'token'    => $token,
     206                                'table'    => (string) $wpdb->options,
     207                        );
     208                }
     209
     210                return $locks;
     211        }
    162212}
  • author-or-user-image/trunk/includes/class-migration.php

    r3796032 r3823635  
    3838         */
    3939        public function maybe_migrate() {
    40                 if ( get_option( self::RELEASE_FAILED_OPTION ) ) {
     40                if ( $this->has_release_failure() ) {
    4141                        try {
    4242                                if ( null === $this->store->read_value( 0, '', 'zmai_avatar_lock_migration' ) ) {
    … …  
    5656                        }
    5757                );
     58        }
     59
     60        /**
     61         * Authoritatively check whether an interrupted migration lock release requires recovery.
     62         *
     63         * @return bool
     64         */
     65        public function has_release_failure() {
     66                try {
     67                        return (bool) $this->store->read_value( 0, '', self::RELEASE_FAILED_OPTION );
     68                } catch ( \Throwable $error ) {
     69                        return (bool) get_option( self::RELEASE_FAILED_OPTION );
     70                }
    5871        }
    5972
    … …  
    502515         */
    503516        public function migration_notice() {
    504                 if ( current_user_can( 'manage_options' ) && get_option( self::RELEASE_FAILED_OPTION ) ) {
     517                if ( current_user_can( 'manage_options' ) && $this->has_release_failure() ) {
    505518                        echo '<div class="notice notice-error"><p>' . esc_html__( 'Author or User Image: a legacy migration lock could not be released. Ask for administrator recovery before retrying migration. See the lifecycle recovery guide.', 'author-or-user-image' ) . '</p></div>';
    506519                }
    … …  
    514527         */
    515528        private function report_error( WP_Error $error ) {
    516                 // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Persistent migration/release failures need an operator-visible diagnostic; no values or paths are logged.
    517                 error_log( 'Author or User Image: legacy migration storage or lock-release failure.' );
     529                if ( function_exists( 'error_log' ) ) {
     530                        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Persistent migration/release failures need an operator-visible diagnostic; no values or paths are logged.
     531                        error_log( 'Author or User Image: legacy migration storage or lock-release failure.' );
     532                }
    518533                do_action( 'zmai_migration_error', $error );
    519534        }
    … …  
    667682                                                return $clean;
    668683                                        }
    669                                         $id = media_handle_sideload( $file, 0, null, array( 'meta_input' => array( Image_Store::ATTACHMENT_OWNER_META => $this->store->owner_name( $user_id ) ) ) );
     684                                        $owner = $this->store->owner_name( $user_id );
     685                                        $id    = Image_Processor::with_unique_filename_file_list(
     686                                                static function () use ( $file, $owner ) {
     687                                                        return media_handle_sideload( $file, 0, null, array( 'meta_input' => array( Image_Store::ATTACHMENT_OWNER_META => $owner ) ) );
     688                                                }
     689                                        );
    670690                                } finally {
    671691                                        wp_delete_file( $temporary );
  • author-or-user-image/trunk/includes/class-plugin.php

    r3796032 r3823635  
    8686                if ( is_admin() ) {
    8787                        new Admin( $this->store );
     88                        if ( ! is_network_admin() && ! is_user_admin() ) {
     89                                new Profile_Admin( $this->store );
     90                        }
    8891                        ( new Import_Admin( $this->migration ) )->register();
    8992                        add_action( 'admin_init', array( $this, 'maybe_migrate' ) );
    … …  
    9396                new Front_End( $this->store );
    9497                new Privacy( $this->store, $this->cleanup );
     98                new REST_API( $this->store );
     99
     100                if ( defined( 'WP_CLI' ) && WP_CLI ) {
     101                        CLI::register( $this->store, $this->migration );
     102                }
    95103        }
    96104
    … …  
    219227        public function finish_user_deletion( $user_id ) {
    220228                $result = $this->cleanup->finish_user_deletion( $user_id );
    221                 if ( is_wp_error( $result ) ) {
     229                if ( is_wp_error( $result ) && function_exists( 'error_log' ) ) {
    222230                        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Core already deleted the user; retain the fence for recovery without aborting bulk deletion.
    223231                        error_log( 'Author or User Image: deletion fence release failed; administrator recovery required.' );
  • author-or-user-image/trunk/includes/class-user-cleanup.php

    r3796032 r3823635  
    239239                        $released = $this->store->get_lock()->release_lock( $lock );
    240240                        unset( $this->deleting_users[ $key ] );
    241                         if ( is_wp_error( $released ) ) {
     241                        if ( is_wp_error( $released ) && function_exists( 'error_log' ) ) {
    242242                                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Shutdown cannot return an error to core; log a fixed diagnostic without tokens or user data.
    243243                                error_log( 'Author or User Image: deletion fence release failed; administrator recovery required.' );
  • author-or-user-image/trunk/readme.txt

    r3796032 r3823635  
    55Tested up to: 7.1
    66Requires PHP: 7.4
    7 Stable tag: 3.1.0
     7Stable tag: 3.2.0
    88License: GPL-2.0-or-later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    1717Features include:
    1818
    19 * Self-service avatar upload and removal for registered users.
    20 * An Avatar upload block and `[author_or_user_image_upload]` shortcode that let signed-in visitors change their own avatar on a page.
     19* Self-service avatar upload and removal for registered users (`Users > Author or User Image` and standard WordPress Profile / Edit User screens).
     20* An Avatar upload block and `[author_or_user_image_upload]` shortcode with configurable preview visibility, preview size, alignment, and labels for signed-in visitors.
    2121* An upload setting that allows all users who can read, or only selected roles, on each site.
    2222* Center-square avatars for new uploads, with the original image kept uncropped.
    2323* An optional default avatar for registered users without a personal image.
    24 * Administrator controls to remove images or block individual users from local avatar uploads.
    25 * An importer for avatars from Simple Local Avatars, One User Avatar, WP User Avatar, WP User Avatars, and User Profile Picture / Metronet.
     24* Administrator controls to manage or block individual users on Edit User and `Users > Avatar Management`, plus read-only lifecycle lock diagnostics under Settings.
     25* A WordPress REST API (`author-or-user-image/v1`) for authenticated avatar, block-list, bulk, and settings management.
     26* An importer for avatars from Simple Local Avatars, One User Avatar, WP User Avatar, WP User Avatars, and User Profile Picture / Metronet, available in admin and via WP-CLI (`wp zmai import`).
    2627* Media Library storage and WordPress-generated image sizes.
    2728* Personal-data export and erasure integration.
    … …  
    34351. Upload the plugin files to `/wp-content/plugins/author-or-user-image`, or install the plugin through the Plugins screen.
    35362. Activate **Author or User Image**.
    36 3. Open **Users > Author or User Image** to upload your avatar.
    37 4. Administrators can set the site default on that page and manage user images under **Users > Avatar Management**.
     373. Open **Users > Author or User Image** or your WordPress **Profile** screen to upload your avatar.
     384. Administrators can set the site default on **Users > Author or User Image**, manage users under **Users > Avatar Management** or **Edit User**, and inspect lifecycle lock status under **Users > Avatar Management > Settings**.
    38395. To let signed-in visitors upload from a page, add the **Avatar upload** block, or use the `[author_or_user_image_upload]` shortcode on a Classic Editor page.
    39 6. Administrators can import avatars from an older avatar plugin under **Users > Avatar Management > Avatar Migration**.
     406. Administrators can import avatars from an older avatar plugin under **Users > Avatar Management > Avatar Migration** or via WP-CLI (`wp zmai import`).
    4041
    4142== Frequently Asked Questions ==
    … …  
    7879Unchecking every role turns off self-service uploads. Existing avatars stay visible, and users can still remove their own. A user with several roles qualifies if any checked role matches. A deleted role stops matching, and a role created later with the same slug matches again. Roles created after you save the list are not included until you check them.
    7980
    80 An individual block still stops that user from uploading, whatever their role. Only administrators can change the default image or manage other users.
     81An individual block still stops that user from uploading, whatever their role. Only administrators can change the default image or manage other users. On multisite, the Profile screen and REST API self-service endpoints always require membership on that site, while the **All users who can read** setting preserves WordPress's standard `read` capability rule on the dashboard and front-end form.
    8182
    8283= Is there an upload rate limit? =
    8384
    84 Each user can make five authorized self-upload attempts per minute and twenty per hour, shared between the dashboard and front-end form on the same site. Multisite counters are per site, so a member of several sites has a separate allowance on each. Failed image attempts count too. Removal, privacy erasure, administrator moderation, imports and site-default changes do not use this counter.
     85Each user can make five authorized self-upload attempts per minute and twenty per hour, shared across the dashboard, Profile screen, front-end form, and REST API on the same site. Multisite counters are per site, so a member of several sites has a separate allowance on each. Failed image attempts count too. Removal, privacy erasure, administrator moderation, imports and site-default changes do not use this counter.
    8586
    8687= How do I add an upload form to a page? =
    … …  
    8889Insert the **Avatar upload** block in the block editor. On a Classic Editor page, use the `[author_or_user_image_upload]` shortcode instead.
    8990
    90 The form changes only the signed-in visitor's own avatar. Neither the block nor the shortcode accepts attributes that choose a user, an attachment, a source URL, or the default avatar. Logged-out visitors see a log-in link. Blocked users, and users the upload setting excludes, see the reason instead of the form. The form posts directly to WordPress, so uploads and removals work with JavaScript turned off.
     91The form changes only the signed-in visitor's own avatar. Presentation options (`showPreview`, `previewSize`, `alignment`, and button or link labels) are supported, while attributes that choose a user, an attachment, a source URL, or the default avatar are ignored. Logged-out visitors see a log-in link. Blocked users, and users the upload setting excludes, see the reason instead of the form. The form posts directly to WordPress, so uploads and removals work with JavaScript turned off.
    9192
    9293Place the block or shortcode as standalone content. Nesting it inside another form is not supported, and some themes nest content that way.
    … …  
    130131= How do I import avatars from another plugin? =
    131132
    132 Open **Users > Avatar Management > Avatar Migration** and use the import action for the detected source plugin. The tab is always available. A separate **Users > Avatar Migration** menu appears when a supported plugin or saved avatar data is detected, or an unfinished import needs attention. No source selector is needed. Only an administrator can run an import. Competitor imports start only from this screen. The automatic migration of this plugin's older data remains separate. The import runs in pages and reports counts, errors, and completion. Stop pauses the import, and Resume continues it. Closing the page stops further batches, so reopen the page and choose Continue or Resume.
     133Open **Users > Avatar Management > Avatar Migration** and use the import action for the detected source plugin. The tab is always available. A separate **Users > Avatar Migration** menu appears when a supported plugin or saved avatar data is detected, or an unfinished import needs attention. No source selector is needed. Only an administrator can run an import. Competitor imports start only from this screen or via WP-CLI (`wp zmai import`). The automatic migration of this plugin's older data remains separate. The import runs in pages and reports counts, errors, and completion. Stop pauses the import, and Resume continues it. Closing the page stops further batches, so reopen the page and choose Continue or Resume.
    133134
    134135A user who already has an imported avatar is skipped by later runs, so the first source imported for that user wins. A user who removes an avatar stays without one, and removal blocks any later re-import for that user.
    … …  
    169170== Upgrade Notice ==
    170171
     172= 3.2.0 =
     173
     174Adds Profile and Edit User screen avatar management, REST API (`author-or-user-image/v1`), configurable Avatar upload block/shortcode display attributes, WP-CLI importer and lock recovery commands, and read-only lock diagnostics.
     175
    171176= 3.1.0 =
    172177
    … …  
    182187
    183188== Changelog ==
     189
     190= 3.2.0 =
     191
     192* Added WordPress Profile and Edit User (`profile.php` / `user-edit.php`) avatar upload, removal, and administrator block controls.
     193* Added a site-scoped REST API under `author-or-user-image/v1` (`/avatars`, `/avatars/{user_id}`, `/default`, `/blocked`, `/blocked/{user_id}`, `/bulk`, and `/settings`) enforcing capabilities, upload policy, rate limits, and metadata stripping.
     194* Added presentation-only attributes (`showPreview`, `previewSize`, `alignment`, `uploadLabel`, `removeLabel`, `loginLabel`) and inspector controls to the Avatar upload block and `[author_or_user_image_upload]` shortcode.
     195* Added WP-CLI commands (`wp zmai import sources|status|run|pause|resume|retry|finish` and `wp zmai locks list|unlock`) for batch competitor imports and exact-token lock recovery.
     196* Added read-only lifecycle lock diagnostics under **Users > Avatar Management > Settings** without exposing lock tokens in the admin screen.
     197* Hardened directory listing, regular-file checks, upload-size checks, and error logging for hosts that disable PHP functions such as scandir, lstat, ini_get, and error_log.
    184198
    185199= 3.1.0 =
Note: See TracChangeset for help on using the changeset viewer.