<commit_before><?php
/**
 * COmanage Registry CO Grouper Provisioner Target Model
 *
 * Copyright (C) 2012-15 University Corporation for Advanced Internet Development, Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * @copyright     Copyright (C) 2012-15 University Corporation for Advanced Internet Development, Inc.
 * @link          http://www.internet2.edu/comanage COmanage Project
 * @package       registry-plugin
 * @since         COmanage Registry v0.8.3
 * @license       Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 * @version       $Id$
 */

App::uses("CoProvisionerPluginTarget", "Model", "ConnectionManager");
App::uses('GrouperRestClient', 'GrouperProvisioner.Lib');
App::uses('GrouperRestClientException', 'GrouperProvisioner.Lib');
App::uses('GrouperCouProvisioningStyle', 'GrouperProvisioner.Lib');

class CoGrouperProvisionerTarget extends CoProvisionerPluginTarget {

  // Define class name for cake
  public $name = "CoGrouperProvisionerTarget";
  
  // Add behaviors
  public $actsAs = array('Containable');
  
  // Association rules from this model to other models
  public $belongsTo = array("CoProvisioningTarget");
  
  public $hasMany = array(
      "CoGrouperProvisionerGroup" => array(
      'className' => 'GrouperProvisioner.CoGrouperProvisionerGroup',
      'dependent' => true
    ),
  );
  
  // Default display field for cake generated views
  public $displayField = "serverurl";
  
  // Validation rules for table elements
  public $validate = array(
    'co_provisioning_target_id' => array(
      'rule' => 'numeric',
      'required' => true,
      'allowEmpty' => false,
      'on' => null,
      'message' => 'A CO Provisioning Target ID must be provided'
    ),
    'serverurl' => array(
      'rule' => array('custom', '/^https?:\/\/.*/'),
      'required' => true,
      'allowEmpty' => false,
      'on' => null,
      'message' => 'Please enter a valid http or https URL'
    ),
    'contextpath' => array(
      'rule' => array('custom', '/^\/.*/'),
      'required' => true,
      'allowEmpty' => false,
      'on' => null,
      'message' => 'Please enter a valid context path'
    ),
    'login' => array(
      'rule' => 'notBlank',
      'required' => true,
      'on' => null,
      'allowEmpty' => false,
    ),
    'password' => array(
      'rule' => 'notBlank',
      'required' => true,
      'on' => null,
      'allowEmpty' => false,
    ),
    'stem' => array(
      'rule' => 'notBlank',
      'required' => true,
      'allowEmpty' => false,
      'on' => null,
    ),
    'login_identifier' => array(
      'rule' => 'notBlank',
      'required' => true,
      'allowEmpty' => false,
      'on' => null,
    ),
    'email_identifier' => array(
      'rule' => 'notBlank',
      'required' => true,
      'allowEmpty' => false,
      'on' => null,
    ),
    'subject_view' => array(
      'subjectViewRule1' => array(
      'rule' => array('maxLength', 30),
      'required' => true,
      'allowEmpty' => false,
      'on' => null,
    ),
    'subjectViewRule2' => array(
      'rule' => 'isUnique',
      'message' => 'The view name must be unique'
      )
    )
  );
  
  /**
   * Called after each successful save operation. Right now used
   * to create the view(s) for Grouper subjects.
   * 
   * @since COmanage Registry v0.9.3
   * @param bool $created True if this save created a new record
   * @param array $options Options passed from Model::save().
   * @return void
   */
  public function afterSave($created, $options = array()) {
    $prefix = "";
    $db =& ConnectionManager::getDataSource('default');
    $db_driver = split("/", $db->config['datasource'], 2);
      
    if(isset($db->config['prefix'])) {
      $prefix = $db->config['prefix'];
    }        
    
    $view = $this->data['CoGrouperProvisionerTarget']['subject_view'];
    
    $args = array();
    $args['conditions']['CoProvisioningTarget.id'] = $this->data['CoGrouperProvisionerTarget']['co_provisioning_target_id'];
    $args['contain'] = false;
    $target = $this->CoProvisioningTarget->find('first', $args);
    $coId = $target['CoProvisioningTarget']['co_id'];
    
    $sqlTemplate = "
CREATE OR REPLACE VIEW $view (id, name, lfname, description, description_lower, loginid, email) AS
SELECT
  CONCAT('COMANAGE_', '$coId', '_', CAST(cm_co_people.id AS @CAST_TYPE@)),
  CONCAT(COALESCE(cm_names.given,''), ' ', COALESCE(cm_names.family,'')),
  CONCAT(COALESCE(cm_names.family,''), ' ', COALESCE(cm_names.given,'')),
  CONCAT(COALESCE(cm_names.given,''), ' ', COALESCE(cm_names.family,''), ' (', cm_cos.name, ')'),
  LOWER(CONCAT(cm_names.given, ' ', cm_names.family, ' ', COALESCE(cm_email_addresses.mail, ''), ' ', COALESCE(cm_identifiers.identifier,''))),
  cm_identifiers.identifier,
  cm_email_addresses.mail
FROM
  cm_co_people
  LEFT JOIN cm_names ON cm_co_people.id = cm_names.co_person_id AND cm_names.primary_name is true
  JOIN cm_cos ON cm_co_people.co_id = cm_cos.id AND cm_cos.id = $coId
  LEFT JOIN cm_identifiers ON cm_co_people.id = cm_identifiers.co_person_id AND cm_identifiers.type = '@IDENTIFIER_TYPE@'
  LEFT JOIN cm_email_addresses ON cm_co_people.id = cm_email_addresses.co_person_id AND cm_email_addresses.type = '@EMAIL_TYPE@'                                                                                                                                              
  WHERE cm_co_people.status = 'A' AND cm_co_people.co_person_id IS NULL
  ";                  
        
    $replacements = array();
    $replacements['cm_'] = $prefix;
    $replacements['@IDENTIFIER_TYPE@'] = $this->data['CoGrouperProvisionerTarget']['login_identifier'];
    $replacements['@EMAIL_TYPE@'] = $this->data['CoGrouperProvisionerTarget']['email_identifier'];  
    
    switch ($db_driver[1]) {
      case 'Mysql':
        $replacements['@CAST_TYPE@'] = 'char';
        break;
      case 'Postgres':
        $replacements['@CAST_TYPE@'] = 'text';
        break;
    }
    
    $sql = strtr($sqlTemplate, $replacements);       <commit_msg>Fix SQL view created by Grouper Provisioner (CO-1269)<commit_after><?php
/**
 * COmanage Registry CO Grouper Provisioner Target Model
 *
 * Copyright (C) 2012-15 University Corporation for Advanced Internet Development, Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * @copyright     Copyright (C) 2012-15 University Corporation for Advanced Internet Development, Inc.
 * @link          http://www.internet2.edu/comanage COmanage Project
 * @package       registry-plugin
 * @since         COmanage Registry v0.8.3
 * @license       Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 * @version       $Id$
 */

App::uses("CoProvisionerPluginTarget", "Model", "ConnectionManager");
App::uses('GrouperRestClient', 'GrouperProvisioner.Lib');
App::uses('GrouperRestClientException', 'GrouperProvisioner.Lib');
App::uses('GrouperCouProvisioningStyle', 'GrouperProvisioner.Lib');

class CoGrouperProvisionerTarget extends CoProvisionerPluginTarget {

  // Define class name for cake
  public $name = "CoGrouperProvisionerTarget";
  
  // Add behaviors
  public $actsAs = array('Containable');
  
  // Association rules from this model to other models
  public $belongsTo = array("CoProvisioningTarget");
  
  public $hasMany = array(
      "CoGrouperProvisionerGroup" => array(
      'className' => 'GrouperProvisioner.CoGrouperProvisionerGroup',
      'dependent' => true
    ),
  );
  
  // Default display field for cake generated views
  public $displayField = "serverurl";
  
  // Validation rules for table elements
  public $validate = array(
    'co_provisioning_target_id' => array(
      'rule' => 'numeric',
      'required' => true,
      'allowEmpty' => false,
      'on' => null,
      'message' => 'A CO Provisioning Target ID must be provided'
    ),
    'serverurl' => array(
      'rule' => array('custom', '/^https?:\/\/.*/'),
      'required' => true,
      'allowEmpty' => false,
      'on' => null,
      'message' => 'Please enter a valid http or https URL'
    ),
    'contextpath' => array(
      'rule' => array('custom', '/^\/.*/'),
      'required' => true,
      'allowEmpty' => false,
      'on' => null,
      'message' => 'Please enter a valid context path'
    ),
    'login' => array(
      'rule' => 'notBlank',
      'required' => true,
      'on' => null,
      'allowEmpty' => false,
    ),
    'password' => array(
      'rule' => 'notBlank',
      'required' => true,
      'on' => null,
      'allowEmpty' => false,
    ),
    'stem' => array(
      'rule' => 'notBlank',
      'required' => true,
      'allowEmpty' => false,
      'on' => null,
    ),
    'login_identifier' => array(
      'rule' => 'notBlank',
      'required' => true,
      'allowEmpty' => false,
      'on' => null,
    ),
    'email_identifier' => array(
      'rule' => 'notBlank',
      'required' => true,
      'allowEmpty' => false,
      'on' => null,
    ),
    'subject_view' => array(
      'subjectViewRule1' => array(
      'rule' => array('maxLength', 30),
      'required' => true,
      'allowEmpty' => false,
      'on' => null,
    ),
    'subjectViewRule2' => array(
      'rule' => 'isUnique',
      'message' => 'The view name must be unique'
      )
    )
  );
  
  /**
   * Called after each successful save operation. Right now used
   * to create the view(s) for Grouper subjects.
   * 
   * @since COmanage Registry v0.9.3
   * @param bool $created True if this save created a new record
   * @param array $options Options passed from Model::save().
   * @return void
   */
  public function afterSave($created, $options = array()) {
    $prefix = "";
    $db =& ConnectionManager::getDataSource('default');
    $db_driver = split("/", $db->config['datasource'], 2);
      
    if(isset($db->config['prefix'])) {
      $prefix = $db->config['prefix'];
    }        
    
    $view = $this->data['CoGrouperProvisionerTarget']['subject_view'];
    
    $args = array();
    $args['conditions']['CoProvisioningTarget.id'] = $this->data['CoGrouperProvisionerTarget']['co_provisioning_target_id'];
    $args['contain'] = false;
    $target = $this->CoProvisioningTarget->find('first', $args);
    $coId = $target['CoProvisioningTarget']['co_id'];
    
    $sqlTemplate = "
CREATE OR REPLACE VIEW $view (id, name, lfname, description, description_lower, loginid, email) AS
SELECT
  CONCAT('COMANAGE_', '$coId', '_', CAST(cm_co_people.id AS @CAST_TYPE@)),
  CONCAT(COALESCE(cm_names.given,''), ' ', COALESCE(cm_names.family,'')),
  CONCAT(COALESCE(cm_names.family,''), ' ', COALESCE(cm_names.given,'')),
  CONCAT(COALESCE(cm_names.given,''), ' ', COALESCE(cm_names.family,''), ' (', cm_cos.name, ')'),
  LOWER(CONCAT(cm_names.given, ' ', cm_names.family, ' ', COALESCE(cm_email_addresses.mail, ''), ' ', COALESCE(cm_identifiers.identifier,''))),
  cm_identifiers.identifier,
  cm_email_addresses.mail
FROM
  cm_co_people
  LEFT JOIN cm_names ON cm_co_people.id = cm_names.co_person_id AND cm_names.primary_name IS TRUE AND cm_names.name_id IS NULL AND cm_names.deleted IS FALSE
  JOIN cm_cos ON cm_co_people.co_id = cm_cos.id AND cm_cos.id = $coId
  LEFT JOIN cm_identifiers ON cm_co_people.id = cm_identifiers.co_person_id AND cm_identifiers.type = '@IDENTIFIER_TYPE@' AND cm_identifiers.identifier_id IS NULL AND cm_identifiers.deleted IS FALSE AND cm_identifiers.status = 'A'
  LEFT JOIN cm_email_addresses ON cm_co_people.id = cm_email_addresses.co_person_id AND cm_email_addresses.type = '@EMAIL_TYPE@' AND cm_email_addresses.email_address_id IS NULL AND cm_email_addresses.deleted IS FALSE
  WHERE cm_co_people.status = 'A' AND cm_co_people.co_person_id IS NULL AND cm_co_people.deleted IS FALSE
  ";                  
        
    $replacements = array();
    $replacements['cm_'] = $prefix;
    $replacements['@IDENTIFIER_TYPE@'] = $this->data['CoGrouperProvisionerTarget']['login_identifier'];
    $replacements['@EMAIL_TYPE@'] = $this->data['CoGrouperProvisionerTarget']['email_identifier'];  
    
    switch ($db_driver[1]) {
      case 'Mysql':
        $replacements['@CAST_TYPE@'] = 'char';
        break;
      case 'Postgres':
        $replacements['@CAST_TYPE@'] = 'text';
        break;
    }
    
    $sql = strtr($sqlTemplate, $replacements);       
{'fraction_non_alphanumeric': 0.1473335341970473, 'fraction_numerical': 0.005272672491714371, 'mean_word_length': 3.1922955478370696, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 131, 'https://': 0, 'lorem ipsum': 0, 'www.': 6, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6816251', 'n_tokens_mistral': 4311, 'n_tokens_neox': 4228, 'n_words': 1014}