Adding all changes of the Gmail Integration

New Change deleting Date
This commit is contained in:
jenny
2015-11-09 11:01:11 -04:00
parent 7fc80c41c7
commit 703d10cdad
14 changed files with 1079 additions and 15 deletions

View File

@@ -0,0 +1,208 @@
<?php
class labelsGmail
{
function listLabels($service)
{
$labels = array();
try {
$labelsResponse = $service->users_labels->listUsersLabels('me');
if ($labelsResponse->getLabels()) {
$labels = array_merge($labels, $labelsResponse->getLabels());
}
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
return $labels;
}
/**
* Modify the Labels a Message is associated with.
*
* @param Google_Service_Gmail $service Authorized Gmail API instance.
* @param string $userId User's email address. The special value 'me'
* can be used to indicate the authenticated user.
* @param string $messageId ID of Message to modify.
* @param array $labelsToAdd Array of Labels to add.
* @param array $labelsToRemove Array of Labels to remove.
*/
function modifyMessage($service, $userId, $messageId, $labelsToAdd, $labelsToRemove) {
$mods = new Google_Service_Gmail_ModifyMessageRequest();
$mods->setAddLabelIds($labelsToAdd);
$mods->setRemoveLabelIds($labelsToRemove);
try {
$message = $service->users_messages->modify($userId, $messageId, $mods);
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
}
/**
* Get list of Messages in user's mailbox.
*
* @param Google_Service_Gmail $service Authorized Gmail API instance.
* @param string $userId User's email address. The special value 'me'
* can be used to indicate the authenticated user.
* @return array Array of Messages.
*/
function listMessages($service, $userId, $query, $labels) {
$pageToken = NULL;
$messages = array();
$opt_param = array();
do {
try {
if ($pageToken) {
$opt_param['pageToken'] = $pageToken;
}
$opt_param['labelIds'] = $labels;
$opt_param['q'] = $query;
$opt_param['maxResults'] = 3;
$messagesResponse = $service->users_messages->listUsersMessages($userId, $opt_param);
if ($messagesResponse->getMessages()) {
$messages = array_merge($messages, $messagesResponse->getMessages());
}
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
} while ($pageToken);
return $messages;
}
function setLabels($caseId, $index, $actualLastIndex, $unassigned=false){
//First getting the actual thread data
$Pmgmail = new \ProcessMaker\BusinessModel\Pmgmail();
$appData = $Pmgmail->getDraftApp($caseId, $index);
foreach ($appData as $application){
$appNumber = $application['APP_NUMBER'];
$index = $application['DEL_INDEX'];
$threadUsr = $application['USR_UID'];
$proName = $application['APP_PRO_TITLE'];
$threadStatus = $application['DEL_THREAD_STATUS'];
}
if($threadStatus == 'CLOSED' || $unassigned == true){
//Getting the privious User email
$oUsers = new \Users();
$usrData = $oUsers->loadDetails($threadUsr);
$mail = $usrData['USR_EMAIL'];
//The Subject to search the email
$subject = "[PM] " .$proName. " Case: ". $appNumber;
$pmGoogle = new PMGoogleApi();
$pmGoogle->setUser($mail);
$pmGoogle->setScope('https://www.googleapis.com/auth/gmail.modify');
$client = $pmGoogle->serviceClient();
$service = new Google_Service_Gmail($client);
//getting all the label's ids of the user's mail
$listlabels = $this->listLabels($service);
foreach ($listlabels as $label) {
$labId = $label->getId();
$labName = $label->getName();
switch($labName){
case "* Inbox":
$idLabInbox = $labId;
break;
case "* Participated":
$idLabParticipated = $labId;
break;
case "* Unassigned":
$idLabUnassigned = $labId;
break;
case "* Draft":
$idLabDraft = $labId;
break;
case "* Paused":
$idLabPaused = $labId;
break;
}
}
if($actualLastIndex == 0){
$labelsToRemove = $idLabDraft;
$labelsToSearch = "*-draft";
$labelsToAdd = $idLabParticipated;
} else if ( ($actualLastIndex == -1) && ($unassigned == true) ){ //Unassigned
$labelsToRemove = $idLabUnassigned;
$labelsToSearch = "*-unassigned";
$labelsToAdd = $idLabInbox;
} else if($actualLastIndex >= 1) {
$labelsToRemove = $idLabInbox;
$labelsToSearch = "*-inbox";
$labelsToAdd = $idLabParticipated;
}
//Searching the email in the user's mail
$q = "subject:('".preg_quote($subject, '-')."') label:('".$labelsToSearch."')";
$messageList = $this->listMessages($service, $mail, $q, $labelsToRemove);
foreach ($messageList as $message) {
$messageId = $message->getId();
$modifyResult = $this->modifyMessage($service, $mail, $messageId, array($labelsToAdd), array($labelsToRemove));
}
}
}
/**
* Delete Label with given ID.
*
* @param Google_Service_Gmail $service Authorized Gmail API instance.
* @param string $userId User's email address. The special value 'me'
* can be used to indicate the authenticated user.
* @param string $labelId Id of Label to be updated.
*/
public function deleteLabel($service, $user, $labelId)
{
try {
$service->users_labels->delete($user, $labelId);
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
}
/**
* Delete PMGmail integration labels getting the list of labels in an email account.
* @param string $mail User mail adress.
*
*/
public function deletePMGmailLabels($mail)
{
$pmGoogle = new PMGoogleApi();
$pmGoogle->setUser($mail);
$pmGoogle->setScope('https://www.googleapis.com/auth/gmail.modify');
$client = $pmGoogle->serviceClient();
$service = new Google_Service_Gmail($client);
$count = 0;
$listlabels = $this->listLabels($service);
foreach ($listlabels as $label) {
if ($label->getName() == '* Inbox' ||
$label->getName() == '* Participated' ||
$label->getName() == '* Unassigned' ||
$label->getName() == '* Draft' ||
$label->getName() == '* Inbox' ||
$label->getName() == '--- ProcessMaker ---' ||
$label->getName() == '* Paused'
) {
$oresp = $this->deleteLabel($service, 'me', $label->getId());
$count++;
}
}
return $count . ' labels successfully deleted.';
}
}

View File

@@ -11,6 +11,8 @@ if (isset( $_GET['ux'] )) {
default: default:
$url = 'casesListExtJs'; $url = 'casesListExtJs';
} }
} else if( isset( $_GET['gmail'] ) ){
$url = 'derivatedGmail';
} else { } else {
$url = 'casesListExtJs'; $url = 'casesListExtJs';
} }
@@ -19,7 +21,11 @@ if (isset( $_GET['ux'] )) {
} }
echo " window.parent.location.href = '$url';"; echo " window.parent.location.href = '$url';";
if (isset( $_GET['ux'] )) { if (isset( $_GET['ux'] )) {
echo '} else { window.parent.location.href = \'casesListExtJs\'; }'; if(PMLicensedFeatures::getSingleton()->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')){
echo '} else { window.parent.location.href = \'derivatedGmail\'; }';
} else {
echo '} else { window.parent.location.href = \'casesListExtJs\'; }';
}
} }
?> ?>
} }

View File

@@ -67,6 +67,15 @@ $aDelegation = $oAppDelegation->load( $sAppUid, $iDelIndex );
//if there are no user in the delegation row, this case is still in selfservice //if there are no user in the delegation row, this case is still in selfservice
if ($aDelegation['USR_UID'] == "") { if ($aDelegation['USR_UID'] == "") {
$oCase->setCatchUser( $_SESSION['APPLICATION'], $_SESSION['INDEX'], $_SESSION['USER_LOGGED'] ); $oCase->setCatchUser( $_SESSION['APPLICATION'], $_SESSION['INDEX'], $_SESSION['USER_LOGGED'] );
//changing email labels if the claim comes from gmail
if($_SESSION['gmail'] == 1){
$labGmail = new labelsGmail();
$oResponse = $labGmail->setLabels($sAppUid, $iDelIndex, -1, true);
die( '<script type="text/javascript">
parent.document.getElementById("iframePM").setAttribute("src", "'.$_SESSION["server"].'cases/cases_Open?APP_UID=' . $_SESSION["APPLICATION"] . '&DEL_INDEX=' . $_SESSION["INDEX"] . '&action=unassigned");
</script>' );
}
} else { } else {
G::SendMessageText( G::LoadTranslation( 'ID_CASE_ALREADY_DERIVATED' ), 'error' ); G::SendMessageText( G::LoadTranslation( 'ID_CASE_ALREADY_DERIVATED' ), 'error' );
} }

View File

@@ -24,7 +24,52 @@
if (!isset($_SESSION['USER_LOGGED'])) { if (!isset($_SESSION['USER_LOGGED'])) {
G::SendTemporalMessage( 'ID_LOGIN_AGAIN', 'warning', 'labels' ); G::SendTemporalMessage( 'ID_LOGIN_AGAIN', 'warning', 'labels' );
die( '<script type="text/javascript"> die( '<script type="text/javascript">
parent.location = "../cases/casesStartPage?action=startCase"; var olink = parent.uri;
var flag = 0;
if(olink == undefined){
olink = window.frameElement.src;
flag = 1;
}
if(olink.search("gmail") == -1){
parent.location = "../cases/casesStartPage?action=startCase";
} else {
var data = olink.split("?");
var odata = data[1].split("&");
var appUid = odata[0].split("=");
var delIndex = odata[1].split("=");
var action = odata[2].split("=");
var dataToSend = {
"action": "credentials",
"operation": "refreshPmSession",
"type": "processCall",
"funParams": [
appUid[1],
delIndex[1],
action[1],
0
],
"expectReturn": false
};
if (flag == 0){
parent.parent.postMessage(JSON.stringify(dataToSend), "https://mail.google.com");
} else {
dataToSend = {
"action": "credentials",
"operation": "refreshPmSession",
"type": "processCall",
"funParams": [
appUid[1],
delIndex[1],
action[1],
1
],
"expectReturn": false
};
parent.postMessage(JSON.stringify(dataToSend), "*");
}
}
</script>'); </script>');
} }
/* Permissions */ /* Permissions */
@@ -176,6 +221,8 @@ try {
if (isset( $_SESSION['user_experience'] )) { if (isset( $_SESSION['user_experience'] )) {
$aNextStep['PAGE'] = 'casesListExtJsRedirector?ux=' . $_SESSION['user_experience']; $aNextStep['PAGE'] = 'casesListExtJsRedirector?ux=' . $_SESSION['user_experience'];
$debuggerAvailable = false; $debuggerAvailable = false;
} else if( isset( $_SESSION['gmail'] ) ){
$aNextStep['PAGE'] = 'casesListExtJsRedirector?gmail='.$_SESSION['gmail'];
} else { } else {
$aNextStep['PAGE'] = 'casesListExtJsRedirector'; $aNextStep['PAGE'] = 'casesListExtJsRedirector';
} }

View File

@@ -22,6 +22,10 @@
* Coral Gables, FL, 33134, USA, or email info@colosa.com. * Coral Gables, FL, 33134, USA, or email info@colosa.com.
*/ */
if(isset( $_GET['gmail']) && $_GET['gmail'] == 1){
$_SESSION['gmail'] = 1;
}
/* Permissions */ /* Permissions */
if ($RBAC->userCanAccess( 'PM_CASES' ) != 1) { if ($RBAC->userCanAccess( 'PM_CASES' ) != 1) {
switch ($RBAC->userCanAccess( 'PM_CASES' )) { switch ($RBAC->userCanAccess( 'PM_CASES' )) {

View File

@@ -27,10 +27,61 @@ if (!isset($_SESSION['USER_LOGGED'])) {
die( '<script type="text/javascript"> die( '<script type="text/javascript">
try try
{ {
prnt = parent.parent; var olink = parent.uri;
top.location = top.location; var flag = 0;
if(olink == undefined){
olink = window.frameElement.src;
flag = 1;
}
if(olink.search("gmail") == -1){
prnt = parent.parent;
top.location = top.location;
} else {
var data = olink.split("?");
var odata = data[1].split("&");
var appUid = odata[0].split("=");
var delIndex = odata[1].split("=");
var action = odata[2].split("=");
var dataToSend = {
"action": "credentials",
"operation": "refreshPmSession",
"type": "processCall",
"funParams": [
appUid[1],
delIndex[1],
action[1],
0
],
"expectReturn": false
};
if (flag == 0){
parent.parent.postMessage(JSON.stringify(dataToSend), "https://mail.google.com");
}else {
//top.location =
var x = window.postMessage(JSON.stringify(dataToSend), "https://mail.google.com");
if(x == undefined){
//Here the code to access the extension from the gadget
dataToSend = {
"action": "credentials",
"operation": "refreshPmSession",
"type": "processCall",
"funParams": [
appUid[1],
delIndex[1],
action[1],
1
],
"expectReturn": false
};
parent.postMessage(JSON.stringify(dataToSend), "*");
}
}
}
} }
catch (err) catch (err)
{ {
parent.location = parent.location; parent.location = parent.location;
} }

View File

@@ -2,6 +2,11 @@
require_once 'classes/model/AppDelegation.php'; require_once 'classes/model/AppDelegation.php';
$delegation = new AppDelegation(); $delegation = new AppDelegation();
if( $delegation->alreadyRouted($_SESSION['APPLICATION'],$_SESSION['INDEX']) ) { if( $delegation->alreadyRouted($_SESSION['APPLICATION'],$_SESSION['INDEX']) ) {
if($_SESSION['gmail'] == 1){
$mUrl = '../cases/cases_Open?APP_UID='.$_SESSION['APPLICATION'].'&DEL_INDEX='.$_SESSION['INDEX'].'&action=sent';
header( 'location:' . $mUrl );
die();
}
G::header('location: ../cases/casesListExtJs'); G::header('location: ../cases/casesListExtJs');
die(); die();
} }
@@ -9,16 +14,67 @@ if( $delegation->alreadyRouted($_SESSION['APPLICATION'],$_SESSION['INDEX']) ) {
if (!isset($_SESSION['USER_LOGGED'])) { if (!isset($_SESSION['USER_LOGGED'])) {
G::SendTemporalMessage( 'ID_LOGIN_AGAIN', 'warning', 'labels' ); G::SendTemporalMessage( 'ID_LOGIN_AGAIN', 'warning', 'labels' );
die( '<script type="text/javascript"> die( '<script type="text/javascript">
try try
{ {
prnt = parent.parent; var olink = parent.uri;
top.location = top.location; var flag = 0;
} if(olink == undefined){
catch (err) olink = window.frameElement.src;
{ flag = 1;
parent.location = parent.location; }
} if(olink.search("gmail") == -1){
</script>'); prnt = parent.parent;
top.location = top.location;
} else {
var data = olink.split("?");
var odata = data[1].split("&");
var appUid = odata[0].split("=");
var delIndex = odata[1].split("=");
var action = odata[2].split("=");
var dataToSend = {
"action": "credentials",
"operation": "refreshPmSession",
"type": "processCall",
"funParams": [
appUid[1],
delIndex[1],
action[1],
0
],
"expectReturn": false
};
if (flag == 0){
parent.parent.postMessage(JSON.stringify(dataToSend), "https://mail.google.com");
}else {
//top.location =
var x = window.postMessage(JSON.stringify(dataToSend), "https://mail.google.com");
if(x == undefined){
//Here the code to access the extension from the gadget
dataToSend = {
"action": "credentials",
"operation": "refreshPmSession",
"type": "processCall",
"funParams": [
appUid[1],
delIndex[1],
action[1],
1
],
"expectReturn": false
};
parent.postMessage(JSON.stringify(dataToSend), "*");
}
}
}
}
catch (err)
{
parent.location = parent.location;
}
</script>');
} }
/** /**
* cases_Step.php * cases_Step.php

View File

@@ -0,0 +1,47 @@
<?php
use Gulliver\core\ServiceContainer;
$sc = ServiceContainer::getInstance();
$session = $sc->make('session.store');
$licensedFeatures = & PMLicensedFeatures::getSingleton();
if (!$licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) {
G::SendTemporalMessage( 'ID_USER_HAVENT_RIGHTS_PAGE', 'error', 'labels' );
G::header( 'location: ../login/login' );
die;
}
$caseId = $session->get('APPLICATION');
$usrUid = $session->get('USER_LOGGED');
$usrName = $session->get('USR_FULLNAME');
$actualIndex = $session->get('INDEX');
$cont = 0;
use \ProcessMaker\Services\Api;
$appDel = new AppDelegation();
$actualThread = $appDel->Load($caseId, $actualIndex);
$actualLastIndex = $actualThread['DEL_PREVIOUS'];
$appDelPrev = $appDel->LoadParallel($caseId);
if($appDelPrev == array()){
$appDelPrev['0'] = $actualThread;
}
$Pmgmail = new \ProcessMaker\BusinessModel\Pmgmail();
foreach ($appDelPrev as $app){
if( ($app['DEL_INDEX'] != $actualIndex) && ($app['DEL_PREVIOUS'] != $actualLastIndex) ){ //Sending the email to all threads of the case except the actual thread
$response = $Pmgmail->sendEmail($caseId, "", $app['DEL_INDEX']);
}
}
$oLabels = new labelsGmail();
$oResponse = $oLabels->setLabels($caseId, $actualIndex, $actualLastIndex, false);
if( $session->get('gmail') === 1 ){
//$session->set('gmail', 0);
$mUrl = '/sys'. $session->get('WORKSPACE') .'/en/neoclassic/cases/cases_Open?APP_UID='.$caseId.'&DEL_INDEX='.$actualIndex.'&action=sent';
} else{
$mUrl = 'casesListExtJs';
}
header( 'location:' . $mUrl );

View File

@@ -28,6 +28,12 @@
* @date Jan 3th, 2010 * @date Jan 3th, 2010
*/ */
$tBarGmail = false;
if(isset( $_GET['gmail']) && $_GET['gmail'] == 1){
$_SESSION['gmail'] = 1;
$tBarGmail = true;
}
if (! isset( $_GET['APP_UID'] ) || ! isset( $_GET['DEL_INDEX'] )) { if (! isset( $_GET['APP_UID'] ) || ! isset( $_GET['DEL_INDEX'] )) {
if (isset( $_GET['APP_NUMBER'] )) { if (isset( $_GET['APP_NUMBER'] )) {
G::LoadClass( 'case' ); G::LoadClass( 'case' );
@@ -102,6 +108,7 @@ $oHeadPublisher->assign( '_ENV_CURRENT_DATE', $conf->getSystemDate( date( 'Y-m-d
$oHeadPublisher->assign( '_ENV_CURRENT_DATE_NO_FORMAT', date( 'Y-m-d-h-i-A' ) ); $oHeadPublisher->assign( '_ENV_CURRENT_DATE_NO_FORMAT', date( 'Y-m-d-h-i-A' ) );
$oHeadPublisher->assign( 'idfirstform', is_null( $oStep ) ? '' : $oStep->getStepUidObj() ); $oHeadPublisher->assign( 'idfirstform', is_null( $oStep ) ? '' : $oStep->getStepUidObj() );
$oHeadPublisher->assign( 'appStatus', $case['APP_STATUS'] ); $oHeadPublisher->assign( 'appStatus', $case['APP_STATUS'] );
$oHeadPublisher->assign( 'tbarGmail', $tBarGmail);
if(!isset($_SESSION['APPLICATION']) || !isset($_SESSION['TASK']) || !isset($_SESSION['INDEX'])) { if(!isset($_SESSION['APPLICATION']) || !isset($_SESSION['TASK']) || !isset($_SESSION['INDEX'])) {
$_SESSION['APPLICATION'] = $case['APP_UID']; $_SESSION['APPLICATION'] = $case['APP_UID'];

View File

@@ -0,0 +1,310 @@
<?php
namespace ProcessMaker\BusinessModel;
use \G;
/**
* @copyright Colosa - Bolivia
*/
class Pmgmail {
/**
* Get User by usrGmail
*
* @param string $usr_gmail Unique id of User
*
* return uid
*
*/
public function getUserByEmail($usr_gmail)
{
require_once (PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "model" . PATH_SEP . "Users.php");
$oUsers = new \Users();
$response = $oUsers->loadByUserEmailInArray($usr_gmail);
return $response;
}
/**
* Post Token by usrGmail
*
* @param string $request_data
*
* return token
*
*/
public function postTokenbyEmail($request_data)
{
//Lets verify the gmail token
$url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='.$request_data['token'];
// init curl object
$ch = curl_init();
// define options
$optArray = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false
);
// apply those options
curl_setopt_array($ch, $optArray);
// execute request and get response
$result = curl_exec($ch);
$response = (json_decode($result));
// Check if any error occurred
if(curl_errno($ch))
{
throw (new \Exception('The url is not valid.'));
}
$info = curl_getinfo($ch);
curl_close($ch);
//If there is response
if($info['http_code'] == 200 && isset($response->email)){
//If the usermail that was send in the end point es the same of the one in the response
if($request_data['mail'] == $response->email){
$oUsers = new \Users();
$userExist = $oUsers->loadByUserEmailInArray($request_data['mail']);
if(count($userExist) == 1){
if($userExist['0']['USR_STATUS'] == "ACTIVE"){
//User Active! lets create the token and register it in the DB for this user
$oauthServer = new \ProcessMaker\Services\OAuth2\Server;
$server = $oauthServer->getServer();
$config = array(
'allow_implicit' => $server->getConfig('allow_implicit'),
'access_lifetime' => $server->getConfig('access_lifetime')
);
$storage = $server->getStorages();
$accessToken = new \OAuth2\ResponseType\AccessToken($storage['access_token'],$storage['refresh_token'],$config);
$token = $accessToken->createAccessToken($request_data['clientid'], $userExist['0']['USR_UID'],$request_data['scope']);
}else {
throw (new \Exception('The user is not ACTIVE!'));
}
}else{
throw (new \Exception('This email is assigned to more than one user. Please contact your administrator.'));
die;
}
} else {
throw (new \Exception('The email does not corresponds to the token gmail user.'));
}
}else {
throw (new \Exception('The gmail token is not valid.'));
}
return $token;
}
/**
* Get Application data by appUid
*
* @param string $app_uid Unique id of the app
* @param string $index
*
* return row app_cache_view
*
*/
public function getDraftApp($app_uid, $index=1)
{
$response = \AppCacheViewQuery::create()
->filterByAppUid($app_uid)
->filterByDelIndex($index)
->find()
->toArray(null, false, \BasePeer::TYPE_FIELDNAME);
return $response;
}
/**
* Send email using appUid and mail
*
* @param string $app_uid Unique id of the app
* @param string $mail
*
* return uid
*
*/
public function sendEmail($app_uid, $mail, $index)
{
require_once (PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "model" . PATH_SEP . "Application.php");
$oApplication = new \Application();
$formData = $oApplication->Load($app_uid);
$frmData = unserialize($formData['APP_DATA']);
$dataFormToShowString = "";
foreach ($frmData as $field=>$value){
if( ($field != 'SYS_LANG') &&
($field != 'SYS_SKIN') &&
($field != 'SYS_SYS') &&
($field != 'APPLICATION') &&
($field != 'PROCESS') &&
($field != 'TASK') &&
($field != 'INDEX') &&
($field != 'USER_LOGGED') &&
($field != 'USR_USERNAME') &&
($field != 'DYN_CONTENT_HISTORY') &&
($field != 'PIN') ){
$dataFormToShowString .= " " . $field . " " . $value;
}
}
$appData = $this->getDraftApp($app_uid, $index);
foreach ($appData as $application){
$appNumber = $application['APP_NUMBER'];
$appStatus = $application['APP_STATUS'];
$index = $application['DEL_INDEX'];
$prvUsr = $application['APP_DEL_PREVIOUS_USER'];
$delegateDate = $application['DEL_DELEGATE_DATE'];
$nextUsr = $application['USR_UID'];
$proUid = $application['PRO_UID'];
$proName = $application['APP_PRO_TITLE'];
$tasName = $application['APP_TAS_TITLE'];
$threadStatus = $application['DEL_THREAD_STATUS'];
$tasUid = $application['TAS_UID'];
$lastIndex = $application['DEL_LAST_INDEX'];
if($appStatus == "DRAFT"){
$labelID = "PMDRFT";
} else {
$labelID = "PMIBX";
}
if($mail == ""){
require_once (PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "model" . PATH_SEP . "Users.php");
$oUsers = new \Users();
if($nextUsr == ""){
//Unassigned:
$mail = "";
require_once (PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "model" . PATH_SEP . "TaskUser.php");
$oTaskUsers = new \TaskUser();
$taskUsers = $oTaskUsers->getAllUsersTask($tasUid);
foreach ($taskUsers as $user){
$usrData = $oUsers->loadDetails($user['USR_UID']);
$nextMail = $usrData['USR_EMAIL'];
$mail .= ($mail == '') ? $nextMail : ','. $nextMail;
}
$labelID = "PMUASS";
}else {
$usrData = $oUsers->loadDetails($nextUsr);
$mail = $usrData['USR_EMAIL'];
}
}
//first template
$pathTemplate = PATH_DATA_SITE . "mailTemplates" . PATH_SEP . "pmGmail.html";
if (!file_exists($pathTemplate)){
$file = @fopen($pathTemplate, "w");
fwrite($file, '<div>');
fwrite($file, '<span style="display: none !important;">');
fwrite($file, '-**- Process Name: @#proName<br/>');
fwrite($file, '-**- Case Number: @#appNumber<br/>');
fwrite($file, '-**- Case UID: @#caseUid<br/>');
fwrite($file, '-**- Task Name: @#taskName<br/>');
fwrite($file, '-**- Index: @#index<br/>');
fwrite($file, '-**- Action: @#action<br/>');
fwrite($file, '-**- Previous User: @#prevUser<br/>');
fwrite($file, '-**- Delegate Date: @#delDate<br/>');
fwrite($file, '-**- Process Id: @#proUid<br/>');
fwrite($file, '-**- Type: @#type<br/>');
fwrite($file, '-**- FormFields: @@oform<br/>');
fwrite($file, '</span>');
fwrite($file, '</div>');
fclose($file);
}
$change = array('[', ']', '"');
$fdata = str_replace($change, ' ', $dataFormToShowString);
$aFields = array('proName' => $proName,
'appNumber' => $appNumber,
'caseUid' => $app_uid,
'taskName' => $tasName,
'index' => $index,
'action' => $appStatus,
'prevUser' => $prvUsr,
'delDate' => $delegateDate,
'proUid' => $proUid,
'type' => $labelID,
'oform' => $fdata
);
$subject = "[PM] " .$proName. " (" . $index . ") Case: ". $appNumber;
require_once (PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "class.wsBase.php");
$ws = new \wsBase();
$resultMail = $ws->sendMessage(
$app_uid,
'inbox.pm@processmaker.com', //From,
$mail,//To,
'',
'',
$subject,
'pmGmail.html',//template
$aFields, //fields
array(),
true,
0,
array(),
1
);
return $resultMail;
}
return 'The appUid cant be founded';
}
/**
* Get if the license has the feature
*
* return uid
*
*/
public function hasGmailFeature()
{
require_once (PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "class.licensedFeatures.php");
$licensedFeatures = new \PMLicensedFeatures();
if (!$licensedFeatures->verifyfeature('7qhYmF1eDJWcEdwcUZpT0k4S0xTRStvdz09')) {
return false;
}else {
return true;
}
}
/**
* Get the default 'email from account' that is used to send emails in the server email in PM
*
* return uid
*
*/
public function emailAccount()
{
$emailServer = new \EmailServer();
$response = $emailServer->loadDefaultAccount();
return $response['MESS_ACCOUNT'];
}
/**
* Business Model to delete all the labels of an acount
*
* @param string $mail
*
* return uid
*
*/
public function deleteLabels($mail)
{
require_once(PATH_HOME . "engine" . PATH_SEP . "classes" . PATH_SEP . "class.labelsGmail.php");
$oLabels = new \labelsGmail();
$response = $oLabels->deletePMGmailLabels($mail);
return $response;
}
}

View File

@@ -0,0 +1,137 @@
<?php
namespace ProcessMaker\Services\Api;
use \ProcessMaker\Services\Api;
use \Luracast\Restler\RestException;
/**
* GmailIntegration Api Controller
*
*
* @protected
*/
class GmailIntegration extends Api
{
/**
* Get User by usr_gmail
*
* @param string $usr_gmail {@from path}
*
*
* @url GET /userexist/:usr_gmail
*
*/
public function doGetUserbyEmail($usr_gmail)
{
try {
$Pmgmail = new \ProcessMaker\BusinessModel\Pmgmail();
$response = $Pmgmail->getUserByEmail($usr_gmail);
return $response;
} catch (\Exception $e) {
throw (new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()));
}
}
/**
* Get Application by app_uid
*
* @param string $app_uid {@from path}
*
*
* @url GET /application/:app_uid
*
*/
public function doGetApplication($app_uid)
{
try {
$Pmgmail = new \ProcessMaker\BusinessModel\Pmgmail();
$response = $Pmgmail->getDraftApp($app_uid);
return $response;
} catch (\Exception $e) {
throw (new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()));
}
}
/**
* Send Email
*
* @param string $app_uid {@from path}
* @param string $mail {@from path}
* @param string $index {@from path}
*
*
* @url POST /sendEmail/:app_uid/to/:mail/index/:index
*
*/
public function doPostSendMail($app_uid, $mail, $index)
{
try {
$Pmgmail = new \ProcessMaker\BusinessModel\Pmgmail();
$response = $Pmgmail->sendEmail($app_uid, $mail, $index);
return $response;
} catch (\Exception $e) {
throw (new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()));
}
}
/**
* Get if the license has the gmail integration feature
*
*
* @url GET /verifyGmailfeature
*
*/
public function doGetVerifyGmailFeature()
{
try {
$Pmgmail = new \ProcessMaker\BusinessModel\Pmgmail();
$response = $Pmgmail->hasGmailFeature();
return $response;
} catch (\Exception $e) {
throw (new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()));
}
}
/**
* Get the default 'email from account' that is used to send emails in the server email in PM
*
*
* @url GET /current-email-account
*
*/
public function doGetEmailAccount()
{
try {
$Pmgmail = new \ProcessMaker\BusinessModel\Pmgmail();
$response = $Pmgmail->emailAccount();
return $response;
} catch (\Exception $e) {
throw (new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()));
}
}
/**
* End Point to delete Labels in an uninstalation of the extension
*
* @param string $mail {@from path}
*
*
* @url POST /deleteLabels/:mail
*
*/
public function doPostDeleteLabels($mail)
{
try {
$Pmgmail = new \ProcessMaker\BusinessModel\Pmgmail();
$response = $Pmgmail->deleteLabels($mail);
return $response;
} catch (\Exception $e) {
throw (new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()));
}
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace ProcessMaker\Services\Api;
use \ProcessMaker\Services\Api;
use \Luracast\Restler\RestException;
/**
* GmailIntegration Api Controller
*
*
* @hybrid
*/
class GmailToken extends Api
{
/**
* Get token by usr_gmail
*
* @param array $request_data
*
*
* @url POST /token
*
*/
public function doPostAuthenticationbyEmail ($request_data){
try{
$Pmgmail = new \ProcessMaker\BusinessModel\Pmgmail();
$response = $Pmgmail->postTokenbyEmail($request_data);
return $response;
} catch (\Exception $e){
throw (new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage()));
}
}
}

View File

@@ -117,3 +117,7 @@ debug = 1
[alias: google] [alias: google]
authentication = "ProcessMaker\Services\Api\Google\Authentication" authentication = "ProcessMaker\Services\Api\Google\Authentication"
[alias: gmailIntegration]
gmailIntegration = "ProcessMaker\Services\Api\GmailIntegration"
token = "ProcessMaker\Services\Api\GmailToken"

View File

@@ -0,0 +1,143 @@
<?php
require_once(dirname(__FILE__) . '/../../../gulliver/init.php');
use Gulliver\core\ServiceContainer;
$sc = ServiceContainer::getInstance();
$session = $sc->make('session.store');
$request = $sc->make('request');
$gmailToken = $request->query->get('gmailToken');
$gmail = $request->query->get('gmail');
$pmtoken = $request->query->get('pmtoken');
$pmws = $request->query->get('pmws');
$appUid = $request->query->get('appUid');
$delIndex = $request->query->get('delIndex');
$action = $request->query->get('action');
$proUid = $request->query->has('proUid') ? $request->query->get('proUid') : '';
$server = $request->query->get('server');
//First check if the feature is enabled in the license.
$gCurl = curl_init( 'https://' . $server . '/api/1.0/' . $pmws . '/gmailIntegration/verifyGmailfeature/' );
curl_setopt( $gCurl, CURLOPT_HTTPHEADER, array( 'Authorization: Bearer ' . $pmtoken ) );
curl_setopt( $gCurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt( $gCurl, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt( $gCurl, CURLOPT_CONNECTTIMEOUT ,0);
$gCurl_response = curl_exec( $gCurl );
curl_close($gCurl);
$gResp = json_decode($gCurl_response);
if($gResp == false){
echo Bootstrap::LoadTranslation( 'ID_NO_LICENSE_FEATURE_ENABLED' );
die;
}
set_time_limit(60);
$curl = curl_init( 'https://' . $server . '/api/1.0/' . $pmws . '/gmailIntegration/userexist/' . $gmail );
curl_setopt( $curl, CURLOPT_HTTPHEADER, array( 'Authorization: Bearer ' . $pmtoken ) );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT ,0);
$curl_response = curl_exec( $curl );
curl_close($curl);
$decodedResp = json_decode($curl_response);
if(count($decodedResp) > 1){
echo Bootstrap::LoadTranslation( 'ID_EMAIL_MORE_THAN_ONE_USER' );
die;
}
//validationg if there is an actual PM session
if( !$session->has('USER_LOGGED') || $session->get('USER_LOGGED') != $decodedResp['0']->USR_UID){
$url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='.$gmailToken;
// init curl object
$ch = curl_init();
// define options
$optArray = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false
);
// apply those options
curl_setopt_array($ch, $optArray);
// execute request and get response
$result = curl_exec($ch);
$response = (json_decode($result));
curl_close($ch);
//First validate if this user (mail) corresponds to a PM user
if(isset($response->email) && ($gmail == $response->email)){
//If the email corresponds I get the username and with the gmail user_id the session is created.
if($decodedResp['0']->USR_STATUS == "ACTIVE"){
//User Active! lets create the Session
$request = $sc->make('request');
$session = $sc->make('session.store');
$session->setId($request->cookies->get($session->getName()));
$session->start();
setcookie($session->getName(), $session->getId(), 0, '/');
$request->setSession($session);
if (PHP_VERSION < 5.2) {
setcookie("workspaceSkin", "neoclasic", time() + (24 * 60 * 60), "/sys" . "neoclasic", "; HttpOnly");
} else {
setcookie("workspaceSkin", "neoclasic", time() + (24 * 60 * 60), "/sys" . "neoclasic", null, false, true);
}
$session->set('__EE_INSTALLATION__', 2);
$session->set('__EE_SW_PMLICENSEMANAGER__', 1);
$session->set('phpLastFileFound', '');
$session->set('USERNAME_PREVIOUS1', 'admin');
$session->set('USERNAME_PREVIOUS2', 'admin');
$session->set('WORKSPACE', $pmws);
$session->set('USER_LOGGED', $decodedResp['0']->USR_UID);
$session->set('USR_USERNAME', $decodedResp['0']->USR_USERNAME);
$session->set('USR_FULLNAME', $decodedResp['0']->USR_FIRSTNAME. ' ' .$decodedResp['0']->USR_LASTNAME);
$session->set('__sw__', 1);
$session->save();
//session created
} else {
echo Bootstrap::LoadTranslation( 'ID_USER_NOT_ACTIVE' );
die;
}
} else {
echo Bootstrap::LoadTranslation( 'ID_USER_DOES_NOT_CORRESPOND' );
die;
}
}
if ($action == "draft"){
//sending the email
$curlApp = curl_init( 'https://' . $server . '/api/1.0/' . $pmws . '/gmailIntegration/sendEmail/' . $appUid . '/to/' . $gmail . '/index/' . $delIndex );
curl_setopt( $curlApp, CURLOPT_HTTPHEADER, array( 'Authorization: Bearer ' . $pmtoken ) );
curl_setopt( $curlApp, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt( $curlApp, CURLOPT_RETURNTRANSFER, true);
curl_setopt( $curlApp, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt( $curlApp, CURLOPT_CONNECTTIMEOUT ,0);
$curl_response_app = curl_exec( $curlApp );
curl_close( $curlApp );
$mainUrl = '/sys'. $pmws .'/en/neoclassic/cases/open?APP_UID='.$appUid.'&DEL_INDEX='.$delIndex.'&action='.$action.'&gmail=1';
header( 'location:' . $mainUrl );
die;
}
$session->set('server', 'https://' . $server . '/sys'. $pmws .'/en/neoclassic/');
$session->set('PMCase', 'cases/cases_Open?APP_UID='.$appUid.'&DEL_INDEX='.$delIndex.'&action='.$action.'&gmail=1');
$session->set('PMProcessmap', 'designer?prj_uid=' . $proUid . '&prj_readonly=true&app_uid=' . $appUid);
$session->set('PMCasesHistory', 'cases/ajaxListener?action=caseHistory');
$session->set('PMHistoryDynaform', 'cases/casesHistoryDynaformPage_Ajax?actionAjax=historyDynaformPage');
$session->set('PMUploadedDocuments', 'cases/ajaxListener?action=uploadedDocuments');
$session->set('PMGeneratedDocuments', 'cases/casesGenerateDocumentPage_Ajax.php?actionAjax=casesGenerateDocumentPage');
ob_end_flush();
$session->save();
header( 'location:' . 'templateForm.php' );