<commit_before><?php

namespace NightOwl\Model;

use NightOwl\Model\Audit;
use MongoClient;

/**
* LaunchCodesModel provides a concrete mechanism for retrieving and persisting
* Launch Codes. It connects to a Consul Key/Value store to persist the basic
* data pertaining to the code. It also uses MongoDB to store meta-data about
* each code that is important for administration but not required in production.
*
* Author: <NAME>
* Date: April 30, 2015
*/
class LaunchCodesModel
{
    /* HTTP Statuses that indicate Consul response types. */
    const CONSUL_SUCCESS_CODE = 200;

    /**
    * Create a new instance of LaunchCodesModel and connect to the MongoDB.
    */
    public function __construct()
    {
        $this->config = $this->getConfig();

        // Create DB
        $dbn = $this->config['mongo']['name'];
        $m = new MongoClient($this->config['mongo']['url']);
        $this->db = $m->$dbn;

        // Create Audit Controller
        $this->audit = new Audit();
    }

    /**
    * Get the list of Launch Codes.
    *
    * This function will retrieve the list of launch codes from Consul that
    * either (a) are wholly the prefix (if recurse is false) or (b) contain the
    * the prefix (if recurse is true). It does not retrieve code meta-data from
    * the MongoDB.
    *
    * Params:
    *      $dataCentre : the Consul data centre to retrieve launch codes from.
    *      $prefix : the prefix (or key) to search for in the data store.
    *      $recurse : if True, all keys beginning with $prefix will be returned
    *                 if False, only that key matching the $prefix is returned.
    *
    * Returns:
    *      The list of launch codes as returned by Consul (may be empty) if
    *      successful. If an error occurred, FALSE is returned instead.
    *
    * Author: <NAME>
    * Date: April 30, 2015
    */
    public function getLaunchCodes($dataCentre, $prefix, $recurse)
    {
        $httpCode = 0;
        $result = '';
        $url = $this->getConsulKVUrl() . $prefix;

        // Build the data centre into the URL if set
        if ($dataCentre !== '')
        {
            $url .= '?dc=' . $dataCentre;

            // Append 'recurse' property if requested
            if ($recurse)
                $url .= '&recurse';
        }
        // Append only 'recurse' if required.
        else if ($recurse)
        {
            $url .= '?recurse';
        }

        // Request data through curl
        $result = $this->doCurlRequest($url, $httpCode, 'GET');

        // Successfully retrieved data from Consul
        if ($httpCode == self::CONSUL_SUCCESS_CODE)
        {
            return json_decode(($result), true);
        }

        // An error occurred or the set is empty
        return FALSE;
    }

    /**
    * Create a new launch code in both Consul and the MongoDB.
    *
    * Params:
    *    $token         : the users authorization token
    *		$key           : the Launch Code Key
    *		$restriction   : the restriction type (eg "boolean")
    *		$value 		     : the value associated with the restriction (eg "true")
    *		$description   : a description of the Launch Code
    *		$availableToJS : true or false - whether the code is available in JavaScript.
    *
    * Returns: True on success, False on failure
    *
    * Author: <NAME>
    * Date: May 1, 2015
    *
    * REVISIONS:
    *      Calvin Rempel - May 3, 2015
    *          - Added Mongo insertion/updating.
    */
    public function createOrEditLaunchCode($token, $key, $restriction, $value, $owner, $description, $availableToJS)
    {
        $logMessage = ' - EDIT - ';

        // Try to set the code in Consul. If that works, add to Mongo.
        if ($this->setInConsul($key, $restriction, $value, $availableToJS))
        {
            // Setup update/creation constraints
            $where = array('key' => $key);
            $obj = array(
                'key'         => $key,
                'description' => $description,
                'createdDate' => date('Y-m-d H:i:s'),
                'owner'       => $owner,
            );
            $options = array('upsert' => true);

            // If the code doesn't already exist, set the creation date.
            $code = array('key' => $key);
            if(is_null(($code = $this->db->LaunchCodes->findOne($code))))
            {
                $obj['createdDate'] = $code['createdDate'];
                $logMessage = ' - CREATE - ';
            }

            // Create/Edit the LaunchCode in Mongo
            $this->db->LaunchCodes->update($where, $obj, $options);

            // Log the edit
            $logMessage .= $restriction . ' - ' . $value . ' JS(';
            $logMessage .= ($availableToJS ? 'True' : 'False') . ')';

            $this->audit->LogEdit($token, $logMessage, $key);

            return true;
        }

        return false;
    }

    /**
    * Delete a Launch Code from Consul (and eventually MongoDB).
    *
    * Params:
    *    $token : the users authorization token
    *		$key   : the key of the launch code to delete.
    *
    * Returns: True on success, False on failure.
    *<commit_msg>Fixed code creation/edit time<commit_after><?php

namespace NightOwl\Model;

use NightOwl\Model\Audit;
use MongoClient;

/**
* LaunchCodesModel provides a concrete mechanism for retrieving and persisting
* Launch Codes. It connects to a Consul Key/Value store to persist the basic
* data pertaining to the code. It also uses MongoDB to store meta-data about
* each code that is important for administration but not required in production.
*
* Author: <NAME>
* Date: April 30, 2015
*/
class LaunchCodesModel
{
    /* HTTP Statuses that indicate Consul response types. */
    const CONSUL_SUCCESS_CODE = 200;

    /**
    * Create a new instance of LaunchCodesModel and connect to the MongoDB.
    */
    public function __construct()
    {
        $this->config = $this->getConfig();

        // Create DB
        $dbn = $this->config['mongo']['name'];
        $m = new MongoClient($this->config['mongo']['url']);
        $this->db = $m->$dbn;

        // Create Audit Controller
        $this->audit = new Audit();
    }

    /**
    * Get the list of Launch Codes.
    *
    * This function will retrieve the list of launch codes from Consul that
    * either (a) are wholly the prefix (if recurse is false) or (b) contain the
    * the prefix (if recurse is true). It does not retrieve code meta-data from
    * the MongoDB.
    *
    * Params:
    *      $dataCentre : the Consul data centre to retrieve launch codes from.
    *      $prefix : the prefix (or key) to search for in the data store.
    *      $recurse : if True, all keys beginning with $prefix will be returned
    *                 if False, only that key matching the $prefix is returned.
    *
    * Returns:
    *      The list of launch codes as returned by Consul (may be empty) if
    *      successful. If an error occurred, FALSE is returned instead.
    *
    * Author: <NAME>
    * Date: April 30, 2015
    */
    public function getLaunchCodes($dataCentre, $prefix, $recurse)
    {
        $httpCode = 0;
        $result = '';
        $url = $this->getConsulKVUrl() . $prefix;

        // Build the data centre into the URL if set
        if ($dataCentre !== '')
        {
            $url .= '?dc=' . $dataCentre;

            // Append 'recurse' property if requested
            if ($recurse)
                $url .= '&recurse';
        }
        // Append only 'recurse' if required.
        else if ($recurse)
        {
            $url .= '?recurse';
        }

        // Request data through curl
        $result = $this->doCurlRequest($url, $httpCode, 'GET');

        // Successfully retrieved data from Consul
        if ($httpCode == self::CONSUL_SUCCESS_CODE)
        {
            return json_decode(($result), true);
        }

        // An error occurred or the set is empty
        return FALSE;
    }

    /**
    * Create a new launch code in both Consul and the MongoDB.
    *
    * Params:
    *    $token         : the users authorization token
    *		$key           : the Launch Code Key
    *		$restriction   : the restriction type (eg "boolean")
    *		$value 		     : the value associated with the restriction (eg "true")
    *		$description   : a description of the Launch Code
    *		$availableToJS : true or false - whether the code is available in JavaScript.
    *
    * Returns: True on success, False on failure
    *
    * Author: <NAME>
    * Date: May 1, 2015
    *
    * REVISIONS:
    *      <NAME> - May 3, 2015
    *          - Added Mongo insertion/updating.
	*
	*	   <NAME> - May 8, 2015
	*		   - Fix: Creation date set on creation, not altered on edit.
    */
    public function createOrEditLaunchCode($token, $key, $restriction, $value, $owner, $description, $availableToJS)
    {
        $logMessage = ' - CREATE - ';

        // Try to set the code in Consul. If that works, add to Mongo.
        if ($this->setInConsul($key, $restriction, $value, $availableToJS))
        {
            // Setup update/creation constraints
            $where = array('key' => $key);
            $obj = array(
                'key'         => $key,
                'description' => $description,
                'createdDate' => date('Y-m-d H:i:s'),
                'owner'       => $owner,
            );
            $options = array('upsert' => true);

            // If the code doesn't already exist, set the creation date.
            $code = array('key' => $key);
            if(!is_null(($code = $this->db->LaunchCodes->findOne($code))))
            {
                $obj['createdDate'] = $code['createdDate'];
                $logMessage = ' - EDIT - ';
            }

            // Create/Edit the LaunchCode in Mongo
            $this->db->LaunchCodes->update($where, $obj, $options);

            // Log the edit
            $logMessage .= $restriction . ' - ' . $value . ' JS(' . $availableToJS . ')';

            $this->audit->LogEdit($token, $logMessage, $key);

            return true;
        }

        return false;
    }

    /**
    * Delete a Launch Code from Consul (and eventually MongoDB).
    *
    * Params:
    *    $token : the users authorization token
    *		$key   : the key of the launch code to delete.
    *
    * Returns: True on success, False on failure.
    *
{'fraction_non_alphanumeric': 0.11594482492524356, 'fraction_numerical': 0.005498215491463297, 'mean_word_length': 1.8808002222839677, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 61, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, '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': '673545', 'n_tokens_mistral': 3118, 'n_tokens_neox': 2953, 'n_words': 1009}