<commit_before><?php

require_once 'ndipermissions.civix.php';

/*** Create New Permissions ***/
function ndipermissions_civicrm_permission( &$permissions ){
  $prefix = ts('NDI CiviCRM County-State Permissions') . ': '; 
  $permissions = array(
    'view county contacts'     => $prefix . ts('view all contacts who live in your county'),
    'edit county contacts'     => $prefix . ts('edit all contacts who live in your county'),
    'delete county contacts'   => $prefix . ts('delete all contacts who live in your county'),
    'view state contacts'      => $prefix . ts('view all contacts who live in your state'),
    'edit state contacts'      => $prefix . ts('edit all contacts who live in your state'),
    'delete state contacts'    => $prefix . ts('delete all contacts who live in your state'),
  ); // NB: note the convention of using delete in ComponentName, plural for edits
}
/*** Add permissions to current user and adds primary address to new table ***/
function ndipermissions_civicrm_aclWhereClause( $type, &$tables, &$whereTables, &$contactID, &$where ){
  require_once 'CRM/Contact/BAO/Contact/Permission.php';
  if ((CRM_Core_Permission::check('view state contacts') && $type == "1")
      || (CRM_Core_Permission::check('edit state contacts') && $type == "2")
        || (CRM_Core_Permission::check('delete state contacts') && $type == "3")){
    $address_table = 'civicrm_address';
    $tables[$address_table] = $whereTables[$address_table] = "LEFT JOIN {$address_table} ON {$address_table}.contact_id = contact_a.id";
    $where = "{$address_table}.state_province_id IN 
								(SELECT state_province_id FROM civicrm_address WHERE contact_id = {$contactID} AND is_primary = 1 )";
  } elseif ((CRM_Core_Permission::check('view county contacts') && $type == "1")
           || (CRM_Core_Permission::check('edit county contacts') && $type == "2")
             || (CRM_Core_Permission::check('delete county contacts') && $type == "3")){
    $address_table = 'civicrm_address';
    $tables[$address_table] = $whereTables[$address_table] = "LEFT JOIN {$address_table} ON {$address_table}.contact_id = contact_a.id";
    $where = "{$address_table}.county_id IN (SELECT county_id FROM civicrm_address WHERE contact_id = {$contactID} AND is_primary = 1 )";
  }
}
/*** Prevents address_id from being overriden, creates address record will NULL id ***/
function ndipermissions_civicrm_postprocess($formName, &$form){
  if (CRM_Utils_Array::value('address', $form->getVar('_values'))){
    $contactID = $form->_contactId;
    $settings =  CRM_Core_BAO_Setting::getItem("Permission Address");
    $custom_id = $settings["custom_id"];
    $addresses = $form->_values['address'];
    $settings =  CRM_Core_BAO_Setting::getItem("Permission Address");
    $submitted = $form->_submitValues["address"];
    $table = "address_permissions";
    foreach ($addresses as $key => $value) { 
    	foreach($submitted[$key] as $k => $v){
     		$keys = explode("_", $k);
     		if ($keys[0] == "custom" && $keys[1] == $custom_id && $v == 1){
    			$sql  = "SELECT address_id FROM {$table} WHERE contact_id = {$contactID} AND address_id = {$value['id']}";
    			$dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
    			if (!$dao->fetch( )) {
      			$insertSql = "INSERT INTO {$table} (contact_id, address_id) VALUES ({$contactID}, {$value['id']})";
      			$dao2 = CRM_Core_DAO::executeQuery($insertSql, CRM_Core_DAO::$_nullArray);
    			}
     		} elseif ( $keys[0] == "custom" && $keys[1] == $custom_id && $v == 0 ){
    			$sql  = "SELECT address_id FROM {$table} WHERE contact_id = {$contactID} AND address_id = {$value['id']}";
    			$dao = CRM_Core_DAO::executeQuery( $sql, CRM_Core_DAO::$_nullArray );
          if ($dao->fetch()){
            $sql = "DELETE FROM {$table} WHERE address_id = {$value['id']} AND contact_id = {$contactID}";
            $dao = CRM_Core_DAO::executeQuery($sql);
          }
        } else {
        	$checksql = "SELECT address_id FROM {$table} WHERE address_id = {$value['id']}";
      		$checkdao = CRM_Core_DAO::executeQuery( $checksql, CRM_Core_DAO::$_nullArray );
      		if (!$checkdao->fetch()){
        		$sql = "SELECT id, state_province_id, county_id FROM civicrm_address WHERE id = {$value['id']}";
        		$dao = CRM_Core_DAO::executeQuery( $sql, CRM_Core_DAO::$_nullArray );
        		$dao->fetch();
        		if ( ($dao->id > 0) && (array_key_exists('county_id', $value) && $value['county_id'] == $dao->county_id) && ($value['state_province_id'] == $dao->state_province_id ) && (!CRM_Core_Permission::check('edit county contacts') || !CRM_Core_Permission::check('edit all contacts') ) ){
          		$value['id'] = "NULL";
        		}
      		}
        }
   		}//end foreach
    }//end foreach
  }//end if
}
/*** Freeze state and county field is user doesn't have permission to change ***/
function ndipermissions_civicrm_buildform($formName, &$form){
  if (CRM_Utils_Array::value('address', $form->getVar('_values')) && CRM_Core_Permission::check('edit all contacts') != "1"){
    foreach ($form->_values['address'] as $key => $value){
      $sql = "SELECT address_id FROM address_permissions WHERE address_id = {$value['id']}";
      $dao = CRM_Core_DAO::executeQuery( $sql, CRM_Core_DAO::$_nullArray );
      if ($dao->fetch()){
        foreach ($form->_elements as $k => $v) {
          if(CRM_Utils_Array::value('name', $v->_attributes)){
          	if(strpos($v->_attributes['name'],"county_id")){
            	$element = $form->_elements[$k];
            	$element->_flagFrozen = 1;
          	}
		        if(strpos($v->_attributes['name'],"state_province_id")){
		          $element = $form->_elements[$k];
		          $element->_flagFrozen = 1;
		        }
          }
        }
      }
    }
  }
}

/*
 * Implementation of hook_civicrm_config
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_config
 */
function ndipermissions_civicrm_config(&$config) {
  _ndipermissions_civix_civicrm_config($config);
}

/**

 * Implementation of hook_civicrm_xmlMenu
 *
 * @param $files array(string)
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_xmlMenu
 */
function ndipermissions_civicrm_xmlMenu(&$files) {
  _ndipermissions_civix_civicrm_xmlMenu($files);
}

/**
 * Implementation of hook_civicrm_install
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_install
 */
function ndipermissions_civicrm_install() {
  $sql = 'DROP TABLE IF EXISTS address_permissions';
  $dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
  $sql = 'CREATE TABLE address_permissions ( address_id int, contact_id int );';
  $dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
  $params = array (
        'version'=>'3',
        'name' => 'permissioned_address',
        'title' => 'Permissioned Address',
        'extends' => 'Address',
        'style' => 'Inline',
        'collapse_display' => '0',
        'weight' => '3',
        'is_active' => '1',
        'is_multiple' => '0');
  $results=civicrm_api('CustomGroup','create', $params);
  $gid=$results['id'];
  $params = array('version'=>'3',
                "custom_group_id"=>$gid,
                "name"=>"is_permissioned",
                "label"=>"Is Permissioned",
                "data_type"=>"Boolean",
                "html_type"=>"Radio",
                "help_post" => "If enabled this contact will have permission over contacts in this graphical region",
                "is_required"=>"0",
                "is_searchable"=>"1",
                "is_search_range"=>"0",<commit_msg>fixed join alias references and added county as address option in format and block display<commit_after><?php

require_once 'ndipermissions.civix.php';

/*** Create New Permissions ***/
function ndipermissions_civicrm_permission( &$permissions ){
  $prefix = ts('NDI CiviCRM County-State Permissions') . ': '; 
  $permissions = array(
    'view county contacts'     => $prefix . ts('view all contacts who live in your county'),
    'edit county contacts'     => $prefix . ts('edit all contacts who live in your county'),
    'delete county contacts'   => $prefix . ts('delete all contacts who live in your county'),
    'view state contacts'      => $prefix . ts('view all contacts who live in your state'),
    'edit state contacts'      => $prefix . ts('edit all contacts who live in your state'),
    'delete state contacts'    => $prefix . ts('delete all contacts who live in your state'),
  ); // NB: note the convention of using delete in ComponentName, plural for edits
}
/*** Add permissions to current user and adds primary address to new table ***/
function ndipermissions_civicrm_aclWhereClause( $type, &$tables, &$whereTables, &$contactID, &$where ){
  require_once 'CRM/Contact/BAO/Contact/Permission.php';
  if ((CRM_Core_Permission::check('view state contacts') && $type == "1")
      || (CRM_Core_Permission::check('edit state contacts') && $type == "2")
        || (CRM_Core_Permission::check('delete state contacts') && $type == "3")){
    $address_table = 'civicrm_address';
    $tables[$address_table] = $whereTables[$address_table] = "LEFT JOIN {$address_table} ON {$address_table}.contact_id = contact_a.id";
    $where = "{$address_table}.state_province_id IN 
								(SELECT state_province_id FROM civicrm_address WHERE contact_id = {$contactID} AND is_primary = 1 )";
  } elseif ((CRM_Core_Permission::check('view county contacts') && $type == "1")
           || (CRM_Core_Permission::check('edit county contacts') && $type == "2")
             || (CRM_Core_Permission::check('delete county contacts') && $type == "3")){
    $address_table = 'civicrm_address';
    $tables[$address_table] = $whereTables[$address_table] = "LEFT JOIN {$address_table} ON {$address_table}.contact_id = contact_a.id";
    $where = "{$address_table}.county_id IN (SELECT county_id FROM civicrm_address WHERE contact_id = {$contactID} AND is_primary = 1 )";
  }
}
/*** Prevents address_id from being overriden, creates address record will NULL id ***/
function ndipermissions_civicrm_postprocess($formName, &$form){
  if (CRM_Utils_Array::value('address', $form->getVar('_values'))){
    $contactID = $form->_contactId;
    $settings =  CRM_Core_BAO_Setting::getItem("Permission Address");
    $custom_id = $settings["custom_id"];
    $addresses = $form->_values['address'];
    $settings =  CRM_Core_BAO_Setting::getItem("Permission Address");
    $submitted = $form->_submitValues["address"];
    $table = "address_permissions";
    foreach ($addresses as $key => $value) { 
    	foreach($submitted[$key] as $k => $v){
     		$keys = explode("_", $k);
     		if ($keys[0] == "custom" && $keys[1] == $custom_id && $v == 1){
    			$sql  = "SELECT address_id FROM {$table} WHERE contact_id = {$contactID} AND address_id = {$value['id']}";
    			$dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
    			if (!$dao->fetch( )) {
      			$insertSql = "INSERT INTO {$table} (contact_id, address_id) VALUES ({$contactID}, {$value['id']})";
      			$dao2 = CRM_Core_DAO::executeQuery($insertSql, CRM_Core_DAO::$_nullArray);
    			}
     		} elseif ( $keys[0] == "custom" && $keys[1] == $custom_id && $v == 0 ){
    			$sql  = "SELECT address_id FROM {$table} WHERE contact_id = {$contactID} AND address_id = {$value['id']}";
    			$dao = CRM_Core_DAO::executeQuery( $sql, CRM_Core_DAO::$_nullArray );
          if ($dao->fetch()){
            $sql = "DELETE FROM {$table} WHERE address_id = {$value['id']} AND contact_id = {$contactID}";
            $dao = CRM_Core_DAO::executeQuery($sql);
          }
        } else {
        	$checksql = "SELECT address_id FROM {$table} WHERE address_id = {$value['id']}";
      		$checkdao = CRM_Core_DAO::executeQuery( $checksql, CRM_Core_DAO::$_nullArray );
      		if (!$checkdao->fetch()){
        		$sql = "SELECT id, state_province_id, county_id FROM civicrm_address WHERE id = {$value['id']}";
        		$dao = CRM_Core_DAO::executeQuery( $sql, CRM_Core_DAO::$_nullArray );
        		$dao->fetch();
        		if ( ($dao->id > 0) && (array_key_exists('county_id', $value) && $value['county_id'] == $dao->county_id) && ($value['state_province_id'] == $dao->state_province_id ) && (!CRM_Core_Permission::check('edit county contacts') || !CRM_Core_Permission::check('edit all contacts') ) ){
          		$value['id'] = "NULL";
        		}
      		}
        }
   		}//end foreach
    }//end foreach
  }//end if
}
/*** Freeze state and county field is user doesn't have permission to change ***/
function ndipermissions_civicrm_buildform($formName, &$form){
  if (CRM_Utils_Array::value('address', $form->getVar('_values')) && CRM_Core_Permission::check('edit all contacts') != "1"){
    foreach ($form->_values['address'] as $key => $value){
      $sql = "SELECT address_id FROM address_permissions WHERE address_id = {$value['id']}";
      $dao = CRM_Core_DAO::executeQuery( $sql, CRM_Core_DAO::$_nullArray );
      if ($dao->fetch()){
        foreach ($form->_elements as $k => $v) {
          if(CRM_Utils_Array::value('name', $v->_attributes)){
          	if(strpos($v->_attributes['name'],"county_id")){
            	$element = $form->_elements[$k];
            	$element->_flagFrozen = 1;
          	}
		        if(strpos($v->_attributes['name'],"state_province_id")){
		          $element = $form->_elements[$k];
		          $element->_flagFrozen = 1;
		        }
          }
        }
      }
    }
  }
}

/*
 * Implementation of hook_civicrm_config
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_config
 */
function ndipermissions_civicrm_config(&$config) {
  _ndipermissions_civix_civicrm_config($config);
}

/**

 * Implementation of hook_civicrm_xmlMenu
 *
 * @param $files array(string)
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_xmlMenu
 */
function ndipermissions_civicrm_xmlMenu(&$files) {
  _ndipermissions_civix_civicrm_xmlMenu($files);
}

/**
 * Implementation of hook_civicrm_install
 *
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_install
 */
function ndipermissions_civicrm_install() {
$result = civicrm_api3('Setting', 'create', array(
  'address_options' => array("1", "2", "4","5","7","8","9"),
  'address_format' => "{contact.address_name}\\n{contact.street_address}\\n{contact.supplemental_address_1}\\n{contact.city}{, }{contact.state_province}{ }{contact.postal_code}\\n{contact.county}{ }{contact.country}",
));
  $sql = 'DROP TABLE IF EXISTS address_permissions';
  $dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
  $sql = 'CREATE TABLE address_permissions ( address_id int, contact_id int );';
  $dao = CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
  $params = array (
        'version'=>'3',
        'name' => 'permissioned_address',
        'title' => 'Permissioned Address',
        'extends' => 'Address',
        'style' => 'Inline',
        'collapse_display' => '0',
        'weight' => '3',
        'is_active' => '1',
        'is_multiple' => '0');
  $results=civicrm_api('CustomGroup','create', $params);
  $gid=$results['id'];
  $params = array('version'=>'3',
                "custom_group_id"=>$gid,
                "name"=>"is_permissioned",
                "label"=>"Is Permissioned",
                "data_type"=>"Boolean",
                "html_type"=>"Radio",
                "help_post" => "If enabled this contact will have permission over contacts in this graphical region",
                "is_required"=>"0",
                "is_searchable"=>"1",
                "is_search_range"=>"0",
{'fraction_non_alphanumeric': 0.1675941917738118, 'fraction_numerical': 0.00415787116996098, 'mean_word_length': 3.6696535244922344, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 109, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 8}, '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': '6915502', 'n_tokens_mistral': 5270, 'n_tokens_neox': 5142, 'n_words': 1066}