From 703d10cdad179c6c70613ceb74ca1bf79c7338f0 Mon Sep 17 00:00:00 2001 From: jenny Date: Mon, 9 Nov 2015 11:01:11 -0400 Subject: [PATCH] Adding all changes of the Gmail Integration New Change deleting Date --- workflow/engine/classes/class.labelsGmail.php | 208 ++++++++++++ .../cases/casesListExtJsRedirector.php | 8 +- .../methods/cases/cases_CatchExecute.php | 9 + .../engine/methods/cases/cases_Derivate.php | 49 ++- workflow/engine/methods/cases/cases_Open.php | 4 + .../engine/methods/cases/cases_SaveData.php | 57 +++- workflow/engine/methods/cases/cases_Step.php | 76 ++++- .../engine/methods/cases/derivatedGmail.php | 47 +++ workflow/engine/methods/cases/open.php | 7 + .../ProcessMaker/BusinessModel/Pmgmail.php | 310 ++++++++++++++++++ .../Services/Api/GmailIntegration.php | 137 ++++++++ .../ProcessMaker/Services/Api/GmailToken.php | 35 ++ .../engine/src/ProcessMaker/Services/api.ini | 4 + workflow/public_html/pmGmail/sso.php | 143 ++++++++ 14 files changed, 1079 insertions(+), 15 deletions(-) create mode 100644 workflow/engine/classes/class.labelsGmail.php create mode 100644 workflow/engine/methods/cases/derivatedGmail.php create mode 100644 workflow/engine/src/ProcessMaker/BusinessModel/Pmgmail.php create mode 100644 workflow/engine/src/ProcessMaker/Services/Api/GmailIntegration.php create mode 100644 workflow/engine/src/ProcessMaker/Services/Api/GmailToken.php create mode 100644 workflow/public_html/pmGmail/sso.php diff --git a/workflow/engine/classes/class.labelsGmail.php b/workflow/engine/classes/class.labelsGmail.php new file mode 100644 index 000000000..84a672074 --- /dev/null +++ b/workflow/engine/classes/class.labelsGmail.php @@ -0,0 +1,208 @@ +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.'; + } + +} + diff --git a/workflow/engine/methods/cases/casesListExtJsRedirector.php b/workflow/engine/methods/cases/casesListExtJsRedirector.php index 3013d1233..2e32eeb60 100755 --- a/workflow/engine/methods/cases/casesListExtJsRedirector.php +++ b/workflow/engine/methods/cases/casesListExtJsRedirector.php @@ -11,6 +11,8 @@ if (isset( $_GET['ux'] )) { default: $url = 'casesListExtJs'; } +} else if( isset( $_GET['gmail'] ) ){ + $url = 'derivatedGmail'; } else { $url = 'casesListExtJs'; } @@ -19,7 +21,11 @@ if (isset( $_GET['ux'] )) { } echo " window.parent.location.href = '$url';"; 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\'; }'; + } } ?> } diff --git a/workflow/engine/methods/cases/cases_CatchExecute.php b/workflow/engine/methods/cases/cases_CatchExecute.php index 82351fdb2..1bf0d68c5 100755 --- a/workflow/engine/methods/cases/cases_CatchExecute.php +++ b/workflow/engine/methods/cases/cases_CatchExecute.php @@ -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 ($aDelegation['USR_UID'] == "") { $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( '' ); + } } else { G::SendMessageText( G::LoadTranslation( 'ID_CASE_ALREADY_DERIVATED' ), 'error' ); } diff --git a/workflow/engine/methods/cases/cases_Derivate.php b/workflow/engine/methods/cases/cases_Derivate.php index d98d82820..8fcc492af 100755 --- a/workflow/engine/methods/cases/cases_Derivate.php +++ b/workflow/engine/methods/cases/cases_Derivate.php @@ -24,7 +24,52 @@ if (!isset($_SESSION['USER_LOGGED'])) { G::SendTemporalMessage( 'ID_LOGIN_AGAIN', 'warning', 'labels' ); die( ''); } /* Permissions */ @@ -176,6 +221,8 @@ try { if (isset( $_SESSION['user_experience'] )) { $aNextStep['PAGE'] = 'casesListExtJsRedirector?ux=' . $_SESSION['user_experience']; $debuggerAvailable = false; + } else if( isset( $_SESSION['gmail'] ) ){ + $aNextStep['PAGE'] = 'casesListExtJsRedirector?gmail='.$_SESSION['gmail']; } else { $aNextStep['PAGE'] = 'casesListExtJsRedirector'; } diff --git a/workflow/engine/methods/cases/cases_Open.php b/workflow/engine/methods/cases/cases_Open.php index acdea01ce..f74b952ac 100755 --- a/workflow/engine/methods/cases/cases_Open.php +++ b/workflow/engine/methods/cases/cases_Open.php @@ -22,6 +22,10 @@ * Coral Gables, FL, 33134, USA, or email info@colosa.com. */ +if(isset( $_GET['gmail']) && $_GET['gmail'] == 1){ + $_SESSION['gmail'] = 1; +} + /* Permissions */ if ($RBAC->userCanAccess( 'PM_CASES' ) != 1) { switch ($RBAC->userCanAccess( 'PM_CASES' )) { diff --git a/workflow/engine/methods/cases/cases_SaveData.php b/workflow/engine/methods/cases/cases_SaveData.php index b9580fe2b..4bfb2123a 100755 --- a/workflow/engine/methods/cases/cases_SaveData.php +++ b/workflow/engine/methods/cases/cases_SaveData.php @@ -27,10 +27,61 @@ if (!isset($_SESSION['USER_LOGGED'])) { die( ''); + try + { + var olink = parent.uri; + 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) + { + parent.location = parent.location; + } + '); } /** * cases_Step.php diff --git a/workflow/engine/methods/cases/derivatedGmail.php b/workflow/engine/methods/cases/derivatedGmail.php new file mode 100644 index 000000000..a02d3f0bc --- /dev/null +++ b/workflow/engine/methods/cases/derivatedGmail.php @@ -0,0 +1,47 @@ +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 ); + diff --git a/workflow/engine/methods/cases/open.php b/workflow/engine/methods/cases/open.php index cf0a7c3f4..ce9e0ea62 100755 --- a/workflow/engine/methods/cases/open.php +++ b/workflow/engine/methods/cases/open.php @@ -28,6 +28,12 @@ * @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_NUMBER'] )) { 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( 'idfirstform', is_null( $oStep ) ? '' : $oStep->getStepUidObj() ); $oHeadPublisher->assign( 'appStatus', $case['APP_STATUS'] ); +$oHeadPublisher->assign( 'tbarGmail', $tBarGmail); if(!isset($_SESSION['APPLICATION']) || !isset($_SESSION['TASK']) || !isset($_SESSION['INDEX'])) { $_SESSION['APPLICATION'] = $case['APP_UID']; diff --git a/workflow/engine/src/ProcessMaker/BusinessModel/Pmgmail.php b/workflow/engine/src/ProcessMaker/BusinessModel/Pmgmail.php new file mode 100644 index 000000000..713d3ab6b --- /dev/null +++ b/workflow/engine/src/ProcessMaker/BusinessModel/Pmgmail.php @@ -0,0 +1,310 @@ +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, '
'); + fwrite($file, ''); + fwrite($file, '-**- Process Name: @#proName
'); + fwrite($file, '-**- Case Number: @#appNumber
'); + fwrite($file, '-**- Case UID: @#caseUid
'); + fwrite($file, '-**- Task Name: @#taskName
'); + fwrite($file, '-**- Index: @#index
'); + fwrite($file, '-**- Action: @#action
'); + fwrite($file, '-**- Previous User: @#prevUser
'); + fwrite($file, '-**- Delegate Date: @#delDate
'); + fwrite($file, '-**- Process Id: @#proUid
'); + fwrite($file, '-**- Type: @#type
'); + fwrite($file, '-**- FormFields: @@oform
'); + fwrite($file, '
'); + fwrite($file, '
'); + 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; + } + +} + + + diff --git a/workflow/engine/src/ProcessMaker/Services/Api/GmailIntegration.php b/workflow/engine/src/ProcessMaker/Services/Api/GmailIntegration.php new file mode 100644 index 000000000..2b8586503 --- /dev/null +++ b/workflow/engine/src/ProcessMaker/Services/Api/GmailIntegration.php @@ -0,0 +1,137 @@ +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())); + } + } + +} + + diff --git a/workflow/engine/src/ProcessMaker/Services/Api/GmailToken.php b/workflow/engine/src/ProcessMaker/Services/Api/GmailToken.php new file mode 100644 index 000000000..f3a04ac50 --- /dev/null +++ b/workflow/engine/src/ProcessMaker/Services/Api/GmailToken.php @@ -0,0 +1,35 @@ +postTokenbyEmail($request_data); + return $response; + } catch (\Exception $e){ + throw (new RestException(Api::STAT_APP_EXCEPTION, $e->getMessage())); + } + } + +} diff --git a/workflow/engine/src/ProcessMaker/Services/api.ini b/workflow/engine/src/ProcessMaker/Services/api.ini index 19f5e4fb4..3ead08f07 100644 --- a/workflow/engine/src/ProcessMaker/Services/api.ini +++ b/workflow/engine/src/ProcessMaker/Services/api.ini @@ -117,3 +117,7 @@ debug = 1 [alias: google] authentication = "ProcessMaker\Services\Api\Google\Authentication" + +[alias: gmailIntegration] + gmailIntegration = "ProcessMaker\Services\Api\GmailIntegration" + token = "ProcessMaker\Services\Api\GmailToken" \ No newline at end of file diff --git a/workflow/public_html/pmGmail/sso.php b/workflow/public_html/pmGmail/sso.php new file mode 100644 index 000000000..dc928d692 --- /dev/null +++ b/workflow/public_html/pmGmail/sso.php @@ -0,0 +1,143 @@ +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' ); +