0

Im programming a wordpress plugin in php, The code that I show in the following lines is the main file of the plugin:

<?php

use Plugin\Wtemailcc\includes\cHelper;
use Plugin\Wtemailcc\includes\cMenu;


defined('ABSPATH') || exit;

define( 'WTEMAILCC_PLUGIN_NAME',    plugin_basename(__FILE__) );

$wtemailcc = new wtemailcc;

register_deactivation_hook( __FILE__, ['Plugin\Wtemailcc\includes\cHelper', 'WTDeactivate'] ); // Deactivation method
register_activation_hook( __FILE__, ['Plugin\Wtemailcc\includes\cHelper', 'WTDeactivate'] ); // Deactivation method


class wtemailcc
{

    public $options = array();

    public function __construct()
    {
        
        $this->options = get_option( 'wtemailcc' );

        add_action('plugins_loaded', [$this, 'LoadScripts']); //Carga el autoloader

        add_action('admin_menu', [$this, 'WTBuildMenu']); //Arma el menu del plugin en wp-admin

        add_action( 'admin_enqueue_scripts', [$this, 'WTEnqueque'] ); //Rutea los css y js

        add_action( 'init', ['Plugin\Wtemailcc\includes\cHelper', 'WTRegisterCPT'] ); //Registra custom post type para las plantillas

        add_action( 'init', ['Plugin\Wtemailcc\includes\cHelper', 'WTLoadCustomLanguage'] ); //Carga lenguaje que corresponda

        add_action( 'current_screen', [$this, 'WTOnPageLoad'] ); //Ejecuta acciones y filtros segun la pagina que se está mostrando

        add_filter( 'plugin_action_links_'.WTEMAILCC_PLUGIN_NAME, ['Plugin\Wtemailcc\includes\cMenu', 'WTAddCustomLinks'] ); //Agrega links propios en la lista de plugins

        add_action( 'admin_init', ['Plugin\Wtemailcc\includes\cHelper', 'WTSaveSettings'] ); //Registra los cambios de seteo en la bd

        add_action( 'plugins_loaded', ['Plugin\Wtemailcc\includes\cHelper', 'WTActivate'] ); // Activation method

        

    }



    public function LoadScripts()
    {
        
        if (!self::CheckSystem()) return false; //Si no cumple los requisitos minimos, el plugin no funcionará

        spl_autoload_register 
        (
            function ( $class ) 
            {
                if ( strpos( $class, 'Wtemailcc' ) === false ) return;

                $name = str_replace( '\\', '/', $class );
                $name = str_replace( 'Plugin/Wtemailcc/', '', $name );

                require_once plugin_dir_path(__FILE__) . $name . '.php';
            }

        );

        

    }



    public static function CheckSystem()
    {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
        
        $system = self::CheckComponents();

        if ( $system['flag'] ) 
        {
            deactivate_plugins( plugin_basename(__FILE__) );

            echo '<div class="notice notice-error is-dismissible">';
            echo '<p>' . sprintf( __('<strong>%s/strong> requiere al menos %s version %s o mayor.', 'entregar' ), self::PLUGIN_NAME, $system['flag'], $system['version']) . '</p>';
            echo '</div>';

            return false;
        }

        return true;
    }



    private static function CheckComponents()
    {

        global $wp_version;
        $flag = $version = false;

        if (version_compare(PHP_VERSION, '7.0', '<')) 
        {
            $flag       = 'PHP';
            $version    = '7.0';
        } 
        elseif (version_compare($wp_version, '4.9', '<')) 
        {
            $flag       = 'WordPress';
            $version    = '4.9';
        }

        return 
        [
            'flag'      => $flag,
            'version'   => $version
        ];
    }



    public function WTEnqueque() 
    {

        $this->WTEnquequeBootStrap();

        wp_register_style( 'cssWTemailcc_admin',WTEMAILCC_URL.'admin/css/style.css' );
        wp_enqueue_style ( 'cssWTemailcc_admin' );
        
        wp_register_script( 'jsWTaceEditor',WTEMAILCC_URL.'admin/js/ace-editor/src-min-noconflict/ace.js' ); //Ace-editor (for custom css section)
        wp_enqueue_script ( 'jsWTaceEditor' );

    }



    public function WTEnquequeBootStrap()
    {
        global $wp_scripts;

        $bootstrap_enqueued = FALSE;
        foreach( $wp_scripts->queue  as $script ) 
        {
            if ((stristr($wp_scripts->registered[$script]->src, 'bootstrap.min.js') !== FALSE ||    stristr($wp_scripts->registered[$script]->src, 'bootstrap.js') != FALSE) && wp_script_is($wp_scripts->registered[$script]->handle, $list = 'enqueued')) 
            {
                $bootstrap_enqueued = TRUE;
                break;
            }
        }

        if (!$bootstrap_enqueued)
        {
            wp_enqueue_style( 'cssWTemailccBootStrap', WTEMAILCC_URL.'includes/bootstrap-4.3.1/css/bootstrap.min.css' );
            wp_register_script( 'jsWTBootstrap', WTEMAILCC_URL.'includes/bootstrap-4.3.1/js/bootstrap.min.js' ); 
            wp_enqueue_script( 'jsWTBootstrap' );
        }
        
    }



    public function WTOnPageLoad( $screen ) 
    {
        
        switch ($screen->id) {
            
            case 'edit-wt-template': //ACIONES Y  FILTROS pantalla: LISTADO DE PLANTILLAS
                                
                add_action( 'admin_enqueue_scripts', [$this, 'WTEnquequeCPT'] ); //CPT LIST: Load all the css & js files for the CPT list
                
                
                break;
            


            case 'toplevel_page_email-contact-center':
                
                add_action( 'admin_enqueue_scripts', [$this, 'WTRegisterSettingsStuff'] );
                
                break;



            case 'mensajeria-ok_page_view-sended':
                
                add_action( 'admin_enqueue_scripts', [$this, 'WTRegisterSettingsStuff'] );
                
                break;



            case 'dashboard':
                
                add_action( 'admin_enqueue_scripts', [$this, 'WTEnquequeBootStrap'] );

                break;
        }       
    }


    public function WTLoadSendEmailTemplate()
    {
        require_once WTEMAILCC_PLUGIN_DIR.'admin/html/send-mail.php';
    }



    public function WTLoadHistoryTemplate()
    {
        require_once WTEMAILCC_PLUGIN_DIR.'admin/html/log-sended.php';
    }



    public function WTLoadSetupTemplate()
    {
        require_once WTEMAILCC_PLUGIN_DIR.'admin/html/settings.php';
    }



    public function WTBuildMenu()
    {
        
            $pages = $subpages = array();

            //Array of pages to create
            $pages = [
                [
                    'page_title'    => 'Email Contact Center', 
                    'menu_title'    => 'Mensajeria OK', 
                    'capability'    => 'enviar_mensajes', 
                    'menu_slug'     => 'email-contact-center', 
                    'callback'  => ['wtemailcc', 'WTLoadSendEmailTemplate'], 
                    'icon_url'  => 'dashicons-email-alt', 
                    'position'  => 1
                ]
            ];
            
            //Array of subpages to create
            $subpages = [
                [
                    'parent_slug'   => 'email-contact-center',
                    'page_title'    => __('Historico de enviados', 'wtemailcc'), 
                    'menu_title'    => __('Historico de enviados', 'wtemailcc'), 
                    'capability'    => 'enviar_mensajes', 
                    'menu_slug'     => 'view-sended',
                    'callback'  => ['wtemailcc', 'WTLoadHistoryTemplate'],
                    'icon_url'  => 'dashicons-admin-generic', 
                    'position'  => 150
                ],
                [
                    'parent_slug'   => 'email-contact-center',
                    'page_title'    => __('Configuraciones', 'wtemailcc'), 
                    'menu_title'    => __('Configuraciones', 'wtemailcc'), 
                    'capability'    => 'admin_mensajeria', 
                    'menu_slug'     => 'setup',
                    'callback'  => ['wtemailcc', 'WTLoadSetupTemplate'],
                    'icon_url'  => 'dashicons-admin-generic', 
                    'position'  => 165
                ]
            ];

            $cMenu = new cMenu;
            $cMenu -> WTAddPages( $pages ) -> WTWithSubPage( __('Mensajes', 'wtemailcc') ) -> WTAddSubPages( $subpages ) ;
                
        
    }

}

?>

I have the other file cHelper.php that contains the other class called into the main file:

<?php

namespace Plugin\Wtemailcc\includes;

/**
 *
 * This file contains the class with methods of the plugin
 *
 * @author  Ezequiel Cattaneo <webstower@gmail.com>
 *
 * @link    https://www.webstower.com/wordpress/wtemailcc/welcome
 *
 **/
 
 
class cHelper 
{

    use customPostRolesTrait;
    use mailTrait;
    use settingsTrait;
    use systemTrait;
    use listingCPTTrait;

    function __construct() 
    {
    }



    public static function WTActivate() 
    {
        $result = self::WTCreateDefaultSettings(); //Crea los seteos por defecto

        //$result = $this->WTCreateContactedHistoryTable(); //Crea la tabla que guardará el historico de contactos
        
        //$result = $this->WTCreateCustomRoles(); //Crea los nuevos roles
    }



    public static function WTDeactivate() 
    {
        unregister_post_type ('WT-Template');

        flush_rewrite_rules();
    }



    private static function WTCreateDefaultSettings() 
    {
        $options = array(
            'mensajeria_servidor_smtp'  => 'mail.kimoro.com',
            'mensajeria_puerto'         => '587',
            'mensajeria_mail'           => 'info@kimoro.com',
            'mensajeria_pass'           => '123456',
            'mensajeria_nombre'         => 'kimoro',
            'custom_rol_callcenter'         => 0,
        );

        if ( get_option('wtemailcc') == false ) update_option( 'wtemailcc', $options ); //Si no existen los seteos en la base de datos entonces se los crea
    }



    private function WTCreateContactedHistoryTable() 
    {
        global $wpdb;
        
            $sql ="CREATE TABLE IF NOT EXISTS {$wpdb->prefix}mensajes_enviados(
    
                `id` INT NOT NULL AUTO_INCREMENT , 
                `id_usuario` INT NOT NULL , 
                `hora` DATE NOT NULL , 
                `mensaje` VARCHAR(60) NOT NULL , 
                `destinatario` VARCHAR(30) NOT NULL , 
                PRIMARY KEY (`id`));";

        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        $result = dbDelta( $sql );

        return $result;
    }



    public static function WTLoadCustomLanguage()
    {
        load_plugin_textdomain( 'wtemailcc', false, WTEMAILCC_PLUGIN_DIR . 'languages' );
    }



    public function WTAdminNotice( $mensaje, $type = 'success' )
    {
        ?>
        <div class="updated notice-<?php echo $type?> is-dismissible" >
            <p> <?php echo __( $mensaje, 'wtemailcc' ) ?> </p>
        </div>
        <?php
    }

}
?>

Every time that I deactivate de plugin, no errors are showed in the screen, but, when I try to activate, the following error is showed:

Notice: Constant WTEMAILCC_PLUGIN_NAME already defined in /path to the plugin...../wp-content/plugins/wtemailcc/wtemailcc.php on line 23

Fatal error: Cannot declare class wtemailcc, because the name is already in use in /path to the plugin...../wp-content/plugins/wtemailcc/wtemailcc.php on line 34

  • This generally means you are either including the same file twice or you have duplicate class names. Check or post the stack trace to see which is the offending line. Since you also have an attempt to re-declare a constant, my best guess is you are including the file `wtemailcc.php` twice. – endeavour May 24 '21 at 14:12
  • This is the backtrace.. Notice: Constant WTEMAILCC_PLUGIN_NAME already defined in /plugin path.../wp-content/plugins/wtemailcc/wtemailcc.php on line 23 Fatal error: Cannot declare class wtemailcc, because the name is already in use in /plugin path.../wp-content/plugins/wtemailcc/wtemailcc.php on line 34 – Ezequiel Cattaneo May 24 '21 at 14:48
  • This is the error, Is this a dev server? Consider installing xdebug on a dev server.This page has more details on backtrace https://stackoverflow.com/questions/1159216/how-can-i-get-php-to-produce-a-backtrace-upon-errors – endeavour May 24 '21 at 14:59

0 Answers0