You are here

function workflow_cron in Workflow 7

Same name and namespace in other branches
  1. 8 workflow.module \workflow_cron()
  2. 5.2 workflow.module \workflow_cron()
  3. 5 workflow.module \workflow_cron()
  4. 6.2 workflow.module \workflow_cron()
  5. 6 workflow.module \workflow_cron()
  6. 7.2 workflow.module \workflow_cron()

Implements hook_cron().

File

./workflow.module, line 158
Support workflows made up of arbitrary states.

Code

function workflow_cron() {
  $clear_cache = FALSE;

  // If the time now is greater than the time to execute a transition, do it.
  foreach (WorkflowScheduledTransition::loadBetween() as $scheduled_transition) {
    $entity_type = $scheduled_transition->entity_type;
    $entity = $scheduled_transition
      ->getEntity();

    // If user didn't give a comment, create one.
    if (empty($scheduled_transition->comment)) {
      $scheduled_transition
        ->addDefaultComment();
    }

    // A Field API will return a WorkflowItem. A Node API will not.
    $workflowItem = $scheduled_transition
      ->getWorkflowItem();
    $field_info = $workflowItem ? $workflowItem
      ->getField() : array();
    $current_sid = workflow_node_current_state($entity, $entity_type, $field_info);

    // Make sure transition is still valid; i.e., the node is
    // still in the state it was when the transition was scheduled.
    if ($current_sid == $scheduled_transition->old_sid) {

      // Save the user who wanted this.
      $entity->workflow_uid = $scheduled_transition->uid;

      // Do transition. Force it because user who scheduled was checked.
      // The scheduled transition is also deleted from DB.
      // A watchdog message is created with the result.
      $new_sid = $scheduled_transition
        ->execute($force = TRUE);
      if ($field_info) {

        // Only in case of Workflow Field API (not for Workflow Node API), do a separate update,
        // because $workflowItem only works on Node form and Comment form.
        // @todo: move this to a better place.
        $items[0]['value'] = $new_sid;
        $field_name = $field_info['field_name'];
        $entity->{$field_name}['und'] = $items;
        $workflowItem
          ->entitySave($entity_type, $entity);
      }
      $clear_cache = TRUE;
    }
    else {

      // Node is not in the same state it was when the transition
      // was scheduled. Defer to the node's current state and
      // abandon the scheduled transition.
      $scheduled_transition
        ->delete();
    }
  }
  if ($clear_cache) {

    // Clear the cache so that if the transition resulted in a node
    // being published, the anonymous user can see it.
    cache_clear_all();
  }
}