Plugin Directory

Changeset 3253191


Ignore:
Timestamp:
03/10/2025 09:25:50 AM (13 months ago)
Author:
lwsdevelopers
Message:

New attributes for wr_available_coupons shortcode. Admin page role management.

Location:
woorewards/trunk
Files:
1 added
10 edited

Legend:

Unmodified
Added
Removed
  • woorewards/trunk/assets/lws-adminpanel/include/pages/field/input.php

    r3188612 r3253191  
    4444        $others = $this->getDomAttributes();
    4545
    46         return "<input name='$name' value='$value'$attrs{$others}$id$size>";
     46        $datalist = '';
     47        if (isset($this->extra['datalist']) && $this->extra['datalist']) {
     48            if (!($this->extra['list_id'] ?? false)) {
     49                static $unicifier = 0;
     50                $this->extra['list_id'] = \md5(\serialize($this->extra['datalist'])) . '_' . ($unicifier++);
     51            }
     52            if (\is_array($this->extra['datalist'])) {
     53                $datalist = sprintf('<datalist id="%s">', \esc_attr($this->extra['list_id']));
     54                foreach ($this->extra['datalist'] as $label) {
     55                    $datalist .= sprintf('<option value="%s"%s>', \esc_attr((string)$label), $value === $label ? ' selected' : '');
     56                }
     57                $datalist .= '</datalist>';
     58            } else {
     59                $datalist = $this->extra['datalist'];
     60            }
     61        }
     62        if ($this->extra['list_id'] ?? false) {
     63            $attrs .= sprintf(' list="%s"', \esc_attr($this->extra['list_id']));
     64        }
     65
     66        return "<input name='$name' value='$value'$attrs{$others}$id$size>" . $datalist;
    4767    }
    4868}
  • woorewards/trunk/assets/lws-adminpanel/include/pages/head.php

    r3234695 r3253191  
    178178                'id'       => $level->getId(),
    179179                'title'    => $level->getPageTitle(),
    180                 'url'      => $level->getLink($tabPath),
     180                'url'      => \apply_filters('lws_adminpanel_breadcrums_particle_url', $level->getLink($tabPath), $level),
    181181                'siblings' => array(),
    182182            );
     
    185185                'id'       => $level['id'],
    186186                'title'    => $level['title'],
    187                 'url'      => $this->page->getLink($tabPath),
     187                'url'      => \apply_filters('lws_adminpanel_breadcrums_particle_url', $this->page->getLink($tabPath), $level),
    188188                'siblings' => array(),
    189189            );
  • woorewards/trunk/assets/lws-adminpanel/include/tools/conveniences.php

    r3234695 r3253191  
    660660            \add_action($hook, $callable, $priority);
    661661    }
     662
     663    /** @return string the associated capability if the current user role is in the given array $roles,
     664     * or fallback on $capability. */
     665    public static function getCapOnRole($capability, array $roles = ['administrator' => 'manage_options']): string
     666    {
     667        $user = \wp_get_current_user();
     668        if ($user) {
     669            if (!$roles) $roles = ['administrator' => 'manage_options'];
     670            $cross = \array_intersect_key($roles, \array_fill_keys((array)$user->roles, true));
     671            if ($cross) {
     672                return (string)\reset($cross);
     673            }
     674        }
     675        return (string)($capability ?? 'manage_options');
     676    }
     677
     678    /** @param $roles array of array [role => [capability]] */
     679    public static function updateRolesCapabilities(array $roles)
     680    {
     681        foreach ($roles as $slug => $caps) {
     682            $role = \get_role($slug);
     683            if (!$role) continue;
     684            foreach ($caps as $cap) {
     685                if (!$role->has_cap($cap)) $role->add_cap($cap);
     686            }
     687        }
     688    }
    662689}
  • woorewards/trunk/assets/lws-adminpanel/include/tools/request.php

    r3234695 r3253191  
    287287        }
    288288
    289         $ret = $wpdb->query($sql); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPressDotOrg.sniffs.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.NotPrepared
    290         return $ret ? $wpdb->insert_id : false;
     289        return $wpdb->query($sql); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPressDotOrg.sniffs.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.NotPrepared
    291290    }
    292291
  • woorewards/trunk/assets/lws-adminpanel/lws-adminpanel.php

    r3234695 r3253191  
    66 * Author: Long Watch Studio
    77 * Author URI: https://longwatchstudio.com
    8  * Version: 5.5.16
     8 * Version: 5.5.18
    99 * Text Domain: lws-adminpanel
    1010 *
     
    5858
    5959add_filter('lws_adminpanel_versions', function($versions){
    60     $versions['5.5.16'] = __FILE__;
     60    $versions['5.5.18'] = __FILE__;
    6161    return $versions;
    6262});
  • woorewards/trunk/include/conveniencies.php

    r3227529 r3253191  
    6969
    7070    /* Get Available WooCommerce coupons for the provided user */
    71     public function getCoupons($userId)
     71    public function getCoupons($userId, $where=false)
    7272    {
    7373        $user = \get_user_by('ID', $userId);
    74         if (empty($user->user_email))
    75             return array();
    76         $todayDate = strtotime(date('Y-m-d'));
     74        if (!$user->user_email) return [];
     75
    7776        global $wpdb;
    78         $query = <<<EOT
    79             SELECT p.ID, p.post_content, p.post_title, p.post_excerpt, e.meta_value AS expiry_date
    80             FROM {$wpdb->posts} as p
    81             INNER JOIN {$wpdb->postmeta} as m ON p.ID = m.post_id AND m.meta_key='customer_email'
    82             LEFT JOIN {$wpdb->postmeta} as l ON p.ID = l.post_id AND l.meta_key='usage_limit'
    83             LEFT JOIN {$wpdb->postmeta} as u ON p.ID = u.post_id AND u.meta_key='usage_count'
    84             LEFT JOIN {$wpdb->postmeta} as e ON p.ID = e.post_id AND e.meta_key='date_expires'
    85             WHERE m.meta_value=%s AND post_type = 'shop_coupon' AND post_status = 'publish'
    86             AND (e.meta_value is NULL OR e.meta_value = '' OR e.meta_value >= '{$todayDate}')
    87             AND (u.meta_value < l.meta_value OR u.meta_value IS NULL OR l.meta_value IS NULL OR l.meta_value=0)
    88 EOT;
    89         $result = $wpdb->get_results($wpdb->prepare($query, serialize(array($user->user_email))), OBJECT_K);
    90         if (empty($result))
    91             return $result;
     77        $query = \LWS\Adminpanel\Tools\Request::from($wpdb->posts, 'p');
     78        $query->select(['p.ID', 'p.post_content', 'p.post_title', 'p.post_excerpt', 'MAX(e.meta_value) AS expiry_date']);
     79        $query->group('p.ID');
     80        $query->innerJoin($wpdb->postmeta, 'm', ["p.ID = m.post_id AND m.meta_key='customer_email'"]);
     81        $query->leftJoin($wpdb->postmeta, 'l', ["l.post_id = m.post_id AND l.meta_key='usage_limit'"]);
     82        $query->leftJoin($wpdb->postmeta, 'u', ["u.post_id = m.post_id AND u.meta_key='usage_count'"]);
     83        $query->leftJoin($wpdb->postmeta, 'e', ["e.post_id = m.post_id AND e.meta_key='date_expires'"]);
     84        $query->where([
     85            "m.meta_value = %s",
     86            "post_type = 'shop_coupon'",
     87            "post_status = 'publish'",
     88            "(e.meta_value is NULL OR e.meta_value = '' OR e.meta_value >= %s)",
     89            "(u.meta_value < l.meta_value OR u.meta_value IS NULL OR l.meta_value IS NULL OR l.meta_value=0)",
     90        ]);
     91        $query->arg(\serialize([$user->user_email]));
     92        $query->arg(\strtotime(\date('Y-m-d')));
     93        if ($where) {
     94            $query->where($where);
     95        }
     96
     97        $result = $query->getResults(OBJECT_K);
     98        if (!$result) return [];
    9299
    93100        $ids = implode(",", array_map('intval', array_keys($result)));
  • woorewards/trunk/include/ui/admin.php

    r3188612 r3253191  
    174174            'title'     => __("MyRewards", 'woorewards-lite'),
    175175            'id'          => LWS_WOOREWARDS_PAGE,
    176             'rights'    => 'manage_rewards',
     176            'rights'    => \LWS\Adminpanel\Tools\Conveniences::getCapOnRole('manage_rewards'),
    177177            'dashicons' => '',
    178178            'index'     => 57,
     
    207207            'title'    => __("Customers", 'woorewards-lite'),
    208208            'id'       => LWS_WOOREWARDS_PAGE . '.customers',
    209             'rights'   => 'manage_rewards',
     209            'rights'   => \LWS\Adminpanel\Tools\Conveniences::getCapOnRole('manage_rewards'),
    210210            'color'    => '#A8CE38',
    211211            'image'     => LWS_WOOREWARDS_IMG . '/r-customers.png',
     
    237237        return array(
    238238            'title'    => __("Settings", 'woorewards-lite'),
    239             'rights'   => 'manage_rewards',
     239            'rights'   => \LWS\Adminpanel\Tools\Conveniences::getCapOnRole('manage_rewards'),
    240240            'id'       => LWS_WOOREWARDS_PAGE . '.loyalty',
    241241            'color'    => '#526981',
     
    265265            'subtitle' => __("Wizard", 'woorewards-lite'),
    266266            'id'       => LWS_WIZARD_SUMMONER . LWS_WOOREWARDS_PAGE,
    267             'rights'   => 'manage_rewards',
     267            'rights'   => \LWS\Adminpanel\Tools\Conveniences::getCapOnRole('manage_rewards'),
    268268            'color'    => '#00B7EB',
    269269            'image'    => LWS_WOOREWARDS_IMG . '/r-wizard.png',
     
    445445            'subtitle' => __("Appearance", 'woorewards-lite'),
    446446            'id'       => LWS_WOOREWARDS_PAGE . '.appearance',
    447             'rights'   => 'manage_rewards',
    448             'color'         => '#4CBB41',
    449             'image'         => LWS_WOOREWARDS_IMG . '/r-appearance.png',
     447            'rights'   => \LWS\Adminpanel\Tools\Conveniences::getCapOnRole('manage_rewards'),
     448            'color'    => '#4CBB41',
     449            'image'    => LWS_WOOREWARDS_IMG . '/r-appearance.png',
    450450            'description'   => __("Use this page to display loyalty content to your customers on your website", 'woorewards-lite'),
    451451            'tabs'     => array(
     
    474474            'subtitle'      => __("System", 'woorewards-lite'),
    475475            'id'            => LWS_WOOREWARDS_PAGE . '.system',
    476             'rights'        => 'manage_rewards',
    477             'color'         => '#7958A5',
    478             'image'         => LWS_WOOREWARDS_IMG . '/r-system.png',
     476            'rights'        => \LWS\Adminpanel\Tools\Conveniences::getCapOnRole('manage_rewards'),
     477            'color'       => '#7958A5',
     478            'image'       => LWS_WOOREWARDS_IMG . '/r-system.png',
    479479            'description'   => __("Export or import your customers points, process past orders in this page", 'woorewards-lite'),
    480480            'delayedFunction' => array($this, 'showCronStatus'),
     
    630630            'pagetitle' => __("Pro Version", 'woorewards-lite'),
    631631            'id'        => LWS_WOOREWARDS_PAGE . '-proversion',
    632             'rights'    => 'manage_options',
    633             'color'     => '#4f9bbf',
    634             'nosave'    => true,
    635             'image'     => LWS_WOOREWARDS_IMG . '/r-pro.png',
     632            'rights'    => \LWS\Adminpanel\Tools\Conveniences::getCapOnRole('manage_rewards'),
     633            'color'     => '#4f9bbf',
     634            'nosave'    => true,
     635            'image'     => LWS_WOOREWARDS_IMG . '/r-pro.png',
    636636            'description' => __("Unlock this plugin's full potential by switching to the pro version. Check all the features and discover how to install it", 'woorewards-lite'),
    637637        );
  • woorewards/trunk/include/ui/shortcodes/availablecoupons.php

    r3188612 r3253191  
    88class AvailableCoupons
    99{
     10    CONST SLUG = 'wr_available_coupons';
    1011
    1112    static function install()
     
    1314        $me = new self();
    1415        /** Shortcode */
    15         \add_shortcode('wr_available_coupons', array($me, 'shortcode'));
     16        \add_shortcode(self::SLUG, array($me, 'shortcode'));
    1617        /** Admin */
    1718        \add_filter('lws_woorewards_shortcodes', array($me, 'admin'));
     
    9596                        'desc' => __("(Optional) Override the expiration label if any. Use the <b>%s</b> placeholder for the date. You can set an empty string to display nothing.", 'woorewards-lite'),
    9697                        'example' => '[wr_available_coupons expire-html=" (Expires on %s)"]'
     98                    ),
     99                    array(
     100                        'option' => 'in-the-last',
     101                        'desc' => [
     102                            __("(Optional) Show only coupons created in the last given period.", 'woorewards-lite'),
     103                            __("A period is defined by a number and a duration unit.", 'woorewards-lite'),
     104                            __("Accepted units are:", 'woorewards-lite'), ['tag' => 'ul',
     105                                ['D', __("for Days", 'woorewards-lite')],
     106                                ['W', __("for Weeks", 'woorewards-lite')],
     107                                ['M', __("for Months", 'woorewards-lite')],
     108                                ['Y', __("for Years", 'woorewards-lite')],
     109                            ],
     110                        ],
     111                        'example' => '[wr_available_coupons in-the-last="1M"]'
     112                    ),
     113                    array(
     114                        'option' => 'reset-day',
     115                        'desc' => [
     116                            sprintf(__("(Optional) Works with %s attribute to build an incremental period instead the default shift date.", 'woorewards-lite'), '`<i>in-the-last</i>`'),
     117                            __("Expect the day of the month the period should reset within the original rolling period.", 'woorewards-lite'),
     118                            __("The value is automatically clamped to the last day of the month if necessary.", 'woorewards-lite'),
     119                        ],
     120                        'example' => '[wr_available_coupons in-the-last="1Y" reset-day="1"]'
    97121                    ),
    98122                ),
     
    129153            return '';
    130154        }
    131         if (!$userId = \get_current_user_id()) {
     155        $userId = \apply_filters('lws_woorewards_shortcode_current_user_id', \get_current_user_id(), $atts, self::SLUG);
     156        if (!$userId) {
    132157            return \do_shortcode((string)$content);
    133158        }
    134         if (empty($data = \LWS\WOOREWARDS\Conveniences::instance()->getCoupons($userId))) {
    135             return \do_shortcode((string)$content);
    136         }
     159
    137160        $atts = \LWS\Adminpanel\Tools\Conveniences::sanitizeAttr(\wp_parse_args($atts, array(
    138161            'buttons'   => false,
     
    141164            'element'   => 'line',
    142165            'expire-html' => false,
     166            'in-the-last' => false,
     167            'min-date'    => false,
     168            'reset-day'   => false,
    143169        )));
     170        $where = $this->checkDateFilters($atts);
     171
     172        $data = \LWS\WOOREWARDS\Conveniences::instance()->getCoupons($userId, $where);
     173        if (!$data) {
     174            return \do_shortcode((string)$content);
     175        }
     176
    144177        $this->enqueueScripts();
    145178        return $this->getContent($atts, $data);
     179    }
     180
     181    /** merge $atts to set a 'reset-date' entry to filter coupon by min creation date.
     182     * @param $atts array inout
     183     * @return array sql where filter @see \LWS\WOOREWARDS\Conveniences\getCoupons */
     184    private function checkDateFilters(array &$atts): array
     185    {
     186        if ($atts['min-date']) {
     187            $atts['min-date'] = \date_create_immutable($atts['min-date'], \wp_timezone());
     188        }
     189
     190        if ($atts['in-the-last']) {
     191            $atts['reset-day'] = (int)$atts['reset-day'];
     192
     193            // test a valid format
     194            $pattern = '/(\d+)\s*([ymdw])/i';
     195            if (\preg_match_all($pattern, $atts['in-the-last'], $matches, PREG_SET_ORDER)) {
     196                $period = ['_' =>'P'];
     197                foreach ($matches as $match) {
     198                    $u = \strtoupper($match[2]);
     199                    $period[$u] = $match[1] . $u;
     200                }
     201
     202                $interval = new \DateInterval(\implode('', $period));
     203                $date = \date_create_immutable('now', \wp_timezone())->sub($interval);
     204
     205                if ($atts['reset-day']) {
     206                    $coming = \LWS\Adminpanel\Tools\Dates::replace($date, ['day' => $atts['reset-day']]);
     207                    if ($coming->setTime(0, 0) < $date->setTime(0, 0)) {
     208                        $coming = \LWS\Adminpanel\Tools\Dates::addMonths($coming, 1, $atts['reset-day']);
     209                    }
     210                    $atts['min-date'] = $coming;
     211                } else {
     212                    $atts['min-date'] = $date;
     213                }
     214            } else {
     215                $atts['in-the-last'] = false;
     216            }
     217        }
     218
     219        if ($atts['min-date']) {
     220            return [
     221                sprintf(
     222                    "p.post_date_gmt >= '%s'",
     223                    $atts['min-date']->setTime(0, 0)->setTimezone(new \DateTimeZone('UTC'))->format('Y-m-d H:i:s')
     224                ),
     225            ];
     226        } else {
     227            return [];
     228        }
    146229    }
    147230
  • woorewards/trunk/readme.txt

    r3234695 r3253191  
    55Tested up to: 6.7
    66Requires PHP: 7.0.0
    7 Stable tag: 5.4.8
     7Stable tag: 5.4.9
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
     
    110110== Changelog ==
    111111
    112 = 5.4.8 ==
     112= 5.4.9 =
     113* Tag - WooCommerce 9.7
     114* Feature - new attributes for wr_available_coupons shortcode
     115
     116= 5.4.8 =
    113117* MyRewards Pro :
    114118    * Fix - single free product reward with WC new cart bloc
    115119
    116 = 5.4.7 ==
     120= 5.4.7 =
    117121* Tag - WooCommerce 9.6
    118122* Update - translations
     
    121125    * Feature - new attributes for wr_available_rewards shortcode
    122126
    123 = 5.4.6 ==
     127= 5.4.6 =
    124128* Fix - WordPress 6.7 Delay translation time
    125129
  • woorewards/trunk/woorewards.php

    r3234695 r3253191  
    77 * Author: Long Watch Studio
    88 * Author URI: https://longwatchstudio.com
    9  * Version: 5.4.8
     9 * Version: 5.4.9
    1010 * License: Copyright LongWatchStudio 2022
    1111 * Text Domain: woorewards-lite
    1212 * Domain Path: /languages
    1313 * WC requires at least: 7.1.0
    14  * WC tested up to: 9.6
     14 * WC tested up to: 9.7
    1515 *
    1616 * Copyright (c) 2022 Long Watch Studio (email: plugins@longwatchstudio.com). All rights reserved.
     
    111111    private function defineConstants()
    112112    {
    113         define('LWS_WOOREWARDS_VERSION', '5.4.8');
     113        define('LWS_WOOREWARDS_VERSION', '5.4.9');
    114114        define('LWS_WOOREWARDS_FILE', __FILE__);
    115115        define('LWS_WOOREWARDS_DOMAIN', 'woorewards-lite');
     
    149149    public function addPluginVersion($url)
    150150    {
    151         return '5.4.8';
     151        return '5.4.9';
    152152    }
    153153
Note: See TracChangeset for help on using the changeset viewer.