✏️ 正在编辑: GMail.php
路径:
/srv/systems_dir/koruspay/library/Core/GMail.php
提示:
您可以编辑任何文件(包括二进制文件),但请注意不当修改可能导致文件损坏。
<?php // require '/srv/google/vendor/autoload.php'; class Core_GMail { private $_client = null; private $_service = null; private $_tokenPath = APPLICATION_PATH . '/../data/token.json'; public function checkEmail() { $client = $this->_getClient(); $this->_getToken(); $this->_service = new \Google_Service_Gmail($client); $optParams = []; $optParams['labelIds'] = ['UNREAD', "INBOX"]; $messages = $this->_service->users_messages->listUsersMessages('me', $optParams); $listMessages = $messages->getMessages(); $listedMessages = []; if (count($listMessages) > 0) { foreach ($listMessages as $i => $item) { $messageDetails = $this->_getMessageDetails($item->getId()); if( !$messageDetails['status'] ){ continue; } $listedMessages[$i]["columns"] = $messageDetails['data']['headers']; $listedMessages[$i]["columns"]["Snippet"] = nl2br($messageDetails['data']['snippet']); if( !empty($messageDetails['data']['body']['text/plain']) ){ $listedMessages[$i]["columns"]["Snippet"] = strip_tags(nl2br($messageDetails['data']['body']['text/plain'][0])); } $listedMessages[$i]["columns"]["Message_id"] = $item->getId(); $listedMessages[$i]["columns"]["threadId"] = $messageDetails['data']['threadId']; $this->_markAsRead($item->getId()); $this->_markAsRead($messageDetails['data']['threadId']); if( !empty($messageDetails['data']['files']) ){ $urlAttachment = $this->_downloadAttachmentSendS3($item->getId(), $messageDetails['data']['files']); $listedMessages[$i]["columns"]["url_attachment"] = $urlAttachment; } } } return $listedMessages; } protected function _getClient() { $credentials = APPLICATION_PATH . '/../data/client_secret_771255707542-m6940oueib49mngnhf2i288g3jc9bf0u.apps.googleusercontent.com.json'; $this->_client = new \Google_Client(); $this->_client->setApplicationName('Yuppie Agenda'); $this->_client->setRedirectUri("https://{$_SERVER['HTTP_HOST']}/yuppie/public/service/check-email"); $this->_client->setScopes([ \Google_Service_Gmail::GMAIL_READONLY, \Google_Service_Gmail::GMAIL_MODIFY ]); $this->_client->setAuthConfig($credentials); $this->_client->setAccessType('offline'); $this->_client->setPrompt('select_account consent'); return $this->_client; } protected function _getToken() { // Load previously authorized token from a file, if it exists. // The file token.json stores the user's access and refresh tokens, and is // created automatically when the authorization flow completes for the first // time. if (file_exists($this->_tokenPath)) { $accessToken = json_decode(file_get_contents($this->_tokenPath), true); $this->_client->setAccessToken($accessToken); } // If there is no previous token or it's expired. if ($this->_client->isAccessTokenExpired()) { // Refresh the token if possible, else fetch a new one. if ($this->_client->getRefreshToken()) { $this->_client->fetchAccessTokenWithRefreshToken($this->_client->getRefreshToken()); } else { // Request authorization from the user. throw new Core_Exception("Autorização necessária!", 100); } } } public function getAuthUrl() { $this->_getClient(); return $this->_client->createAuthUrl(); } public function authenticatedCode($authCode) { $this->_getClient(); // Exchange authorization code for an access token. $accessToken = $this->_client->fetchAccessTokenWithAuthCode($authCode); $this->_client->setAccessToken($accessToken); // Check to see if there was an error. if (array_key_exists('error', $accessToken)) { throw new Exception(join(', ', $accessToken)); } // Save the token to a file. if (!file_exists(dirname($this->_tokenPath))) { mkdir(dirname($this->_tokenPath), 0700, true); } file_put_contents($this->_tokenPath, json_encode($this->_client->getAccessToken())); } /** * Returns a base64 decoded web safe string * @param String $string The string to be decoded * @return string Decoded string */ public function base64UrlDecode($string) { return base64_decode(str_replace(array('-', '_'), array('+', '/'), $string)); } /** * Returns a web safe base64 encoded string, used for encoding * @param String $string The string to be encoded * @return String Encoded string */ public function base64UrlEncode($string) { return rtrim(strtr(base64_encode($string), '+/', '-_'), '='); } protected function _getMessageDetails($messageId) { try { $optParam = ['format' => 'full']; $data = []; $headers = []; $body = ['text/plain' => [], 'text/html' => []]; $files = []; $message = $this->_service->users_messages->get("me", $messageId, $optParam); $messageDetails = $message->getPayload(); foreach ($messageDetails['headers'] as $item) { if( $item == "X-Autorespond" ){ return ['status' => false, 'message' => "Email de resposta automática"]; } if( $item->getName() == "From" ){ preg_match_all('#<(.*)>#', $item->getValue(), $matches); $matches = array_filter($matches); if( $matches ){ $email = $matches[1][0]; $headers["From_email"] = $email; } } $headers[$item->name] = $item->value; } $data['headers'] = $headers; if (!is_null($messageDetails['body']['data'])) { array_push($body['text/plain'], nl2br($this->base64UrlDecode($messageDetails['body']['data']))); } foreach ($messageDetails['parts'] as $value) { if( isset($value['parts']) ){ foreach( $value['parts'] as $part ){ if (isset($part['body']['data'])) { array_push($body[$part['mimeType']], nl2br($this->base64UrlDecode($part['body']['data']))); } } } if (isset($value['body']['data'])) { array_push($body[$value['mimeType']], nl2br($this->base64UrlDecode($value['body']['data']))); } else { array_push($files, $value['partId']); } } $data['body'] = $body; $data['threadId'] = $message->getThreadId(); $data['labelIds'] = $message->getLabelIds(); $data['snippet'] = $message->getSnippet(); $data['files'] = $files; return ['status' => true, 'data' => $data]; } catch (\Google_Service_Exception $e) { return ['status' => false, 'message' => $e->getMessage()]; } catch(\Google_Exception $e) { return ['status' => false, 'message' => $e->getMessage()]; } catch(\Exception $e) { return ['status' => false, 'message' => $e->getMessage()]; } } protected function _getAttachment($messageId, $partId) { try { $attachmentDetails = $this->_getAttachmentDetailsFromMessage($messageId, $partId); if (!$attachmentDetails['status']) { return $attachmentDetails; } $attachment = $this->_service->users_messages_attachments->get("me", $messageId, $attachmentDetails['attachmentId']); $attachmentDetails['data'] = $this->base64UrlDecode($attachment->data); return ['status' => true, 'data' => $attachmentDetails]; } catch (\Google_Service_Exception $e) { return ['status' => false, 'message' => $e->getMessage()]; } catch(\Google_Exception $e) { return ['status' => false, 'message' => $e->getMessage()]; } catch(\Exception $e) { return ['status' => false, 'message' => $e->getMessage()]; } } /** * Returns the attachments details from the message data, so a downloadable file can be created * @param string $messageId The id of the message * @param int $partId The id of the part of the given message, that references the selected attachment * @return array Status and data/error message depending on the success of the operation */ protected function _getAttachmentDetailsFromMessage($messageId, $partId) { try { $attachmentHeaders = []; $message = $this->_service->users_messages->get("me", $messageId); $messageDetails = $message->getPayload(); foreach ($messageDetails['parts'][$partId]['headers'] as $item) { $attachmentHeaders[$item->name] = $item->value; } if( !isset($messageDetails['parts'][$partId]['body']['attachmentId']) ){ return ['status' => false, 'message' => "attachmentId is null" ]; } return ['status' => true, 'mimeType' => $messageDetails['parts'][$partId]['mimeType'], 'filename' => $messageDetails['parts'][$partId]['filename'] , 'headers' => $attachmentHeaders, 'attachmentId' => $messageDetails['parts'][$partId]['body']['attachmentId'] ]; } catch (\Google_Service_Exception $e) { return ['status' => false, 'message' => $e->getMessage()]; } catch(\Google_Exception $e) { return ['status' => false, 'message' => $e->getMessage()]; } catch(\Exception $e) { return ['status' => false, 'message' => $e->getMessage()]; } } protected function _markAsRead($messageId) { $modify = new \Google_Service_Gmail_ModifyMessageRequest(); $modify->setRemoveLabelIds(["UNREAD"]); $this->_service->users_messages->modify("me", $messageId, $modify); } protected function _downloadAttachmentSendS3($messageId, $files) { if( empty($files) ){ return ['status' => false, 'message' => 'Sem anexo']; } if( !empty($files) ){ $zip = new ZipArchive(); $filename = UPLOAD_PATH . "/email-" . time() . ".zip"; if ($zip->open($filename, ZIPARCHIVE::CREATE) !== TRUE) { exit("cannot open <$filename>\n"); } $filesDelete = array(); foreach( $files as $value ){ $attachment = $this->_getAttachment($messageId, $value); if( !$attachment['status'] ){ continue; } $newFile = basename($attachment['data']['filename']); file_put_contents(UPLOAD_PATH . "/{$newFile}", $attachment['data']['data']); $urlAttachment = UPLOAD_PATH . "/{$newFile}"; $zip->addFile($urlAttachment, $newFile); $filesDelete[] = $urlAttachment; } $zip->close(); foreach( $filesDelete as $file ){ unlink($file); } } return $filename ? $filename : null; } }
💾 保存文件
← 返回文件管理器