Open OliverTempel opened 7 years ago
PHP Code:
<?php
require_once(t3lib_extMgm::extPath('ot_intranet').'lib/HTMLPurifier.auto.php');
class tx_otintranet_scheduler extends tx_scheduler_Task {
private $folderID = 347;//332
private $catID = 125;
private $host = '195.37.66.15';
private $username = '###########';
private $password = '##########';
private $version = '';
private $outPath = '';
private $webDir = '';
private $message;
private $limit = 5;
private $onlyUnread = true;
private $maxShort = 160;
private $purifier;
private $ews;
public function execute() {
if(!$this->init()){
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Cron konnte nicht initialisiert werden.'));
return false;
}
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Initialisierung EWS Abgeschlossen'));
if($this->setOutdir('/fileadmin/mails/')){
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Output Verzeichnis erfolgreich gesetzt'));
$this->ews = $this->connectEWS();
if($this->ews){
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Verbindung zum Exchange hergestellt'));
/* Verbindung hergestellt zum Exchange Server */
$request = new EWSType_FindItemType();
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Request erstellt'));
$request->ItemShape = new EWSType_ItemResponseShapeType();
$request->ItemShape->BaseShape = EWSType_DefaultShapeNamesType::DEFAULT_PROPERTIES;
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Shape erstellt'));
$request->Traversal = EWSType_ItemQueryTraversalType::SHALLOW;
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Traversal gesetzt'));
// Limits the number of items retrieved
$request->IndexedPageItemView = new EWSType_IndexedPageViewType();
$request->IndexedPageItemView->BasePoint = "Beginning";
$request->IndexedPageItemView->Offset = 0; // Item number you want to start at
$request->IndexedPageItemView->MaxEntriesReturned = $this->limit; // Numer of items to return in total
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Limit gesetzt'));
//Alle E-Mails aus einem Ordner
$request->ParentFolderIds = new EWSType_NonEmptyArrayOfBaseFolderIdsType();
//Alle Mails aus dem Ordner INBOX
//$request->ParentFolderIds->DistinguishedFolderId = new EWSType_DistinguishedFolderIdType();
//$request->ParentFolderIds->DistinguishedFolderId->Id = EWSType_DistinguishedFolderIdNameType::INBOX;
//Alle Mails aus dem Ordner TYPO3
$folder_id = 'AQAhAEludHJhbmV0RXh0ZXJuZU5ld3NAbWgtbHVlYmVjay5kZQAuAAAD3o419MiM20SzsQacBRR+wAEAKgUe+EJe0UKI8ZiZ0bjZiwAAAWKeIgAAAA==';
$folder_id = $this->convertID($folder_id);
$request->ParentFolderIds->FolderId = new EWSType_FolderIdType();
$request->ParentFolderIds->FolderId->Id = $folder_id;
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Folder-ID gesetzt'));
// sort order
$request->SortOrder = new EWSType_NonEmptyArrayOfFieldOrdersType();
$request->SortOrder->FieldOrder = array();
$order = new EWSType_FieldOrderType();
// sorts mails so that newest appear first
// more field uri definitions can be found from types.xsd (look for UnindexedFieldURIType)
$order->FieldURI->FieldURI = 'item:DateTimeReceived';
$order->Order = 'Descending';
$request->SortOrder->FieldOrder[] = $order;
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Sort Order erstellt'));
// List Only unread Mails
if($this->onlyUnread==true){
$request->Restriction = new EWSType_RestrictionType();
$request->Restriction->IsEqualTo = new EWSType_IsEqualToType();
$request->Restriction->IsEqualTo->FieldURI = new EWSType_PathToUnindexedFieldType();
$request->Restriction->IsEqualTo->FieldURI->FieldURI = 'message:IsRead';
$request->Restriction->IsEqualTo->FieldURIOrConstant = new EWSType_FieldURIOrConstantType();
$request->Restriction->IsEqualTo->FieldURIOrConstant->Constant = new EWSType_ConstantValueType();
$request->Restriction->IsEqualTo->FieldURIOrConstant->Constant->Value = "false";
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Filter ungelesen erstellt'));
}
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Anfrage abgesendet'));
try {
$response = $this->ews->FindItem($request);
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Response gesendet'));
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array($response));
if(is_array($response->ResponseMessages->FindItemResponseMessage->RootFolder->Items->Message)){
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Mehrere E-Mails gefunden: '.count($response->ResponseMessages->FindItemResponseMessage->RootFolder->Items->Message)));
foreach($response->ResponseMessages->FindItemResponseMessage->RootFolder->Items->Message as $message){
$this->message = $message;
$mailRequest = new EWSType_GetItemType();
$mailRequest->ItemShape = new EWSType_ItemResponseShapeType();
$mailRequest->ItemShape->BaseShape = EWSType_DefaultShapeNamesType::ALL_PROPERTIES;
$mailRequest->ItemShape->IncludeMimeContent = true;
$mailRequest->ItemIds = new EWSType_NonEmptyArrayOfBaseItemIdsType();
$mailRequest->ItemIds->ItemId = new EWSType_ItemIdType();
$mailRequest->ItemIds->ItemId->Id = $message->ItemId->Id;
$mailResponse = $this->ews->GetItem($mailRequest);
$this->saveMessage($mailResponse,$message);
/**/
}
} elseif(is_object($response->ResponseMessages->FindItemResponseMessage->RootFolder->Items->Message)){
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Eine E-Mail gefunden.'));
$this->message = $response->ResponseMessages->FindItemResponseMessage->RootFolder->Items->Message;
$mailRequest = new EWSType_GetItemType();
$mailRequest->ItemShape = new EWSType_ItemResponseShapeType();
$mailRequest->ItemShape->BaseShape = EWSType_DefaultShapeNamesType::ALL_PROPERTIES;
$mailRequest->ItemShape->IncludeMimeContent = true;
$mailRequest->ItemIds = new EWSType_NonEmptyArrayOfBaseItemIdsType();
$mailRequest->ItemIds->ItemId = new EWSType_ItemIdType();
$mailRequest->ItemIds->ItemId->Id = $this->message->ItemId->Id;
$mailResponse = $this->ews->GetItem($mailRequest);
$this->saveMessage($mailResponse,$this->message);
} else{
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Keine E-Mails gefunden'));
}
} catch (Exception $e) {
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Exception abgefangen'=>$e));
}
} else {
$this->log('Verbindung zum Exchange war nicht möglich.');
}
} else {
$this->log('Verzeichnis existiert nicht.');
}
$this->writeLog();
return true;
}
function convertID($id){
$ewsID = '';
try{
$request = new EWSType_ConvertIdType();
/*Specify the original format of the ID (types are 'EntryId', 'EwsId', 'EwsLegacyId', 'HexEntryId', 'OwaId', 'StoreId') */
$request->SourceIds->AlternateId->Format='EwsLegacyId';
//Replace $TheIdYouWantToConvert with The original Id
$request->SourceIds->AlternateId->Id=$id;
$request->SourceIds->AlternateId->Mailbox='IntranetExterneNews@mh-luebeck.de';
/*Specify the new format you want (types are 'EntryId', 'EwsId', 'EwsLegacyId', 'HexEntryId', 'OwaId', 'StoreId') */
$request->DestinationFormat='EwsId';
$response = $this->ews->ConvertId($request);
$ewsID = $response->ResponseMessages->ConvertIdResponseMessage->AlternateId->Id;
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('old'=>$id,'new'=>$ewsID));
} catch(Exception $e){
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Exception ConvertID abgefangen: '.$e->getMessage()));
}
return $ewsID;
}
function init(){
if(!$this->loadEWS()){
$this->log('EWS wurde nicht geladen');
return false;
}
$this->loadHTMLPurifier();
$this->setShowOnlyUnread();
$this->setLimit(100);
$this->setMaxShort(160);
$this->setFolderID(347);
$this->setCatID(125);
$this->setUsername('IntranetExterneNewsF');
$this->setPassword('###');
$this->setHost('###');
#$this->setEWSVersion(ExchangeWebServices::VERSION_2007);
$this->setEWSVersion(ExchangeWebServices::VERSION_2010_SP2);
return true;
}
function log($content){
$this->log[]=$content;
}
function writeLog(){
if(count($this->log)>0){
$content = implode("\r\n",$this->log);
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,$this->log);
$file = PATH_site.'/'.date('Ymd').'_email_cron.log';
@file_put_contents($file,"\r\n".$content,FILE_APPEND);
}
}
function setOutdir($dir){
$status = false;
$localDir = PATH_site.$dir;
if(!is_dir($localDir)){
mkdir($localDir,0777,true);
}
if(is_dir($localDir)){
$this->outPath = $localDir;
$this->webDir = $this->getUrl().$dir;
$status=true;
}
return $status;
}
function saveMessage($mailResponse){
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('E-Mail speichern'));
if (($mailResponse->ResponseMessages->GetItemResponseMessage->ResponseCode == 'NoError') &&
($mailResponse->ResponseMessages->GetItemResponseMessage->ResponseClass == 'Success')) {
$message = $mailResponse->ResponseMessages->GetItemResponseMessage->Items->Message;
$recieved = $message->DateTimeReceived;
$subject = $message->Subject;
$tmp = explode('T',$recieved);
$date = explode('-',$tmp[0]);
$time = explode(':',trim($tmp[1],'Z'));
$recievedTime = mktime($time[0],$time[1],$time[2],$date[1],$date[2],$date[0]);
$tmp = explode('@',$message->InternetMessageId);
$short = $this->getTextFromHTML ($message->Body->_);
$short = str_replace("\n", "", $short);
$short = preg_replace("%(\r\n)|(\r)|(\n)%", " ", $short);
$short = preg_replace('/(\s)+/', ' ', $short);
if(strlen($short) > $this->maxShort){
$short = substr($short,0,$this->maxShort-3).'...';
}
$filename = sha1(date("dmY-His",$recievedTime).' - '.$tmp[0].' - '.$subject);
//$itemID = $this->message->ItemId->Id;
//$filename = $itemID;
//$time = time();
$dbData = array(
'pid' => $this->folderID,
'crdate' => $recievedTime,
'tstamp' => $recievedTime,
'datetime' => $recievedTime,
'title' => $subject,
'category' => 1,
'ext_url' => $this->webDir.$filename.'.eml',
'type' => 2,
'author' => $message->Sender->Mailbox->Name,
'author_email' => $message->Sender->Mailbox->EmailAddress,
'short' => $short,
);
$GLOBALS['TYPO3_DB']->exec_INSERTquery('tt_news',$dbData);
$newsID = $GLOBALS['TYPO3_DB']->sql_insert_id();
#$newsID = 0;
if($newsID>0){
$dbData = array(
'uid_local' => $newsID,
'uid_foreign' => $this->catID,
);
$GLOBALS['TYPO3_DB']->exec_INSERTquery('tt_news_cat_mm',$dbData);
file_put_contents($this->outPath.$filename.'.eml', base64_decode($mailResponse->ResponseMessages->GetItemResponseMessage->Items->Message->MimeContent->_));
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('E-Mail gespeichert'));
/* Mark Item as Unread */
$this->markAsRead();
}
} else{
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('E-Mail konnte nicht gespeichert werden'));
}
}
private function markAsRead(){
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('E-Mail als gelesen markieren'));
$request2 = new EWSType_UpdateItemType();
$request2->MessageDisposition = 'SaveOnly';
$request2->ConflictResolution = 'AlwaysOverwrite';
$request2->ItemChanges = array();
$change = new EWSType_ItemChangeType();
$change->ItemId = new EWSType_ItemIdType();
$change->ItemId->Id = $this->message->ItemId->Id;
$change->ItemId->ChangeKey = $this->message->ItemId->ChangeKey;
$field = new EWSType_SetItemFieldType();
$field->FieldURI = new EWSType_PathToUnindexedFieldType();
$field->FieldURI->FieldURI = "message:IsRead";
$field->Message = new EWSType_MessageType();
$field->Message->IsRead = true;
$change->Updates->SetItemField[] = $field;
$request2->ItemChanges[] = $change;
$this->ews->UpdateItem($request2);
}
private function connectEWS(){
//print_r(array($this->host, $this->username, $this->password, $this->version));
try{
$ews = new ExchangeWebServices($this->host, $this->username, $this->password,$this->version);
return $ews;
} catch (Exception $e){
$this->log('Exception abgefangen: ', $e->getMessage());
}
}
private function getUrl($withUri=false){
return sprintf(
"%s://%s%s",
isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
$_SERVER['SERVER_NAME'],
$withUri===true?$_SERVER['REQUEST_URI']:''
);
}
private function getTextFromHTML($html){
return $this->purifier->purify($html);
}
private function loadHTMLPurifier(){
$config = HTMLPurifier_Config::createDefault();
//$config->set('Core', 'Encoding', 'ISO-8859-1'); // not using UTF-8
$config->set('HTML', 'Allowed', ''); // Allow Nothing
$this->purifier = new HTMLPurifier($config);
}
private function loadEWSClasses($classname){
$filename = PATH_site.'/ews/php-ews/' . str_replace( '_', '/', $classname ) . '.php';
include_once $filename;
}
private function loadEWS(){
//$path = t3lib_extMgm::extPath('ot_ewsync').'/lib/php-ews/';
spl_autoload_register(array($this,'loadEWSClasses'));
$path = PATH_site.'/ews/php-ews/';
if(is_file($path.'html2text.php')){
include_once($path.'html2text.php');
} else{
$this->log('html2text not found');
return false;
}
if(is_file($path.'ExchangeWebServices.php')){
include_once($path.'ExchangeWebServices.php');
} else{
$this->log('ExchangeWebServices not found');
return false;
}
if(is_file($path.'EWSType.php')){
include_once($path.'EWSType.php');
} else{
$this->log('EWSType not found');
return false;
}
if(is_file($path.'EWSType/ItemType.php')){
include_once($path.'EWSType/ItemType.php');
} else{
$this->log('ItemType not found');
return false;
}
if(is_file($path.'EWSType/RecurrencePatternBaseType.php')){
include_once($path.'EWSType/RecurrencePatternBaseType.php');
} else{
$this->log('RecurrencePatternBaseType not found');
return false;
}
if(is_file($path.'EWS_Exception.php')){
include_once($path.'EWS_Exception.php');
} else{
$this->log('EWS_Exception not found');
return false;
}
if(is_file($path.'EWSAutodiscover.php')){
include_once($path.'EWSAutodiscover.php');
} else{
$this->log('EWSAutodiscover not found');
return false;
}
if(is_file($path.'NTLMSoapClient.php')){
include_once($path.'NTLMSoapClient.php');
} else{
$this->log('NTLMSoapClient not found');
return false;
}
if(is_dir($path.'EWSType/')){
$ewsTypes = scandir($path.'EWSType/');
foreach($ewsTypes as $file){
if($file!='.' && $file!='..' && $file !='TraversalType.php'){
if(is_file($path.'EWSType/'.$file) && is_readable($path.'EWSType/'.$file)){
//echo '<pre>'.$this->log('load: '.$file."\r\n", true).'</pre>';
include_once($path.'EWSType/'.$file);
}
}
}
} else{
$this->log('EWSType Dir not found');
return false;
}
if(is_dir($path.'NTLMSoapClient/')){
$ewsTypes = scandir($path.'NTLMSoapClient/');
foreach($ewsTypes as $file){
if($file!='.' && $file!='..'){
if(is_file($path.'NTLMSoapClient/'.$file) && is_readable($path.'NTLMSoapClient/'.$file)){
include_once($path.'NTLMSoapClient/'.$file);
}
}
}
} else {
$this->log('NTLMSoapClient Dir not found');
return false;
}
return true;
}
public function setUsername($username){
if(!empty($username)){
$this->username = $username;
}
}
public function setPassword($password){
if(!empty($password)){
$this->password = $password;
}
}
public function setHost($host){
if(!empty($host)){
$this->host = $host;
}
}
public function setFolderID($folderID){
$folderID = intval($folderID);
if(!empty($folderID)){
$this->folderID=$folderID;
}
}
public function setCatID($catID){
$catID = intval($catID);
if(!empty($catID)){
$this->catID=$catID;
}
}
public function setShowOnlyUnread(){
$this->onlyUnread=true;
}
public function setLimit($limit){
$limit = intval($limit);
if(!empty($limit)){
$this->limit=$limit;
}
}
public function setMaxShort($maxShort=160){
$maxShort = intval($maxShort);
if(!empty($maxShort)){
$this->maxShort=$maxShort;
}
}
public function setEWSVersion($version){
$this->version = $version;
}
}
?>
In the future, please format your code using Markdown code blocks: https://guides.github.com/features/mastering-markdown/
I see that you are using an old version of this library which is not supported. Upgrading to the latest beta may resolve your issue, as many bugs have addressed.
Thanks, so i changed up to version 1, and i had the same error.
PHP Fatal error: SOAP-ERROR: Encoding: Violation of encoding rules in vendor/php-ews/php-ews/src/Client.php on line 1631
PHP Code:
<?php
date_default_timezone_set('Europe/Berlin');
error_reporting(E_ALL & ~E_NOTICE);
ini_set('error_reporting', E_ALL & ~E_NOTICE);
ini_set('display_errors', 1);
require_once(PATH_site.'vendor/autoload.php');
require_once(t3lib_extMgm::extPath('ot_intranet').'lib/HTMLPurifier.auto.php');
use \jamesiarmes\PhpEws\Client;
use \jamesiarmes\PhpEws\Request\FindItemType;
use \jamesiarmes\PhpEws\Request\GetItemType;
use \jamesiarmes\PhpEws\Request\UpdateItemType;
use \jamesiarmes\PhpEws\ArrayType\NonEmptyArrayOfBaseFolderIdsType;
use \jamesiarmes\PhpEws\ArrayType\NonEmptyArrayOfBaseItemIdsType;
use \jamesiarmes\PhpEws\Enumeration\DefaultShapeNamesType;
use \jamesiarmes\PhpEws\Enumeration\FolderQueryTraversalType;
use \jamesiarmes\PhpEws\Enumeration\ResponseClassType;
use \jamesiarmes\PhpEws\Type\ItemIdType;
use \jamesiarmes\PhpEws\Type\ConstantValueType;
use \jamesiarmes\PhpEws\Type\FieldURIOrConstantType;
use \jamesiarmes\PhpEws\Type\IsEqualToType;
use \jamesiarmes\PhpEws\Type\ItemResponseShapeType;
use \jamesiarmes\PhpEws\Type\PathToUnindexedFieldType;
use \jamesiarmes\PhpEws\Type\RestrictionType;
use \jamesiarmes\PhpEws\Type\FolderIdType;
use \jamesiarmes\PhpEws\Type\ItemChangeType;
use \jamesiarmes\PhpEws\Type\SetItemFieldType;
use \jamesiarmes\PhpEws\Type\MessageType;
class tx_otintranet_scheduler extends tx_scheduler_Task {
private $folderID = 347;//332
private $catID = 125;
private $host = '######';
private $username = '######';
private $password = ''######';';
private $ewsFolderID = '';
private $version = '';
private $outPath = '';
private $webDir = '';
private $message;
private $limit = 5;
private $onlyUnread = true;
private $maxShort = 160;
private $purifier;
private $ewsClient;
public function execute() {
if(!$this->init()){
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Cron konnte nicht initialisiert werden.'));
return false;
} else{
$this->ewsClient = $this->connectEWS();
if($this->ewsClient){
$request = new FindItemType();
$request->ParentFolderIds = new NonEmptyArrayOfBaseFolderIdsType();
// Search recursively.
$request->Traversal = FolderQueryTraversalType::SHALLOW;
// Build the unread restriction.
$request->Restriction = new RestrictionType();
$request->Restriction->IsEqualTo = new IsEqualToType();
$request->Restriction->IsEqualTo->FieldURI = new PathToUnindexedFieldType();
$request->Restriction->IsEqualTo->FieldURI->FieldURI = 'message:IsRead';
$request->Restriction->IsEqualTo->FieldURIOrConstant = new FieldURIOrConstantType();
$request->Restriction->IsEqualTo->FieldURIOrConstant->Constant = new ConstantValueType();
$request->Restriction->IsEqualTo->FieldURIOrConstant->Constant->Value = "false";
// Return all message properties.
$request->ItemShape = new ItemResponseShapeType();
$request->ItemShape->BaseShape = DefaultShapeNamesType::ALL_PROPERTIES;
// Search in TYPO3 folder
$request->ParentFolderIds->FolderId = new FolderIdType();
$request->ParentFolderIds->FolderId->Id = $this->ewsFolderID;
$response = $this->ewsClient->FindItem($request);
// Iterate over the results, printing any error messages or message subjects.
$response_messages = $response->ResponseMessages->FindItemResponseMessage;
foreach ($response_messages as $response_message) {
// Make sure the request succeeded.
if ($response_message->ResponseClass != ResponseClassType::SUCCESS) {
$message = $response_message->ResponseCode;
echo "Failed to search for messages with \"$message\"\n";
continue;
}
// Iterate over the messages that were found, printing the subject for each.
$items = $response_message->RootFolder->Items->Message;
foreach ($items as $message) {
//$subject = $message->Subject;
//$id = $message->ItemId->Id;
//echo '<pre>'.print_r($message,true).'</pre>';
$mailRequest = new GetItemType();
$mailRequest->ItemShape = new ItemResponseShapeType();
$mailRequest->ItemShape->BaseShape = DefaultShapeNamesType::ALL_PROPERTIES;
$mailRequest->ItemShape->IncludeMimeContent = true;
$mailRequest->ItemIds = new NonEmptyArrayOfBaseItemIdsType();
$mailRequest->ItemIds->ItemId = new ItemIdType();
$mailRequest->ItemIds->ItemId->Id = $message->ItemId->Id;
$mailResponse = $this->ewsClient->GetItem($mailRequest);
//echo '<pre>'.print_r($mailResponse,true).'</pre>';
if (($mailResponse->ResponseMessages->GetItemResponseMessage[0]->ResponseCode == 'NoError') &&
($mailResponse->ResponseMessages->GetItemResponseMessage[0]->ResponseClass == 'Success')) {
$message = $mailResponse->ResponseMessages->GetItemResponseMessage[0]->Items->Message[0];
//echo '<pre>'.print_r($message,true).'</pre>';
$recieved = $message->DateTimeReceived;
$subject = $message->Subject;
$tmp = explode('T',$recieved);
$date = explode('-',$tmp[0]);
$time = explode(':',trim($tmp[1],'Z'));
$recievedTime = mktime($time[0],$time[1],$time[2],$date[1],$date[2],$date[0]);
$tmp = explode('@',$message->InternetMessageId);
$short = strip_tags($message->Body->_);
$short = str_replace("\n", "", $short);
$short = preg_replace("%(\r\n)|(\r)|(\n)%", " ", $short);
$short = preg_replace('/(\s)+/', ' ', $short);
if(strlen($short) > 160){
$short = substr($short,0,157).'...';
}
$filename = sha1(date("dmY-His",$recievedTime).' - '.$tmp[0].' - '.$subject);
//$itemID = $this->message->ItemId->Id;
//$filename = $itemID;
//$time = time();
$dbData = array(
'pid' => $this->folderID,
'crdate' => $recievedTime,
'tstamp' => $recievedTime,
'datetime' => $recievedTime,
'title' => $subject,
'category' => 1,
'ext_url' => $this->webDir.$filename.'.eml',
'type' => 2,
'author' => $message->Sender->Mailbox->Name,
'author_email' => $message->Sender->Mailbox->EmailAddress,
'short' => $short,
);
echo '<pre>'.print_r($dbData,true).'</pre>';
$GLOBALS['TYPO3_DB']->exec_INSERTquery('tt_news',$dbData);
$newsID = $GLOBALS['TYPO3_DB']->sql_insert_id();
#$newsID = 0;
if($newsID>0){
$dbData = array(
'uid_local' => $newsID,
'uid_foreign' => $this->catID,
);
$GLOBALS['TYPO3_DB']->exec_INSERTquery('tt_news_cat_mm',$dbData);
file_put_contents($this->outPath.$filename.'.eml', base64_decode($mailResponse->ResponseMessages->GetItemResponseMessage->Items->Message->MimeContent->_));
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('E-Mail gespeichert'));
/* Mark Item as Unread */
$this->markAsRead($this->ewsClient,$message->ItemId->Id,$message->ItemId->ChangeKey);
}
}
}
}
} else{
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('Keine Verbindung zu Exchange Server'));
return false;
}
}
return true;
}
function init(){
$this->loadHTMLPurifier();
$this->setShowOnlyUnread();
$this->setLimit(100);
$this->setMaxShort(160);
$this->setFolderID(347);
$this->setCatID(125);
$this->setUsername('######');
$this->setPassword('######');
$this->setHost('######');
$this->setEWSVersion(Client::VERSION_2010_SP2);
$this->setEWSFolderID('AQMkAGQyNWI1MDk0LTk1YzUtNGMzNy1hNmViLWMwM2VjZDhhNTEwZAAuAAAD3o419MiM20SzsQacBRR+wAEAKgUe+EJe0UKI8ZiZ0bjZiwAAAWKeIgAAAA==');
return true;
}
function setOutdir($dir){
$status = false;
$localDir = PATH_site.$dir;
if(!is_dir($localDir)){
mkdir($localDir,0777,true);
}
if(is_dir($localDir)){
$this->outPath = $localDir;
$this->webDir = $this->getUrl().$dir;
$status=true;
}
return $status;
}
private function markAsRead($client,$id,$changeKey){
t3lib_div::devLog('EWS-E-Mail-Task','ot_intranet',0,array('E-Mail als gelesen markieren'));
$request2 = new UpdateItemType();
$request2->MessageDisposition = 'SaveOnly';
$request2->ConflictResolution = 'AlwaysOverwrite';
$request2->ItemChanges = array();
$change = new ItemChangeType();
$change->ItemId = new ItemIdType();
$change->ItemId->Id = $id;
$change->ItemId->ChangeKey = $changeKey;
$field = new SetItemFieldType();
$field->FieldURI = new PathToUnindexedFieldType();
$field->FieldURI->FieldURI = "message:IsRead";
$field->Message = new MessageType();
$field->Message->IsRead = true;
$change->Updates->SetItemField[] = $field;
$request2->ItemChanges[] = $change;
$client->UpdateItem($request2);
}
private function connectEWS(){
//print_r(array($this->host, $this->username, $this->password, $this->version));
try{
$client = new Client($this->host, $this->username, $this->password, $this->version);
$client->setCurlOptions(array(CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false));
return $client;
} catch (Exception $e){
$this->log('Exception abgefangen: ', $e->getMessage());
}
}
private function getTextFromHTML($html){
return $this->purifier->purify($html);
}
private function loadHTMLPurifier(){
$config = HTMLPurifier_Config::createDefault();
//$config->set('Core', 'Encoding', 'ISO-8859-1'); // not using UTF-8
$config->set('HTML', 'Allowed', ''); // Allow Nothing
$this->purifier = new HTMLPurifier($config);
}
public function setUsername($username){
if(!empty($username)){
$this->username = $username;
}
}
public function setPassword($password){
if(!empty($password)){
$this->password = $password;
}
}
public function setHost($host){
if(!empty($host)){
$this->host = $host;
}
}
public function setFolderID($folderID){
$folderID = intval($folderID);
if(!empty($folderID)){
$this->folderID=$folderID;
}
}
public function setCatID($catID){
$catID = intval($catID);
if(!empty($catID)){
$this->catID=$catID;
}
}
public function setShowOnlyUnread(){
$this->onlyUnread=true;
}
public function setLimit($limit){
$limit = intval($limit);
if(!empty($limit)){
$this->limit=$limit;
}
}
public function setMaxShort($maxShort=160){
$maxShort = intval($maxShort);
if(!empty($maxShort)){
$this->maxShort=$maxShort;
}
}
public function setEWSVersion($version){
$this->version = $version;
}
public function setEWSFolderID($id){
$this->ewsFolderID = $id;
}
}
?>
The fact that this works via web and not cli points to an environmental issue. I would recommend looking at the difference between your configurations of each. In particular, if you're using PHP < 7.0, check that the always_populate_raw_post_data matches, it should be either 0 or -1 on both.
If that doesn't help you solve your issue, some googling seems to indicate that this exception is raised when a response from the web service does not match what is defined in the WSDL and/or XSD. Can you wrap the actual request operation in a try/catch and post the raw XML request and response, like so:
try {
$client->UpdateItem($request2);
} catch (\SoapFault $e) {
$soap = $client->getClient();
$request_xml = $soap->__getLastRequest();
$response_xml = $soap->__getLastResponse();
}
After Update from PHP 7.2 to PHP 7.4 I get the same Error (before it worked):
PHP Fatal error: SOAP-ERROR: Encoding: Violation of encoding rules in vendor/php-ews/php-ews/src/Client.php on line 1631
Not on UpdateItem() call but on FindItem()
So i used your code for debugging the xml:
try {
$response = $client->FindItem($request);
} catch (\SoapFault $e) {
$soap = $client->getClient();
$request_xml = $soap->__getLastRequest();
$response_xml = $soap->__getLastResponse();
}
request xml is:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="http://schemas.microsoft.com/exchange/services/2006/types"
xmlns:ns2="http://schemas.microsoft.com/exchange/services/2006/messages">
<SOAP-ENV:Header>
<ns1:RequestServerVersion version="Exchange2016"/>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<ns2:FindItem Traversal="Shallow">
<ns2:ItemShape>
<ns1:BaseShape>AllProperties</ns1:BaseShape>
<ns1:BodyType>Text</ns1:BodyType>
</ns2:ItemShape>
<ns2:IndexedPageItemView MaxEntriesReturned="100" Offset="0" BasePoint="Beginning"/>
<ns2:Restriction>
<ns1:IsGreaterThanOrEqualTo>
<ns1:FieldURI FieldURI="item:DateTimeReceived"/>
<ns1:FieldURIOrConstant>
<ns1:Constant value="2019-11-28T10:33:09+01:00"/>
</ns1:FieldURIOrConstant>
</ns1:IsGreaterThanOrEqualTo>
</ns2:Restriction>
<ns2:SortOrder>
<ns1:FieldOrder Order="Ascending">
<ns1:FieldURI FieldURI="item:DateTimeReceived"/>
</ns1:FieldOrder>
</ns2:SortOrder>
<ns2:ParentFolderIds>
<ns1:FolderId
id="AQMkAGJhNWRmODY1LTJmMTctNDcxMC1iZTFmLWYyYTBkMjY4YThmNAAuAAAD/95Kx7SdbEq1pP39AGC5RXEBAElLRRjFjS5Nix3n700/zTsAAAIBDAAAAA=="/>
</ns2:ParentFolderIds>
</ns2:FindItem>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
My IDE is marking the "value=" and "id=" as Error as it expects upper case "Value=" and "Id=" matching the Class Members - but i dont know if this is connected to the error.
the response xml is:
<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<h:ServerVersionInfo MajorVersion="15" MinorVersion="1" MajorBuildNumber="1779" MinorBuildNumber="7"
version="V2017_07_11" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types"
xmlns="http://schemas.microsoft.com/exchange/services/2006/types"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
</s:Header>
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<m:FindItemResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
<m:ResponseMessages>
<m:FindItemResponseMessage ResponseClass="Success">
<m:ResponseCode>NoError</m:ResponseCode>
<m:RootFolder IndexedPagingOffset="18" TotalItemsInView="18" IncludesLastItemInRange="true">
<t:Items>
<t:Message>
<t:ItemId
id="AAMkAGJhNWRmODY1LTJmMTctNDcxMC1iZTFmLWYyYTBkMjY4YThmNABGAAAAAAD/3krHtJ1sSrWk/f1guUVxBwBJS0UYxY0uTYsd5+9NP807AAAAAAEMAABJS0UYxY0uTYsd5+9NP807AAF2m+2IAAA="
ChangeKey="CQAAABYAAABJS0UYxY0uTYsd5+9NP807AAF2nIVw"/>
<t:ParentFolderId
id="AQMkAGJhNWRmODY1LTJmMTctNDcxMC1iZTFmLWYyYTBkMjY4YThmNAAuAAAD/95Kx7SdbEq1pP39AGC5RXEBAElLRRjFjS5Nix3n700/zTsAAAIBDAAAAA=="
ChangeKey="AQAAAA=="/>
<t:ItemClass>IPM.Note</t:ItemClass>
<t:Subject>xxx</t:Subject>
<t:Sensitivity>Normal</t:Sensitivity>
<t:DateTimeReceived>2019-11-28T09:58:49Z</t:DateTimeReceived>
<t:Size>88952</t:Size>
<t:Importance>Normal</t:Importance>
<t:IsSubmitted>false</t:IsSubmitted>
<t:IsDraft>false</t:IsDraft>
<t:IsFromMe>false</t:IsFromMe>
<t:IsResend>false</t:IsResend>
<t:IsUnmodified>true</t:IsUnmodified>
<t:DateTimeSent>2019-11-28T09:58:46Z</t:DateTimeSent>
<t:DateTimeCreated>2019-11-28T09:58:49Z</t:DateTimeCreated>
<t:ReminderIsSet>false</t:ReminderIsSet>
<t:ReminderMinutesBeforeStart>0</t:ReminderMinutesBeforeStart>
<t:DisplayCc/>
<t:DisplayTo>xxx
</t:DisplayTo>
<t:HasAttachments>false</t:HasAttachments>
<t:Culture>de-DE</t:Culture>
<t:EffectiveRights>
<t:CreateAssociated>false</t:CreateAssociated>
<t:CreateContents>false</t:CreateContents>
<t:CreateHierarchy>false</t:CreateHierarchy>
<t:Delete>true</t:Delete>
<t:Modify>true</t:Modify>
<t:Read>true</t:Read>
<t:ViewPrivateItems>true</t:ViewPrivateItems>
</t:EffectiveRights>
<t:LastModifiedName>xxx</t:LastModifiedName>
<t:LastModifiedTime>2019-11-28T09:58:49Z</t:LastModifiedTime>
<t:IsAssociated>false</t:IsAssociated>
<t:WebClientReadFormQueryString>
https://mail.xxx.com/owa?ItemID=AAMkAGJhNWRmODY1LTJmMTctNDcxMC1iZTFmLWYyYTBkMjY4YThmNABGAAAAAAD%2F3krHtJ1sSrWk%2Ff1guUVxBwBJS0UYxY0uTYsd5%2B9NP807AAAAAAEMAABJS0UYxY0uTYsd5%2B9NP807AAF2m%2B2IAAA%3D&exvsurl=1&viewmodel=ReadMessageItem
</t:WebClientReadFormQueryString>
<t:ConversationId
id="AAQkAGJhNWRmODY1LTJmMTctNDcxMC1iZTFmLWYyYTBkMjY4YThmNAAQAD+usJYH2k3XkNWS5NlRnJg="/>
<t:Flag>
<t:FlagStatus>NotFlagged</t:FlagStatus>
</t:Flag>
<t:InstanceKey>AQAAAAAAAQwBAAABdpvtiAAAAAA=</t:InstanceKey>
<t:Sender>
<t:Mailbox>
<t:Name>xxx</t:Name>
<t:EmailAddress>xxx@xxx.com</t:EmailAddress>
<t:RoutingType>SMTP</t:RoutingType>
<t:MailboxType>OneOff</t:MailboxType>
</t:Mailbox>
</t:Sender>
<t:IsReadReceiptRequested>false</t:IsReadReceiptRequested>
<t:IsDeliveryReceiptRequested>false</t:IsDeliveryReceiptRequested>
<t:ConversationIndex>AdWl0mxmP66wlgfaTdeQ1ZLk2VGcmA==</t:ConversationIndex>
<t:ConversationTopic>xxx
</t:ConversationTopic>
<t:From>
<t:Mailbox>
<t:Name>xxx</t:Name>
<t:EmailAddress>xxx@xxx.com</t:EmailAddress>
<t:RoutingType>SMTP</t:RoutingType>
<t:MailboxType>OneOff</t:MailboxType>
</t:Mailbox>
</t:From>
<t:InternetMessageId><c66928708690495985bf21574b5aa83e@xxx.com>
</t:InternetMessageId>
<t:IsRead>false</t:IsRead>
<t:ReceivedBy>
<t:Mailbox>
<t:Name>xxx</t:Name>
<t:RoutingType>EX</t:RoutingType>
<t:MailboxType>OneOff</t:MailboxType>
</t:Mailbox>
</t:ReceivedBy>
<t:ReceivedRepresenting>
<t:Mailbox>
<t:Name>xxx</t:Name>
<t:EmailAddress>xxx
</t:EmailAddress>
<t:RoutingType>EX</t:RoutingType>
<t:MailboxType>OneOff</t:MailboxType>
</t:Mailbox>
</t:ReceivedRepresenting>
</t:Message>
</t:Items>
</m:RootFolder>
</m:FindItemResponseMessage>
</m:ResponseMessages>
</m:FindItemResponse>
</s:Body>
</s:Envelope>
Hi,
In my case the "SOAP-ERROR: Encoding: Violation of encoding rules" appears after upgrading php from 7.2 to 7.4. In fact this message is shown because the curl request itself returns the Following error : "Maximum (20) redirects".
To solve this, I Added a curl options after connecting $ews = new ExchangeWebServices($this->host, $this->username, $this->password,$this->version); $ews->setCurlOptions(array(CURLOPT_MAXREDIRS => -1));
Hope this helps, Kellermin.
Thanks for your answer - i can not test this right now but if the curl operation itself would trigger this error I should not get any response xml or should I?
In my case I got no data, just the error message displayed by php.
Well… I was wrong, I thaught I had found the problem but I realize that the solution in my previous post finally do not solve the problem. Sorry for this ! Kellermin.
Version 0.1
Microsoft Exchange version: 2010 SP2
Description of problem: Collecting all unread mails of a special folder. When running in web, all things are fine, when running in cron i got the following error:
SOAP-ERROR: Encoding: Violation of encoding rules in [...]/ews/php-ews/ExchangeWebServices.php
Example request: Web-Request
when cron is calling script request is:
Cant see any differences, so why i get this error when collecting mails.