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, '