Skip to content

Commit

Permalink
Merge pull request #22 from damo-veda/master
Browse files Browse the repository at this point in the history
Added the provision to retrieve the zoom regitrants and update them u…
  • Loading branch information
rajeshrhino authored Nov 13, 2020
2 parents ce0b78f + 7b2c902 commit d587b7c
Show file tree
Hide file tree
Showing 8 changed files with 385 additions and 15 deletions.
43 changes: 42 additions & 1 deletion CRM/CivirulesActions/Participant/AddToZoom.php
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,47 @@ public static function checkEventWithZoom($params){
}
}

public static function getZoomRegistrants($eventId){
if(empty($eventId)){
return [];
}
$object = new CRM_CivirulesActions_Participant_AddToZoom;
$webinarId = $object->getWebinarID($eventId);
$meetingId = $object->getMeetingID($eventId);
$zoomRegistrantsList = [];
if(empty($webinarId) && empty($meetingId)){
return $zoomRegistrantsList;
}
$url = '';
$accountId = CRM_NcnCiviZoom_Utils::getZoomAccountIdByEventId($eventId);
$settings = CRM_NcnCiviZoom_Utils::getZoomSettings();

if(!empty($meetingId)){
$url = $settings['base_url'] . "/meetings/".$meetingId.'/registrants?page=';
} elseif (!empty($webinarId)) {
$url = $settings['base_url'] . "/webinars/".$webinarId.'/registrants?page=';
}
$page = 1;
$token = $object->createJWTToken($accountId);
$result = [];
do {
$fetchUrl = $url.$page;
$token = $object->createJWTToken($accountId);
$response = Zttp::withHeaders([
'Content-Type' => 'application/json;charset=UTF-8',
'Authorization' => "Bearer $token"
])->get($fetchUrl);
CRM_Core_Error::debug_var('zoom response', $response);
$result = $response->json();
if(!empty($result['registrants'])){
$zoomRegistrantsList = array_merge($result['registrants'], $zoomRegistrantsList);
}
$page++;
} while ($page <= $result['page_count']);

return $zoomRegistrantsList;
}

/**
* Method to return the url for additional form processing for action
* and return false if none is needed
Expand All @@ -235,4 +276,4 @@ public function getExtraDataInputUrl($ruleActionId) {
return FALSE;
}

}
}
7 changes: 5 additions & 2 deletions CRM/NcnCiviZoom/Constants.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@
* @package CiviCRM
*/
class CRM_NcnCiviZoom_Constants {
//Zoom account settings - table name
//Zoom account settings - table name
CONST ZOOM_ACCOUNT_SETTINGS = 'zoom_account_settings',
ID = 'id', // id
NAME = 'name', //name of the account
API_KEY = 'api_key', //api_key of the account
SECRET_KEY = 'secret_key' //secret key of the account
,CG_Event_Zoom_Notes = 'Event_Zoom_Notes' //Zoom notes Custom group name
,CF_Event_Zoom_Notes = 'Event_Zoom_Notes' //Zoom notes Custom field name
,SEND_ZOOM_REGISTRANTS_EMAIL_TEMPLATE_TITLE = 'send_recent_zoom_registrants'
;
}
}
33 changes: 33 additions & 0 deletions CRM/NcnCiviZoom/Upgrader.php
Original file line number Diff line number Diff line change
Expand Up @@ -160,4 +160,37 @@ public function upgrade_1002(){
return TRUE;
}

//Upgrade function to add the note type custom field to the events
public function upgrade_1003(){
$customGroupName = CRM_NcnCiviZoom_Constants::CG_Event_Zoom_Notes;
$customFieldName = CRM_NcnCiviZoom_Constants::CF_Event_Zoom_Notes;

$customGroupDetails = civicrm_api3('CustomGroup', 'create', [
'sequential' => 1,
'title' => "Event Zoom Notes",
'extends' => "Event",
'name' => $customGroupName,
]);

civicrm_api3('CustomField', 'create', [
'sequential' => 1,
'custom_group_id' => $customGroupDetails['values'][0]['id'],
'label' => "Event Zoom Notes",
'name' => $customFieldName,
'data_type' => "Memo",
'html_type' => "TextArea",
'is_view' => 1,
]);

$sendZoomRegistrantsEmailTemplateTitle = CRM_NcnCiviZoom_Constants::SEND_ZOOM_REGISTRANTS_EMAIL_TEMPLATE_TITLE;
$msgHtml = "<br> {event_title} <br> {registrants} <br>";
$msgSubject = "Recently Joined to the zoom event: {event_title}";
civicrm_api3('MessageTemplate', 'create', [
'msg_title' => $sendZoomRegistrantsEmailTemplateTitle,
'msg_html' => $msgHtml,
'msg_subject' => $msgSubject,
]);
return TRUE;
}

}
220 changes: 217 additions & 3 deletions CRM/NcnCiviZoom/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public function getZoomAccountSettingsByIdOrName($id=NULL, $name = null) {
*/
public function getAllZoomSettingsNamesAndIds(){
$zoomSettings = self::getAllZoomAccountSettings();
$zoomList = [];
$zoomList[0] = "--select--";
if(!empty($zoomSettings)){
foreach ($zoomSettings as $key => $value) {
$zoomList[$key] = $value['name'];
Expand Down Expand Up @@ -174,13 +174,13 @@ public static function checkRequiredProfilesForAnEvent($profileIds = [], $checkF

public function addZoomListToEventForm(&$form){

$zoomList = CRM_NcnCiviZoom_Utils::getAllZoomSettingsNamesAndIds();
$zoomList = self::getAllZoomSettingsNamesAndIds();

$form->add(
'select',
'zoom_account_list',
'Select the zoom account',
array_merge(['0' => "--select--"] , $zoomList),
$zoomList,
FALSE,
array('multiple' => FALSE, 'id' => 'zoom_account_list')
);
Expand Down Expand Up @@ -216,4 +216,218 @@ public function addZoomListToEventForm(&$form){
}
}
}

/**
* Union two given arrays
*
* @param array1 - Array
* @param array2 - Array
* @return union - Array
*/
public static function multiDimArrayUnion($array1 = [], $array2 = []){
if(!is_array($array1)){
return $array1;
}

if(!is_array($array2)){
$array2 = [];
}
$merged = array_merge($array1 , $array2);
foreach ($merged as $key => $value) {
$serialized[$key] = serialize($value);
}
$serialized = array_unique($serialized);
foreach ($serialized as $key => $value) {
$union[$key] = unserialize($value);
}

return $union;
}

/**
* Upcoming Events List
*
* @return Array of events
*/
public static function getUpcomingEventsList(){
$today = date("Y-m-d");

$startDate = civicrm_api3('Event', 'get', [
'start_date' => ['>=' => $today],
]);

$endDate = civicrm_api3('Event', 'get', [
'end_date' => ['>=' => $today],
]);

return self::multiDimArrayUnion($startDate['values'], $endDate['values']);
}

/**
* Filter recent registrants list by time(in mins)
*
* @param registrantsList - Array
* @param minsBack - Integer
* @return recentRegistrants - Array
*/
public static function filterZoomRegistrantsByTime($registrantsList = [], $minsBack = 60){
if(empty($registrantsList) || !is_array($registrantsList)){
return;
}
$recentRegistrants = [];
foreach ($registrantsList as $registrant) {
$registrationTime = $registrant['create_time'];

$registrationTime = str_replace(['T','Z'], [' ',''], $registrationTime);
$registrationTime = date($registrationTime);
$now = date('Y-m-d h:i:s');
$seconds = strtotime($now) - strtotime($registrationTime);
$mins = ($seconds/60);
if($mins < $minsBack){
$recentRegistrants[] = $registrant;
}
}

return $recentRegistrants;
}

/**
* String of Registrants
*
* @param registrantsList - Array
* @param glue - String
* @return stringOfRegistrants - String
*/
public static function stringOfRegistrants($registrantsList = [], $glue = ' , '){
if(empty($registrantsList) || !is_array($registrantsList)){
return;
}
$registrantsUpdateArray = [];
foreach ($registrantsList as $registrant) {
$registrantsUpdateArray[] = $registrant['first_name']." ".$registrant['last_name']." - ".$registrant['email'];
}
$stringOfRegistrants = implode($glue, $registrantsUpdateArray);
return $stringOfRegistrants;
}

/**
* Update the Zoom Registrants to event's notes
*
* @param eventId - Integer
* @param registrantsList - Array
*/
public static function updateZoomRegistrantsToNotes($eventId, $registrantsList = []){
$updateResult = '';
if(empty($eventId) || empty($registrantsList) || !is_array($registrantsList)){
$updateResult = 'Params Missing';
return $updateResult;
}

$updateString = self::stringOfRegistrants($registrantsList);
$cFNameEventNotes = CRM_NcnCiviZoom_Constants::CF_Event_Zoom_Notes;

try {
$cFDetails = civicrm_api3('CustomField', 'get', [
'sequential' => 1,
'name' => $cFNameEventNotes,
]);
} catch (Exception $e) {
CRM_Core_Error::debug_var('Error in updateZoomRegistrantsToNotes', $e);
CRM_Core_Error::debug_var('Error while calling api CustomField get', $cFNameEventNotes);
$updateResult = "Couldn't retrieve the Custom Field ".$cFNameEventNotes." data";
}
if(!empty($cFDetails['id'])){
try {
$apiResult = civicrm_api3('CustomValue', 'create', [
'entity_id' => $eventId,
'custom_'.$cFDetails['id'] => $updateString.".",
]);
} catch (Exception $e) {
CRM_Core_Error::debug_var('Error in updateZoomRegistrantsToNotes', $e);
CRM_Core_Error::debug_var('Error while calling api CustomField create', [
'eventId' => $eventId,
'cFDetails' => $cFDetails,
'updateString' => $updateString
]);
}
if($apiResult['values']){
$updateResult = 'Registrants have been updated to the event successfully.';
}
}

return $updateResult;
}

/*
* Function to get message template details
*/
public static function getMessageTemplateDetails($title = null, $id = null) {
if(!empty($title)){
$result = civicrm_api3('MessageTemplate', 'get', array(
'sequential' => 1,
'msg_title' => $title,
));

return $result ['values'][0];
}
}

/**
* Send Registrants as Email
*
* @param toEmails - String
* @param registrantsList - Array
* @param event - Integer
*/
public static function sendZoomRegistrantsToEmail($toEmails, $registrantsList = [], $event){
if(empty($toEmails) || empty($registrantsList)){
return;
}

$msgTitle = CRM_NcnCiviZoom_Constants::SEND_ZOOM_REGISTRANTS_EMAIL_TEMPLATE_TITLE;
$emailContent = self::getMessageTemplateDetails($msgTitle);
if(empty($emailContent)){
return 'Email Template Not found.';
}
$return = [];
// Replacing the tokens
$emailContent['subject'] = str_replace('{event_title}' ,$event, $emailContent['msg_subject']);
$registrantsString = self::stringOfRegistrants($registrantsList, '<br>');
$emailContent['html'] = str_replace(['{registrants}', '{event_title}'], [$registrantsString, $event], $emailContent['msg_html']);
$emailIds = explode(',', $toEmails);
foreach ($emailIds as $emailId) {
$emailSent = self::sendEmail($emailId, $emailContent);
if($emailSent){
$return['email_message'][] = 'Email has been Sent to '.$emailId;
}else{
$return['email_message'][] = "Email couldn't be Sent to ".$emailId;
}
}

return $return;
}

/**
* Function to send email
*/
public static function sendEmail($email, $emailContent) {
$emailSent = FALSE;
if (empty($email) || empty($emailContent)) {
return $emailSent;
}

$mailParams['toName'] = $email;
$mailParams['toEmail'] = $email;

$mailParams['text'] = !empty($emailContent['text']) ? $emailContent['text'] : '';
$mailParams['html'] = !empty($emailContent['html']) ? $emailContent['html'] : '';
$mailParams['subject'] = !empty($emailContent['subject']) ? $emailContent['subject'] : '';
$defaultAddress = CRM_Core_OptionGroup::values('from_email_address', NULL, NULL, NULL, ' AND is_default = 1');
$mailParams['from'] = reset($defaultAddress);

require_once 'CRM/Utils/Mail.php';
$emailSent = CRM_Utils_Mail::send($mailParams);

return $emailSent;
}
}
12 changes: 8 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@



# ncn-civi-zoom
Civirules Conditions/Actions that talk with Zoom developed for NCN.

# What it does
This extension will connect CiviEvents with Zoom, allowing registrations for zoom events to be captured in your CiviCRM install via your website. This has a multitude of benefits, including GDPR compliance, using Zooms workflow, removing the need to manually export/import as well as being able to manage events in the same way you would any other CiviCRM events.
This extension will connect CiviEvents with Zoom, allowing registrations for zoom events to be captured in your CiviCRM install via your website. This has a multitude of benefits, including GDPR compliance, using Zooms workflow, removing the need to manually export/import as well as being able to manage events in the same way you would any other CiviCRM events. This will also pull the registrants' details for the upcoming zoom based events and update them into the 'Event Zoom Notes' field of each event.

## Requirements

Expand Down Expand Up @@ -73,6 +74,9 @@ Once you've decided this you can create a new CiviRule as per the screen shot.
![Screenshot of event configuration](images/event-configuration.jpg)


## Creating a Scheduled Job for a CiviEvent
### Configure the Scheduled Job
* Once you've created a zoom event, you need to create a scheduled job for that event. The Api Entity should be **Event** and the api action should be **Generatezoomattendance**. This api has only one parameter which is 'days'. This will be used the events using the event's end date i.e the events ended 'x' number of days from current date, where 'x' is the 'days' paramter you enter. You can schedule the Job as frequent as you need it to run.
## Creating Scheduled Jobs
### Scheduled Job for Zoom attendance
* Once you've created a zoom event, you need to create a scheduled job for that event. The Api Entity should be **Zoom Event** and the api action should be **Generatezoomattendance**. This api has only one parameter which is 'days'. This will be used the events using the event's end date i.e the events ended 'x' number of days from current date, where 'x' is the 'days' paramter you enter. You can schedule the Job as frequent as you need it to run.

### Scheduled Job for updating Zoom registrants
* Once you've created a zoom event, you need to create a scheduled job for that event. The Api Entity should be **Zoom Event** and the api action should be **Getrecentzoomregistrants**. This api has two parameters one is 'mins' i.e registrants registered that many 'minutes' before will be filtered and will be taken for updation and for sending email. The other parameter is the Email address to which you want the regitrants list to be sent, for multiple email addresses seperate each by a comma symbol.
Loading

0 comments on commit d587b7c

Please sign in to comment.