Plugin Directory

Changeset 1701698


Ignore:
Timestamp:
07/24/2017 02:39:14 PM (9 years ago)
Author:
lovnic
Message:

1.0.6 update

Location:
cmc-hook/trunk
Files:
6 added
10 edited

Legend:

Unmodified
Added
Removed
  • cmc-hook/trunk/cmc_hook.php

    r1699777 r1701698  
    33Plugin Name: cmc-hook
    44Description: Register php functions to hooks(action and filter), run php codes safely, create and quickly test plugins all from dashboad tools
    5 Version: 1.0.5
     5Version: 1.0.6
    66Author: Evans Edem Ladzagla
    77Author URI: https://profiles.wordpress.org/lovnic/
     
    5050
    5151    /**
    52      * Admin Page Url.
    53      *
    54      * @var string
    55      */
    56     public static $menu;
    57 
    58     /**
    5952     * Main cmc_hook Instance.
    6053     *
     
    7669    function __construct(){
    7770        self::constants(); self::includes();
    78         if( !empty($_REQUEST['cmchk_neg']) )self::remote_deactivate_hook();         
    79         add_action( 'plugins_loaded', array( __CLASS__, 'load_hooks' ), 11 );
    80         add_action( 'plugins_loaded', array( __CLASS__, 'init'));
    81         add_action( 'plugins_loaded', array( __CLASS__, 'init2'), 12);
     71        if( !empty($_REQUEST['cmchk_neg']) )cmchk_actions::remote_deactivate_hook();
     72        add_action( 'plugins_loaded', array( __CLASS__, 'init'));       
    8273        add_shortcode('cmchksh', array(__CLASS__, 'shortcode'));
    8374        register_activation_hook( __FILE__, array( __CLASS__, 'plugin_activate' ) );
    8475        register_deactivation_hook( __FILE__, array( __CLASS__, 'plugin_deactivate' ) );           
    8576    }
    86    
    87     /**
    88      * Check whether current user is in permitted role to use cmc-hooks
    89      * By Default administrator has permission
    90      * Other roles has to be added at Settings inorder to allow thier users
    91      */
    92     public static function is_user_allowed(){
    93         if( current_user_can('administrator') ) return true;
    94         $allowed_roles = self::get_setting('allowed_roles');  $allowed_roles = explode('\n', $allowed_roles);
    95         foreach($allowed_roles  as $role){
    96             if( current_user_can( $role ) ) return true;
    97         }
    98         return false;
    99     }
    10077
    10178    /**
     
    10683    */
    10784    public static function init(){
     85        do_action('cmchk_before_init');
    10886        if( is_admin() ){
    109             if( self::is_user_allowed() ){
    110                 $action = !empty($_REQUEST['action'])?$_REQUEST['action']:$_REQUEST['action2'];
    111                 if( $_REQUEST['cmchk_action'] == 'hook_editor' || $action == 'cmchk_hook_editor' )self::hook_table_editor();
    112                 if( $_REQUEST['cmchk_action'] == 'trash_hook' )self::trash_hook();
    113                 if( $_REQUEST['cmchk_action'] == 'trash_project' )self::trash_project();
    114                 if( $_REQUEST['cmchk_action'] == 'hook_code_save' )self::hook_code_save();
    115                 if( $action == 'create_folder' )self::create_folder();
    116                 if( $_REQUEST['cmchk_action'] == 'project_editor' || $action == 'cmchk_project_editor' )self::hook_project_table_editor();
     87            if( cmchk::is_user_allowed() ){             
     88                $action = !empty($_REQUEST['action'])? $_REQUEST['action'] : $_REQUEST['action2'];
     89                if( $_REQUEST['cmchk_action'] == 'hook_editor' || $action == 'cmchk_hook_editor' )cmchk_actions::hook_table_editor();
     90                if( $_REQUEST['cmchk_action'] == 'trash_hook' )cmchk_actions::trash_hook();             
     91                if( $_REQUEST['cmchk_action'] == 'hook_code_save' )cmchk_actions::hook_code_save();             
     92                if( $_REQUEST['cmchk_action'] == 'project_editor' || $action == 'cmchk_project_editor' )cmchk_actions::hook_project_table_editor();
     93                if( $_REQUEST['cmchk_action'] == 'trash_project' )cmchk_actions::trash_project();   
     94                if( $action == 'create_folder' ) cmchk_actions::create_folder();               
    11795            }
    11896        }
     97       
     98        cmchk_actions::load_hooks();       
     99        self::init2();
     100       
     101        do_action('cmchk_init');
    119102    }
    120103   
     
    126109    public static function init2(){             
    127110        if( is_admin() ){
    128             if( self::is_user_allowed() ){
     111            if( cmchk::is_user_allowed() ){
    129112                $action = !empty($_REQUEST['action'])?$_REQUEST['action']:$_REQUEST['action2'];
    130113                if( defined('DOING_AJAX') && DOING_AJAX ){
    131114                    add_action( 'wp_ajax_cmchk_slug', array(__CLASS__, 'save_slug') );                 
    132115                }else{ 
    133                     if( isset($_REQUEST['cmchk_action']) && !empty($_REQUEST['cmchk_action']) ){
     116                    if( !empty($_REQUEST['cmchk_action']) ){
    134117                        switch( $_REQUEST['cmchk_action'] ){
    135                             case 'create_plugin': self::hook_project_create_plugin(); break;
    136                             case 'export': self::export( $_REQUEST['id'] ); break;
    137                             case 'import': self::import(); break;
    138                             case 'jfiletree':self::project_explorer(); break;
     118                            case 'create_plugin': cmchk_actions::hook_project_create_plugin(); break;
     119                            case 'export': cmchk_actions::export( $_REQUEST['id'] ); break;
     120                            case 'import': cmchk_actions::import(); break;
     121                            case 'jfiletree':cmchk_actions::project_explorer(); break;
     122                            case 'hook_settings': cmchk_actions::settings_save(); break;
    139123                        }
    140124                    }
    141125                    if( !empty($action) ){
    142126                        switch( $action ){
    143                             case 'cmchk-hook-bulk-export': self::export_hook(); break;
    144                             case 'cmchk-project-bulk-export': self::export($_POST['bulk-items']); break;
     127                            case 'cmchk-hook-bulk-export': cmchk_actions::export_hook(); break;
     128                            case 'cmchk-project-bulk-export': cmchk_actions::export($_POST['bulk-items']); break;
    145129                        }
    146130                    }
     
    152136            }                     
    153137        }       
    154     }
    155    
    156     /**
    157      * Load activated hooks and projects used for both admin and frontend.
    158      */
    159     public static function load_hooks(){
    160         $on = self::get_setting( 'run_hook_on', 'none' ); $run_hook = false;
    161         if( $on == 'both' ){
    162             $run_hook = true;
    163         }else if( $on == 'none' || ($on == 'backonly' && !is_admin()) || ($on == 'frontonly' && $on == !is_admin()) ){
    164             $run_hook == false;
    165         }           
    166         if( !$run_hook )return;
    167        
    168         global $wpdb;       
    169         $sql = "SELECT * FROM ".CMCHK_TABLE_HOOK." where active != 0 and project_id = 0";
    170         $hooks = $wpdb->get_results( $sql, 'ARRAY_A' );
    171         $hooks = apply_filters('cmchk_load_hook', $hooks);
    172         if( is_array( $hooks ) ){
    173             foreach($hooks as $r){
    174                 self::_load_hook($r);
    175             }           
    176         }
    177        
    178         $sql = "SELECT h.*, p.active pactive FROM `".CMCHK_TABLE_PROJECT.
    179         "` p inner join `".CMCHK_TABLE_HOOK."` h on p.file_run = h.id where p.active != 0 and project_id = -1 ";
    180         $projs = $wpdb->get_results( $sql, 'ARRAY_A' );
    181         $projs  = apply_filters('cmchk_load_project', $projs );
    182         if( is_array( $projs ) ){
    183             foreach($projs as $r){
    184                 if( $r['active'] < 1 && (!is_array($cmchk = explode(',',$_REQUEST['cmchk_safe_proj'])) || !in_array($r['id'], $cmchk)) )continue;
    185                 $sql = "SELECT * FROM `".CMCHK_TABLE_HOOK."` where parent_id = $r[parent_id] and type IN('filter', 'action') and active = 1";
    186                 $actfilters = $wpdb->get_results( $sql, 'ARRAY_A' );
    187                 if( is_array($actfilters) ){
    188                     foreach($actfilters as $a){
    189                         self::_load_hook($a);
    190                     }
    191                 }
    192                 self::_load_hook($r);
    193             }           
    194         }
    195         do_action('cmchk_plugins_loaded');
    196         do_action('cmchk_hook_loaded');
    197     }
    198    
    199     /**
    200      * Load Single hook
    201      * @param hook-record $r
    202      */
    203     public static function _load_hook( $r ){
    204         if( $r['active'] < 1 && (!is_array($cmchk = explode(',',$_REQUEST['cmchk_safe'])) || !in_array($r['id'], $cmchk)) )return;
    205        
    206         $fbody = $r["code"];
    207         if( in_array( $r['type'], array('filter', 'action')) ){
    208             $hook = "add_$r[type]";
    209             $hook($r['hookname'], function() use($fbody){
    210                 self::run_php( $fbody );
    211             }, $r['priority'], $r['args']);       
    212         }else if( $r['type'] == 'file' ){
    213             self::run_php( $fbody );
    214         }
    215     }
    216    
    217     /**
    218      * Remotely Deactivate hook
    219      * If ids are provided Then the hooks with those ids will be deactivated
    220      * If no id is provided, run hook on  is set to none so no hook runs
    221      * The id provided should be one or comma separated multiple e.g. 1,2,3
    222      */
    223     public static function remote_deactivate_hook(){
    224         $neg = $_REQUEST['cmchk_neg']; 
    225         if( (!self::get_setting('deactivate_remote') || $neg != self::get_setting('deactivate_remote_token')) )return;
    226         global $wpdb;
    227         if( !empty( $_REQUEST['cmchk_id'] )  ){
    228             $ids = explode(',', $_REQUEST['cmchk_id'] );
    229             foreach($ids as $id){
    230                 $data['active'] = 0;
    231                 $wpdb->update( CMCHK_TABLE_HOOK, $data, array('id'=> $id, 'project_id'=>0) );
    232             }   
    233         }
    234         if( !empty( $_REQUEST['cmchk_pid'] )  ){
    235             $ids = explode(',', $_REQUEST['cmchk_pid'] );           
    236             foreach($ids as $id){
    237                 $data['active'] = 0;
    238                 $wpdb->update( CMCHK_TABLE_PROJECT, $data, array('id'=> $id, 'project_id'=>0) );
    239             }   
    240         }
    241        
    242         if( !empty($_REQUEST['cmchk_run_on']) && in_array( $_REQUEST['cmchk_run_on'], array( 'backonly', 'none')) ){
    243             global $cmchk_settings_default;
    244             $data = get_option( 'cmc_hook_settings', $cmchk_settings_default );
    245             $data['run_hook_on'] = $_REQUEST['cmchk_run_on'];
    246             update_option('cmc_hook_settings', $data);         
    247         }
    248138    }
    249139   
     
    278168            require("pages/admin.php");
    279169        });
    280         self::$menu = menu_page_url('cmc-hook', false);
    281170        add_action( "load-$hook", array(__CLASS__, "menu_load"));       
    282171    }
     
    286175     */
    287176    public static function menu_load(){
    288         if( !empty($_REQUEST['cmchk_action']) ){
    289             switch( $_REQUEST['cmchk_action'] ){
    290                 case 'hook_settings': self::hook_settings_save(); break;
    291             }
    292         }
    293177
    294178        if( (empty($_REQUEST['tab']) && empty($_REQUEST['section'])) || ($_REQUEST['section'] == 'project') ){
     
    306190
    307191        if( $_REQUEST['tab'] == 'project' && empty( $_REQUEST['section']) ){
    308             require("include/class-cmc-hook-project-table.php");
     192            require( CMCHK_DIR_INCLUDE."class-cmc-hook-project-table.php");
    309193            $option = 'per_page';
    310194            $args   = [
     
    318202        }
    319203
    320         if( self::get_setting('enable_codemirror', true) && $_REQUEST['tab'] == 'explorer' )
     204        if( cmchk::get_setting('enable_codemirror', true) && $_REQUEST['tab'] == 'explorer' )
    321205            self::codemirror_script ();
    322206
     
    326210        wp_enqueue_script( 'main_js', CMCHK_URL_JS.'main.js', array('jquery') );
    327211        wp_enqueue_script( 'into_js', CMCHK_URL_JS.'intro/intro.js', array('jquery') );
    328         wp_enqueue_script( 'tiptip_js', CMCHK_URL_JS.'tiptip/jquery.tipTip.js', array('jquery') );
     212        wp_enqueue_script( 'tiptip_js', CMCHK_URL_JS.'TipTip/jquery.tipTip.js', array('jquery') );
    329213        wp_enqueue_script( 'jqueryFileTree_js', CMCHK_URL_JS.'jqueryFileTree/jqueryFileTree.js', array('jquery') );
    330214       
     
    332216        wp_enqueue_style( 'intro_css', CMCHK_URL_CSS.'intro/introjs.css' );
    333217        wp_enqueue_style( 'font_font-awesome_css', CMCHK_URL_CSS.'font-awesome/css/font-awesome.min.css' );
    334         wp_enqueue_style( 'tiptip_css', CMCHK_URL_JS.'tiptip/tiptip.css' );
     218        wp_enqueue_style( 'tiptip_css', CMCHK_URL_JS.'TipTip/tipTip.css' );
    335219        wp_enqueue_style( 'jqueryFileTree_css', CMCHK_URL_JS.'jqueryFileTree/jqueryFileTree.css' );
    336220        wp_enqueue_media();
     
    366250
    367251        wp_enqueue_style( 'codemirror_css', CMCHK_URL_CSS.'codemirror/codemirror.css');
    368         $theme = self::get_setting('codemirror_theme', '');
     252        $theme = cmchk::get_setting('codemirror_theme', '');
    369253        if( !empty($theme) ){
    370254            wp_enqueue_style( 'codemirror_theme_css', CMCHK_URL_CSS.'codemirror/theme/'.$theme.'.css');
     
    374258       
    375259    }
    376 
    377     /*
    378     *   Generate project explorer list
    379     */
    380     public static function project_explorer(){
    381         global $wpdb; $_POST['dir'] = urldecode($_POST['dir']); $active_proj = '';
    382         $matches = explode("/", rtrim( $_POST['dir'], '/\\') ); $proj_id = $_REQUEST['proj']; $hook_id = $_REQUEST['id'];
    383         $dir_id = reset($matches); $base_hook_id = end($matches);
    384 
    385         if( $dir_id == -2 ){
    386             $base_proj = array('0'=>'Hooks', '-1'=>'Projects'); $base_proj_current = ($proj_id > 0)? -1 : 0;
    387             $ul = "<ul class='jqueryFileTree' style='display: none;' >";
    388             foreach( $base_proj as $k => $v){
    389                 $current = ( $k === $base_proj_current )? 'cmchk-current-project':'';
    390                 $collapsed = ( $k === $base_proj_current )? 'expanded':'collapsed';
    391                 $ul .= "\n\t<li class='directory $collapsed $current '><a href='#' rel='$k/' >$v";
    392                 if( $collapsed == 'expanded' ){
    393                     $ul .= ( $proj_id > 0)? self::proj_exp_projects($proj_id, $hook_id): self::proj_exp_hooks( $proj_id, $hook_id );
    394                 }       
    395                 $ul .= "</a></li>";
    396             }           
    397             $ul .= "\n</ul>";   
    398             echo $ul;
    399         }else if(  $dir_id == -1 ){
    400             echo self::proj_exp_projects( $proj_id, $hook_id );
    401         }else if( $dir_id > -1 ){   
    402             echo self::proj_exp_hooks( $dir_id, $hook_id );
    403         }       
    404         exit();
    405     }
    406    
    407     /*
    408     *   Project Explorer Project list
    409     *
    410     *   @param int $proj_id selected project id
    411     *   @param int $hook_id selected hook id
    412     */
    413     private static function proj_exp_projects( $proj_id, $hook_id ){
    414         global $wpdb; $sql = "SELECT * FROM `".CMCHK_TABLE_PROJECT."` where status != 'trash' and project_id = -1 ";               
    415         $result = $wpdb->get_results( $sql, 'ARRAY_A' );               
    416         if( $result !== false ){
    417             $ul = "<ul class='jqueryFileTree' style='display: none;'>";
    418             $li = array();
    419             foreach( $result as $r ){
    420                 $current = ( $r['id'] === $proj_id )? 'cmchk-current-project':'';
    421                 $collapsed = ( $r['id'] === $proj_id )? 'expanded':'collapsed';
    422                 $lia = "<li class='directory $collapsed $current '><a href='#' rel='$r[id]/' >".htmlentities($r['title']);
    423                 if( $r['id'] == $proj_id ){
    424                     $lia .= self::proj_exp_hooks( $proj_id, $hook_id);
    425                 }
    426                 $lia .= "</a></li>";   
    427                 ( $r['id'] === $proj_id )? ( array_unshift( $li, $lia) ) : ($li[] = $lia);
    428             }
    429             $ul .= implode("\n\t", $li);
    430             $ul .= "\n</ul>";   
    431             return $ul;
    432         }
    433     }
    434    
    435     /*
    436     *   Project Explorer hook list in a project
    437     *
    438     *   @param int $proj_id project id
    439     *   @param int $hook_id selected hook id
    440     */
    441     private static function proj_exp_hooks( $proj_id, $hook_id ){
    442         global $wpdb; $sql = "SELECT * FROM `".CMCHK_TABLE_HOOK."` where project_id = $proj_id and status != 'trash' ";
    443         $result = $wpdb->get_results( $sql, 'ARRAY_A' );               
    444         if( $result !== false ){
    445             $ul = "<ul class='jqueryFileTree' style='display: none;'>";     
    446             foreach( $result as $r ){
    447                 $current = ( $r['id'] === $hook_id )? 'cmchk-current-hook':'';
    448                 $addr = "?page=cmc-hook&tab=explorer&id=$r[id]";
    449                 $ul .= "\n\t<li class='file ext_xml $current'><a href='$addr' rel='$r[project_id]/$r[id]/' >" . htmlentities($r['title']) . "</a></li>";       
    450             }
    451             $ul .= "\n</ul>";
    452             return $ul;
    453         }
    454     }
    455    
    456     /*
    457     *   Saves the code of a hook
    458     */
    459     public static function hook_code_save(){
    460         if ( isset( $_REQUEST['_wpnonce'] ) ) {
    461             $nonce = sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) );                     
    462         }
    463         if ( !isset( $nonce ) and ! wp_verify_nonce( $nonce, 'cmchk-hook-code-save' ) ) {
    464             if( defined('DOING_AJAX') && DOING_AJAX ){
    465                 wp_send_json(array('success'=>false, 'message'=>'Invalid nonce'));
    466             }
    467             die( 'Cheating...' );
    468         }
    469         global $wpdb; $data = array(); $response = array();
    470         $data['code'] = wp_unslash( $_REQUEST['code'] );
    471         $id = (int)sanitize_text_field( wp_unslash( $_REQUEST['id'] ) );
    472        
    473         $result = $wpdb->update( CMCHK_TABLE_HOOK, $data, array('id'=> $id) );
    474        
    475         if( $result === false){
    476             $response['success'] = false; $response['message'] = $wpdb->last_error;
    477         }else{
    478             $response['success'] = true; //$response['message'] = "Saved";
    479         }
    480         wp_send_json($response);
    481         exit();
    482     }
    483    
    484     /**
    485      *  Creates and Edit hooks with or without ajax
    486      */
    487     public static function hook_table_editor(){
    488         if ( isset( $_REQUEST['_wpnonce'] ) ) {
    489             $nonce = sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) );                     
    490         }
    491         if ( !isset( $nonce ) and ! wp_verify_nonce( $nonce, 'cmc-hook-nonce' ) ) {
    492             if( defined('DOING_AJAX') && DOING_AJAX ){
    493                 wp_send_json(array('success'=>false, 'message'=>'Invalid nonce'));
    494             }
    495             die( 'Cheating...' );
    496         }
    497 
    498         $response = self::_hook_editor_table( $_POST );
    499        
    500         if( $response['success'] ){
    501             if( defined('DOING_AJAX') && DOING_AJAX ){
    502                 unset( $response['message'] );
    503                 if( $_REQUEST['tab'] == 'explorer' ){
    504                     $response['url'] = "?page=cmc-hook&tab=explorer&id=".$response['id'];
    505                 }else if( $response['project_id'] > 0){
    506                     $response['url'] = "?page=cmc-hook&tab=project&section=project&id=".$response['project_id'];
    507                 }else{
    508                     $response['url'] = "?page=cmc-hook";
    509                 }               
    510             }else{
    511                 $message = $response['message'];
    512                 add_action( 'admin_notices', function( $message ){
    513                     $class = 'notice notice-success is-dismissible';
    514                     printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( $message ) );
    515                 });
    516             }           
    517             do_action('cmchk_editor_save', $response['record'] );           
    518         }else{
    519             if( !defined('DOING_AJAX') || !DOING_AJAX ){
    520                 $error = $response['message'];
    521                 add_action( 'admin_notices', function() use ( $error ){
    522                     $class = 'notice notice-error is-dismissible'; $message = __( 'An Error Occured', 'cmchk' );
    523                     printf( '<div class="%1$s"><p>%2$s</p>%3$s</div>', esc_attr( $class ), esc_html( $message ), $error );
    524                 });
    525             }
    526         }
    527        
    528         if( defined('DOING_AJAX') && DOING_AJAX ){
    529             //if( $response['is_new'] ){
    530                 ob_start();
    531                     self::include_file( CMCHK_DIR."pages/sections/hook_attributes.php", array('hook_id'=>$response['id']) );               
    532                 $response['replace'] = ob_get_clean();
    533             //}
    534             wp_send_json( $response );
    535         }else{
    536             wp_redirect( self::current_url() );
    537             exit();
    538         }
    539     }
    540    
    541     /**
    542      *  Trash a hook
    543     */
    544     public static function trash_hook(){
    545         $nonce = sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) );
    546         if ( ! wp_verify_nonce( $nonce, 'cmchk-hook-attr-trash-hook' ) ) {
    547           die( 'Go get a life script kiddies' );
    548         }
    549         else {
    550             global $wpdb; $hook_id = intval( $_REQUEST['id'] );
    551             $sql = $wpdb->prepare( "SELECT project_id FROM ".CMCHK_TABLE_HOOK." WHERE id = %d", $hook_id);
    552             $proj_id = $wpdb->get_var( $sql );
    553             $response = self::_trash_hook( $hook_id );
    554             if( $response['success'] ){
    555                 $sql = $wpdb->prepare("SELECT id FROM ".CMCHK_TABLE_HOOK." WHERE project_id = %d and status != 'trash'", $proj_id);
    556                 $hook_id_new = $wpdb->get_var( $sql );
    557                 $response['hook_id'] = $hook_id_new;
    558                 $response['redirect'] = "?page=cmc-hook&tab=explorer&id=$hook_id_new";
    559             }
    560             wp_send_json( $response);
    561             exit;
    562         }
    563     }
    564    
    565     /**
    566      *  Privately trash hook
    567     */
    568     private static function _trash_hook( $id ){
    569         global $wpdb; $response = array(); $data = array();  $hook_id = intval($id);
    570         $data['status'] = 'trash'; $data['active'] = 0;
    571                
    572         $wpdb->update( CMCHK_TABLE_HOOK, $data, array( 'id' => $hook_id ) );
    573         $response['success'] = true; //$response['message'] = "Successfull";
    574         return $response;
    575     }
    576        
    577     /*
    578     *   Used Internally to save sanitized data record to hook table;
    579     *
    580     *   @param array $model record values
    581     */
    582     private function _hook_editor_table( $model = array() ){
    583         global $wpdb; $data = array(); $response = array();
    584         if( empty($model['title']) ){
    585             $response['success'] = false; $response['message'] = 'Title cannot be empty';
    586             return $response;
    587         }
    588 
    589         $data['id'] = isset( $model['id'] )? $model['id'] : 0;
    590         $data['title'] = sanitize_text_field( wp_unslash( $model['title'] ) );         
    591         if( $data['id'] == 0){
    592             $data['project_id'] = !empty($model['project_id'])? $model['project_id'] : 0;
    593             $data['slug'] = self::get_slug( CMCHK_TABLE_HOOK, $data['id'], $data['title'], $data['project_id'] ); //sanitize_text_field( wp_unslash( str_replace(' ', '_', $_POST['title'])) );
    594         }                   
    595        // $data['code'] = !isset($model['code'])? "" : wp_unslash( $model['code'] );
    596         $data['type'] = !isset($model['type'])? "file": sanitize_text_field( wp_unslash( $model['type'] ) );
    597         $data['hookname'] = !isset($model['hookname'])? "": sanitize_text_field( wp_unslash( $model['hookname'] ) );
    598         $data['args'] = !isset($model['args'])? 0 : sanitize_text_field( wp_unslash( $model['args'] ) );
    599         $data['priority'] = !isset($model['priority'])? 10 : sanitize_text_field( wp_unslash( $model['priority'] ) );
    600         $data['description'] = !isset($model['description'])? "": wp_unslash( $model['description'] );
    601         $data['datetimeupdated'] = date('Y-m-d H:i:s');
    602         $data['active'] = empty( $model['active'] ) ? 0 : ($model['active'] < 1 ? -1: 1);
    603         $data['status'] = 'publish';
    604         $data['enable_shortcode'] = ( $data['id'] == 0)? 0 : (isset( $model['enable_shortcode'] ) ? 1 : 0);
    605 
    606         $data = apply_filters( 'cmchk_editor_data_save', $data);
    607         if( $data === false ) return false;
    608        
    609         if( $data['id'] ) {
    610             $result = $wpdb->update( CMCHK_TABLE_HOOK, $data, array('id'=> $data['id']) );
    611         }else {
    612             $wpdb->insert( CMCHK_TABLE_HOOK, $data );
    613             $result = $wpdb->insert_id ? $wpdb->insert_id : false;
    614         }
    615         $response['record'] = $data;
    616         $response['project_id'] = $data['project_id'];
    617 
    618         if( $result === false ){
    619             $response['success'] = false; $response['message'] = __( $wpdb->last_error, 'cmchk' ); 
    620         }else if( $data['id'] > 0 ){
    621             $response['success'] = true; $response['id'] = $data['id']; $response['message'] = __( 'Update Successfull', 'cmchk' );       
    622         }else{
    623             $response['success'] = true; $response['id'] = $result; $response['message'] = __( 'Add Successfully', 'cmchk' );
    624             $response['is_new'] = true;
    625         }   
    626        
    627         return $response;       
    628     }
    629    
    630     /**
    631      *  Creates and Edit projects with or without ajax
    632     */
    633     public static function hook_project_table_editor(){
    634         if ( isset( $_REQUEST['_wpnonce'] ) ) {
    635             $nonce = sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) );                     
    636         }
    637         if ( !isset( $nonce ) and ! wp_verify_nonce( $nonce, 'cmc-hook-project-nonce' ) ) {
    638             if( defined('DOING_AJAX') && DOING_AJAX ){
    639                 wp_send_json(array('success'=>false, 'message'=>'Invalid nonce'));
    640             }
    641             die( 'Cheating...' );
    642         }
    643        
    644         $response = self::_hook_project_table_editor( $_POST );
    645         if( $response['success'] ){
    646             global $wpdb; $proj = $response['record'];
    647             if( $response['is_new'] ){
    648                 $hook_resp = self::_hook_editor_table( array('title'=>$proj['title'], 'type'=>'file', 'project_id'=>$response['id'], 'active'=> 1) );
    649                 if( $hook_resp['success'] ){
    650                     $wpdb->update( CMCHK_TABLE_PROJECT, array('file_run'=>$hook_resp['id']), array('id'=> $response['id']) );
    651                 }
    652             }                       
    653             if( defined('DOING_AJAX') && DOING_AJAX ){
    654                 unset( $response['message'] );
    655                 if( $_REQUEST['tab'] == 'explorer' ){
    656                     $response['url'] = '?page=cmc-hook&tab=explorer&id='.$hook_resp['id'];
    657                 }else{
    658                     $response['url'] = '?page=cmc-hook&tab=project&section=project&id='.$response['id'];
    659                 }               
    660             }else{
    661                 $message = $response['message'];
    662                 add_action( 'admin_notices', function($message){
    663                     $class = 'notice notice-success is-dismissible';
    664                     printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( $message ) );
    665                 });
    666             }       
    667             do_action('cmchk_project_editor_save', $data);
    668         }else{
    669             if( !defined('DOING_AJAX') || !DOING_AJAX ){
    670                 $error = $response['message'];
    671                 add_action( 'admin_notices', function() use ($error){
    672                     $class = 'notice notice-error is-dismissible'; $message = __( 'An Error Occured', 'cmchk' );
    673                     printf( '<div class="%1$s"><p>%2$s</p>%3$s</div>', esc_attr( $class ), esc_html( $message ), $error );
    674                 });
    675             }
    676         }
    677        
    678         if( defined('DOING_AJAX') && DOING_AJAX ){
    679             //if( $response['id'] > 0 ){
    680                 ob_start();
    681                     self::include_file( CMCHK_DIR."pages/sections/project_attributes.php", array('proj_id'=>$response['id']) );
    682                     //require("pages/sections/project_attributes.php");
    683                 $response['replace'] = ob_get_clean();
    684             //}
    685             wp_send_json( $response);
    686         }else{
    687             wp_redirect( self::current_url() );
    688             exit();
    689         }
    690     }
    691 
    692     /*
    693     *   Used Internally to save sanitized data record to hook table;
    694     *
    695     *   @param array $model record values
    696     */
    697     private function _hook_project_table_editor( $model = array() ){
    698         global $wpdb; $data = array(); $response = array();
    699         if( empty($model['title']) ){
    700             $response['success'] = false; $response['message'] = 'Title cannot be empty';
    701             return $response;
    702         }
    703         $data['id'] = isset( $model['id'] )? $model['id'] : 0;
    704         $data['title'] = sanitize_text_field( wp_unslash( $model['title'] ) );     
    705         if( $data['id'] == 0){
    706             $data['project_id'] = !empty($model['cmchk_proj'])? $model['cmchk_proj'] : -1; 
    707             $data['slug'] = self::get_slug( CMCHK_TABLE_PROJECT, $data['id'], $data['title'], $data['project_id'] ) ;
    708         }       
    709         $data['description'] = isset($model['description'])? wp_unslash( $model['description'] ): "";
    710         $data['datetimeupdated'] = date('Y-m-d H:i:s');
    711         $data['active'] = empty( $model['active'] ) ? 0 : ($model['active'] < 1 ? -1: 1);
    712         $data['status'] = 'publish';
    713         $data['file_run'] = !empty($model['file_run'])? $model['file_run'] : 0;
    714 
    715         $data = apply_filters( 'cmchk_project_editor_data_save', $data);
    716         if( $data === false ) return;
    717 
    718         if( $data['id'] ) {
    719             $result = $wpdb->update( CMCHK_TABLE_PROJECT, $data, array('id'=> $data['id']) );
    720         }else {
    721             $wpdb->insert( CMCHK_TABLE_PROJECT, $data );
    722             $result =  $result = $wpdb->insert_id ? $wpdb->insert_id : false;
    723         }
    724         $response['record'] = $data;
    725         $response['project_id'] = $data['project_id'];
    726        
    727         if( $result === false ){
    728             $response['success'] = false; $response['message'] = __( $wpdb->last_error, 'cmchk' ); 
    729         }else if( $data['id'] > 0 ){
    730             $response['success'] = true; $response['id'] = $data['id']; $response['message'] = __( 'Update Successfull', 'cmchk' );       
    731         }else{
    732             $response['success'] = true; $response['id'] = $result; $response['message'] = __( 'Add Successfully', 'cmchk' );
    733             $response['is_new'] = true;
    734         }
    735 
    736         return $response;
    737     }
    738    
    739     /**
    740      *  Trash a project
    741     */
    742     public static function trash_project(){
    743         $nonce = sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) );
    744         if ( ! wp_verify_nonce( $nonce, 'cmchk-project-attr-trash-proj' ) ) {
    745           die( 'Go get a life script kiddies' );
    746         }
    747         global $wpdb; $proj_id = intval( $_REQUEST['id'] );
    748         $response = self::_trash_project( $proj_id );
    749         if( $response['success'] ){
    750             if( $_REQUEST['tab'] == 'explorer' ){
    751                 $response['redirect'] = "?page=cmc-hook&tab=explorer";
    752             }else{
    753                 $response['redirect'] = "?page=cmc-hook&tab=project";
    754             }
    755            
    756         }
    757         wp_send_json( $response);
    758         exit;
    759        
    760     }
    761    
    762     /**
    763      *  Privately trash project
    764     */
    765     private static function _trash_project( $id ){
    766         global $wpdb; $response = array(); $data = array();  $proj_id = intval($id);
    767         $data['status'] = 'trash'; $data['active'] = 0;
    768 
    769         $wpdb->update( CMCHK_TABLE_PROJECT, $data, array( 'id' => $proj_id ) );
    770         $response['success'] = true; //$response['message'] = "Successfull";
    771         return $response;
    772     }
    773        
    774     public static function create_folder(){
    775        
    776     }   
    777        
    778      /**
    779      *  handles bulk Hook actions
    780      */
    781     public static function hook_bulk_action(){
    782        
    783     }
    784 
    785      /**
    786      *  Save hook settings
    787      */
    788     public static function hook_settings_save(){       
    789         if ( isset( $_REQUEST['_wpnonce'] ) ) {
    790             $nonce = sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) );                     
    791         }
    792         if ( !isset( $nonce ) and ! wp_verify_nonce( $nonce, 'cmc-hook-settings-nonce' ) ) {
    793             die( 'Cheating...' );
    794         }
    795         $response = self::_hook_settings_save( $_POST );     
    796 
    797         do_action('cmchk_settings_save', $data);
    798     }
    799    
    800      /**
    801      *  Internally Save hook settings
    802      */
    803     private static function _hook_settings_save( $model = array() ){
    804         $data = array(); $response = array();
    805         $data['run_hook_on'] = sanitize_text_field( wp_unslash( $model['run_hook_on'] ) );
    806         $data['deactivate_remote_token'] = sanitize_text_field( wp_unslash( $model['deactivate_remote_token'] ) );
    807         $data['codemirror_theme'] = sanitize_text_field( wp_unslash( $model['codemirror_theme'] ) );
    808         $data['allowed_users'] = wp_unslash( $model['allowed_users'] );
    809         $data['deactivate_remote'] = isset( $model['deactivate_remote'] ) ? 1 : 0;
    810         $data['del_table_uninstall'] = isset( $model['del_table_uninstall'] ) ? 1 : 0; ;
    811         $data['del_opt_uninstall'] = isset( $model['del_opt_uninstall'] ) ? 1 : 0; ;         
    812         $data['enable_codemirror'] = isset( $model['enable_codemirror'] ) ? 1 : 0;
    813        
    814         $data = apply_filters( 'cmchk_settings_data_save', $data);
    815         if( $data === false )return false;
    816 
    817         update_option('cmc_hook_settings', $data);
    818         $response['success'] = true; $response['message'] = "Saved Successfully";
    819         return $response;
    820     }
    821 
    822     /**
    823      *  Export Projects
    824      */
    825     public static function export( $proj_id ){
    826         if ( isset( $_REQUEST['_wpnonce'] ) ) {
    827             $nonce = sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) );                     
    828         }
    829         if ( !isset( $nonce ) and ! wp_verify_nonce( $nonce, 'cmchk-project-export-nonce' ) ) {
    830             die( 'Cheating...' );
    831         }
    832         global $wpdb; $ids = array();
    833         if( $proj_id == 'all'){
    834             $ids = $wpdb->get_col("SELECT id FROM ".CMCHK_TABLE_PROJECT." where project_id = -1 "); array_unshift($ids, 0);
    835         }else if( is_numeric($proj_id) ){
    836             $ids = array($proj_id);
    837         }else if( is_array($proj_id) ){
    838             $ids = $proj_id;
    839         }
    840         $projs = self::_export( $ids );
    841         if( $projs === false ) return;
    842        
    843         self::output_file( json_encode($projs), 'wp_cmchk.json', 'application/json');
    844     }
    845    
    846     /**
    847      *  Internally Export Projects
    848      */
    849     private static function _export($ids){
    850         global $wpdb; $ids = (array)$ids; $projs = array();     
    851         foreach($ids as $id){
    852             if( !empty( $id ) ){
    853                 $sql = $wpdb->prepare( "select * from `".CMCHK_TABLE_PROJECT."` where id = %d", intval($id) );
    854                 $proj = $wpdb->get_row($sql, ARRAY_A);
    855             }
    856             $proj['id'] = empty( $proj['id'] )? 0 : $proj['id'];
    857             $sql = $wpdb->prepare( "select * from `".CMCHK_TABLE_HOOK."` where project_id = %d", $proj['id'] );
    858             $proj['hooks'] = $wpdb->get_results($sql, ARRAY_A);  $projs[] = $proj; 
    859         }
    860         $projs['meta'] = array(
    861             'ver'=>CMCHK_VERSION,
    862             'site_url'=> get_bloginfo('url'),
    863             'datetime'=> date('Y-m-d H:i:s'),
    864         );
    865         $projs = apply_filters('cmchk_export_projects', $projs);
    866        
    867         return $projs;
    868     }
    869    
    870     /**
    871      *  Export hooks
    872     **/
    873     public static function export_hook(){
    874         global $wpdb; $ids = esc_sql( $_POST['bulk-items'] ); $id = implode(', ', $ids); $proj = array('id'=> 0);
    875         $projs = array();
    876         $sql = "SELECT * FROM `".CMCHK_TABLE_HOOK."` where id IN($id)";
    877         $proj['hooks'] = $wpdb->get_results( $sql, ARRAY_A ); $projs['0'] = $proj; 
    878         $projs = apply_filters('cmchk_export_projects', $projs);
    879         $projs['meta'] = array(
    880             'ver'=>CMCHK_VERSION,
    881             'site_url'=> get_bloginfo('url'),
    882             'datetime'=> date('Y-m-d H:i:s'),
    883         );
    884         if( $projs === false ) return;
    885            
    886         self::output_file( json_encode($projs), 'wp_cmchk.json', 'application/json');
    887     }
    888    
    889     /**
    890      *   Import hooks from a project
    891     **/
    892     public static function import(){
    893         if ( isset( $_REQUEST['_wpnonce'] ) ) {
    894             $nonce = sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) );                     
    895         }
    896         if ( !isset( $nonce ) and ! wp_verify_nonce( $nonce, 'cmc-hook-import-nonce' ) ) {
    897             die( 'Cheating...' );
    898         }
    899         if( empty($_FILES['cmchk_file_import']) )return;
    900         $projs = file_get_contents($_FILES['cmchk_file_import']['tmp_name']);       
    901         $projs = json_decode($projs, true);
    902         $meta = $projs['meta']; unset($projs['meta']);
    903         $response = self::_import( $projs, $meta );
    904        
    905         wp_redirect( self::current_url() );
    906         exit();
    907     }
    908    
    909     /**
    910      *   Internally Import hooks from a project
    911     **/
    912     protected static function _import( $projs, $meta){
    913         global $wpdb; $response = array();
    914         foreach($projs as $proj){
    915             $hooks = $proj['hooks']; $run_hook = $proj['file_run'];
    916             if( $proj && $proj['id'] > 0){             
    917                 unset( $proj['id'] ); unset($proj['hooks']); unset($proj['file_run']);
    918                 $proj['active'] = 0; $proj['slug'] = self::get_slug( CMCHK_TABLE_PROJECT, 0, $proj['slug'], 0 );;
    919                 $proj = apply_filters('cmchk_import_project', $proj);
    920                 if( $proj === false ) continue;
    921                 $wpdb->insert( CMCHK_TABLE_PROJECT, $proj );
    922                 $proj_id = $wpdb->insert_id;
    923             }else{
    924                 $proj_id = 0; $proj = apply_filters('cmchk_import_project', $proj);
    925             }
    926             foreach($hooks as $h){
    927                 $id = $h['id']; unset($h['id']); $h['project_id'] = $proj_id;
    928                 if( $proj_id == 0 ){
    929                     $h['active'] = 0;
    930                     $h['slug'] = self::get_slug( CMCHK_TABLE_HOOK, 0, $h['slug'], 0 );
    931                 }
    932                 $wpdb->insert( CMCHK_TABLE_HOOK, $h );
    933                 if( $run_hook == $id ) $run_hook = $wpdb->insert_id;
    934             }
    935             if( $proj_id > 0)
    936                 $wpdb->update( CMCHK_TABLE_PROJECT, array('file_run'=>$run_hook), array('id'=> $proj_id) );
    937         }
    938        
    939         $response['result'] = true; $response['message'] = "Import successfull";
    940     }
    941    
    942     /**
    943      *  Creates Plugin from project
    944      */
    945     public static function hook_project_create_plugin(){
    946         if ( isset( $_REQUEST['_wpnonce'] ) ) {
    947             $nonce = sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) );                     
    948         }
    949         if ( !isset( $nonce ) and ! wp_verify_nonce( $nonce, 'cmchk-create-plugin-nonce' ) ) {
    950             die( 'Cheating...' );
    951         }
    952        
    953         global $wpdb; $data = array(); $hook_id = intval($_REQUEST['id']);
    954         $sql = $wpdb->prepare( "SELECT p.*, h.slug as h_slug FROM `".CMCHK_TABLE_PROJECT."` ".
    955         " p left join `".CMCHK_TABLE_HOOK."` h on p.file_run = h.id where p.id = %d", $hook_id );
    956         //$sql = $wpdb->prepare("SELECT * FROM {$wpdb->prefix}cmc_hook_project where id = %d", $_REQUEST['cmchk_id']);
    957         $proj = $wpdb->get_row( $sql, 'ARRAY_A' );
    958         if( !$proj )return;
    959 
    960         $out .= "<?php \n";
    961         $out .= "/**\n This file contain all the filters and actions created\n by cmc-hook in the project - $proj[title] \n**/\n\n";
    962         $sql = "SELECT * FROM ".CMCHK_TABLE_HOOK." where type IN('filter', 'action') and active = 1 and project_id = $proj[id]";
    963         $hooks = $wpdb->get_results( $sql, 'ARRAY_A' );
    964         $hooks = apply_filters('cmchk_create_plugin_hooks', $hooks);
    965         if( is_array($hooks)){
    966             foreach( $hooks as $h){
    967                 $h['code'] = self::replacelive( $h['code'] );
    968                 $out .= "add_$h[type]('$h[hookname]', function(){ ?>\n$h[code]\n<?php }, $h[args], $h[priority]); \n\n\n";
    969             }
    970         }
    971         $out .= "\n?>";
    972         is_dir( CMCHK_DIR_ZIP ) || mkdir( CMCHK_DIR_ZIP );
    973         $temp_file = CMCHK_DIR_ZIP.$proj['slug'].'.zip';
    974         if( file_exists($temp_file) ) unlink($temp_file); $zip = new ZipArchive(); $zip->open( $temp_file, ZipArchive::CREATE );   
    975         set_time_limit ( 200 );
    976         $zip->addFromString($proj['slug'].'/'.'hooks.php', $out);           
    977         $out = "";
    978 
    979         $pluginvars = array('pluginname'=>'Plugin Name', 'pluginurl'=>'Plugin URI', 'descirption'=>'Description', 'version'=>'Version', 'author'=>'Author',
    980         'authorurl'=>'Author URI', 'license'=>'License', 'licenseurl'=>'License URI', 'textdomain'=>'Text Domain');
    981         $pluginvars = apply_filters( 'cmchk_export_plugin_info', $pluginvars );
    982         $plugininfo = "";
    983        
    984         foreach( $pluginvars as $k => $v ){
    985             if( !empty($_POST[$k]) ) $plugininfo .= "\n$v: ".str_replace("\n", ' ', $_POST[$k]);
    986         }
    987         if( empty($_POST['addfields']) ){
    988             $plugininfor .= "\n$_POST[addfields]";
    989         }
    990         $plugininfo = "<?php\n /**".$plugininfo."\n**/ \n\ninclude('cmchk_function.php');\ninclude('hooks.php');\n";
    991         /** $plugininfo = $plugininfo . "add_action('plugins_loaded', function(){\n\tinclude('$proj[h_slug].php');\n});\n ?>\n\n"; **/
    992         //$zip->addFromString( $proj['slug'].'/cmchk.php', $plugininfo );
    993         $a = $zip->addFile( CMCHK_DIR_INCLUDE."functions_live.php", $proj['slug'].'/cmchk_function.php');
    994         $sql = "SELECT * FROM ".CMCHK_TABLE_HOOK." where type = 'file' and project_id = $proj[id]";
    995         $hooks = $wpdb->get_results( $sql, 'ARRAY_A' );
    996         $hooks = apply_filters('cmchk_create_plugin_file_hooks', $hooks);
    997         if( is_array($hooks) ){
    998             foreach($hooks as $h){
    999                 $out = $h['code']; $out = self::replacelive( $out );
    1000                 if( $proj['file_run'] == $h['id'] ){
    1001                     if( self::startsWith("<?php", ltrim( $h['code'] )) ){
    1002                         $out = preg_replace('/^' . preg_quote('<?php', '/') . '/', '', $out);
    1003                         $out = $plugininfo ."\n". $out;
    1004                     }else{
    1005                         $out = $plugininfo. "?>\n". $out;
    1006                     }
    1007                    
    1008                 }
    1009                 $zip->addFromString($proj['slug'].'/'.$h['slug'].'.php', $out);     
    1010             }
    1011         }
    1012         $zip->close();
    1013         $out = file_get_contents( $temp_file ); $fname = 'wp_'.$proj['slug'].'.zip';
    1014         unlink( $temp_file );
    1015         self::output_file($out, $fname, 'application/zip' );
    1016         exit;
    1017     }
    1018    
    1019     /**
    1020      *  Replace functions with live ones when exporting
    1021      */
    1022     public static function replacelive( $out ){
    1023         $out = str_replace('cmchk_include', 'cmchk_include_live', $out );
    1024         $out = str_replace('cmchk_project_dir', 'cmchk_project_dir_live', $out );
    1025         $out = str_replace('cmchk_plugins_loaded', 'plugins_loaded', $out );
    1026         return $out;
    1027     }
    1028    
    1029     /**
    1030      *  Download file
    1031      */
    1032     public static function output_file( $out, $fname, $type = 'application/octet-stream' ){
    1033         $type = (empty($type))? 'application/octet-stream' : $type;
    1034         header('Content-Description: File Transfer');       
    1035         header('Content-Type: '.$type);
    1036         header('Content-Disposition: attachment; filename='.$fname);
    1037         header('Expires: 0');
    1038         header('Cache-Control: must-revalidate');
    1039         header('Pragma: public');
    1040         echo $out;
    1041         exit();             
    1042     }
    1043    
    1044     /**
    1045      *  Save slug of hook and project
    1046      */
    1047     public static function save_slug(){
    1048         global $wpdb;
    1049         if( $_REQUEST['table'] == 'hook' ){
    1050             $table = CMCHK_TABLE_HOOK;
    1051             self::slug_update( $table );
    1052         }else if( $_REQUEST['table'] == 'project' ){
    1053             $table = CMCHK_TABLE_PROJECT;
    1054             self::slug_update( $table );
    1055         }
    1056     }
    1057    
    1058     /**
    1059      *  Save slug based on a particular table
    1060      *
    1061      * @param string $table whether hook or project
    1062      */
    1063     public static function slug_update( $table ){
    1064         global $wpdb; $id = $_REQUEST['id']; $slug = $_REQUEST['slug']; $proj_id = !empty($_REQUEST['proj'])? $_REQUEST['proj'] : 0;   
    1065         $slug = self::get_slug( $table, $id, $slug, $proj_id );         
    1066         $data['slug'] = $slug;
    1067         $wpdb->update( $table, $data, array('id'=> $id) );
    1068         wp_send_json(array('slug'=> $data['slug']));
    1069     }
    1070    
    1071     /**
    1072      *  Get Slug of hook or project
    1073      *
    1074      * @param string $table whether to use hook or project table
    1075      * @param string $id  id of the record to generate slug for
    1076      * @param string $slug the string to propose as slug
    1077      * @param int $pid Project id
    1078      */
    1079     public static function  get_slug( $table, $id, $slug, $pid = 0 ){
    1080         global $wpdb; $slug = sanitize_text_field( $slug ); $slug = str_replace(' ', '_', $slug);
    1081         $table = ( $table == CMCHK_TABLE_PROJECT ) ? CMCHK_TABLE_PROJECT: CMCHK_TABLE_HOOK;
    1082         $slug = substr( $slug, 0, 200 );       
    1083         $sql = "SELECT `slug` FROM `$table` WHERE slug = '%s' and id != %d and project_id = %d LIMIT 1 ";
    1084         $check = $wpdb->get_var( $wpdb->prepare( $sql, $slug, $id, $pid ) );
    1085         if( $check ){       
    1086             $suffix = 1;
    1087             do {
    1088                 $slug_suff = substr($slug . "_$suffix", 0, 200);
    1089                 $sql = "SELECT `slug` FROM `$table` WHERE slug = '%s' and id != %d and project_id = %d LIMIT 1 ";           
    1090                 $check = $wpdb->get_var( $wpdb->prepare( $sql, $slug_suff, $id, $pid ) );   
    1091                 $suffix++;         
    1092             } while ( $check );
    1093             $slug = $slug_suff;
    1094         }
    1095         $slug = apply_filters('cmchk_get_slug', $slug, $id, $table, $pid);
    1096         return $slug;
    1097     }
    1098 
    1099     /**
    1100      *  Get value of one Hook Settings
    1101      *
    1102      * @param string $name name of the settings
    1103      * @param string $default default value if name doesnt exist
    1104      */
    1105     public static function get_setting( $name, $default = ""){
    1106         global $cmchk_settings_default;
    1107         $opt = get_option( CMCHK_SETTINGS, $cmchk_settings_default );
    1108         return isset($opt[$name])? $opt[$name]: $default;
    1109     }
    1110260   
    1111261    /**
     
    1203353     */
    1204354    public static function plugin_deactivate(){
    1205         global $wpdb;
    1206 
    1207         if( self::get_setting('del_table_uninstall', false) ){
    1208             $sql = "DROP TABLE IF EXISTS ".CMCHK_TABLE_HOOK;
    1209             $wpdb->query($sql);
    1210             $sql = "DROP TABLE IF EXISTS ".CMCHK_TABLE_PROJECT;
    1211             $wpdb->query($sql);
    1212         }
    1213 
    1214         if( self::get_setting('del_opt_uninstall', false) ){
    1215             delete_option('cmc_hook_settings');
    1216         }
    1217 
    1218     }
    1219        
    1220     /**
    1221      *  Get Current Url
    1222      */
    1223     public static function current_url(){
    1224         return (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    1225     }
    1226    
    1227     /**
    1228      *  Run Php Code
    1229      *
    1230      *  @param string $file path to the file to require
    1231      *  @param array $cmc_args  arguments to pass to the file
    1232      */
    1233     public static function run_php( $code, $cmchk_args = array() ){
    1234         eval('?>'.$code);
    1235     }
    1236    
    1237     /**
    1238      *  Require a file
    1239      *
    1240      *  @param string $file path to the file to require
    1241      *  @param array $cmc_args  arguments to pass to the file
    1242      */
    1243     public static function include_file( $file, $cmc_args = array() ){
    1244         require( $file );
    1245     }
    1246    
    1247     /**
    1248     * Check whether a string starts with another string
    1249     */ 
    1250     function startsWith($needle, $haystack) {
    1251         return preg_match('/^' . preg_quote($needle, '/') . '/', $haystack);
    1252     }
    1253    
    1254     /**
    1255     * Check whether a string ends with another string
    1256     */
    1257     function endsWith($needle, $haystack) {
    1258         return preg_match('/' . preg_quote($needle, '/') . '$/', $haystack);
    1259     }
     355       
     356    }
    1260357
    1261358    /**
     
    1263360     */
    1264361    public static function includes(){
    1265         require_once("include/default_values.php");
    1266         require_once("include/functions.php");
     362        require_once( CMCHK_DIR_INCLUDE."default_values.php");
     363        require_once( CMCHK_DIR_INCLUDE."class-cmchk-functions.php");
     364        require_once( CMCHK_DIR_INCLUDE."functions.php");
     365        require_once( CMCHK_DIR_INCLUDE."class-cmchk-actions.php");
     366        require_once( CMCHK_DIR_INCLUDE."class-cmchk-hook.php");
     367        require_once( CMCHK_DIR_INCLUDE."class-cmchk-project.php");
     368        require_once( CMCHK_DIR_INCLUDE."class-cmchk-explorer.php");
    1267369    }
    1268370   
     
    1272374    public static function constants(){
    1273375        global $wpdb;
    1274         define('CMCHK_VERSION', '1.0.5');
     376        define('CMCHK_VERSION', '1.0.6');
    1275377        define('CMCHK_FOLDER', basename( dirname( __FILE__ ) ) );
    1276378        define('CMCHK_DIR', plugin_dir_path( __FILE__ ) );
     
    1295397
    1296398    /**
    1297     * Unserializing instances of this class is forbidden.\
     399    * Unserializing instances of this class is forbidden.
    1298400    */
    1299401    public function __wakeup() {
     
    1308410 * @return cmc_hook
    1309411 */
    1310 function cmchk() {
     412function cmchkc() {
    1311413   return cmc_hook::instance();
    1312414}
    1313 cmchk();
     415cmchkc();
    1314416?>
  • cmc-hook/trunk/pages/admin.php

    r1699777 r1701698  
    99    exit;
    1010}
    11 if( !cmc_hook::is_user_allowed()){
     11if( !cmchk::is_user_allowed()){
    1212    exit('You do not have permission to view this page');
    1313}
    1414
    15 $menu = array(
    16     'hook'=>array('text'=>__('Hooks', 'cmchk'), 'href'=>'?page=cmc-hook', 'page'=>function(){   
    17         $sections = array(
    18             'hooks'=>array('page'=>function(){
    19                 cmc_hook::$hooks->cmc_admin_view();
    20             }),   
    21         );
    22         $sections = apply_filters('cmchk_admin_page_section', $sections);
    23         $selected = empty($_REQUEST['section'])? 'hooks':$_REQUEST['section'];
    24         $sec_page = $sections[$selected];
    25         call_user_func_array( $sec_page['page'], array() );
    26     }),   
    27     'project'=>array('text'=>__('Project', 'cmchk'), 'href'=>'?page=cmc-hook&tab=project', 'page'=>function(){
    28         $sections = array(
    29             'project'=>array('page'=> function(){
    30                 echo "<div id='cmchk_section_project_editor' class='cmchk_section'>";
    31                 require("sections/project.php");
    32                 echo "<div>";
    33             }),
    34             'projects'=>array('page'=>function(){ 
    35                 cmc_hook::$projects->cmc_admin_view();
    36             }),
    37         );
    38         $sections = apply_filters('cmchk_admin_page_section', $sections);
    39         $selected = empty($_REQUEST['section'])? 'projects':$_REQUEST['section'];
    40         $sec_page = $sections[$selected];
    41         call_user_func_array( $sec_page['page'], array() );
    42     }),
    43     'explorer'=>array('text'=>__('Explorer', 'cmchk'), 'href'=>'?page=cmc-hook&tab=explorer', 'page'=>function(){
    44         $sections = array(
    45             'explorer'=>array('page'=> function(){
    46                 echo "<div id='cmchk_section_explorer' class='cmchk_section'>";
    47                 require("sections/hook_editor.php"); 
    48                 echo "<div>";
    49             }),
    50         );
    51         $sections = apply_filters('cmchk_admin_page_section', $sections);
    52         $selected = empty($_REQUEST['section'])? 'explorer':$_REQUEST['section'];
    53         $sec_page = $sections[$selected];
    54         call_user_func_array( $sec_page['page'], array() );
    55     }),
    56     'settings'=>array('text'=>__('Settings', 'cmchk'), 'href'=>'?page=cmc-hook&tab=settings', 'page'=>function(){
    57         $sections = array(
    58             'settings'=>array('page'=> function(){
    59                 echo "<div id='cmchk_section_settings' class='cmchk_section'>";
    60                 require("sections/settings.php"); 
    61                 echo "<div>";
    62             }),
    63         );
    64         $sections = apply_filters('cmchk_admin_page_section', $sections);
    65         $selected = empty($_REQUEST['section'])? 'settings':$_REQUEST['section'];
    66         $sec_page = $sections[$selected];
    67         call_user_func_array( $sec_page['page'], array() );
    68        
    69     }),
    70 );
     15$menu = array();
     16$menu['hook'] = array('text'=>__('Hooks', 'cmchk'), 'href'=>'?page=cmc-hook',
     17    'sections'=> array(
     18        'hooks'=>array('page' => function(){
     19            cmc_hook::$hooks->cmc_admin_view();
     20        }),
     21    ), 'default'=>'hooks');   
     22$menu['project'] = array('text'=>__('Project', 'cmchk'), 'href'=>'?page=cmc-hook&tab=project',
     23    'sections' => array(
     24        'project'=>array('page'=> function(){
     25            echo "<div id='cmchk_section_project_editor' class='cmchk_section'>";
     26            require("sections/project.php");
     27            echo "<div>";
     28        }),
     29        'projects'=>array('page'=>function(){ 
     30            cmc_hook::$projects->cmc_admin_view();
     31        }),
     32    ), 'default'=>'projects' );
     33$menu['explorer'] = array('text'=>__('Explorer', 'cmchk'), 'href'=>'?page=cmc-hook&tab=explorer',
     34    'sections' => array(
     35        'explorer'=>array('page'=> function(){
     36            echo "<div id='cmchk_section_explorer' class='cmchk_section'>";
     37            require("sections/hook_editor.php"); 
     38            echo "<div>";
     39        }),
     40    ), 'default'=>'explorer' );
     41$menu['settings'] = array('text'=>__('Settings', 'cmchk'), 'href'=>'?page=cmc-hook&tab=settings',
     42    'sections' => array(
     43        'settings'=>array('page'=> function(){
     44            echo "<div id='cmchk_section_settings' class='cmchk_section'>";
     45            require("sections/settings.php"); 
     46            echo "<div>";
     47        }),
     48    ), 'default'=>'settings' );
    7149
    7250$sel_tab = empty($_REQUEST['tab']) ? 'hook': $_REQUEST['tab'];
     
    9775    </h1>
    9876    <div style="width:400px;">       
    99         <form id="cmchk-hook-add-form" class="cmchk-hook-project-folder-add-form" style="display:none;" action="<?php echo admin_url('admin-ajax.php').'?action=cmchk_hook_editor&tab='.$_REQUEST['tab']; ?>" >
     77        <form id="cmchk-hook-add-form" class="cmchk-hook-project-folder-add-form" style="display:none;" action="<?php echo admin_url('admin-ajax.php').'?tab='.$_REQUEST['tab']; ?>" >
    10078            <p>
    10179                <?php wp_nonce_field( 'cmc-hook-nonce','_wpnonce', true, true ); ?>
    10280                <input type="text" name="title" class="widefat" style="width:70%" placeholder="<?php echo __("Hook Title", "cmchk"); ?>" />
    103                 <button type="submit" class="button button-primary" style="width:15%;"><?php echo __('Save', 'cmchk'); ?></button>
     81                <button type="submit" class="button button-primary" name="action" value="cmchk_hook_editor" style="width:15%;"><?php echo __('Save', 'cmchk'); ?></button>
    10482            </p>
    10583        </form>
    106         <form id="cmchk-project-add-form" class="cmchk-hook-project-folder-add-form" style="display:none;" action="<?php echo admin_url('admin-ajax.php').'?action=cmchk_project_editor&tab='.$_REQUEST['tab']; ?>">
     84        <form id="cmchk-project-add-form" class="cmchk-hook-project-folder-add-form" style="display:none;" action="<?php echo admin_url('admin-ajax.php').'?tab='.$_REQUEST['tab']; ?>">
    10785            <p>
    10886                <?php wp_nonce_field( 'cmc-hook-project-nonce','_wpnonce', true, true ); ?>
    10987                <input type="text" name="title" class="widefat" style="width:70%" placeholder="<?php echo __("Project Title", "cmchk"); ?>" />
    110                 <button  type="submit" class="button button-primary" style="width:15%;" ><?php echo __('Save', 'cmchk'); ?></button>
     88                <button  type="submit" class="button button-primary" name="action" value="cmchk_project_editor" style="width:15%;" ><?php echo __('Save', 'cmchk'); ?></button>
    11189            </p>
    11290        </form>
    113         <form id="cmchk-folder-add-form" class="cmchk-hook-project-folder-add-form" method="post" style="display:none;" action="<?php echo admin_url('admin-ajax.php').'?action=cmchk_hook_editor&tab='.$_REQUEST['tab']; ?>" >
     91        <form id="cmchk-folder-add-form" class="cmchk-hook-project-folder-add-form" method="post" style="display:none;" action="<?php echo admin_url('admin-ajax.php').'?tab='.$_REQUEST['tab']; ?>" >
    11492            <p>
    11593                <?php wp_nonce_field( 'cmchk-project-folder-add-nonce','_wpnonce', true, true ); ?>
     
    128106        </form>
    129107    </div>         
    130     <h2 id="cmchk_tab_menu" class="nav-tab-wrapper wp-clearfix">       
    131         <?php             
    132             $menu = apply_filters('cmchk_admin_page_menu', $menu);
    133             foreach($menu as $k => $m){
    134                 if( $m['active'] === false) continue;
    135                 $s = ($sel_tab == $k)? "nav-tab-active":""; $m['class'] = is_array($m['class'])? implode(' ', $m['class']):$m['class'];
    136                 echo sprintf('<a href="%s" class="nav-tab %s %s" %s > %s </a>', $m['href'], $m['class'], $s, $m['atts'], $m['text'] );
    137             }
    138         ?>
    139     </h2>
    140     <div id="cmchk_tab" class="cmchk_tab_<?php echo $sel_tab; ?>">
    141         <?php
    142             $page = $menu[$sel_tab];
    143             call_user_func_array( $page['page'], array() );
    144         ?>
    145     </div>
     108    <div id="cmchk_admin_page_tab">
     109        <h2 id="cmchk_admin_page_menu" class="nav-tab-wrapper wp-clearfix">       
     110            <?php             
     111                $menu = apply_filters('cmchk_admin_page_menu', $menu);
     112                foreach( $menu as $k => $m ){
     113                    if( $m['active'] === false) continue;
     114                    $s = ($sel_tab == $k)? "nav-tab-active":""; $m['class'] = is_array($m['class'])? implode(' ', $m['class']):$m['class'];
     115                    echo sprintf('<a href="%s" class="nav-tab %s %s" %s > %s </a>', $m['href'], $m['class'], $s, $m['atts'], $m['text'] );
     116                }
     117            ?>
     118        </h2>
     119        <div id="cmchk_admin_page_<?php echo $sel_tab; ?>" class="cmchk_admin_page_body">
     120            <?php
     121                cmchk::menu_render( $sel_tab, $_REQUEST['section'], $menu );
     122                //$page = $menu[$sel_tab];
     123               // call_user_func_array( $page['page'], array() );
     124            ?>
     125        </div>
     126    </div>
    146127</div>
    147128<script>
     
    167148            if( $form.is('#cmchk-hook-add-form') ) data.push({name: 'project_id', value: $('#cmchk_project_id').val() || 0});
    168149            if( $form.is('#cmchk-folder-add-form') ) data.push({name: 'project_id', value: $('#cmchk_project_id').val() || 0});
     150            if( $btn.prop('name') != '' ) data.push({name: $btn.prop('name'), value: $btn.prop('value') });
    169151            $.post($form.attr('action'), data, function(result){
    170152                if(result.message) alert(result.message);
  • cmc-hook/trunk/pages/sections/hook_attributes.php

    r1664640 r1701698  
    88    exit;
    99}
    10 if( !cmc_hook::is_user_allowed()){
     10if( !cmchk::is_user_allowed()){
    1111    exit('You do not have permission to view this page');
    1212}
     
    3131?>
    3232<form id="cmchk-hookeditor-hook-attributes" data-cmchk='<?php echo json_encode($html_json); ?>' >
    33     <p data-step="7" data-intro="Enter The Title">     
     33    <p>     
    3434        <label>Title</label><br/>
    3535        <input type="text" name="title" class="widefat" value="<?php echo $model['title']; ?>" />
     
    4747        <input type="text" class="widefat" readonly="true" value="<?php echo $model['id']; ?>" />
    4848    </p>
    49     <p data-step="8" data-intro="Select Type: Hook or php file">
     49    <p>
    5050        <label><?php echo __('Type', 'cmchk') ?></label><br/>
    5151        <select id="cmc-hk-type" name="type" class="widefat" onchange="var r = /filter|action/.test(this.value); jQuery('#cmc-hk-hook-box').toggle( r );" >
     
    6565    <?php } ?>
    6666   
    67     <p data-step="9" data-intro="Describe the record">
     67    <p>
    6868        <label><?php echo __('Description', 'cmchk') ?></label><br/>
    6969        <textarea name="description" row="3" class="widefat" style="vertical-align: top;" ><?php echo $model['description']; ?></textarea>
    7070    </p>
    7171
    72     <p data-step="10" data-intro="Activation and Shortcode">
     72    <p>
    7373        <label>
    7474            <?php echo __('Active', 'cmchk') ?>
     
    9191    </p>
    9292
    93     <p data-step="11" data-intro="Run record in safe mode">
     93    <p>
    9494        <?php global $wp; //$wp->request ?>
    95         <a class="page-title-action" target="_blank" href="<?php echo add_query_arg( array(), cmc_hook::current_url()); ?>" >
     95        <a class="page-title-action" target="_blank" href="<?php echo add_query_arg( array(), admin_url('tools.php?page=cmc-hook') ); ?>" >
    9696            <?php echo __('Run', 'cmchk') ?>
    9797        </a>
    98         <a class="page-title-action" target="_blank" href="<?php echo add_query_arg(array('cmchk_safe'=>$model['id']),cmc_hook::current_url()); ?>" >
     98        <a class="page-title-action" target="_blank" href="<?php echo add_query_arg(array('cmchk_safe'=>$model['id']), admin_url('tools.php?page=cmc-hook') ); ?>" >
    9999            <?php echo __('Run In Safe Mode', 'cmchk') ?>
    100100        </a>
     
    184184                return false
    185185            });
    186            
     186
    187187        })(jQuery);
    188188    </script>
  • cmc-hook/trunk/pages/sections/hook_code.php

    r1699777 r1701698  
    88    exit;
    99}
    10 if( !cmc_hook::is_user_allowed()){
     10if( !cmchk::is_user_allowed()){
    1111    exit('You do not have permission to view this page');
    1212}
     
    5353    </div>
    5454    <p style="margin-top:35px;">
    55         <label data-step="4" data-intro="Select Hook Record to run">
     55        <label>
    5656            <?php echo __('Php File', 'cmchk') ?>
    5757            <select id="cmc-hk-phpfile"  >
     
    6666            </a>
    6767        </label>
    68         <label data-step="5" data-intro="Select Wordpress Function">
     68        <label>
    6969            <?php echo __('WP functions', 'cmchk') ?>
    7070            <select id="cmc-hk-wpfunc">
     
    7979            </a>
    8080        </label>
    81         <a id="cmc-hk-media-insert" class="button button-primary" href="javascript:void(0);" data-step="6" data-intro="Add Media Files">
     81        <a id="cmc-hk-media-insert" class="button button-primary" href="javascript:void(0);">
    8282            <i class="dashicons dashicons-admin-media" style="margin-top:4px;"></i>
    8383        </a>
  • cmc-hook/trunk/pages/sections/hook_editor.php

    r1664640 r1701698  
    88    exit;
    99}
    10 if( !cmc_hook::is_user_allowed()){
     10if( !cmchk::is_user_allowed()){
    1111    exit('You do not have permission to view this page');
    1212}
     
    6060                <?php
    6161                    if( !empty( $model ) ){
    62                         cmc_hook::include_file( CMCHK_DIR."pages/sections/hook_code.php", array('hook_id'=>$hook_id) );
     62                        cmchk::include_file( CMCHK_DIR."pages/sections/hook_code.php", array('hook_id'=>$hook_id) );
    6363                    }                                   
    6464                ?>
     
    8585                                <?php
    8686                                    if( !empty( $model ) ){
    87                                         cmc_hook::include_file( CMCHK_DIR."pages/sections/hook_attributes.php", array('hook_id'=>$hook_id) );
     87                                        cmchk::include_file( CMCHK_DIR."pages/sections/hook_attributes.php", array('hook_id'=>$hook_id) );
    8888                                    }                                   
    8989                                ?>
     
    9292                                <?php
    9393                                    if( $projid > 0){
    94                                         cmc_hook::include_file( CMCHK_DIR."pages/sections/project_attributes.php", array('proj_id'=>$projid) );// require_once("project_attributes.php");
     94                                        cmchk::include_file( CMCHK_DIR."pages/sections/project_attributes.php", array('proj_id'=>$projid) );// require_once("project_attributes.php");
    9595                                    }
    9696                                ?>
  • cmc-hook/trunk/pages/sections/plugin_form.php

    r1664640 r1701698  
    1111    exit;
    1212}
    13 if( !cmc_hook::is_user_allowed()){
     13if( !cmchk::is_user_allowed()){
    1414    exit('You do not have permission to view this page');
    1515}
  • cmc-hook/trunk/pages/sections/project.php

    r1699777 r1701698  
    1010    exit;
    1111}
    12 if( !cmc_hook::is_user_allowed()){
     12if( !cmchk::is_user_allowed()){
    1313    exit('You do not have permission to view this page');
    1414}
     
    6262                <div class="inside">
    6363                    <?php
    64                         cmc_hook::include_file( CMCHK_DIR."pages/sections/project_attributes.php", array('proj_id'=>$proj_id) );
     64                        cmchk::include_file( CMCHK_DIR."pages/sections/project_attributes.php", array('proj_id'=>$proj_id) );
    6565                    ?>               
    6666                </div>
     
    8181<script>
    8282    (function($){
    83         (function($, cmchk){
    84            
    85            
    86         })(jQuery, cmchk);
    8783       
    8884        $('#cmchk-form-project-hook-submit').click(function(){
  • cmc-hook/trunk/pages/sections/project_attributes.php

    r1664640 r1701698  
    1010    exit;
    1111}
    12 if( !cmc_hook::is_user_allowed()){
     12if( !cmchk::is_user_allowed()){
    1313    exit('You do not have permission to view this page');
    1414}
     
    3939        </p>
    4040            <?php if( !empty( $proj_id ) ){ ?>
    41          <p>
     41        <p>
    4242            <label><?php echo __('Project ID', 'cmchk') ?></label><br/>
    4343            <input type="text" class="widefat" readonly="true" value="<?php echo $model['id']; ?>" />
     
    8080        <p>
    8181            <?php global $wp; //$wp->request ?>
    82             <a class="page-title-action" target="_blank" href="<?php echo add_query_arg(array(),cmc_hook::current_url()); ?>" data-step="8" data-intro="Run">
     82            <a class="page-title-action" target="_blank" href="<?php echo add_query_arg(array(),cmchk::current_url()); ?>" data-step="8" data-intro="Run">
    8383                <?php echo __('Run', 'cmchk') ?>
    8484            </a>
    85             <a class="page-title-action" target="_blank" href="<?php echo add_query_arg(array('cmchk_safe_proj'=>$model['id']),cmc_hook::current_url()); ?>" data-step="8" data-intro="Run record in safe mode">
     85            <a class="page-title-action" target="_blank" href="<?php echo add_query_arg(array('cmchk_safe_proj'=>$model['id']),cmchk::current_url()); ?>" data-step="8" data-intro="Run record in safe mode">
    8686                <?php echo __('Run In Safe Mode', 'cmchk') ?>
    8787            </a>
     
    120120        <?php
    121121        if( !empty( $proj_id ) ){
    122             cmc_hook::include_file( CMCHK_DIR."pages/sections/plugin_form.php", array('proj_id'=>$proj_id) );
     122            cmchk::include_file( CMCHK_DIR."pages/sections/plugin_form.php", array('proj_id'=>$proj_id) );
    123123        }
    124124        ?>
  • cmc-hook/trunk/pages/sections/settings.php

    r1664640 r1701698  
    99    exit;
    1010}
    11 if( !cmc_hook::is_user_allowed()){
     11if( !cmchk::is_user_allowed()){
    1212    exit('You do not have permission to view this page');
    1313}
  • cmc-hook/trunk/readme.txt

    r1699777 r1701698  
    44Requires at least: 4.6.0
    55Tested up to: 4.8
    6 Stable tag: 1.0.5
     6Stable tag: 1.0.6
    77License: GPLv3
    88License URI: https://www.gnu.org/licenses/gpl-3.0.html
Note: See TracChangeset for help on using the changeset viewer.