<commit_before><?php

/**
 * WP-CLI port of drush-civicrm integration
 * andyw@circle, 08/03/2014
 */
class CiviCRM_Command extends WP_CLI_Command {

    private $args, $assoc_args;

    /**
     * WP-CLI integration with CiviCRM.
     *
     * wp civicrm rest
     * ===============
     * Rest interface for accessing CiviCRM APIs. It can return xml or json formatted data.
     *
     * wp civicrm restore
     * ==================
     * Restore CiviCRM codebase and database back from the specified backup directory
     *
     * wp civicrm sql-conf
     * ===================
     * Show civicrm database connection details.
     *
     * wp civicrm sql-connect
     * ======================
     * A string which connects to the civicrm database.
     *
     * wp civicrm sql-cli
     * ==================
     * Quickly enter the mysql command line.
     *
     * wp civicrm sql-dump
     * ===================
     * Prints the whole CiviCRM database to STDOUT or save to a file.
     *
     * wp civicrm sql-query
     * ====================
     * Usage: wp civicrm sql-query <query> <options>...\n<query> is a SQL statement, which can alternatively be passed via STDIN. Any additional arguments are passed to the mysql command directly.";
     *  
     * wp civicrm update-cfg
     * =====================
     * Update config_backend to correct config settings, especially when the CiviCRM site has been cloned / migrated.
     * 
     * wp civicrm upgrade
     * ==================
     * Take backups, replace CiviCRM codebase with new specified tarfile and upgrade database by executing the CiviCRM upgrade process - civicrm/upgrade?reset=1. Use civicrm-restore to revert to previous state in case anything goes wrong. 
     *      
     * wp civicrm upgrade-db
     * =====================      
     * Run civicrm/upgrade?reset=1 just as a web browser would.
     *   
     */

    public function __invoke($args, $assoc_args) {
       
        # check for existence of Civi
        if (!function_exists('civicrm_initialize')) 
            return WP_CLI::error("Unable to find CiviCRM install.");

        # define command router
        $command_router = array(
            'api'                => 'api',
            'cache-clear'        => 'cacheClear',
            'enable-debug'       => 'enableDebug',
            'member-records'     => 'memberRecords',
            'process-mail-queue' => 'processMailQueue',
            'sql-cli'            => 'sqlCLI',
            'sql-conf'           => 'sqlConf',
            'sql-connect'        => 'sqlConnect',
            'sql-dump'           => 'sqlDump',
            'sql-query'          => 'sqlQuery',
            'update-cfg'         => 'updateConfig',
            'upgrade-db'         => 'upgradeDB'
        );

        # get command
        $command = array_shift($args);

        # check existence of router entry / handler method
        if (!isset($command_router[$command]) or !method_exists($this, $command_router[$command]))
            return WP_CLI::error("Unrecognized command - '$command'");

        # run command
        return $this->{$command_router[$command]}();
                   
    }

    /**
     * Implementation of command 'api'
     */
    private function api() {
        
        $defaults = array('version' => 3);

        list($entity, $action) = explode('.', $this->args[0]);
        array_shift($this->args);

        # parse $params

        switch ($this->getOption('in', 'args')) {
            
            # input params supplied via args ..
            case 'args':
                $params = $defaults;
                foreach ($this->args as $arg) {
                    preg_match('/^([^=]+)=(.*)$/', $arg, $matches);
                    $params[$matches[1]] = $matches[2];
                }
                break;

            # input params supplied via json ..
            case 'json':
                $json   = stream_get_contents(STDIN);
                $params = (empty($json) ? $defaults : array_merge($defaults, json_decode($json, true)));
                break;

            default:
                WP_CLI::error('Unknown format: ' . $format);
                break;
        }

        civicrm_initialize();
        $result = civicrm_api($entity, $action, $params);

        switch ($this->getOption('out', 'pretty')) {
            
            # pretty-print output (default)
            case 'pretty':
                WP_CLI::line(print_r($result, true));
                break;

            # display output as json
            case 'json':
                WP_CLI::line(json_encode($result));
                break;

            default:
                return WP_CLI::error('Unknown format: ' . $format);
        
        }
    
    }

    /**
     * Implementation of command 'cache-clear'
     */
    private function cacheClear() {
        
        civicrm_initialize();
        require_once 'CRM/Core/Config.php';
        $config = CRM_Core_Config::singleton();

        # clear db caching
        $config->clearDBCache();

        # also cleanup the templates_c directory
        $config->cleanup(1, FALSE);

        # also cleanup the session object
        $session = CRM_Core_Session::singleton();
        $session->reset(1);
    
    }

    /**
     * Implementation of command 'enable-debug'
     */
    private function enableDebug() {
        
        civicrm_initialize();

        $params['debug']     = 1;
        $params['backtrace'] = 1;

        require_once 'CRM/Admin/Form/Setting.php';
        CRM_Admin_Form_Setting::commonProcess($params);
    
        WP_CLI::success('Debug setting enabled.');
    
    }

    /**
     * Implementation of command 'member-records'
     */
    private function memberRecords() {

    }

    /**
     * Implementation of command 'process-mail-queue'
     */
    private function processMailQueue() {

    }

    /**
     * Implementation of command 'sql-conf'
     */
    private function sqlConf() {
        <commit_msg>Implemented 'process-mail-queue' and 'member-records', neither of which work, but will come back to these<commit_after><?php

/**
 * WP-CLI port of drush-civicrm integration
 * andyw@circle, 08/03/2014
 */
class CiviCRM_Command extends WP_CLI_Command {

    private $args, $assoc_args;

    /**
     * WP-CLI integration with CiviCRM.
     *
     * wp civicrm rest
     * ===============
     * Rest interface for accessing CiviCRM APIs. It can return xml or json formatted data.
     *
     * wp civicrm restore
     * ==================
     * Restore CiviCRM codebase and database back from the specified backup directory
     *
     * wp civicrm sql-conf
     * ===================
     * Show civicrm database connection details.
     *
     * wp civicrm sql-connect
     * ======================
     * A string which connects to the civicrm database.
     *
     * wp civicrm sql-cli
     * ==================
     * Quickly enter the mysql command line.
     *
     * wp civicrm sql-dump
     * ===================
     * Prints the whole CiviCRM database to STDOUT or save to a file.
     *
     * wp civicrm sql-query
     * ====================
     * Usage: wp civicrm sql-query <query> <options>...\n<query> is a SQL statement, which can alternatively be passed via STDIN. Any additional arguments are passed to the mysql command directly.";
     *  
     * wp civicrm update-cfg
     * =====================
     * Update config_backend to correct config settings, especially when the CiviCRM site has been cloned / migrated.
     * 
     * wp civicrm upgrade
     * ==================
     * Take backups, replace CiviCRM codebase with new specified tarfile and upgrade database by executing the CiviCRM upgrade process - civicrm/upgrade?reset=1. Use civicrm-restore to revert to previous state in case anything goes wrong. 
     *      
     * wp civicrm upgrade-db
     * =====================      
     * Run civicrm/upgrade?reset=1 just as a web browser would.
     *   
     */

    public function __invoke($args, $assoc_args) {
       
        # check for existence of Civi
        if (!function_exists('civicrm_initialize')) 
            return WP_CLI::error("Unable to find CiviCRM install.");

        # define command router
        $command_router = array(
            'api'                => 'api',
            'cache-clear'        => 'cacheClear',
            'enable-debug'       => 'enableDebug',
            'member-records'     => 'memberRecords',
            'process-mail-queue' => 'processMailQueue',
            'sql-cli'            => 'sqlCLI',
            'sql-conf'           => 'sqlConf',
            'sql-connect'        => 'sqlConnect',
            'sql-dump'           => 'sqlDump',
            'sql-query'          => 'sqlQuery',
            'update-cfg'         => 'updateConfig',
            'upgrade-db'         => 'upgradeDB'
        );

        # get command
        $command = array_shift($args);

        # check existence of router entry / handler method
        if (!isset($command_router[$command]) or !method_exists($this, $command_router[$command]))
            return WP_CLI::error("Unrecognized command - '$command'");

        # run command
        return $this->{$command_router[$command]}();
                   
    }

    /**
     * Implementation of command 'api'
     */
    private function api() {
        
        $defaults = array('version' => 3);

        list($entity, $action) = explode('.', $this->args[0]);
        array_shift($this->args);

        # parse $params

        switch ($this->getOption('in', 'args')) {
            
            # input params supplied via args ..
            case 'args':
                $params = $defaults;
                foreach ($this->args as $arg) {
                    preg_match('/^([^=]+)=(.*)$/', $arg, $matches);
                    $params[$matches[1]] = $matches[2];
                }
                break;

            # input params supplied via json ..
            case 'json':
                $json   = stream_get_contents(STDIN);
                $params = (empty($json) ? $defaults : array_merge($defaults, json_decode($json, true)));
                break;

            default:
                WP_CLI::error('Unknown format: ' . $format);
                break;
        }

        civicrm_initialize();
        $result = civicrm_api($entity, $action, $params);

        switch ($this->getOption('out', 'pretty')) {
            
            # pretty-print output (default)
            case 'pretty':
                WP_CLI::line(print_r($result, true));
                break;

            # display output as json
            case 'json':
                WP_CLI::line(json_encode($result));
                break;

            default:
                return WP_CLI::error('Unknown format: ' . $format);
        
        }
    
    }

    /**
     * Implementation of command 'cache-clear'
     */
    private function cacheClear() {
        
        civicrm_initialize();
        require_once 'CRM/Core/Config.php';
        $config = CRM_Core_Config::singleton();

        # clear db caching
        $config->clearDBCache();

        # also cleanup the templates_c directory
        $config->cleanup(1, FALSE);

        # also cleanup the session object
        $session = CRM_Core_Session::singleton();
        $session->reset(1);
    
    }

    /**
     * Implementation of command 'enable-debug'
     */
    private function enableDebug() {
        
        civicrm_initialize();

        $params['debug']     = 1;
        $params['backtrace'] = 1;

        require_once 'CRM/Admin/Form/Setting.php';
        CRM_Admin_Form_Setting::commonProcess($params);
    
        WP_CLI::success('Debug setting enabled.');
    
    }

    /**
     * Implementation of command 'member-records'
     */
    private function memberRecords() {

        civicrm_initialize();

        if (substr(CRM_Utils_System::version(), 0, 3) >= '4.3') {
            
            $result = civicrm_api('Job', 'Execute', array(
                'version'    => 3,
                'api_action' => 'process_membership'
            ));
            
            if ($result['is_error'])
                return WP_CLI::error($result['error_message']);

            WP_CLI::success("Executed 'process_membership' job.");

        } else {

            $_REQUEST['name'] = $this->getOption('civicrm_cron_username', NULL);
            $_REQUEST['pass'] = $this->getOption('civicrm_cron_password', NULL);
            $_REQUEST['key']  = $this->getOption('civicrm_sitekey', NULL);

            global $argv;
            $argv = array(
                0 => "drush",
                1 => "-u" . $_REQUEST['name'],
                2 => "-p" . $_REQUEST['pass'],
                3 => "-s" . $this->getOption('uri', FALSE),
            );

            # not really sure what this should be set to on WP .. maybe 
            # I should just comment it out then pretend it wasn't me.

            # if (!defined('CIVICRM_CONFDIR')) {
            #     define('CIVICRM_CONFDIR', ABSPATH . '/wp-content/plugins/civicrm');
            # }

            include "bin/UpdateMembershipRecord.php";
        
        }

    }

    /**
     * Implementation of command 'process-mail-queue'
     */
    private function processMailQueue() {
        
        civicrm_initialize();

        if (substr(CRM_Utils_System::version(), 0, 3) >= '4.3') {
            
            $result = civicrm_api('Job', 'Execute', array(
                'version'    => 3,
                'api_action' => 'process_mailing'
            ));
            
            if ($result['is_error'])
                return WP_CLI::error($result['error_message']);

            WP_CLI::success("Executed 'process_mailing' job.");

        } else { 
            $result = civicrm_api('Mailing', 'Process', array('version' => 3));
            if ($result['is_error'])
                WP_CLI::error($result['error_message']);
        }

    }

    /**
     * Implementation of command 'sql-conf'
     */
    private function sqlConf() {
        
{'fraction_non_alphanumeric': 0.14459114139693355, 'fraction_numerical': 0.003620102214650767, 'mean_word_length': 1.7777996845425867, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 68, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2035693', 'n_tokens_mistral': 4000, 'n_tokens_neox': 3757, 'n_words': 950}