function engagements_imap_get_all_received_messages

7.x engagements.module engagements_imap_get_all_received_messages()
6.x engagements.module engagements_imap_get_all_received_messages()

Connect to our imap server, download all received messages from students (or others). We will then delete them, so they don't get read twice.

1 call to engagements_imap_get_all_received_messages()
engagements_cron in modules/engagements/engagements.module
Implements hook_cron

File

modules/engagements/engagements.module, line 2060
This is the primary module file for the engagements module.

Code

function engagements_imap_get_all_received_messages() 
 {

  $host = variable_get('imap_host', '');
  $port = variable_get('imap_port', '');
  $secure = variable_get('imap_secure', '');

  $mailbox_server = "{" . "$host:$port/$secure" . "}";
  $username = variable_get('imap_username', '');
  $password = variable_get('imap_password', '');

  if ($username == "") {
    return FALSE;
  }


  watchdog('imap', "Attempting to connect to imap server.", array(), WATCHDOG_DEBUG);
  $mbox = imap_open($mailbox_server, $username, $password);
  if (!$mbox) {
    watchdog('imap', "Could not connect to imap server!", array(), WATCHDOG_ERROR);
    fp_add_message("Could not connect to IMAP server.", 'error', TRUE);
  }

  // We need to get the name of the "Trash" folder, which might contain a lot of weird extra stuff in the name.
  // TODO:  Maybe save in a cached field so we don't have to retrieve every time it runs?  But, that gets cleared when we clear the cache.
  $mailboxes = imap_list($mbox, $mailbox_server, "*");
  $trash_box_name = "Trash";
  foreach ($mailboxes as $boxname) {
    if (stristr($boxname, "trash")) {
      $trash_box_name = str_replace($mailbox_server, "", $boxname);
      break;
    }
  }



  $mbox_check = imap_check($mbox);

  // Fetch an overview for all messages in INBOX, by going from 1 to the max number messages.
  $result = imap_fetch_overview($mbox, "1:{$mbox_check->Nmsgs}", 0);

  foreach ($result as $overview) {
    $msgno = $overview->msgno;
    $subject = $overview->subject;
    $udate = $overview->udate; // udate is apparently already in UTC, which is what we want.

    watchdog('imap', "Gettign message $msgno. Subject: $subject. Udate: $udate.", array(), WATCHDOG_DEBUG);

    // We need to get our ONLY the email address from the From field, which
    // might look like:  Richard Peacock <richard.peacock@school.domain.co.com>
    // We will use a regular expression to figure it out.  From: https://stackoverflow.com/questions/33865113/extract-email-address-from-string-php
    $ofrom = $overview->from;
    preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $ofrom, $matches);
    $from_email = $matches [0][0]; // Since this is a FROM email, we assume there's only one sender.

    $body = _engagements_imap_get_body($mbox, $msgno);

    watchdog('imap', "Found Body: $body", array(), WATCHDOG_DEBUG);

    // match the from email to a student
    $student_user_id = db_get_user_id_from_email($from_email, 'student');
    if ($student_user_id) {

      watchdog('imap', "Found from student $student_user_id, creating engagement content.", array(), WATCHDOG_DEBUG);

      // create this as an engagement for this student.
      $account = fp_load_user($student_user_id);
      $student_cwid = $account->cwid;

      $content = new stdClass();
      $content->type = 'engagement';
      $content->cid = "new";
      $content->published = 1;
      $content->delete_flag = 0;
      $content->title = $subject; // required

      $content->field__activity_datetime ['value'] = date('Y-m-d H:i:s', $udate);
      $content->field__student_id ['value'] = $student_cwid;
      $content->field__engagement_type ['value'] = 'email';
      $content->field__direction ['value'] = 'received';

      $content->field__engagement_msg ['value'] = $body;

      content_save($content);
      $cid = $content->cid;

      $attachments = _engagements_imap_get_attachments($mbox, $msgno, fp_get_machine_readable($from_email), $cid);

      // save attachements along with the engagement, if there are any
      if (count($attachments) > 0) {

        $fid_line = "";
        foreach ($attachments as $adetails) {
          $fid = $adetails ['fid'];
          $fid_line .= $fid . ",";
        }
        $fid_line = rtrim($fid_line, ",");
        $content->field__attachment ['value'] = $fid_line;
      }


      $content->field__visibility ['value'] = 'public';

      content_save($content);

      // if received, create an activity record.
      // Create a new "activity record" that the student has sent an email message

      $acontent = new stdClass();
      $acontent->type = 'activity_record';
      $acontent->cid = "new";
      $acontent->published = 1;
      $acontent->delete_flag = 0;
      $acontent->title = t('Student replied to email message.');
      $acontent->field__student_id ['value'] = $student_cwid;
      $acontent->field__activity_type ['value'] = 'mail';
      content_save($acontent);

      // Notify the advisor(s).
      // get list of all advisors for this student, and send notifications.
      $advisors = advise_get_advisors_for_student($student_cwid);
      foreach ($advisors as $c => $afaculty_id) {
        $account_user_id = db_get_user_id_from_cwid($afaculty_id, 'faculty');
        if ($account_user_id) {
          $student_name = fp_get_student_name($student_cwid, TRUE);
          $base_url = $GLOBALS ['fp_system_settings']['base_url'];
          $link = $base_url . "/engagements?current_student_id=$student_cwid";
          $tmsg = "";
          $tmsg .= "$student_name has submitted an email to FlightPath.<br><br>\n\n
                    To view, visit the student's Engagements tab by logging in and following this link:<br>\n 
                    <a href='$link'>$link</a>";

          notify_send_notification_to_user($account_user_id, $tmsg, $content->cid, 'engagement');
        }
      }
    } // if student_user_id



    // We are now finished with this email, so we can move it to our trash folder.
    //imap_mail_move($mbox, $msgno, $trash_box_name);
    imap_delete($mbox, $msgno);
  } // foreach result as overview

  // Delete all mail marked for deletion...
  imap_expunge($mbox);

  watchdog('imap', "Closing connection to imap server.", array(), WATCHDOG_DEBUG);
  // Close connection, we're done.  
  imap_close($mbox);


  // Record the last time we called this function.
  variable_set('engagements_imap_get_all_last_check', time());
}