Plugin Directory

Changeset 2250855


Ignore:
Timestamp:
02/26/2020 06:47:42 PM (6 years ago)
Author:
casepress
Message:

update 6.1

Location:
wooms/trunk
Files:
8 added
6 edited

Legend:

Unmodified
Added
Removed
  • wooms/trunk/functions.php

    r2226078 r2250855  
    107107      return $url;
    108108  }
    109  
    110   /**
    111    * Download Image by URL and retrun att id or false or WP_Error
    112    *
    113    * @param [type] $url_api
    114    * @param [type] $file_name
    115    * @param [type] $post_id
    116    * @return void
    117    */
    118   function download_img($url_api, $file_name, $post_id)
    119   {
    120 
    121     if ($check_id = check_exist_image_by_url($url_api)) {
    122       return $check_id;
    123     }
    124 
    125     if (!function_exists('curl_init')) {
    126       do_action(
    127         'wooms_logger_error',
    128         __CLASS__,
    129         'Не удалось обнаружить curl_init. Нужно настроить curl на сервера.'
    130       );
    131       return false;
    132     }
    133 
    134     if (!function_exists('wp_read_image_metadata')) {
    135       require_once ABSPATH . '/wp-admin/includes/image.php';
    136       require_once ABSPATH . 'wp-admin/includes/file.php';
    137     }
    138 
    139     $header_array = [
    140       'Authorization' => 'Basic ' . base64_encode(get_option('woomss_login') . ':' . get_option('woomss_pass')),
    141     ];
    142 
    143     $headers = array();
    144     foreach ($header_array as $name => $value) {
    145       $headers[] = "{$name}: $value";
    146     }
    147 
    148     $ch = \curl_init();
    149     curl_setopt($ch, CURLOPT_URL, $url_api);
    150     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    151     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    152     curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    153     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    154 
    155     // Checking operation system if windows add needed parameter or it will not work
    156     //If PHP_SHLIB_SUFFIX is equal to "dll",
    157     //then PHP is running on a Windows operating system.
    158     if(strtolower(PHP_SHLIB_SUFFIX) === 'dll'){
    159       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    160     }
    161 
    162     $output = curl_exec($ch);
    163     $info   = curl_getinfo($ch); // Получим информацию об операции
    164     curl_close($ch);
    165 
    166     $file_name = sanitize_file_name($file_name);
    167     $tmpfname = wp_tempnam($file_name);
    168     $fh       = fopen($tmpfname, 'w');
    169 
    170     fwrite($fh, $output);
    171 
    172     fclose($fh);
    173 
    174     $filetype = wp_check_filetype($file_name);
    175 
    176     // Array based on $_FILE as seen in PHP file uploads.
    177     $file_args = array(
    178       'name'     => $file_name, // ex: wp-header-logo.png
    179       'type'     => $filetype['type'], //todo do right
    180       'tmp_name' => $tmpfname,
    181       'error'    => 0,
    182       'size'     => filesize($tmpfname),
    183     );
    184 
    185     $overrides = array(
    186       'test_form'   => false,
    187       'test_size'   => false,
    188       'test_upload' => false,
    189     );
    190 
    191     $file_data = wp_handle_sideload($file_args, $overrides);
    192 
    193     // If error storing permanently, unlink.
    194     if (is_wp_error($file_data)) {
    195       @unlink($tmpfname);
    196       do_action(
    197         'wooms_logger_error',
    198         __CLASS__,
    199         'Загрузка картинки - не удалось получить файл',
    200         sprintf('Данные %s', PHP_EOL . print_r($file_data, true))
    201       );
    202 
    203       return false;
    204     }
    205 
    206     if (empty($file_data['url'])) {
    207       do_action(
    208         'wooms_logger_error',
    209         __CLASS__,
    210         'Загрузка картинки - не удалось получить URL',
    211         sprintf('Данные %s', PHP_EOL . print_r($file_data, true))
    212       );
    213       @unlink($tmpfname);
    214 
    215       return false;
    216     }
    217 
    218     $url     = $file_data['url'];
    219     $type    = $file_data['type'];
    220     $file    = $file_data['file'];
    221     $title   = preg_replace('/\.[^.]+$/', '', basename($file));
    222     $content = '';
    223 
    224     // Use image exif/iptc data for title and caption defaults if possible.
    225     if ($image_meta = \wp_read_image_metadata($file)) {
    226       if (trim($image_meta['title']) && !is_numeric(sanitize_title($image_meta['title']))) {
    227         $title = $image_meta['title'];
    228       }
    229       if (trim($image_meta['caption'])) {
    230         $content = $image_meta['caption'];
    231       }
    232     }
    233 
    234     if (isset($desc)) {
    235       $title = $desc;
    236     }
    237 
    238     // Construct the attachment array.
    239     $attachment = array(
    240       'post_mime_type' => $type,
    241       'guid'           => $url,
    242       'post_parent'    => $post_id,
    243       'post_title'     => $title,
    244       'post_content'   => $content,
    245     );
    246 
    247     // This should never be set as it would then overwrite an existing attachment.
    248     unset($attachment['ID']);
    249 
    250     // Save the attachment metadata
    251     $id = wp_insert_attachment($attachment, $file, $post_id);
    252     if (!is_wp_error($id)) {
    253       wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $file));
    254     } else {
    255       return false;
    256     }
    257 
    258     @unlink($tmpfname);
    259 
    260     update_post_meta($id, 'wooms_url', $url_api);
    261 
    262     return $id;
    263   }
    264 
    265   /**
    266    * Check exist image by URL
    267    *
    268    * @param [type] $url_api
    269    * @return void
    270    */
    271   function check_exist_image_by_url($url_api)
    272   {
    273     $posts = get_posts('post_type=attachment&meta_key=wooms_url&meta_value=' . $url_api);
    274 
    275     if (empty($posts)) {
    276       return false;
    277     } else {
    278       return $posts[0]->ID;
    279     }
    280   }
  • wooms/trunk/inc/MSImagesTrait.php

    r2226078 r2250855  
    1717    public static function uploadRemoteImageAndAttach($image_url, $product_id, $filename = 'image.jpg')
    1818    {
     19        if ($check_id = self::check_exist_image_by_url($image_url)) {
     20            return $check_id;
     21        }
    1922
    2023        $uploads_dir = wp_upload_dir();
     
    7174        $attach_data = wp_generate_attachment_metadata($attach_id, $mirror['file']);
    7275
    73         var_dump($attach_data);
     76        update_post_meta($attach_id, 'wooms_url', $image_url);
    7477
    7578        wp_update_attachment_metadata($attach_id, $attach_data);
    7679
     80        do_action(
     81            'wooms_logger',
     82            __CLASS__,
     83            sprintf('Image is downloaded %s (ИД %s, filename: %s)', $product_id, $attach_id, $filename)
     84          );
     85
    7786        return $attach_id;
    7887    }
     88
     89
     90    /**
     91     * Check exist image by URL
     92     */
     93    public static function check_exist_image_by_url($url_api)
     94    {
     95        $posts = get_posts('post_type=attachment&meta_key=wooms_url&meta_value=' . $url_api);
     96        if (empty($posts)) {
     97            return false;
     98        } else {
     99
     100            do_action(
     101                'wooms_logger',
     102                __CLASS__,
     103                sprintf('We have such image (%s) already', $posts[0]->ID)
     104              );
     105
     106            return $posts[0]->ID;
     107        }
     108    }
    79109}
  • wooms/trunk/inc/ProductGallery.php

    r2226078 r2250855  
    2121  {
    2222
    23     add_filter('wooms_product_save', array(__CLASS__, 'update_product'), 40, 3);
    24 
    25     add_action('admin_init', array(__CLASS__, 'settings_init'), 70);
    26 
    27     add_filter('cron_schedules', array(__CLASS__, 'add_schedule'));
    28 
    29     add_action('init', array(__CLASS__, 'add_cron_hook'));
    30 
    31     add_action('wooms_cron_image_downloads', array(__CLASS__, 'download_images_from_metafield'));
    32 
    33     // add_action('init', function(){
    34     //   if( ! isset($_GET['ee']) ) {
    35     //     return;
    36     //   }
    37 
    38     //   self::download_images_by_id(126);
    39 
    40     //   exit;
    41     // });
     23    add_filter('wooms_product_save', [__CLASS__, 'update_product'], 40, 3);
     24
     25    add_action('admin_init', [__CLASS__, 'settings_init'], 70);
     26
     27    add_action('init', [__CLASS__, 'add_schedule_hook']);
     28
     29    add_action('gallery_images_download_schedule', [__CLASS__, 'download_images_from_metafield']);
     30
    4231  }
    4332
     
    6756
    6857    //Check image
    69     if (empty($data_api['rows']) || count($data_api['rows']) == 1 ) {
     58    if (empty($data_api['rows']) || count($data_api['rows']) == 1) {
    7059      return false;
    7160    }
     
    9382
    9483  /**
    95    * Setup cron
    96    *
    97    * @param $schedules
     84   * Setup schedule
    9885   *
    9986   * @return mixed
    10087   */
    101   public static function add_schedule($schedules)
    102   {
    103 
    104     $schedules['wooms_cron_worker_images'] = array(
    105       'interval' => 60,
    106       'display'  => 'WooMS Cron Load Images 60 sec',
    107     );
    108 
    109     return $schedules;
    110   }
    111 
    112   /**
    113    * Init Cron
    114    */
    115   public static function add_cron_hook()
     88  public static function add_schedule_hook()
    11689  {
    11790
     
    12093    }
    12194
    122     if (!wp_next_scheduled('wooms_cron_image_downloads')) {
    123       wp_schedule_event(time(), 'wooms_cron_worker_images', 'wooms_cron_image_downloads');
    124     }
    125   }
    126 
    127 
    128   /**
    129    * Action for UI
    130    */
    131   public static function ui_action()
    132   {
    133 
    134     $data = self::download_images_from_metafield();
    135 
    136     echo '<hr>';
    137 
    138     if (empty($data)) {
    139       echo '<p>Нет картинок для загрузки</p>';
    140     } else {
    141       echo "<p>Загружены миниатюры для продуктов:</p>";
    142       foreach ($data as $key => $value) {
    143         printf('<p><a href="%s">ID %s</a></p>', get_edit_post_link($value), $value);
    144       }
    145       echo "<p>Чтобы повторить загрузку - обновите страницу</p>";
    146     }
     95
     96    if (self::check_schedule_needed()) {
     97      // Adding schedule hook
     98      as_schedule_recurring_action(
     99        time(),
     100        60,
     101        'gallery_images_download_schedule',
     102        [],
     103        'ProductGallery'
     104      );
     105    }
     106
     107    if (get_transient('gallery_images_downloaded') && empty(get_transient('wooms_start_timestamp'))) {
     108
     109      as_unschedule_all_actions('gallery_images_download_schedule', [], 'ProductGallery');
     110      set_transient('gallery_images_downloaded', false);
     111    }
     112  }
     113
     114  /**
     115   * Checking if schedule can be created or not
     116   *
     117   * @return void
     118   */
     119  public static function check_schedule_needed()
     120  {
     121
     122    // If next schedule is not this one and the sync is active and the all gallery images is downloaded
     123    if (as_next_scheduled_action('gallery_images_download_schedule', [], 'ProductGallery')) {
     124      return false;
     125    }
     126
     127    // Checking if there is any of this type pending schedules
     128    $future_schedules = as_get_scheduled_actions(
     129      [
     130        'hook' => 'gallery_images_download_schedule',
     131        'status' => \ActionScheduler_Store::STATUS_PENDING,
     132        'group' => 'ProductGallery'
     133      ]
     134    );
     135
     136    if (!empty($future_schedules)) {
     137      return false;
     138    }
     139
     140    if (empty(get_transient('wooms_start_timestamp'))) {
     141      return false;
     142    }
     143
     144    if (get_transient('gallery_images_downloaded')) {
     145      return false;
     146    }
     147
     148    return true;
    147149  }
    148150
     
    176178    $list = get_posts($args);
    177179
     180    // If no images left to download
    178181    if (empty($list)) {
     182
     183      // If sync product already finished
     184      if (empty(get_transient('wooms_start_timestamp'))) {
     185
     186        // Adding the option that all images downloaded and the sync is over
     187        set_transient('gallery_images_downloaded', true);
     188
     189        do_action(
     190          'wooms_logger',
     191          __CLASS__,
     192          sprintf('All gallery images is downloaded and sync is over ')
     193        );
     194      }
     195
    179196      return false;
    180197    }
     
    214231    foreach ($img_data_list as $image_name => $url) {
    215232
     233      if ($check_id = self::check_exist_image_by_url($image_name)) {
     234        return $check_id;
     235      }
     236
    216237      $media_id = self::uploadRemoteImageAndAttach($url, $product_id, $image_name);
    217238
     
    232253        'wooms_logger',
    233254        __CLASS__,
    234         sprintf('Загружена картинка для продукта %s (ИД %s, filename: %s)', $product_id, $media_id, $image_name)
     255        sprintf('Image is attach to the product %s (Image id list [%s], filename: %s)', $product_id, implode(',', $media_data_list), $image_name)
    235256      );
    236257    } else {
     
    238259        'wooms_logger_error',
    239260        __CLASS__,
    240         sprintf('Ошибка нозначения галереи продукта %s', $product_id)
     261        sprintf('Error image attachments %s', $product_id)
    241262      );
    242263    }
  • wooms/trunk/inc/ProductImage.php

    r2226078 r2250855  
    1212class ProductImage
    1313{
    14    
     14
    1515    use MSImages;
    1616
     
    2727
    2828        //     self::download_images_from_metafield();
    29        
     29
    3030
    3131        //     die('end');
     
    3535         * Обновление данных о продукте
    3636         */
    37         add_filter('wooms_product_save', array(__CLASS__, 'update_product'), 35, 3);
    38 
    39         add_action('admin_init', array(__CLASS__, 'settings_init'), 50);
    40 
    41         add_action('init', array(__CLASS__, 'add_cron_hook'));
    42 
    43         add_action('wooms_cron_image_downloads', array(__CLASS__, 'download_images_from_metafield'));
    44 
    45         add_action('woomss_tool_actions_btns', array(__CLASS__, 'ui_for_manual_start'), 15);
    46         add_action('woomss_tool_actions_wooms_products_images_manual_start', array(__CLASS__, 'ui_action'));
     37        add_filter('wooms_product_save', [__CLASS__, 'update_product'], 35, 3);
     38
     39        add_action('admin_init', [__CLASS__, 'settings_init'], 50);
     40
     41        add_action('init', [__CLASS__, 'add_schedule_hook']);
     42
     43        add_action('main_image_download_schedule', [__CLASS__, 'download_images_from_metafield']);
     44
     45        add_action('woomss_tool_actions_btns', [__CLASS__, 'ui_for_manual_start'], 15);
     46        add_action('woomss_tool_actions_wooms_products_images_manual_start', [__CLASS__, 'ui_action']);
    4747    }
    4848
     
    7676
    7777    /**
    78      * Init Cron
    79      */
    80     public static function add_cron_hook()
     78     * Init Scheduler
     79     */
     80    public static function add_schedule_hook()
    8181    {
    8282        if (empty(get_option('woomss_images_sync_enabled'))) {
     
    8484        }
    8585
    86         if (!wp_next_scheduled('wooms_cron_image_downloads')) {
    87             wp_schedule_event(time(), 'every_minute', 'wooms_cron_image_downloads');
    88         }
     86        if (self::check_schedule_needed()) {
     87            // Adding schedule hook
     88            as_schedule_recurring_action(
     89                time(),
     90                60,
     91                'main_image_download_schedule',
     92                [],
     93                'ProductImage'
     94            );
     95        }
     96
     97        if (get_transient('main_images_downloaded') && empty(get_transient('wooms_start_timestamp'))) {
     98
     99            as_unschedule_all_actions('main_image_download_schedule', [], 'ProductImage');
     100            set_transient('main_images_downloaded', false);
     101        }
     102    }
     103
     104    /**
     105     * Checking if schedule can be created or not
     106     *
     107     * @return void
     108     */
     109    public static function check_schedule_needed()
     110    {
     111
     112        // If next schedule is not this one and the sync is active and the all gallery images is downloaded
     113        if (as_next_scheduled_action('main_image_download_schedule', [], 'ProductImage')) {
     114            return false;
     115        }
     116
     117        // Checking if there is any of this type pending schedules
     118        $future_schedules = as_get_scheduled_actions(
     119            [
     120                'hook' => 'main_image_download_schedule',
     121                'status' => \ActionScheduler_Store::STATUS_PENDING,
     122                'group' => 'ProductImage'
     123            ]
     124        );
     125
     126        if (!empty($future_schedules)) {
     127            return false;
     128        }
     129
     130        if (empty(get_transient('wooms_start_timestamp'))) {
     131            return false;
     132        }
     133
     134        if (get_transient('main_images_downloaded')) {
     135            return false;
     136        }
     137
     138        return true;
    89139    }
    90140
     
    140190
    141191        if (empty($list)) {
     192
     193            // Adding the option that all images downloaded
     194            set_transient('main_images_downloaded', true);
     195
     196            do_action(
     197                'wooms_logger',
     198                __CLASS__,
     199                sprintf('Main images is downloaded')
     200            );
     201
    142202            return false;
    143203        }
     
    195255    }
    196256
    197     /**
    198      * Download Image by URL and retrun att id or false or WP_Error
    199      */
    200     public static function download_img($url_api, $file_name, $post_id)
    201     {
    202         if ($check_id = self::check_exist_image_by_url($url_api)) {
    203             return $check_id;
    204         }
    205 
    206         if (!function_exists('curl_init')) {
    207             do_action(
    208                 'wooms_logger_error',
    209                 __CLASS__,
    210                 'Не удалось обнаружить curl_init. Нужно настроить curl на сервера.'
    211             );
    212             return false;
    213         }
    214        
    215         if (!function_exists('wp_read_image_metadata') || !function_exists('wp_tempnam')) {
    216             require_once(ABSPATH . 'wp-admin/includes/file.php');
    217             require_once(ABSPATH . 'wp-admin/includes/image.php');
    218         }
    219 
    220         $header_array = [
    221             'Authorization' => 'Basic ' . base64_encode(get_option('woomss_login') . ':' . get_option('woomss_pass')),
    222         ];
    223 
    224         $headers = array();
    225         foreach ($header_array as $name => $value) {
    226             $headers[] = "{$name}: $value";
    227         }
    228 
    229         $ch = \curl_init();
    230         curl_setopt($ch, CURLOPT_URL, $url_api);
    231         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    232         curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    233         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    234         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    235         $output = curl_exec($ch);
    236         $info   = curl_getinfo($ch); // Получим информацию об операции
    237         curl_close($ch);
    238 
    239         $file_name = sanitize_file_name($file_name);
    240         $tmpfname = wp_tempnam($file_name);
    241         $fh       = fopen($tmpfname, 'w');
    242 
    243         if ($url_api == $info['url']) { //если редиректа нет записываем файл
    244             fwrite($fh, $output);
    245         } else {
    246             // fix https://github.com/wpcraft-ru/wooms/issues/203
    247             $context_options = array(
    248                 "ssl" => array(
    249                     "verify_peer" => false,
    250                     "verify_peer_name" => false,
    251                 ),
    252             );
    253             //если редирект есть то скачиваем файл по ссылке
    254             $file = file_get_contents($info['url'], false, stream_context_create($context_options));
    255             if (!$file) {
    256                 do_action(
    257                     'wooms_logger_error',
    258                     __CLASS__,
    259                     'Загрузка картинки - не удалось закачать файл',
    260                     sprintf('Данные %s', PHP_EOL . print_r($info['url'], true))
    261                 );
    262                 return false;
    263             }
    264             fwrite($fh, $file);
    265         }
    266        
    267         fclose($fh);
    268         $filetype = wp_check_filetype($file_name);
    269         // Array based on $_FILE as seen in PHP file uploads.
    270         $file_args = array(
    271             'name'     => $file_name, // ex: wp-header-logo.png
    272             'type'     => $filetype['type'], //todo do right
    273             'tmp_name' => $tmpfname,
    274             'error'    => 0,
    275             'size'     => filesize($tmpfname),
    276         );
    277         $overrides = array(
    278             'test_form'   => false,
    279             'test_size'   => false,
    280             'test_upload' => false,
    281         );
    282         $file_data = wp_handle_sideload($file_args, $overrides);
    283         // If error storing permanently, unlink.
    284         if (is_wp_error($file_data)) {
    285             @unlink($tmpfname);
    286             do_action(
    287                 'wooms_logger_error',
    288                 __CLASS__,
    289                 'Загрузка картинки - не удалось получить файл',
    290                 sprintf('Данные %s', PHP_EOL . print_r($file_data, true))
    291             );
    292             return false;
    293         }
    294         if (empty($file_data['url'])) {
    295             do_action(
    296                 'wooms_logger_error',
    297                 __CLASS__,
    298                 'Загрузка картинки - не удалось получить URL',
    299                 sprintf('Данные %s', PHP_EOL . print_r($file_data, true))
    300             );
    301             @unlink($tmpfname);
    302             return false;
    303         }
    304 
    305         $url     = $file_data['url'];
    306         $type    = $file_data['type'];
    307         $file    = $file_data['file'];
    308         $title   = preg_replace('/\.[^.]+$/', '', basename($file));
    309         $content = '';
    310         // Use image exif/iptc data for title and caption defaults if possible.
    311         if ($image_meta = \wp_read_image_metadata($file)) {
    312             if (trim($image_meta['title']) && !is_numeric(sanitize_title($image_meta['title']))) {
    313                 $title = $image_meta['title'];
    314             }
    315             if (trim($image_meta['caption'])) {
    316                 $content = $image_meta['caption'];
    317             }
    318         }
    319         if (isset($desc)) {
    320             $title = $desc;
    321         }
    322         // Construct the attachment array.
    323         $attachment = array(
    324             'post_mime_type' => $type,
    325             'guid'           => $url,
    326             'post_parent'    => $post_id,
    327             'post_title'     => $title,
    328             'post_content'   => $content,
    329         );
    330         // This should never be set as it would then overwrite an existing attachment.
    331         unset($attachment['ID']);
    332         // Save the attachment metadata
    333         $id = wp_insert_attachment($attachment, $file, $post_id);
    334         if (!is_wp_error($id)) {
    335             wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $file));
    336         } else {
    337             return false;
    338         }
    339         @unlink($tmpfname);
    340         update_post_meta($id, 'wooms_url', $url_api);
    341         return $id;
    342     }
    343 
    344257
    345258    /**
     
    354267        <h2>Изображения</h2>
    355268        <p>Ручная загрузка изображений по 5 штук за раз.</p>
    356        
    357         <?php printf('<a href="%s" class="button button-primary">Выполнить</a>', add_query_arg('a', 'wooms_products_images_manual_start', admin_url('admin.php?page=moysklad')));
     269
     270<?php printf('<a href="%s" class="button button-primary">Выполнить</a>', add_query_arg('a', 'wooms_products_images_manual_start', admin_url('admin.php?page=moysklad')));
    358271    }
    359272
  • wooms/trunk/readme.txt

    r2226076 r2250855  
    7676== Changelog ==
    7777
     78= 6.1 =
     79* исправлена ошибка по дублированию картинок https://github.com/wpcraft-ru/wooms/issues/221
     80* добавлен вывод ошибок в новой странице Инструменты->Здоровье сайта ( проверка и вывод всех возможных ошибок )
     81* перенесено большинство крон задач на Action Sheduler
     82* в качестве эксперимента реализована поддержка Action Sheduler в части синка галлереи (сильно упрощает понимние истории синхронизации и диагностику ошибок) https://github.com/wpcraft-ru/wooms/issues/212
     83* добавлен вывод ошибок 'не правильный пароль' в раздел Здоровье Cайта https://github.com/wpcraft-ru/wooms/issues/216
     84* добавлен вывод ошибок при разных версиях базого и XT в раздел Здоровье Cайта https://github.com/wpcraft-ru/wooms/issues/216
     85
    7886= 6.0 =
    7987* добавлена поддержка галлереи изображений продукта https://github.com/wpcraft-ru/wooms/issues/27
  • wooms/trunk/wooms.php

    r2226076 r2250855  
    11<?php
     2
    23/**
    34 * Plugin Name: WooMS
     
    1617 * License: GPLv2 or later
    1718 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
    18  * Version: 6.0
    19  * WooMS XT Latest: 6.0
     19 * Version: 6.1
     20 * WooMS XT Latest: 6.1
    2021 */
    2122
    2223// Exit if accessed directly
    23 defined( 'ABSPATH' ) || exit;
     24defined('ABSPATH') || exit;
    2425
    2526/**
    2627 * Core
    2728 */
    28 class WooMS_Core {
     29class WooMS_Core
     30{
    2931
    3032  /**
     
    4143   * The init
    4244   */
    43   public static function init(){
     45  public static function init()
     46  {
    4447
    4548    /**
     
    4750     * Птм что иначе хук wooms_activate не срабатывает
    4851     */
    49     require_once __DIR__ . '/inc/class-logger.php';
     52    require_once __DIR__ . '/inc/Logger.php';
    5053    require_once __DIR__ . '/functions.php';
    5154
     
    5356     * Add hook for activate plugin
    5457     */
    55     register_activation_hook( __FILE__, function(){
     58    register_activation_hook(__FILE__, function () {
    5659      do_action('wooms_activate');
    5760    });
    5861
    59     register_deactivation_hook( __FILE__, function(){
     62    register_deactivation_hook(__FILE__, function () {
    6063      do_action('wooms_deactivate');
    6164    });
    6265
    63     add_filter('woocommerce_status_log_items_per_page', function($per_page){
     66    add_action('plugins_loaded', [__CLASS__, 'true_load_plugin_textdomain']);
     67
     68    add_filter('woocommerce_status_log_items_per_page', function ($per_page) {
    6469      return 100;
    6570    });
    6671
    67     add_action('plugins_loaded', function(){
     72    add_action('plugins_loaded', function () {
    6873
    6974      /**
    7075       * Подключение компонентов
    7176       */
    72       require_once __DIR__ . '/inc/class-menu-settings.php';
    73       require_once __DIR__ . '/inc/class-menu-tool.php';
    74       require_once __DIR__ . '/inc/class-products-walker.php';
    75       require_once __DIR__ . '/inc/class-import-product-categories.php';
    76       require_once __DIR__ . '/inc/class-import-prices.php';
    77       require_once __DIR__ . '/inc/class-hide-old-products.php';
     77      require_once __DIR__ . '/inc/MenuSettings.php';
     78      require_once __DIR__ . '/inc/MenuTools.php';
     79      require_once __DIR__ . '/inc/ProductsWalker.php';
     80      require_once __DIR__ . '/inc/ProductsCategories.php';
     81      require_once __DIR__ . '/inc/ProductsPrices.php';
     82      require_once __DIR__ . '/inc/ProductsHiding.php';
    7883
    7984      require_once __DIR__ . '/inc/MSImagesTrait.php';
    8085      require_once __DIR__ . '/inc/ProductGallery.php';
    8186      require_once __DIR__ . '/inc/ProductImage.php';
    82 
    83       add_action( 'admin_notices', array(__CLASS__, 'show_notices_35') );
    84       add_action( 'admin_notices', array(__CLASS__, 'show_error_notice') );
    85 
    86       add_action( 'after_plugin_row_wooms-extra/wooms-extra.php', array(__CLASS__, 'xt_plugin_update_message'), 10, 2 );
    87 
    88       add_filter( "plugin_action_links_" . plugin_basename( __FILE__ ), array(__CLASS__, 'plugin_add_settings_link') );
    89 
    90     });
    91 
     87      require_once __DIR__ . '/inc/SiteHealth.php';
     88
     89      add_action('admin_notices', array(__CLASS__, 'show_notices_35'));
     90      add_action('admin_notices', array(__CLASS__, 'show_error_notice'));
     91
     92      add_action('after_plugin_row_wooms-extra/wooms-extra.php', array(__CLASS__, 'xt_plugin_update_message'), 10, 2);
     93
     94      add_filter("plugin_action_links_" . plugin_basename(__FILE__), array(__CLASS__, 'plugin_add_settings_link'));
     95    });
    9296  }
    9397
     
    9599   * Add Settings link in pligins list
    96100   */
    97   public static function plugin_add_settings_link( $links ) {
     101  public static function plugin_add_settings_link($links)
     102  {
    98103    $settings_link = '<a href="admin.php?page=mss-settings">Настройки</a>';
    99104    $xt_link = '<a href="//wpcraft.ru/product/wooms-xt/" target="_blank">Расширенная версия</a>';
     
    104109
    105110  /**
     111   * Add languages
     112   *
     113   * @return void
     114   */
     115  public static function true_load_plugin_textdomain()
     116  {
     117    load_plugin_textdomain('wooms', false, dirname(plugin_basename(__FILE__)) . '/languages/');
     118  }
     119
     120  /**
    106121   * Проверяем актуальность расширенной версии и сообщаем если есть обновления
    107122   * Проверка происходит на базе данных в комментарии базовой версии
    108123   */
    109   public static function xt_plugin_update_message( $data, $response ) {
    110 
    111     $data = get_file_data( __FILE__, array('xt_version' => 'WooMS XT Latest') );
     124  public static function xt_plugin_update_message($data, $response)
     125  {
     126
     127    $data = get_file_data(__FILE__, array('xt_version' => 'WooMS XT Latest'));
    112128    $xt_version_remote = $data['xt_version'];
    113129
    114130    // $data = get_file_data( __FILE__, array('xt_version' => 'WooMS XT Latest') );
    115     $data = get_plugin_data( plugin_dir_path( __DIR__ ) . "wooms-extra/wooms-extra.php", false, false );
     131    $data = get_plugin_data(plugin_dir_path(__DIR__) . "wooms-extra/wooms-extra.php", false, false);
    116132    $xt_version_local = $data['Version'];
    117133    // $data = plugin_dir_path( __DIR__ );
    118134
    119     $check = version_compare( $xt_version_local, $xt_version_remote, '>=' );
    120 
    121     if($check){
     135    $check = version_compare($xt_version_local, $xt_version_remote, '>=');
     136
     137    if ($check) {
    122138      return;
    123139    }
    124     $wp_list_table = _get_list_table( 'WP_Plugins_List_Table' );
     140    $wp_list_table = _get_list_table('WP_Plugins_List_Table');
    125141
    126142    printf(
     
    135151      $xt_version_remote
    136152    );
    137 
    138153  }
    139154
     
    141156   * Ошибки - проверка и уведомленич
    142157   */
    143   public static function show_error_notice() {
     158  public static function show_error_notice()
     159  {
    144160    global $wp_version;
    145161
    146     $wooms_version = get_file_data( __FILE__, array('wooms_ver' => 'Version') );
     162    $wooms_version = get_file_data(__FILE__, array('wooms_ver' => 'Version'));
    147163
    148164    $message = '';
     
    150166    $php       = 5.6;
    151167    $wp        = 4.7;
    152     $php_check = version_compare( PHP_VERSION, $php, '<' );
    153     $wp_check  = version_compare( $wp_version, $wp, '<' );
    154 
    155     if ( $php_check ) {
     168    $php_check = version_compare(PHP_VERSION, $php, '<');
     169    $wp_check  = version_compare($wp_version, $wp, '<');
     170
     171    if ($php_check) {
    156172      $message .= sprintf('<p>Для работы плагина WooMS требуется более свежая версия php минимум - %s</p>', $php);
    157173    }
    158174
    159     if ( $wp_check ) {
     175    if ($wp_check) {
    160176      $message .= sprintf('<p>Для работы плагина WooMS требуется более свежая версия WordPress минимум - %s</p>', $wp);
    161177    }
     
    163179    $message = apply_filters('wooms_error_message', $message);
    164180
    165     if ( empty($message) ) {
     181    if (empty($message)) {
    166182      return;
    167183    }
     
    173189   * Вывод сообщения в консоли
    174190   */
    175   public static function show_notices_35() {
    176 
    177     if(is_plugin_active( 'wooms-extra/wooms-extra.php' )){
    178       $data = get_plugin_data( plugin_dir_path( __DIR__ ) . "wooms-extra/wooms-extra.php", false, false );
    179       if(empty($data['Version'])){
     191  public static function show_notices_35()
     192  {
     193
     194    if (is_plugin_active('wooms-extra/wooms-extra.php')) {
     195      $data = get_plugin_data(plugin_dir_path(__DIR__) . "wooms-extra/wooms-extra.php", false, false);
     196      if (empty($data['Version'])) {
    180197        return;
    181198      }
     
    184201      // $data = plugin_dir_path( __DIR__ );
    185202
    186       $check = version_compare( $xt_version_local, '3.5', '>=' );
    187 
    188       if($check){
     203      $check = version_compare($xt_version_local, '3.5', '>=');
     204
     205      if ($check) {
    189206        return;
    190207      }
    191       ?>
     208?>
    192209      <div class="notice notice-error">
    193210        <p>
     
    196213        </p>
    197214      </div>
    198       <?php
     215<?php
    199216    }
    200217
    201218    return;
    202 
    203   }
    204 
     219  }
    205220}
    206221
Note: See TracChangeset for help on using the changeset viewer.