You are here

function advpoll_node_presave in Advanced Poll 7.3

Same name and namespace in other branches
  1. 7 advpoll.module \advpoll_node_presave()
  2. 7.2 advpoll.module \advpoll_node_presave()

Implements hook_node_presave().

File

./advpoll.module, line 297

Code

function advpoll_node_presave($node) {
  if ($node->type === 'advpoll') {
    $lang = entity_language('node', $node);

    // Get all existing choices in the node.
    if (isset($node->advpoll_choice[$lang])) {
      $choices = $node->advpoll_choice[$lang];
    }
    else {
      $choices = $node->advpoll_choice[LANGUAGE_NONE];
    }
    $count = count($choices);

    // Set up for the benefit of Devel to ensure values present a
    // normal/average type of poll setting.
    if (isset($node->devel_generate)) {
      $node->advpoll_dates[$lang][0]['value'] = date('Y-m-d 00:00:00', time());
      $node->advpoll_dates[$lang][0]['value2'] = date('Y-m-d 00:00:00', time() + 60 * 60 * 24 * 30);
      $node->advpoll_max_choices[$lang][0]['value'] = $count;
      $node->advpoll_closed[$lang][0]['value'] = 'open';
      $node->advpoll_mode[$lang][0]['value'] = 'normal';
      $node->advpoll_cookie_duration[$lang][0]['value'] = 60;
      $node->advpoll_results[$lang][0]['value'] = 'aftervote';
      unset($node->advpoll_options);
    }

    // Ensure there are no duplicate choice_ids in this node.
    $ids = array();
    for ($i = 0; $i < $count; $i++) {
      $id = $choices[$i]['choice_id'];
      if (!in_array($id, $ids)) {
        $ids[] = $id;
      }
      else {
        $new_id = dechex(time() * rand(5, 50));
        $node->advpoll_choice[$lang][$i]['choice_id'] = $new_id;
        $ids[] = $new_id;
      }
    }

    // Check for vote results for this node.
    if (isset($node->nid)) {
      $criteria = array();
      $criteria['entity_id'] = $node->nid;
      $criteria['entity_type'] = 'node';
      $results = votingapi_select_votes($criteria);

      // Scrub any votes that are orphaned when a choice is removed.
      if ($results) {
        $no_match = array();
        foreach ($results as $vote) {
          if (!in_array($vote['tag'], $ids)) {
            $no_match[] = $vote;
          }
        }
        votingapi_delete_votes($no_match);
      }
    }
  }
}