You are here

mortgage_calculator.module in Real Estate Mortgage Calculator 7

Same filename and directory in other branches
  1. 8 mortgage_calculator.module

Mortgage Calculator module

File

mortgage_calculator.module
View source
<?php

/**
 * @file
 * Mortgage Calculator module
 */

/**
 * Implements hook_menu().
 */
function mortgage_calculator_menu() {
  $items['mortgage-calculator'] = array(
    'title' => 'Mortgage calculator',
    'page callback' => 'mortgage_calculator_page',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Implements hook_block_info().
 */
function mortgage_calculator_block_info() {
  $blocks['mortgage_calculator_1'] = array(
    'info' => t('Mortgage Calculator'),
    'cache' => DRUPAL_CACHE_PER_PAGE,
    'weight' => -11,
    'status' => BLOCK_CUSTOM_ENABLED,
    'region' => 'content',
    'visibility' => BLOCK_VISIBILITY_LISTED,
    'pages' => 'mortgage-calculator',
  );
  $blocks['mortgage_calculator_js_1'] = array(
    'info' => t('Mortgage Calculator JS'),
    'cache' => DRUPAL_CACHE_PER_PAGE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function mortgage_calculator_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'mortgage_calculator_1':
      $block['subject'] = t('Mortgage Calculator');
      $form = drupal_get_form('mortgage_calculator_form');
      $block['content'] = $form;
      break;
    case 'mortgage_calculator_js_1':
      $block['subject'] = t('Mortgage Calculator');
      $form = drupal_get_form('mortgage_calculator_js_form');
      $block['content'] = $form;
      break;
  }
  return $block;
}

/**
 * Implements hook_block_configure().
 */
function mortgage_calculator_block_configure($delta = '') {

  // todo: add supporting entity tokens https://api.drupal.org/api/examples/token_example!token_example.module/function/token_example_example_form/7
  $form = array();
  if ($delta == 'mortgage_calculator_1') {
    $form['mortgage_calculator_payment_frequency_list'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Payment Frequency'),
      '#default_value' => variable_get('mortgage_calculator_payment_frequency_list', array(
        'monthly',
        'yearly',
      )),
      '#options' => _mortgage_calculator_payment_frequency(),
    );
    $form['mc_defaults'] = array(
      '#title' => t('Default values'),
      '#type' => 'fieldset',
      '#collapsible' => FALSE,
      '#collapsed' => FALSE,
    );
    $form['mc_defaults']['mortgage_calculator_config_loan_amount'] = array(
      '#type' => 'textfield',
      '#title' => t('Price of Home'),
      '#default_value' => variable_get('mortgage_calculator_config_loan_amount', ''),
      '#size' => 50,
    );
    $form['mc_defaults']['mortgage_calculator_config_mortgage_rate'] = array(
      '#type' => 'textfield',
      '#title' => t('Mortgage Rate'),
      '#default_value' => variable_get('mortgage_calculator_config_mortgage_rate', ''),
      '#size' => 50,
    );
    $form['mc_defaults']['mortgage_calculator_config_years_to_pay'] = array(
      '#type' => 'textfield',
      '#title' => t('Years to Pay'),
      '#default_value' => variable_get('mortgage_calculator_config_years_to_pay', ''),
      '#size' => 50,
    );
  }
  elseif ($delta == 'mortgage_calculator_js_1') {
    $form['mortgage_calculator_js_payment_frequency_list'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Payment Frequency'),
      '#default_value' => variable_get('mortgage_calculator_js_payment_frequency_list', array(
        'monthly',
      )),
      '#options' => _mortgage_calculator_payment_frequency(),
    );
    $form['mc_defaults'] = array(
      '#title' => t('Default values'),
      '#type' => 'fieldset',
      '#collapsible' => FALSE,
      '#collapsed' => FALSE,
    );
    $form['mc_defaults']['mortgage_calculator_js_config_loan_amount_2'] = array(
      '#type' => 'textfield',
      '#title' => t('Price of Home'),
      '#size' => 50,
      '#default_value' => variable_get('mortgage_calculator_js_config_loan_amount_2', ''),
    );
    $form['mc_defaults']['mortgage_calculator_js_config_mortgage_rate_2'] = array(
      '#type' => 'textfield',
      '#title' => t('Mortgage Rate'),
      '#size' => 50,
      '#default_value' => variable_get('mortgage_calculator_js_config_mortgage_rate_2', ''),
    );
    $form['mc_defaults']['mortgage_calculator_js_config_years_to_pay_2'] = array(
      '#type' => 'textfield',
      '#title' => t('Years to Pay'),
      '#size' => 50,
      '#default_value' => variable_get('mortgage_calculator_js_config_years_to_pay_2', ''),
    );
  }
  if (module_exists('token')) {
    $form['mc_defaults']['content'] = array(
      '#token_types' => array(
        'node',
      ),
      '#theme' => 'token_tree',
      '#global_types' => FALSE,
      '#click_insert' => TRUE,
    );
  }
  else {
    $form['mc_defaults']['content'] = array(
      '#markup' => t('For viewing the available tokens, please enable the <a href="@mod_url">Token module</a>.', array(
        '@mod_url' => url('https://drupal.org/project/token'),
      )),
    );
  }
  return $form;
}

/**
 * Implements hook_block_save().
 */
function mortgage_calculator_block_save($delta = '', $edit = array()) {
  if ($delta == 'mortgage_calculator_1') {
    variable_set('mortgage_calculator_payment_frequency_list', $edit['mortgage_calculator_payment_frequency_list']);
    variable_set('mortgage_calculator_config_loan_amount', $edit['mortgage_calculator_config_loan_amount']);
    variable_set('mortgage_calculator_config_mortgage_rate', $edit['mortgage_calculator_config_mortgage_rate']);
    variable_set('mortgage_calculator_config_years_to_pay', $edit['mortgage_calculator_config_years_to_pay']);
  }
  elseif ($delta == 'mortgage_calculator_js_1') {
    variable_set('mortgage_calculator_js_payment_frequency_list', $edit['mortgage_calculator_js_payment_frequency_list']);
    variable_set('mortgage_calculator_js_config_loan_amount_2', $edit['mortgage_calculator_js_config_loan_amount_2']);
    variable_set('mortgage_calculator_js_config_mortgage_rate_2', $edit['mortgage_calculator_js_config_mortgage_rate_2']);
    variable_set('mortgage_calculator_js_config_years_to_pay_2', $edit['mortgage_calculator_js_config_years_to_pay_2']);
  }
}

/**
 * Helper function for getting a payment frequency array by an index.
 *
 * @param array $types
 *   an array of selected types
 *
 * @return array
 *   a payment frequency array
 */
function _mortgage_calculator_payment_frequency($types = array()) {
  $payments = array(
    'monthly' => t('Monthly'),
    'yearly' => t('Yearly'),
    'semi-monthly' => t('Semi-monthly'),
    'bi-weekly' => t('Bi-weekly'),
    'weekly' => t('Weekly'),
    'accelerated_bi-weekly' => t('Accelerated Bi-weekly'),
    'accelerated_weekly' => t('Accelerated Weekly'),
  );
  if (empty($types)) {
    return $payments;
  }
  else {
    return array_intersect_key($payments, array_flip($types));
  }
}

/**
 * Form for a mortgage calculator.
 */
function mortgage_calculator_form($form_state) {
  $node = menu_get_object();
  $loan_amount = isset($_SESSION['mortgage_calculator_loan_amount']) ? $_SESSION['mortgage_calculator_loan_amount'] : 0;
  $mortgage_rate = isset($_SESSION['mortgage_calculator_mortgage_rate']) ? $_SESSION['mortgage_calculator_mortgage_rate'] : 0;
  $years_to_pay = isset($_SESSION['mortgage_calculator_years_to_pay']) ? $_SESSION['mortgage_calculator_years_to_pay'] : 0;
  $desired_display = isset($_SESSION['mortgage_calculator_desired_display']) ? $_SESSION['mortgage_calculator_desired_display'] : 'monthly';
  $form['mortgage_calculator_loan_amount'] = array(
    '#type' => 'textfield',
    '#title' => t('Price of Home'),
    '#default_value' => variable_get('mortgage_calculator_config_loan_amount', '') ? token_replace(variable_get('mortgage_calculator_config_loan_amount', '0'), array(
      'node' => $node,
    )) : $loan_amount,
    '#size' => 10,
    '#maxlength' => 64,
  );
  $form['mortgage_calculator_mortgage_rate'] = array(
    '#type' => 'textfield',
    '#title' => t('Mortgage Rate'),
    '#default_value' => variable_get('mortgage_calculator_config_mortgage_rate', '') ? token_replace(variable_get('mortgage_calculator_config_mortgage_rate', '0'), array(
      'node' => $node,
    )) : $mortgage_rate,
    '#size' => 10,
    '#maxlength' => 64,
  );
  $form['mortgage_calculator_years_to_pay'] = array(
    '#type' => 'textfield',
    '#title' => t('Years to Pay'),
    '#default_value' => variable_get('mortgage_calculator_config_years_to_pay', '') ? token_replace(variable_get('mortgage_calculator_config_years_to_pay', '0'), array(
      'node' => $node,
    )) : $years_to_pay,
    '#size' => 10,
    '#maxlength' => 64,
  );
  $form['mortgage_calculator_desired_display'] = array(
    '#type' => 'select',
    '#title' => t('Desired table display'),
    '#default_value' => $desired_display,
    '#options' => _mortgage_calculator_payment_frequency(variable_get('mortgage_calculator_payment_frequency_list', array(
      'monthly',
      'yearly',
    ))),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Calculate'),
  );
  $form['reset'] = array(
    '#type' => 'submit',
    '#value' => t('Reset'),
  );
  return $form;
}

/**
 * Form for a mortgage calculator - validation function.
 */
function mortgage_calculator_form_validate($form, &$form_state) {
  if ($form_state['triggering_element']['#array_parents'][0] != 'reset') {
    if ($form_state['values']['mortgage_calculator_loan_amount'] == '' || $form_state['values']['mortgage_calculator_loan_amount'] <= 0) {
      form_set_error('mortgage_calculator_loan_amount', t('Please enter a value of loan amount.'));
    }
    if ($form_state['values']['mortgage_calculator_mortgage_rate'] == '' || $form_state['values']['mortgage_calculator_mortgage_rate'] <= 0) {
      form_set_error('mortgage_calculator_mortgage_rate', t('Please enter a value of mortgage rate.'));
    }
    if ($form_state['values']['mortgage_calculator_years_to_pay'] == '' || $form_state['values']['mortgage_calculator_years_to_pay'] <= 0) {
      form_set_error('mortgage_calculator_years_to_pay', t('Please enter a value of years to pay.'));
    }
  }
}

/**
 * Form for a mortgage calculator - submit function.
 */
function mortgage_calculator_form_submit($form, &$form_state) {
  if ($form_state['triggering_element']['#array_parents'][0] != 'reset') {
    $_SESSION['mortgage_calculator_loan_amount'] = $form_state['values']['mortgage_calculator_loan_amount'];
    $_SESSION['mortgage_calculator_mortgage_rate'] = $form_state['values']['mortgage_calculator_mortgage_rate'];
    $_SESSION['mortgage_calculator_years_to_pay'] = $form_state['values']['mortgage_calculator_years_to_pay'];
    $_SESSION['mortgage_calculator_desired_display'] = $form_state['values']['mortgage_calculator_desired_display'];
    $form_state['redirect'] = 'mortgage-calculator';
  }
  else {
    unset($_SESSION['mortgage_calculator_loan_amount']);
    unset($_SESSION['mortgage_calculator_mortgage_rate']);
    unset($_SESSION['mortgage_calculator_years_to_pay']);
    unset($_SESSION['mortgage_calculator_desired_display']);
  }
}

/**
 * Mortgage calculator page.
 */
function mortgage_calculator_page() {
  $theme_values = array();
  if (isset($_SESSION['mortgage_calculator_loan_amount']) & isset($_SESSION['mortgage_calculator_mortgage_rate']) & isset($_SESSION['mortgage_calculator_years_to_pay']) & isset($_SESSION['mortgage_calculator_desired_display'])) {
    $theme_values = array(
      'loan_amount' => $_SESSION['mortgage_calculator_loan_amount'],
      'mortgage_rate' => $_SESSION['mortgage_calculator_mortgage_rate'],
      'years_to_pay' => $_SESSION['mortgage_calculator_years_to_pay'],
      'desired_display' => $_SESSION['mortgage_calculator_desired_display'],
    );
    $theme_values += mortgage_calculator_calculation($theme_values['loan_amount'], $theme_values['mortgage_rate'], $theme_values['years_to_pay'], $theme_values['desired_display']);
  }
  $output = theme('mortgage_calculator', $theme_values);
  return $output;
}

/**
 * Implements hook_theme().
 */
function mortgage_calculator_theme($existing, $type, $theme, $path) {
  return array(
    'mortgage_calculator' => array(
      'variables' => array(
        'loan_amount' => NULL,
        'mortgage_rate' => NULL,
        'years_to_pay' => NULL,
        'desired_display' => NULL,
        'rows' => array(),
        'row' => array(
          'number_of_payments' => 0,
          'payment' => 0,
        ),
      ),
      'template' => 'mortgage-calculator',
    ),
  );
}

/**
 * Preprocess function.
 */
function template_preprocess_mortgage_calculator(&$variables) {
  $header = array(
    t('Month'),
    t('Beginning Balance'),
    t('Interest'),
    t('Payment Amount'),
    t('Ending Balance'),
  );
  if ($variables['desired_display'] == 'monthly') {
    $header[0] = t('Month');
  }
  elseif ($variables['desired_display'] == 'yearly') {
    $header[0] = t('Year');
  }
  elseif ($variables['desired_display'] == 'semi-monthly') {
    $header[0] = t('Semi-Month');
  }
  elseif ($variables['desired_display'] == 'bi-weekly') {
    $header[0] = t('Two Week');
  }
  elseif ($variables['desired_display'] == 'weekly') {
    $header[0] = t('Week');
  }
  elseif ($variables['desired_display'] == 'accelerated_bi-weekly') {
    $header[0] = t('Two Week');
  }
  elseif ($variables['desired_display'] == 'accelerated_weekly') {
    $header[0] = t('Week');
  }
  $variables['header'] = $header;
}

/**
 * Function for a mortgage calculation.
 *
 * @param int $loan_amount
 *   a loan amount
 * @param int $mortgage_rate
 *   a mortgage rate
 * @param int $years_to_pay
 *   years to pay
 * @param array $desired_display
 *   possible values 'monthly', 'yearly', 'semi-monthly', 'bi-weekly', 'weekly',
 *   'accelerated_bi-weekly', 'accelerated_weekly'
 *
 * @return array
 *   where a key 'rows' contains array of rows
 *   with $desired_display mortgage calculations
 */
function mortgage_calculator_calculation($loan_amount, $mortgage_rate, $years_to_pay, $desired_display) {
  if ($desired_display == 'monthly') {
    $rate_per = $mortgage_rate / 100 / 12;
    $number_of_payments = $years_to_pay * 12;
  }
  elseif ($desired_display == 'yearly') {
    $rate_per = $mortgage_rate / 100;
    $number_of_payments = $years_to_pay;
  }
  elseif ($desired_display == 'semi-monthly') {
    $rate_per = $mortgage_rate / 100 / 24;
    $number_of_payments = $years_to_pay * 24;
  }
  elseif ($desired_display == 'bi-weekly') {
    $rate_per = $mortgage_rate / 100 / 26;
    $number_of_payments = $years_to_pay * 26;
  }
  elseif ($desired_display == 'weekly') {
    $rate_per = $mortgage_rate / 100 / 52;
    $number_of_payments = $years_to_pay * 52;
  }
  elseif ($desired_display == 'accelerated_bi-weekly') {
    $rate_per = $mortgage_rate / 100 / 24;
    $number_of_payments = $years_to_pay * 26;
  }
  elseif ($desired_display == 'accelerated_weekly') {
    $rate_per = $mortgage_rate / 100 / 48;
    $number_of_payments = $years_to_pay * 52;
  }
  if ($mortgage_rate != 0) {
    $payment = $loan_amount * pow(1 + $rate_per, $number_of_payments) * $rate_per / (pow(1 + $rate_per, $number_of_payments) - 1);
  }
  else {
    $payment = $loan_amount / $number_of_payments;
  }
  $beginning_balance = $loan_amount;
  for ($i = 1; $i <= $number_of_payments; $i++) {
    $interest = $rate_per * $beginning_balance;
    $rows[] = array(
      $i,
      round($beginning_balance),
      round($interest),
      round($payment),
      abs(round($beginning_balance - ($payment - $interest))),
    );
    $beginning_balance -= $payment - $interest;
  }
  return array(
    'rows' => $rows,
    'row' => array(
      'number_of_payments' => $number_of_payments,
      'payment' => $payment,
    ),
  );
}

/**
 * Form for a mortgage calculator JS.
 */
function mortgage_calculator_js_form($form_state) {
  $node = menu_get_object();
  $form['loan_amount_2'] = array(
    '#type' => 'textfield',
    '#title' => t('Price of Home'),
    '#size' => 10,
    '#maxlength' => 64,
    '#default_value' => token_replace(variable_get('mortgage_calculator_js_config_loan_amount_2', ''), array(
      'node' => $node,
    )),
  );
  $form['mortgage_rate_2'] = array(
    '#type' => 'textfield',
    '#title' => t('Mortgage Rate'),
    '#size' => 10,
    '#maxlength' => 64,
    '#default_value' => token_replace(variable_get('mortgage_calculator_js_config_mortgage_rate_2', ''), array(
      'node' => $node,
    )),
  );
  $form['years_to_pay_2'] = array(
    '#type' => 'textfield',
    '#title' => t('Years to Pay'),
    '#size' => 10,
    '#maxlength' => 64,
    '#default_value' => token_replace(variable_get('mortgage_calculator_js_config_years_to_pay_2', ''), array(
      'node' => $node,
    )),
  );
  $payment_frequencies = variable_get('mortgage_calculator_js_payment_frequency_list', array(
    'monthly',
  ));
  if (!(count($payment_frequencies) == 1 && $payment_frequencies[0] == 'monthly')) {
    $form['payment_frequency_2'] = array(
      '#type' => 'select',
      '#title' => t('Payment Frequency'),
      '#default_value' => variable_get('payment_frequency_2', 'monthly'),
      '#options' => _mortgage_calculator_payment_frequency($payment_frequencies),
    );
  }
  $form['#executes_submit_callback'] = FALSE;
  $form['calculate_2'] = array(
    '#type' => 'submit',
    '#value' => t('Calculate'),
  );
  $form['result_2'] = array(
    '#type' => 'textfield',
    '#title' => check_plain(count($payment_frequencies) == 1 && $payment_frequencies[0] == 'monthly' ? t('Monthly Payment') : t('Payment Amount')),
    '#size' => 10,
    '#maxlength' => 64,
    '#attributes' => array(
      'readonly' => array(
        'readonly',
      ),
    ),
  );
  $form['#attached']['js'][] = drupal_get_path('module', 'mortgage_calculator') . '/mortgage_calculator.js';
  return $form;
}

/**
 * Implements hook_filter_info().
 */
function mortgage_calculator_filter_info() {
  $filters['mortgage_calculator_filter'] = array(
    'title' => t('Embed Mortgage Calculator JS'),
    'description' => t('in format [mortgage_calculator_js:PRICE;RATE;YEARS] for JS version'),
    'process callback' => '_mortgage_calculator_filter',
    'tips callback' => '_mortgage_calculator_filter_tips',
    'cache' => FALSE,
  );
  return $filters;
}

/**
 * Helper function for the mortgage_calculator_filter_info() hook.
 */
function _mortgage_calculator_filter($text, $filter, $format, $langcode, $cache, $cache_id) {
  if (preg_match_all('/\\[mortgage_calculator_js\\:(.+)\\]/isU', $text, $matches_code)) {

    // For preventing infinite loop.
    static $mortgage_calculator_js;
    if (!$mortgage_calculator_js) {
      $mortgage_calculator_js = TRUE;
      $code = $matches_code[0][0];
      $values = explode(';', $matches_code[1][0]);
      variable_set('loan_amount_2', $values[0]);
      variable_set('mortgage_rate_2', $values[1]);
      variable_set('years_to_pay_2', $values[2]);
      $form = drupal_get_form('mortgage_calculator_js_form');
      $calculator = drupal_render($form);
      variable_set('loan_amount_2', '');
      variable_set('mortgage_rate_2', '');
      variable_set('years_to_pay_2', '');
      $text = str_replace($code, $calculator, $text);
    }
  }
  return $text;
}

/**
 * Helper function for the mortgage_calculator_filter_info() hook.
 */
function _mortgage_calculator_filter_tips($filter, $format, $long = FALSE) {
  return t('Mortgage Calculator JS can be added inline by [mortgage_calculator_js:PRICE;RATE;YEARS]. For example [mortgage_calculator_js:10000;4.5;10]. More in README.txt');
}

Functions

Namesort descending Description
mortgage_calculator_block_configure Implements hook_block_configure().
mortgage_calculator_block_info Implements hook_block_info().
mortgage_calculator_block_save Implements hook_block_save().
mortgage_calculator_block_view Implements hook_block_view().
mortgage_calculator_calculation Function for a mortgage calculation.
mortgage_calculator_filter_info Implements hook_filter_info().
mortgage_calculator_form Form for a mortgage calculator.
mortgage_calculator_form_submit Form for a mortgage calculator - submit function.
mortgage_calculator_form_validate Form for a mortgage calculator - validation function.
mortgage_calculator_js_form Form for a mortgage calculator JS.
mortgage_calculator_menu Implements hook_menu().
mortgage_calculator_page Mortgage calculator page.
mortgage_calculator_theme Implements hook_theme().
template_preprocess_mortgage_calculator Preprocess function.
_mortgage_calculator_filter Helper function for the mortgage_calculator_filter_info() hook.
_mortgage_calculator_filter_tips Helper function for the mortgage_calculator_filter_info() hook.
_mortgage_calculator_payment_frequency Helper function for getting a payment frequency array by an index.