<commit_before><?php

class CRM_Raisely_Page_Raisely extends CRM_Core_Page {

  private function _parseDonor($json) {
    // Raisely JSON data contains all information about a donor inside a
    // certain path of their JSON tree. It is currently
    // JSON->data->result->metadata
    $data = $json['data']['result']['metadata'];

    // The following field names are not guaranteed - depends on
    // configuration of specific Raisely campaigns.
    // TODO permit definition of field names through admin interface
    // the set would be passed as an array to this function

    $donor_keys = [
      'first_name',
      'last_name',
      'email',
      'private.street_address',
      'private.postcode',
      'private.suburb',
      'private.state',
      'private.country',
    ];

    // Loop through donor keys, check none are missing
    // and assign to $donor variable for return
    foreach ($donor_keys as $key) {
      if (!array_key_exists($key, $data)) {
        return NULL;
      }
      $donor[$key] = $data[$key];
    }
    $donor['contact_type'] = 'Individual';
    return $donor;
  }

  private function _parseContribution($json) {
    // Raisely JSON data contains all information about a contribution
    // Parse that data and return an associate array with the relevant
    // details for a CiviCRM contribution record

    $data = $json['data']['result'];
    $civicrm_match_keys = [
      'id' => 'trnx_id',
      'description' => 'source',
      'amount' => 'total_amount',
      'created' => 'receive_date',
      'currency' => 'currency',
    ];
    $contrib_keys = [
      'id', // Stripe transaction ID
      'status',
      'description', // Simple description of contribution
      'amount', // no decimal point
      'created', // Unix epoch time
      'currency', // 3 letter currency code
    ];
    foreach ($contrib_keys as $key) {
      if (!array_key_exists($key, $data)) {
        return NULL;
      }
      $value = $data[$key];
      if ($key == 'created') {
        $dt = new DateTime($value);
        $contribution[$civicrm_match_keys[$key]] = $dt->format('Y-m-d H:i:s');
      }
      elseif ($key == 'status') {
        if ($value == 'succeeded') {
          $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
            'labelColumn' => 'name',
            'flip' => 1,
          ));
          $contribution['contribution_status_id'] = $contributionStatuses['Completed'];
        }
        else {
          $contribution[$civicrm_match_keys[$key]] = $data[$key];
        }
      }
    }
    return $contribution;
  }

  public function _lookupStateId($state) {
    try {
      $result = civicrm_api3('Address', 'getoptions', array(
        'field' => 'state_province_id',
        'context' => 'abbreviate',
      ));
    }
    catch (CiviCRM_API3_Exception $e) {
      $log->error('State Abbrieation lookup failed');
    }
    $result = array_flip($result['values']);
    if (array_key_exists($state, $result)) {
      return $result[$state];
    }
    else {
      return NULL;
    }
  }

  public function _lookupCountryId($country) {
    try {
      $result = civicrm_api3('Address', 'getoptions', array(
        'field' => 'country_id',
        'context' => 'abbreviate',
      ));
    }
    catch (CiviCRM_API3_Exception $e) {
      $log->error('Country Abbreviation lookup failed');
    }
    $result = array_flip($result['values']);
    if (array_key_exists($country, $result)) {
      return $result[$country];
    }
    else {
      return NULL;
    }

  }

  public static function _parseAddressforContact($donor, $contactId) {
    $stateId = self::_lookupStateId($donor['private.state']);
    $countryId = self::_lookupCountryId($donor['private.country']);
    $primaryAddress = civicrm_api3('Address', 'getSingle', array('contact_id' => $contactId, 'is_primary' => 1));
    $params = array(
      'state_province_id' => $stateId,
      'country_id' => $countryId,
      'contact_id' => $contactId,
    );
    $keys = array(
      'street_address' => 'private.street_address',
      'postal_code' => 'private.postcode',
      'city' => 'private.suburb',
    );
    foreach ($keys as $civiField => $raisleyField) {
      $params[$civiField] = $donor[$raisleyField];
    }
    $addressIsMatched = TRUE;
    foreach ($params as $key => $value) {
      if ($addressIsMatched) {
        $addressIsMatched = ($value == $primaryAddress[$key]);
      }
    }
    if (!$addressIsMatched) {
      try {
        $previousAddress = civicrm_api3('Address', 'getSingle', array('contact_id' => $contactId, 'location_type_id' => 'Previous'));
      }
      catch (CiviCRM_API3_Exception $e) {
        $previousAddress = array();
      }
      if (!empty($previousAddress)) {
        $note = "Raisely Extension deleted the following previous address of \n {$previousAddress['street_address']} {$previousAddress['city']} {$previousAddress['state_province_id']} {$previousAddress['postal_code']} {$previousAddress['country_id']}";
        civicrm_api3('Note', 'create', array(
          'contact_id' => $contact_id,
          'entity_id' => $entity_id,
          'entity_table' => 'civicrm_contact',
          'subject' => 'Previous Address deleted by Raisely Extension',
          'note' => $note,
        ));
        civicrm_api3('Address', 'Delete', array('id' => $previousAddress['id']));
      }
      civicrm_api3('Address', 'create', array('id' => $primaryAddress['id'], 'is_primary' => 0, 'location_type_id' => 'Previous'));
      civicrm_api3('Address', 'create', $params);
    }
  }

  public function run() {
    $log = New CRM_Utils_SystemLogger();
    // Test method - fail gracefully on non-POST methods
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
      echo "Oh dear...this is unexpected.";
      CRM_Utils_System::civiExit();
    }

    // Get POST data and test that it's JSON
    $data = $_REQUEST;
    if (!($data = $_POST)) {
      $data = json_decode(file_get_contents("php://input"), TRUE);
    }

    if (is_null($data)) {
      $log->error("You didn't give me POST JSON data!");
      CRM_Utils_System::civiExit();
    }

    // Check that the action is "donation"
    if ($data['action'] != 'donation') {
      $log->error("This isn't a donation");
      CRM_Utils_System::civiExit();
    }
<commit_msg>Attempt to fix issues following testing of handing created date and creating address and creating note<commit_after><?php

class CRM_Raisely_Page_Raisely extends CRM_Core_Page {

  private function _parseDonor($json) {
    // Raisely JSON data contains all information about a donor inside a
    // certain path of their JSON tree. It is currently
    // JSON->data->result->metadata
    $data = $json['data']['result']['metadata'];

    // The following field names are not guaranteed - depends on
    // configuration of specific Raisely campaigns.
    // TODO permit definition of field names through admin interface
    // the set would be passed as an array to this function

    $donor_keys = [
      'first_name',
      'last_name',
      'email',
      'private.street_address',
      'private.postcode',
      'private.suburb',
      'private.state',
      'private.country',
    ];

    // Loop through donor keys, check none are missing
    // and assign to $donor variable for return
    foreach ($donor_keys as $key) {
      if (!array_key_exists($key, $data)) {
        return NULL;
      }
      $donor[$key] = $data[$key];
    }
    $donor['contact_type'] = 'Individual';
    return $donor;
  }

  private function _parseContribution($json) {
    // Raisely JSON data contains all information about a contribution
    // Parse that data and return an associate array with the relevant
    // details for a CiviCRM contribution record

    $data = $json['data']['result'];
    $civicrm_match_keys = [
      'id' => 'trnx_id',
      'description' => 'source',
      'amount' => 'total_amount',
      'created' => 'receive_date',
      'currency' => 'currency',
    ];
    $contrib_keys = [
      'id', // Stripe transaction ID
      'status',
      'description', // Simple description of contribution
      'amount', // no decimal point
      'created', // Unix epoch time
      'currency', // 3 letter currency code
    ];
    foreach ($contrib_keys as $key) {
      if (!array_key_exists($key, $data)) {
        return NULL;
      }
      $value = $data[$key];
      if ($key == 'created') {
        //$dt = new DateTime($value);
        //$contribution[$civicrm_match_keys[$key]] = $dt->format('Y-m-d H:i:s');
        $contribution[$civicrm_match_keys[$key]] = date('Y-m-d H:i:s', $value);
      }
      elseif ($key == 'status') {
        if ($value == 'succeeded') {
          $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
            'labelColumn' => 'name',
            'flip' => 1,
          ));
          $contribution['contribution_status_id'] = $contributionStatuses['Completed'];
        }
        else {
          $contribution[$civicrm_match_keys[$key]] = $data[$key];
        }
      }
    }
    return $contribution;
  }

  public function _lookupStateId($state) {
    try {
      $result = civicrm_api3('Address', 'getoptions', array(
        'field' => 'state_province_id',
        'context' => 'abbreviate',
      ));
    }
    catch (CiviCRM_API3_Exception $e) {
      $log->error('State Abbrieation lookup failed');
    }
    $result = array_flip($result['values']);
    if (array_key_exists($state, $result)) {
      return $result[$state];
    }
    else {
      return NULL;
    }
  }

  public function _lookupCountryId($country) {
    try {
      $result = civicrm_api3('Address', 'getoptions', array(
        'field' => 'country_id',
        'context' => 'abbreviate',
      ));
    }
    catch (CiviCRM_API3_Exception $e) {
      $log->error('Country Abbreviation lookup failed');
    }
    $result = array_flip($result['values']);
    if (array_key_exists($country, $result)) {
      return $result[$country];
    }
    else {
      return NULL;
    }

  }

  public static function _parseAddressforContact($donor, $contactId) {
    $stateId = self::_lookupStateId($donor['private.state']);
    $countryId = self::_lookupCountryId($donor['private.country']);
    $primaryAddress = civicrm_api3('Address', 'getSingle', array('contact_id' => $contactId, 'is_primary' => 1));
    $params = array(
      'state_province_id' => $stateId,
      'country_id' => $countryId,
      'contact_id' => $contactId,
    );
    $keys = array(
      'street_address' => 'private.street_address',
      'postal_code' => 'private.postcode',
      'city' => 'private.suburb',
    );
    foreach ($keys as $civiField => $raisleyField) {
      $params[$civiField] = $donor[$raisleyField];
    }
    $addressIsMatched = TRUE;
    foreach ($params as $key => $value) {
      if ($addressIsMatched) {
        $addressIsMatched = ($value == $primaryAddress[$key]);
      }
    }
    if (!$addressIsMatched) {
      try {
        $previousAddress = civicrm_api3('Address', 'getSingle', array('contact_id' => $contactId, 'location_type_id' => 'Previous'));
      }
      catch (CiviCRM_API3_Exception $e) {
        $previousAddress = array();
      }
      if (!empty($previousAddress)) {
        $note = "Raisely Extension deleted the following previous address of \n {$previousAddress['street_address']} {$previousAddress['city']} {$previousAddress['state_province_id']} {$previousAddress['postal_code']} {$previousAddress['country_id']}";
        civicrm_api3('Note', 'create', array(
          'contact_id' => $contact_id,
          'entity_id' => $contact_id,
          'entity_table' => 'civicrm_contact',
          'subject' => 'Previous Address deleted by Raisely Extension',
          'note' => $note,
        ));
        civicrm_api3('Address', 'Delete', array('id' => $previousAddress['id']));
      }
      civicrm_api3('Address', 'create', array('id' => $primaryAddress['id'], 'is_primary' => 0, 'location_type_id' => 'Previous'));
      $default_location_type = civicrm_api3('LocationType', 'getsingle', array('is_default' => 1));
      $params['location_type_id'] = $default_location_type['id'];
      civicrm_api3('Address', 'create', $params);
    }
  }

  public function run() {
    $log = New CRM_Utils_SystemLogger();
    // Test method - fail gracefully on non-POST methods
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
      echo "Oh dear...this is unexpected.";
      CRM_Utils_System::civiExit();
    }

    // Get POST data and test that it's JSON
    $data = $_REQUEST;
    if (!($data = $_POST)) {
      $data = json_decode(file_get_contents("php://input"), TRUE);
    }

    if (is_null($data)) {
      $log->error("You didn't give me POST JSON data!");
      CRM_Utils_System::civiExit();
    }

    // Check that the action is "donation"
    if ($data['action'] != 'donation') {
      $log->error("This isn't a donation");
      CRM_Utils_System::civiExit();
    }

{'fraction_non_alphanumeric': 0.15414110429447853, 'fraction_numerical': 0.00245398773006135, 'mean_word_length': 2.8662911354876965, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 84, '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': '7030240', 'n_tokens_mistral': 4111, 'n_tokens_neox': 4011, 'n_words': 920}