public function request($method, $url = '', $body = null, $headers = array()) { $headers['user-agent'] = Constants::DAV_USER_AGENT; $sLog = "REQUEST: " . $method; if ($url != '') { $sLog = $sLog . " " . $url; } if ($body != null) { $sLog = $sLog . "\r\nBody:\r\n" . $body; } \CApi::Log($sLog, \ELogLevel::Full, 'dav-'); \CApi::LogObject($headers, \ELogLevel::Full, 'dav-'); $response = array(); try { $response = parent::request($method, $url, $body, $headers); } catch (\Sabre\DAV\Exception $ex) { \CApi::LogObject($ex->getMessage(), \ELogLevel::Full, 'dav-'); throw $ex; } $sLog = "RESPONSE: " . $method; if (!empty($response['body'])) { $sLog = $sLog . "\r\nBody:\r\n" . $response['body']; } \CApi::Log($sLog, \ELogLevel::Full, 'dav-'); if (!empty($response['headers'])) { \CApi::LogObject($response['headers'], \ELogLevel::Full, 'dav-'); } return $response; }
/** * @param CAccount $oAccount */ public function ChangePasswordProcess($oAccount) { if (0 < strlen($oAccount->PreviousMailPassword) && $oAccount->PreviousMailPassword !== $oAccount->IncomingMailPassword) { $cpanel_hostname = CApi::GetConf('plugins.cpanel-change-password.config.hostname', 'localhost'); $cpanel_username = CApi::GetConf('plugins.cpanel-change-password.config.username', 'local'); $cpanel_password = CApi::GetConf('plugins.cpanel-change-password.config.password', ''); $email_user = urlencode($oAccount->Email); $email_password = urlencode($oAccount->IncomingMailPassword); $email_domain = urlencode($oAccount->Domain->Name); $query = "https://" . $cpanel_hostname . ":2083/execute/Email/passwd_pop?email=" . $email_user . "&password="******"&domain=" . $email_domain; $curl = curl_init(); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $header[0] = "Authorization: Basic " . base64_encode($cpanel_username . ":" . $cpanel_password) . "\n\r"; curl_setopt($curl, CURLOPT_HTTPHEADER, $header); curl_setopt($curl, CURLOPT_URL, $query); $result = curl_exec($curl); if ($result == false) { CApi::Log("curl_exec threw error \"" . curl_error($curl) . "\" for {$query}"); curl_close($curl); throw new CApiManagerException(Errs::UserManager_AccountNewPasswordUpdateError); } else { curl_close($curl); $json_res = json_decode($result); if (!$json_res->status) { throw new CApiManagerException(Errs::UserManager_AccountNewPasswordUpdateError); } } } }
public static function Init($oTenant = null) { parent::Init($oTenant); $bResult = false; $oUser = null; $oClient = self::CreateClient($oTenant); if ($oClient) { if ($success = $oClient->Initialize()) { if ($success = $oClient->Process()) { if (strlen($oClient->access_token)) { $success = $oClient->CallAPI('https://api.twitter.com/1.1/account/verify_credentials.json', 'GET', array(), array('FailOnAccessError' => true), $oUser); } } $success = $oClient->Finalize($success); } if ($oClient->exit) { $bResult = false; exit; } if ($success && $oUser) { // if you need re-ask user for permission //$oClient->ResetAccessToken(); $aSocial = array('type' => self::$ConnectorName, 'id' => $oUser->id, 'name' => $oUser->name, 'email' => isset($oUser->email) ? $oUser->email : '', 'access_token' => $oClient->access_token, 'scopes' => self::$Scopes); \CApi::Log('social_user_' . self::$ConnectorName); \CApi::LogObject($oUser); $bResult = $aSocial; } else { $bResult = false; $oClient->ResetAccessToken(); self::_socialError($oClient->error, self::$ConnectorName); } } return $bResult; }
/** * This method is called before any HTTP method, but after authentication. * * @param string $sMethod * @param string $path * @throws \Sabre\DAV\Exception\NotAuthenticated * @return bool */ public function beforeMethod($sMethod, $path) { $aHeaders = $this->server->httpRequest->getHeaders(); \CApi::Log($sMethod . ' ' . $path, \ELogLevel::Full, 'sabredav-'); \CApi::LogObject($aHeaders, \ELogLevel::Full, 'sabredav-'); $bLogBody = (bool) \CApi::GetConf('labs.dav.log-body', false); if ($bLogBody) { $body = $this->server->httpRequest->getBodyAsString(); $this->server->httpRequest->setBody($body); \CApi::LogObject($body, \ELogLevel::Full, 'sabredav-'); } \CApi::Log('', \ELogLevel::Full, 'sabredav-'); return; }
public static function Init($oTenant = null) { parent::Init($oTenant); $bResult = false; $oUser = null; $oClient = self::CreateClient($oTenant); if ($oClient) { if ($success = $oClient->Initialize()) { if ($success = $oClient->Process()) { if (strlen($oClient->access_token)) { $success = $oClient->CallAPI('https://www.googleapis.com/oauth2/v1/userinfo', 'GET', array(), array('FailOnAccessError' => true), $oUser); } else { $oClient->error = $oClient->authorization_error; $success = false; } } $success = $oClient->Finalize($success); } if ($oClient->exit) { $bResult = false; exit; } if ($success && $oUser) { // if you need re-ask user for permission $oClient->ResetAccessToken(); $iExpiresIn = 3600; $dAccessTokenExpiry = new DateTime($oClient->access_token_expiry); $aAccessToken = json_encode(array('access_token' => $oClient->access_token, 'created' => $dAccessTokenExpiry->getTimestamp() - $iExpiresIn, 'expires_in' => $iExpiresIn)); $aSocial = array('type' => self::$ConnectorName, 'id' => $oUser->id, 'name' => $oUser->name, 'email' => isset($oUser->email) ? $oUser->email : '', 'access_token' => $aAccessToken, 'refresh_token' => $oClient->refresh_token, 'scopes' => self::$Scopes); \CApi::Log('social_user_' . self::$ConnectorName); \CApi::LogObject($oUser); $bResult = $aSocial; } else { $bResult = false; $oClient->ResetAccessToken(); self::_socialError($oClient->error, self::$ConnectorName); } } return $bResult; }
/** * @return void */ public function Handle() { $sVersion = file_get_contents(PSEVEN_APP_ROOT_PATH . 'VERSION'); define('PSEVEN_APP_VERSION', $sVersion); if (!class_exists('MailSo\\Version')) { echo 'MailSo'; return ''; } else { if (!class_exists('\\CApi') || !\CApi::IsValid()) { echo 'AfterLogic API'; return ''; } } $sPathInfo = \trim(\trim($this->oHttp->GetServer('PATH_INFO', '')), ' /'); if (!empty($sPathInfo)) { if ('dav' === \substr($sPathInfo, 0, 3)) { $this->oActions->PathInfoDav(); return ''; } } /* @var $oApiIntegrator \CApiIntegratorManager */ $oApiIntegrator = \CApi::Manager('integrator'); // ------ Redirect to HTTPS $oSettings =& \CApi::GetSettings(); $bRedirectToHttps = $oSettings->GetConf('Common/RedirectToHttps'); $bHttps = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== "off" || isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == "443"; if ($bRedirectToHttps && !$bHttps) { header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); } // ------ /* @var $oApiCapability \CApiCapabilityManager */ $oApiCapability = \CApi::Manager('capability'); $sResult = ''; $sQuery = \trim(\trim($this->oHttp->GetServer('QUERY_STRING', '')), ' /'); \CApi::Plugin()->RunQueryHandle($sQuery); $iPos = \strpos($sQuery, '&'); if (0 < $iPos) { $sQuery = \substr($sQuery, 0, $iPos); } $aPaths = explode('/', $sQuery); if (0 < count($aPaths) && !empty($aPaths[0])) { $sFirstPart = strtolower($aPaths[0]); if ('ping' === $sFirstPart) { @header('Content-Type: text/plain; charset=utf-8'); $sResult = 'Pong'; } else { if ('pull' === $sFirstPart) { if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { pclose(popen("start /B git pull", "r")); } else { exec("git pull > /dev/null 2>&1 &"); } \CApi::Location('./'); } else { if ('ajax' === $sFirstPart) { @ob_start(); $aResponseItem = null; $sAction = $this->oHttp->GetPost('Action', null); try { \CApi::Log('AJAX: Action: ' . $sAction); if ('SystemGetAppData' !== $sAction && \CApi::GetConf('labs.webmail.csrftoken-protection', true) && !$this->validateToken()) { throw new \ProjectCore\Exceptions\ClientException(\ProjectCore\Notifications::InvalidToken); } else { if (!empty($sAction)) { $sMethodName = 'Ajax' . $sAction; $this->oActions->SetActionParams($this->oHttp->GetPostAsArray()); if (method_exists($this->oActions, $sMethodName) && is_callable(array($this->oActions, $sMethodName))) { $aResponseItem = call_user_func(array($this->oActions, $sMethodName)); } if (\CApi::Plugin()->JsonHookExists($sMethodName)) { $aResponseItem = \CApi::Plugin()->RunJsonHook($this->oActions, $sMethodName, $aResponseItem); } } } if (!is_array($aResponseItem)) { throw new \ProjectCore\Exceptions\ClientException(\ProjectCore\Notifications::UnknownError); } } catch (\Exception $oException) { //if ($oException instanceof \ProjectCore\Exceptions\ClientException && // \ProjectCore\Notifications::AuthError === $oException->getCode()) //{ // $oApiIntegrator = /* @var $oApiIntegrator \CApiIntegratorManager */ \CApi::Manager('integrator'); // $oApiIntegrator->setLastErrorCode(\ProjectCore\Notifications::AuthError); // $oApiIntegrator->logoutAccount(); //} \CApi::LogException($oException); $sAction = empty($sAction) ? 'Unknown' : $sAction; $aAdditionalParams = null; if ($oException instanceof \ProjectCore\Exceptions\ClientException) { $aAdditionalParams = $oException->GetObjectParams(); } $aResponseItem = $this->oActions->ExceptionResponse(null, $sAction, $oException, $aAdditionalParams); } @header('Content-Type: application/json; charset=utf-8'); \CApi::Plugin()->RunHook('ajax.response-result', array($sAction, &$aResponseItem)); $sResult = \MailSo\Base\Utils::Php2js($aResponseItem, \CApi::MailSoLogger()); // \CApi::Log('AJAX: Response: '.$sResult); } else { if ('upload' === $sFirstPart) { @ob_start(); $aResponseItem = null; $sAction = empty($aPaths[1]) ? '' : $aPaths[1]; if ($this->oHttp->IsPut()) { $rPutData = fopen("php://input", "r"); $aFilePath = array_slice($aPaths, 3); $sFilePath = implode('/', $aFilePath); $this->oActions->SetActionParams(array('FileData' => array('name' => basename($sFilePath), 'size' => (int) $this->oHttp->GetHeader('Content-Length'), 'tmp_name' => $rPutData), 'AdditionalData' => json_encode(array('Type' => empty($aPaths[2]) ? 'personal' : strtolower($aPaths[2]), 'CalendarID' => empty($aPaths[2]) ? '' : strtolower($aPaths[2]), 'Folder' => dirname($sFilePath), 'Path' => dirname($sFilePath), 'GroupId' => '', 'IsShared' => false)), 'IsExt' => '1' === (string) $this->oHttp->GetQuery('IsExt', '0') ? '1' : '0', 'TenantHash' => (string) $this->oHttp->GetQuery('TenantHash', ''), 'AuthToken' => $this->oHttp->GetHeader('Auth-Token'), 'AccountID' => empty($aPaths[2]) ? '0' : strtolower($aPaths[2]))); try { $sMethodName = 'Upload' . $sAction; if (method_exists($this->oActions, $sMethodName) && is_callable(array($this->oActions, $sMethodName))) { $aResponseItem = call_user_func(array($this->oActions, $sMethodName)); } if (!is_array($aResponseItem) && empty($sError)) { throw new \ProjectCore\Exceptions\ClientException(\ProjectCore\Notifications::UnknownError); } } catch (\Exception $oException) { \CApi::LogException($oException); $aResponseItem = $this->oActions->ExceptionResponse(null, 'Upload', $oException); $sError = 'exception'; } if (0 < strlen($sError)) { $aResponseItem['Error'] = $sError; } } else { try { $sMethodName = 'Upload' . $sAction; if (method_exists($this->oActions, $sMethodName) && is_callable(array($this->oActions, $sMethodName))) { $sError = ''; $sInputName = 'jua-uploader'; $iError = UPLOAD_ERR_OK; $_FILES = isset($_FILES) ? $_FILES : null; if (isset($_FILES, $_FILES[$sInputName], $_FILES[$sInputName]['name'], $_FILES[$sInputName]['tmp_name'], $_FILES[$sInputName]['size'], $_FILES[$sInputName]['type'])) { $iError = isset($_FILES[$sInputName]['error']) ? (int) $_FILES[$sInputName]['error'] : UPLOAD_ERR_OK; if (UPLOAD_ERR_OK === $iError) { $this->oActions->SetActionParams(array('AccountID' => $this->oHttp->GetPost('AccountID', ''), 'FileData' => $_FILES[$sInputName], 'AdditionalData' => $this->oHttp->GetPost('AdditionalData', null), 'IsExt' => '1' === (string) $this->oHttp->GetPost('IsExt', '0') ? '1' : '0', 'TenantHash' => (string) $this->oHttp->GetPost('TenantHash', ''), 'Token' => $this->oHttp->GetPost('Token', ''), 'AuthToken' => $this->oHttp->GetPost('AuthToken', ''))); \CApi::LogObject($this->oActions->GetActionParams()); $aResponseItem = call_user_func(array($this->oActions, $sMethodName)); } else { $sError = $this->oActions->convertUploadErrorToString($iError); } } else { if (!isset($_FILES) || !is_array($_FILES) || 0 === count($_FILES)) { $sError = 'size'; } else { $sError = 'unknown'; } } } if (!is_array($aResponseItem) && empty($sError)) { throw new \ProjectCore\Exceptions\ClientException(\ProjectCore\Notifications::UnknownError); } } catch (\Exception $oException) { \CApi::LogException($oException); $aResponseItem = $this->oActions->ExceptionResponse(null, 'Upload', $oException); $sError = 'exception'; } if (0 < strlen($sError)) { $aResponseItem['Error'] = $sError; } } @ob_get_clean(); @header('Content-Type: text/html; charset=utf-8'); $sResult = \MailSo\Base\Utils::Php2js($aResponseItem); } else { if ('speclogon' === $sFirstPart || 'speclogoff' === $sFirstPart) { \CApi::SpecifiedUserLogging('speclogon' === $sFirstPart); \CApi::Location('./'); } else { if ('sso' === $sFirstPart) { $oApiIntegratorManager = \CApi::Manager('integrator'); try { $sHash = $this->oHttp->GetRequest('hash'); if (!empty($sHash)) { $sData = \CApi::Cacher()->get('SSO:' . $sHash, true); $aData = \CApi::DecodeKeyValues($sData); if (!empty($aData['Email']) && isset($aData['Password'], $aData['Login'])) { $oAccount = $oApiIntegratorManager->loginToAccount($aData['Email'], $aData['Password'], $aData['Login']); if ($oAccount) { $oApiIntegratorManager->setAccountAsLoggedIn($oAccount); } } } else { $oApiIntegratorManager->logoutAccount(); } } catch (\Exception $oExc) { \CApi::LogException($oExc); } \CApi::Location('./'); } else { if ('autodiscover' === $sFirstPart) { $oSettings =& \CApi::GetSettings(); $sInput = \file_get_contents('php://input'); \CApi::Log('#autodiscover:'); \CApi::LogObject($sInput); $aMatches = array(); $aEmailAddress = array(); \preg_match("/\\<AcceptableResponseSchema\\>(.*?)\\<\\/AcceptableResponseSchema\\>/i", $sInput, $aMatches); \preg_match("/\\<EMailAddress\\>(.*?)\\<\\/EMailAddress\\>/", $sInput, $aEmailAddress); if (!empty($aMatches[1]) && !empty($aEmailAddress[1])) { $sIncMailServer = trim($oSettings->GetConf('WebMail/ExternalHostNameOfLocalImap')); $sOutMailServer = trim($oSettings->GetConf('WebMail/ExternalHostNameOfLocalSmtp')); if (0 < \strlen($sIncMailServer) && 0 < \strlen($sOutMailServer)) { $iIncMailPort = 143; $iOutMailPort = 25; $aMatch = array(); if (\preg_match('/:([\\d]+)$/', $sIncMailServer, $aMatch) && !empty($aMatch[1]) && is_numeric($aMatch[1])) { $sIncMailServer = preg_replace('/:[\\d]+$/', $sIncMailServer, ''); $iIncMailPort = (int) $aMatch[1]; } $aMatch = array(); if (\preg_match('/:([\\d]+)$/', $sOutMailServer, $aMatch) && !empty($aMatch[1]) && is_numeric($aMatch[1])) { $sOutMailServer = preg_replace('/:[\\d]+$/', $sOutMailServer, ''); $iOutMailPort = (int) $aMatch[1]; } $sResult = \implode("\n", array('<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/responseschema/2006">', ' <Response xmlns="' . $aMatches[1] . '">', ' <Account>', ' <AccountType>email</AccountType>', ' <Action>settings</Action>', ' <Protocol>', ' <Type>IMAP</Type>', ' <Server>' . $sIncMailServer . '</Server>', ' <LoginName>' . $aEmailAddress[1] . '</LoginName>', ' <Port>' . $iIncMailPort . '</Port>', ' <SSL>' . (993 === $iIncMailPort ? 'on' : 'off') . '</SSL>', ' <SPA>off</SPA>', ' <AuthRequired>on</AuthRequired>', ' </Protocol>', ' <Protocol>', ' <Type>SMTP</Type>', ' <Server>' . $sOutMailServer . '</Server>', ' <LoginName>' . $aEmailAddress[1] . '</LoginName>', ' <Port>' . $iOutMailPort . '</Port>', ' <SSL>' . (465 === $iOutMailPort ? 'on' : 'off') . '</SSL>', ' <SPA>off</SPA>', ' <AuthRequired>on</AuthRequired>', ' </Protocol>', ' </Account>', ' </Response>', '</Autodiscover>')); } } if (empty($sResult)) { $usec = $sec = 0; list($usec, $sec) = \explode(' ', microtime()); $sResult = \implode("\n", array('<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/responseschema/2006">', empty($aMatches[1]) ? ' <Response>' : ' <Response xmlns="' . $aMatches[1] . '">', ' <Error Time="' . \gmdate('H:i:s', $sec) . \substr($usec, 0, \strlen($usec) - 2) . '" Id="2477272013">', ' <ErrorCode>600</ErrorCode>', ' <Message>Invalid Request</Message>', ' <DebugData />', ' </Error>', ' </Response>', '</Autodiscover>')); } header('Content-Type: text/xml'); $sResult = '<' . '?xml version="1.0" encoding="utf-8"?' . '>' . "\n" . $sResult; \CApi::Log(''); \CApi::Log($sResult); } else { if ('profile' === $sFirstPart) { /* @var $oApiIosManager \CApiIosManager */ $oApiIosManager = \CApi::Manager('ios'); $oAccount = $oApiIntegrator->getLogginedDefaultAccount(); $mResultProfile = $oApiIosManager && $oAccount ? $oApiIosManager->generateXMLProfile($oAccount) : false; if ($mResultProfile !== false) { header('Content-type: application/x-apple-aspen-config; chatset=utf-8'); header('Content-Disposition: attachment; filename="afterlogic.mobileconfig"'); echo $mResultProfile; } else { \CApi::Location('./?IOS/Error'); } } else { if ('ios' === $sFirstPart) { $sResult = file_get_contents(PSEVEN_APP_ROOT_PATH . 'templates/Ios.html'); $iUserId = $oApiIntegrator->getLogginedUserId(); if (0 < $iUserId) { $oAccount = $oApiIntegrator->getLogginedDefaultAccount(); $bError = isset($aPaths[1]) && 'error' === strtolower($aPaths[1]); // TODO @setcookie('skip_ios', '1', time() + 3600 * 3600, '/', null, null, true); $sResult = strtr($sResult, array('{{IOS/HELLO}}' => \CApi::ClientI18N('IOS/HELLO', $oAccount), '{{IOS/DESC_P1}}' => \CApi::ClientI18N('IOS/DESC_P1', $oAccount), '{{IOS/DESC_P2}}' => \CApi::ClientI18N('IOS/DESC_P2', $oAccount), '{{IOS/DESC_P3}}' => \CApi::ClientI18N('IOS/DESC_P3', $oAccount), '{{IOS/DESC_P4}}' => \CApi::ClientI18N('IOS/DESC_P4', $oAccount), '{{IOS/DESC_P5}}' => \CApi::ClientI18N('IOS/DESC_P5', $oAccount), '{{IOS/DESC_P6}}' => \CApi::ClientI18N('IOS/DESC_P6', $oAccount), '{{IOS/DESC_P7}}' => \CApi::ClientI18N('IOS/DESC_P7', $oAccount), '{{IOS/DESC_BUTTON_YES}}' => \CApi::ClientI18N('IOS/DESC_BUTTON_YES', $oAccount), '{{IOS/DESC_BUTTON_SKIP}}' => \CApi::ClientI18N('IOS/DESC_BUTTON_SKIP', $oAccount), '{{IOS/DESC_BUTTON_OPEN}}' => \CApi::ClientI18N('IOS/DESC_BUTTON_OPEN', $oAccount), '{{AppVersion}}' => PSEVEN_APP_VERSION, '{{IntegratorLinks}}' => $oApiIntegrator->buildHeadersLink())); } else { \CApi::Location('./'); } } else { if ('raw' === $sFirstPart) { $sAction = empty($aPaths[1]) ? '' : $aPaths[1]; try { if (!empty($sAction)) { $sMethodName = 'Raw' . $sAction; if (method_exists($this->oActions, $sMethodName)) { $this->oActions->SetActionParams(array('AccountID' => empty($aPaths[2]) || '0' === (string) $aPaths[2] ? '' : $aPaths[2], 'RawKey' => empty($aPaths[3]) ? '' : $aPaths[3], 'IsExt' => empty($aPaths[4]) ? '0' : ('1' === (string) $aPaths[4] ? '1' : 0), 'TenantHash' => empty($aPaths[5]) ? '' : $aPaths[5], 'AuthToken' => empty($aPaths[6]) ? '' : $aPaths[6])); if (!call_user_func(array($this->oActions, $sMethodName))) { \CApi::Log('False result.', \ELogLevel::Error); } } else { \CApi::Log('Invalid action.', \ELogLevel::Error); } } else { \CApi::Log('Empty action.', \ELogLevel::Error); } } catch (\Exception $oException) { \CApi::LogException($oException, \ELogLevel::Error); $this->oHttp->StatusHeader(404); } } else { if ('post' === $sFirstPart) { $sAction = $this->oHttp->GetPost('Action'); try { if (!empty($sAction)) { $sMethodName = 'Post' . $sAction; if (method_exists($this->oActions, $sMethodName) && is_callable(array($this->oActions, $sMethodName))) { $this->oActions->SetActionParams($this->oHttp->GetPostAsArray()); if (!call_user_func(array($this->oActions, $sMethodName))) { \CApi::Log('False result.', \ELogLevel::Error); } } else { \CApi::Log('Invalid action.', \ELogLevel::Error); } } else { \CApi::Log('Empty action.', \ELogLevel::Error); } } catch (\Exception $oException) { \CApi::LogException($oException, \ELogLevel::Error); } } else { if (\CApi::IsHelpdeskModule()) { $sResult = $this->indexHTML(true, $this->oHttp->GetQuery('helpdesk')); } else { if ($this->oHttp->HasQuery('invite')) { $aInviteValues = \CApi::DecodeKeyValues($this->oHttp->GetQuery('invite')); $oApiUsersManager = \CApi::Manager('users'); $oApiCalendarManager = \CApi::Manager('calendar'); if (isset($aInviteValues['organizer'])) { $oAccountOrganizer = $oApiUsersManager->getAccountByEmail($aInviteValues['organizer']); if (isset($oAccountOrganizer, $aInviteValues['attendee'], $aInviteValues['calendarId'], $aInviteValues['eventId'], $aInviteValues['action'])) { $oCalendar = $oApiCalendarManager->getCalendar($oAccountOrganizer, $aInviteValues['calendarId']); if ($oCalendar) { $oEvent = $oApiCalendarManager->getEvent($oAccountOrganizer, $aInviteValues['calendarId'], $aInviteValues['eventId']); if ($oEvent && is_array($oEvent) && 0 < count($oEvent) && isset($oEvent[0])) { if (is_string($sResult)) { $sResult = file_get_contents(PSEVEN_APP_ROOT_PATH . 'templates/CalendarEventInviteExternal.html'); $dt = new \DateTime(); $dt->setTimestamp($oEvent[0]['startTS']); if (!$oEvent[0]['allDay']) { $sDefaultTimeZone = new \DateTimeZone($oAccountOrganizer->getDefaultStrTimeZone()); $dt->setTimezone($sDefaultTimeZone); } $sAction = $aInviteValues['action']; $sActionColor = 'green'; $sActionText = ''; switch (strtoupper($sAction)) { case 'ACCEPTED': $sActionColor = 'green'; $sActionText = 'Accepted'; break; case 'DECLINED': $sActionColor = 'red'; $sActionText = 'Declined'; break; case 'TENTATIVE': $sActionColor = '#A0A0A0'; $sActionText = 'Tentative'; break; } $sDateFormat = 'm/d/Y'; $sTimeFormat = 'h:i A'; switch ($oAccountOrganizer->User->DefaultDateFormat) { case \EDateFormat::DDMMYYYY: $sDateFormat = 'd/m/Y'; break; case \EDateFormat::DD_MONTH_YYYY: $sDateFormat = 'd/m/Y'; break; default: $sDateFormat = 'm/d/Y'; break; } switch ($oAccountOrganizer->User->DefaultTimeFormat) { case \ETimeFormat::F24: $sTimeFormat = 'H:i'; break; case \EDateFormat::DD_MONTH_YYYY: \ETimeFormat::F12; $sTimeFormat = 'h:i A'; break; default: $sTimeFormat = 'h:i A'; break; } $sDateTime = $dt->format($sDateFormat . ' ' . $sTimeFormat); $mResult = array('{{COLOR}}' => $oCalendar->Color, '{{EVENT_NAME}}' => $oEvent[0]['subject'], '{{EVENT_BEGIN}}' => ucfirst(\CApi::ClientI18N('REMINDERS/EVENT_BEGIN', $oAccountOrganizer)), '{{EVENT_DATE}}' => $sDateTime, '{{CALENDAR}}' => ucfirst(\CApi::ClientI18N('REMINDERS/CALENDAR', $oAccountOrganizer)), '{{CALENDAR_NAME}}' => $oCalendar->DisplayName, '{{EVENT_DESCRIPTION}}' => $oEvent[0]['description'], '{{EVENT_ACTION}}' => $sActionText, '{{ACTION_COLOR}}' => $sActionColor); $sResult = strtr($sResult, $mResult); } else { \CApi::Log('Empty template.', \ELogLevel::Error); } } else { \CApi::Log('Event not found.', \ELogLevel::Error); } } else { \CApi::Log('Calendar not found.', \ELogLevel::Error); } $sAttendee = $aInviteValues['attendee']; if (!empty($sAttendee)) { $oApiCalendarManager->updateAppointment($oAccountOrganizer, $aInviteValues['calendarId'], $aInviteValues['eventId'], $sAttendee, $aInviteValues['action']); } } } } else { if (\CApi::IsCalendarPubModule()) { $sResult = $this->indexHTML(false, '', $this->oHttp->GetQuery('calendar-pub')); } else { if (\CApi::IsFilesPubModule()) { $sResult = $this->indexHTML(false, '', '', $this->oHttp->GetQuery('files-pub')); } else { if ('min' === $sFirstPart || 'window' === $sFirstPart) { $sAction = empty($aPaths[1]) ? '' : $aPaths[1]; try { if (!empty($sAction)) { $sMethodName = $aPaths[0] . $sAction; if (method_exists($this->oActions, $sMethodName)) { if ('Min' === $aPaths[0]) { $oMinManager = \CApi::Manager('min'); $mHashResult = $oMinManager->getMinByHash(empty($aPaths[2]) ? '' : $aPaths[2]); $this->oActions->SetActionParams(array('Result' => $mHashResult, 'Hash' => empty($aPaths[2]) ? '' : $aPaths[2])); } else { $this->oActions->SetActionParams(array('AccountID' => empty($aPaths[2]) || '0' === (string) $aPaths[2] ? '' : $aPaths[2], 'RawKey' => empty($aPaths[3]) ? '' : $aPaths[3])); } $mResult = call_user_func(array($this->oActions, $sMethodName)); $sTemplate = isset($mResult['Template']) && !empty($mResult['Template']) && is_string($mResult['Template']) ? $mResult['Template'] : null; if (!empty($sTemplate) && is_array($mResult) && file_exists(PSEVEN_APP_ROOT_PATH . $sTemplate)) { $sResult = file_get_contents(PSEVEN_APP_ROOT_PATH . $sTemplate); if (is_string($sResult)) { $sResult = strtr($sResult, $mResult); } else { \CApi::Log('Empty template.', \ELogLevel::Error); } } else { if (!empty($sTemplate)) { \CApi::Log('Empty template.', \ELogLevel::Error); } else { if (true === $mResult) { $sResult = ''; } else { \CApi::Log('False result.', \ELogLevel::Error); } } } } else { \CApi::Log('Invalid action.', \ELogLevel::Error); } } else { \CApi::Log('Empty action.', \ELogLevel::Error); } } catch (\Exception $oException) { \CApi::LogException($oException); } } else { if ('twilio' === $sFirstPart) { $sResult = $this->oTwilio->getTwiML($aPaths, $this->oHttp); } else { if ('plugins' === $sFirstPart) { $sType = !empty($aPaths[1]) ? trim($aPaths[1]) : ''; if ('js' === $sType) { @header('Content-Type: application/javascript; charset=utf-8'); $sResult = \CApi::Plugin()->CompileJs(); } else { if ('images' === $sType) { if (!empty($aPaths[2]) && !empty($aPaths[3])) { $oPlugin = \CApi::Plugin()->GetPluginByName($aPaths[2]); if ($oPlugin) { echo $oPlugin->GetImage($aPaths[3]); exit; } } } else { if ('fonts' === $sType) { if (!empty($aPaths[2]) && !empty($aPaths[3])) { $oPlugin = \CApi::Plugin()->GetPluginByName($aPaths[2]); if ($oPlugin) { echo $oPlugin->GetFont($aPaths[3]); exit; } } } } } } else { if ('postlogin' === $sFirstPart && \CApi::GetConf('labs.allow-post-login', false)) { $oSettings =& \CApi::GetSettings(); $sEmail = trim((string) $this->oHttp->GetRequest('Email', '')); $sLogin = (string) $this->oHttp->GetRequest('Login', ''); $sPassword = (string) $this->oHttp->GetRequest('Password', ''); $sAtDomain = trim($oSettings->GetConf('WebMail/LoginAtDomainValue')); if (\ELoginFormType::Login === (int) $oSettings->GetConf('WebMail/LoginFormType') && 0 < strlen($sAtDomain)) { $sEmail = \api_Utils::GetAccountNameFromEmail($sLogin) . '@' . $sAtDomain; $sLogin = $sEmail; } if (0 !== strlen($sPassword) && 0 !== strlen($sEmail . $sLogin)) { try { $oAccount = $oApiIntegrator->loginToAccount($sEmail, $sPassword, $sLogin); } catch (\Exception $oException) { $iErrorCode = \ProjectCore\Notifications::UnknownError; if ($oException instanceof \CApiManagerException) { switch ($oException->getCode()) { case \Errs::WebMailManager_AccountDisabled: case \Errs::WebMailManager_AccountWebmailDisabled: $iErrorCode = \ProjectCore\Notifications::AuthError; break; case \Errs::UserManager_AccountAuthenticationFailed: case \Errs::WebMailManager_AccountAuthentication: case \Errs::WebMailManager_NewUserRegistrationDisabled: case \Errs::WebMailManager_AccountCreateOnLogin: case \Errs::Mail_AccountAuthentication: case \Errs::Mail_AccountLoginFailed: $iErrorCode = \ProjectCore\Notifications::AuthError; break; case \Errs::UserManager_AccountConnectToMailServerFailed: case \Errs::WebMailManager_AccountConnectToMailServerFailed: case \Errs::Mail_AccountConnectToMailServerFailed: $iErrorCode = \ProjectCore\Notifications::MailServerError; break; case \Errs::UserManager_LicenseKeyInvalid: case \Errs::UserManager_AccountCreateUserLimitReached: case \Errs::UserManager_LicenseKeyIsOutdated: case \Errs::TenantsManager_AccountCreateUserLimitReached: $iErrorCode = \ProjectCore\Notifications::LicenseProblem; break; case \Errs::Db_ExceptionError: $iErrorCode = \ProjectCore\Notifications::DataBaseError; break; } } $sRedirectUrl = \CApi::GetConf('labs.post-login-error-redirect-url', './'); \CApi::Location($sRedirectUrl . '?error=' . $iErrorCode); exit; } if ($oAccount instanceof \CAccount) { $oApiIntegrator->setAccountAsLoggedIn($oAccount); } } \CApi::Location('./'); } else { if ('mobile' === $sFirstPart) { if ($oApiIntegrator && $oApiCapability && $oApiCapability->isNotLite()) { $oApiIntegrator->setMobile(true); } \CApi::Location('./'); } else { @ob_start(); \CApi::Plugin()->RunServiceHandle($sFirstPart, $aPaths); $sResult = @ob_get_clean(); if (0 === strlen($sResult)) { $sResult = $this->getIndexHTML(); } } } } } } } } } } } } } } } } } } } } } } else { $sResult = $this->getIndexHTML(); } // Output result echo $sResult; }
/** * @param int $iUserId * @param string $sSearch * @param int $iRequestLimit * @return bool|array */ public function GetSuggestContactItems($iUserId, $sSearch, $iRequestLimit) { $aResult = array(); $this->init($iUserId); $sDefaultAB = \afterlogic\DAV\Constants::ADDRESSBOOK_DEFAULT_NAME; $sCollectedAB = \afterlogic\DAV\Constants::ADDRESSBOOK_COLLECTED_NAME; $aCollectedContactItems = $this->Dav->GetVcards($this->AddressBookHomeSet . $sCollectedAB); $aDefaultContactItems = $this->Dav->GetVcards($this->AddressBookHomeSet . $sDefaultAB); $aContactItems = array_merge($aDefaultContactItems, $aCollectedContactItems); foreach ($aContactItems as $oItem) { $sItemId = $oItem['href']; $vCard = null; try { $vCard = \Sabre\VObject\Reader::read($oItem['data']); } catch (Exception $ex) { CApi::Log('SABREDAV: Invalid VCard with Id=' . $sItemId); } if (isset($vCard)) { $oContactItem = new CContactListItem(); $oContactItem->InitBySabreCardDAVCard($vCard); if (empty($sSearch) || stripos($oContactItem->Name, $sSearch) !== false || stripos($oContactItem->Email, $sSearch) !== false) { $aResult[] = $oContactItem; } unset($oContactItem); } unset($vCard); } $this->sortItems($aResult, EContactSortField::Frequency, ESortOrder::ASC); return array_slice($aResult, 0, $iRequestLimit); }
/** * @return void */ public function InitAjaxAction($sPostName, $sTab, &$sMessage, &$sError, &$sRef) { if ($this->oTableAjaxAction && $this->IsInTab($sTab)) { $sQueryAction = CPost::Get('QueryAction', ''); $sAjaxActionFunction = ucfirst($sTab) . ucfirst($sQueryAction) . (empty($sPostName) ? '' : '_' . $sPostName); if (method_exists($this->oTableAjaxAction, $sAjaxActionFunction)) { CApi::Log('call ' . get_class($this) . '->TableAjaxAction->' . $sAjaxActionFunction . '()'); $this->oTableAjaxAction->{$sAjaxActionFunction}(); if (!empty($this->oTableAjaxAction->LastError)) { $sError = $this->oTableAjaxAction->LastError; } else { if (!empty($this->oTableAjaxAction->LastMessage)) { $sMessage = $this->oTableAjaxAction->LastMessage; } } if (!empty($this->oTableAjaxAction->Ref)) { $sRef = $this->oTableAjaxAction->Ref; } if (!empty($sError)) { CApi::Log('function ' . $sAjaxActionFunction . '() return $sError = ' . $sError, ELogLevel::Error); } } } }
/** * @return bool */ public function Disconnect() { $result = false; if ($this->oPDO != null) { if (is_resource($this->rResultId)) { $this->rResultId->closeCursor(); } $this->rResultId = null; if (CApi::$bUseDbLog) { CApi::Log('DB : disconnect from ' . $this->sUser . '@' . $this->sHost); } unset($this->oPDO); $this->oPDO = null; $result = true; } return $result; }
/** * @param object $oObject * @param object $oHelper * @return array */ public static function DbInsertArrays($oObject, $oHelper) { $aResult = array(false, false); $sQueryParams = ''; $bUseLogQueryParams = (bool) CApi::GetConf('labs.db.log-query-params', false); $oObject->initBeforeChange(); $aStaticMap = $oObject->getMap(); $aMap = api_AContainer::DbWriteKeys($aStaticMap, true); $aDbKeys = array_keys($aMap); $aResult[0] = array_map(array(&$oHelper, 'EscapeColumn'), $aDbKeys); $aDbValues = array_values($aMap); foreach ($aDbValues as $iIndex => $sKey) { $mValue = $oObject->{$sKey}; if (isset($aStaticMap[$sKey][0])) { if ('password' === $aStaticMap[$sKey][0]) { $mValue = api_Utils::EncodePassword($mValue); } else { if ('datetime' === $aStaticMap[$sKey][0]) { $mValue = $oHelper->TimeStampToDateFormat($mValue); } else { if ('serialize' === $aStaticMap[$sKey][0]) { $mValue = '' === $mValue ? '' : serialize($mValue); } } } } $aDbValues[$iIndex] = is_string($mValue) ? $oHelper->EscapeString($mValue) : (int) $mValue; if ($bUseLogQueryParams) { $sDbKey = isset($aDbKeys[$iIndex]) ? $aDbKeys[$iIndex] : '!unknown!'; $sQueryParams .= API_CRLF . API_TAB . $sDbKey . ' = ' . $aDbValues[$iIndex]; } } $aResult[1] = $aDbValues; if ($bUseLogQueryParams) { CApi::Log($sQueryParams); } return $aResult; }
/** * @return bool */ public function Modify($sModifyDn, $aModifyEntry) { $bResult = false; if (!empty($sModifyDn)) { if (!empty($this->sSearchDN)) { $sModifyDn = $sModifyDn . ',' . $this->sSearchDN; } CApi::Log('ldap_modify = ' . $sModifyDn); CApi::LogObject($aModifyEntry); $bResult = !!@ldap_modify($this->rLink, $sModifyDn, $aModifyEntry); $this->validateLdapErrorOnFalse($bResult); } return $bResult; }
/** * @param string $sLine * @return bool */ public function WriteLine($sLine, $aHideValues = array()) { $sLine = $sLine . "\r\n"; $sLogLine = 0 < count($aHideValues) ? str_replace($aHideValues, '*******', $sLine) : $sLine; CApi::Log('NET > ' . api_Utils::ShowCRLF($sLogLine)); if (!@fputs($this->rConnect, $sLine)) { CApi::Log('NET[Error] < Could not send user request', ELogLevel::Error); return false; } return true; }
public static function LogEnd() { CApi::Log('# script shutdown'); }
/** * @param CAccount $oAccount * @return bool */ public function ClearAllContactsAndGroups($oAccount) { $bResult = false; $this->InitByAccount($oAccount); $oAddressBooks = new \Sabre\CardDAV\UserAddressBooks(\afterlogic\DAV\Backend::Carddav(), $this->Principal); foreach ($oAddressBooks->getChildren() as $oAddressBook) { if ($oAddressBook && $oAddressBook instanceof \Sabre\CardDAV\AddressBook) { try { $oAddressBook->delete(); $bResult = true; } catch (Exception $ex) { CApi::Log($ex->getTraceAsString()); $bResult = false; } } } return $bResult; }
/** * @param string $sTab * @return void */ protected function initAjaxActionModules($sTab) { $sError = ''; $sMessage = ''; $sRef = ''; if ($this->IsAuth()) { if (!$this->IsOnlyReadAuthType()) { try { foreach ($this->aModules as $oModule) { if ($oModule->IsInTab($sTab)) { $oModule->InitAjaxAction('Pre', $sTab, $sMessage, $sError, $sRef); } } if (empty($sError)) { foreach ($this->aModules as $oModule) { if ($oModule->IsInTab($sTab)) { $oModule->InitAjaxAction('', $sTab, $sMessage, $sError, $sRef); } } } if (empty($sError)) { foreach ($this->aModules as $oModule) { if ($oModule->IsInTab($sTab)) { $oModule->InitAjaxAction('Post', $sTab, $sMessage, $sError, $sRef); } } } } catch (Exception $oException) { if (empty($sError)) { $sError = $oException->getMessage(); } } } else { $sError = AP_LANG_ADMIN_ONLY_READ; } } else { $sError = AP_LANG_LOGIN_ACCESS_ERROR; } $sOb = @ob_get_contents(); @ob_clean(); if (0 < strlen($sOb)) { CApi::Log(AP_CRLF . $sOb, ELogLevel::Error); if (!empty($sError)) { $sError = 'Json parse error'; } } $sAjaxResult = '{ "null": "null"'; if (!empty($sError)) { $sAjaxResult .= ', "error": "' . ap_Utils::ReBuildStringToJavaScript($sError, '"') . '"'; } else { if (!empty($sMessage)) { $sAjaxResult .= ', "message": "' . ap_Utils::ReBuildStringToJavaScript($sMessage, '"') . '"'; } } if (!empty($sRef)) { $sAjaxResult .= ', "ref": "' . ap_Utils::ReBuildStringToJavaScript($sRef, '"') . '"'; if (!empty($sError)) { $this->ShowError($sError); } else { if (!empty($sMessage)) { $this->ShowMessage($sMessage); } } } $sAjaxResult .= ' }'; echo $sAjaxResult; CApi::Log('AJAX: ' . $sAjaxResult); }
public function Execute() { CApi::Log('---------- Start cron script', ELogLevel::Full, 'cron-'); $oTimeZoneUTC = new \DateTimeZone('UTC'); $oNowDT_UTC = new \DateTime('now', $oTimeZoneUTC); $iNowTS_UTC = $oNowDT_UTC->getTimestamp(); $oStartDT_UTC = clone $oNowDT_UTC; $oStartDT_UTC->sub(new DateInterval('PT30M')); if (file_exists($this->sCurRunFilePath)) { $handle = fopen($this->sCurRunFilePath, 'r'); $sCurRunFileTS = fread($handle, 10); if (!empty($sCurRunFileTS) && is_numeric($sCurRunFileTS)) { $oStartDT_UTC = new \DateTime("@{$sCurRunFileTS}"); } } $iStartTS_UTC = $oStartDT_UTC->getTimestamp(); if ($iNowTS_UTC >= $iStartTS_UTC) { CApi::Log('Start time: ' . $oStartDT_UTC->format('r'), ELogLevel::Full, 'cron-'); CApi::Log('End time: ' . $oNowDT_UTC->format('r'), ELogLevel::Full, 'cron-'); $aEvents = $this->GetReminders($iStartTS_UTC, $iNowTS_UTC); foreach ($aEvents as $sEmail => $aUserCalendars) { foreach ($aUserCalendars as $sCalendarUri => $aUserEvents) { foreach ($aUserEvents as $aUserEvent) { $aSubEvents = $aUserEvent['data']; if (isset($aSubEvents, $aSubEvents['vcal'])) { $vCal = $aSubEvents['vcal']; foreach ($aSubEvents as $mKey => $aEvent) { if ($mKey !== 'vcal') { $oAccount = $this->getAccount($sEmail); $oCalendar = $this->getCalendar($oAccount, $sCalendarUri); if ($oCalendar) { $sEventId = $aEvent['uid']; $sEventStart = $aEvent['start']; $iEventStartTS = $aEvent['startTS']; $sEventName = $aEvent['subject']; $sEventText = $aEvent['description']; $bAllDay = $aEvent['allDay']; $sDate = $aUserEvent['time']; $sSubject = $this->getSubject($oAccount, $sEventStart, $iEventStartTS, $sEventName, $sDate, $iNowTS_UTC, $bAllDay); $aAccounts = array(); $aAccounts[] = $oAccount; $aCalendarUsers = $this->oApiCalendarManager->getCalendarUsers($oAccount, $oCalendar); if (0 < count($aCalendarUsers)) { foreach ($aCalendarUsers as $aCalendarUser) { $oCalendarAccount = $this->getAccount($aCalendarUser['email']); if ($oCalendarAccount) { $aAccounts[] = $oCalendarAccount; } } } foreach ($aAccounts as $oAccountItem) { $bIsMessageSent = $this->sendMessage($oAccountItem, $sSubject, $sEventName, $sDate, $oCalendar->DisplayName, $sEventText, $oCalendar->Color); if ($bIsMessageSent) { $this->oApiCalendarManager->updateReminder($oAccountItem->Email, $sCalendarUri, $sEventId, $vCal->serialize()); CApi::Log('Send reminder for event: \'' . $sEventName . '\' started on \'' . $sDate . '\' to \'' . $oAccountItem->Email . '\'', \ELogLevel::Full, 'cron-'); } else { CApi::Log('Send reminder for event: FAILED!', ELogLevel::Full, 'cron-'); } } } else { CApi::Log('Calendar ' . $sCalendarUri . ' not found!', ELogLevel::Full, 'cron-'); } } } } } } } file_put_contents($this->sCurRunFilePath, $iNowTS_UTC); } CApi::Log('---------- End cron script', ELogLevel::Full, 'cron-'); }
/** * The method create contact in global address book for each system account * * @param CAccount $oAccount * @param bool $bSelfOnly * * @return bool */ public function synchronizeExternalContacts($oAccount, $bSelfOnly = false) { $aIds = array(); if ($this->oApiGContactsManager) { if ($bSelfOnly) { $oGlobalContact = $this->oApiGContactsManager->getContactByTypeId($oAccount, $oAccount->IdUser, true); /* @var $oGlobalContact CContact */ if ($oGlobalContact) { $mContactId = $this->oApiContactsMainManager->ConvertedContactLocalId($oAccount, $oGlobalContact->IdContact, EContactType::Global_); if ($mContactId) { $aIds[$mContactId] = $oGlobalContact->IdContact; } } } else { $aIds = $this->oApiContactsMainManager->ConvertedContactLocalIdCollection($oAccount, EContactType::Global_); } if ($aIds && is_array($aIds) && 0 < count($aIds)) { CApi::Log('synchronizeExternalContacts: ' . count($aIds)); $aLinkedContact = $this->oApiContactsMainManager->ContactIdsLinkedToGroups(array_keys($aIds)); $aLinkedContact = is_array($aLinkedContact) ? $aLinkedContact : array(); $aContactToDelete = array(); foreach ($aIds as $iLocalContactId => $sGlobalId) { if (in_array($iLocalContactId, $aLinkedContact)) { $oGlobalContact = $this->oApiGContactsManager->getContactById($oAccount, $sGlobalId, true); if ($oGlobalContact) { $oLocalGlobalContact = $this->oApiContactsMainManager->getContactById($oAccount->IdUser, $iLocalContactId, true); if ($oLocalGlobalContact && EContactType::Global_ === $oLocalGlobalContact->Type) { if ($oLocalGlobalContact->CompareAndComputedByNewGlobalContact($oGlobalContact)) { $this->updateContact($oLocalGlobalContact, false); } } } else { $aContactToDelete[] = $iLocalContactId; } } else { $aContactToDelete[] = $iLocalContactId; } } if (0 < count($aContactToDelete)) { $this->deleteContacts($oAccount->IdUser, $aContactToDelete); } return true; } else { CApi::Log('synchronizeExternalContacts: none'); } } return true; }
/** * @param string $path * @throws \Sabre\DAV\Exception\NotAuthenticated * @return bool */ public function afterUnbind($path) { if (self::isFilestoragePrivate($path) || self::isFilestorageCorporate($path)) { $oAccount = $this->getAccount(); if ($oAccount) { $iType = self::getTypeFromPath($path); $sFilePath = self::getFilePathFromPath(dirname($path)); $sFileName = basename($path); $oMin = $this->getMinMan(); $this->sOldPath = $path; $this->sOldID = implode('|', array($oAccount->IdAccount, $iType, $sFilePath, $sFileName)); $aData = $oMin->GetMinByID($this->sOldID); \CApi::Log('OldID: ' . $this->sOldID, \ELogLevel::Full, 'fs-'); \CApi::Log('NewID: ' . $this->sNewID, \ELogLevel::Full, 'fs-'); if (isset($this->sNewPath)) { // $node = $this->server->tree->getNodeForPath($this->sNewPath); // \CApi::LogObject($node, \ELogLevel::Full, 'fs-'); } if (isset($this->sNewID) && !empty($aData['__hash__'])) { $aNewData = explode('|', $this->sNewID); $aParams = array('Type' => $aNewData[1], 'Path' => $aNewData[2], 'Name' => $aNewData[3], 'Size' => $aData['Size']); $oMin->UpdateMinByID($this->sOldID, $aParams, $this->sNewID); } else { $oMin->DeleteMinByID($this->sOldID); } } } $GLOBALS['__FILESTORAGE_MOVE_ACTION__'] = false; return true; }
} $oContactTo->IdContact = ''; if (empty($oContactTo->FullName)) { $oContactTo->FullName = $oContactTo->FirstName . ' ' . $oContactTo->LastName; } /* if (0 < count($oContact->GroupsIds)) { foreach ($oContact->GroupsIds as $sGroupId) { $oGroup = $oApiContactsManagerTo->GetGroupById($iUserId, (string) $sGroupId); } } */ $oContactTo->GroupsIds = array(); CApi::Log('Add contact: ' . $oListItem->Id, ELogLevel::Full, 'migration-'); $oContactTo->__SKIP_VALIDATE__ = true; $oApiContactsManagerTo->CreateContact($oContactTo); unset($oContactTo); } else { CApi::Log('Skip contact: ' . $oListItem->Id, ELogLevel::Full, 'migration-'); } set_time_limit(30); } CApi::Log('--------------------', ELogLevel::Full, 'migration-'); } } $iCurUsersPage++; } $iCurUsersPage = 0; }
/** * @param int $iCode * @param Exception $oPrevious = null * @param array $aParams = array() * @param array $aObjectParams = array() */ public function __construct($iCode, $oPrevious = null, $aParams = array(), $aObjectParams = array()) { if (CApiErrorCodes::Validation_InvalidPort === $iCode) { CApi::Log('Exception error: ' . CApiErrorCodes::GetMessageByCode($iCode, $aParams), ELogLevel::Error); $iCode = CApiErrorCodes::Validation_InvalidPort_OutInfo; } else { if (CApiErrorCodes::Validation_InvalidEmail === $iCode) { CApi::Log('Exception error: ' . CApiErrorCodes::GetMessageByCode($iCode, $aParams), ELogLevel::Error); $iCode = CApiErrorCodes::Validation_InvalidEmail_OutInfo; } else { if (CApiErrorCodes::Validation_FieldIsEmpty === $iCode) { CApi::Log('Exception error: ' . CApiErrorCodes::GetMessageByCode($iCode, $aParams), ELogLevel::Error); $iCode = CApiErrorCodes::Validation_FieldIsEmpty_OutInfo; } } } $this->aObjectParams = $aObjectParams; $this->oPrevious = $oPrevious ? $oPrevious : null; if ($this->oPrevious) { CApi::Log('Previous Exception: ' . $this->oPrevious->getMessage(), ELogLevel::Error); } parent::__construct(CApiErrorCodes::GetMessageByCode($iCode, $aParams), $iCode); }
/** * @param string $sErrorDesc * @return void */ protected function errorLog($sErrorDesc) { CApi::Log('DB ERROR < ' . trim($sErrorDesc), ELogLevel::Error); }
/** * Delete a calendar and all it's objects * * @param string $calendarId * @return void */ public function deleteCalendar($calendarId) { \CApi::Log('deleteCalendar', \ELogLevel::Full, 'del-'); parent::deleteCalendar($calendarId); $this->deleteCalendarShares($calendarId); }
/** * @return array */ public function AjaxSystemDoServerInitializations() { $oAccount = $this->getAccountFromParam(); $bResult = false; $oApiIntegrator = \CApi::Manager('integrator'); if ($oAccount && $oApiIntegrator) { $oApiIntegrator->resetCookies(); } $oApiHelpdesk = \CApi::Manager('helpdesk'); if ($this->oApiCapability->isGlobalContactsSupported($oAccount, true)) { $oApiContacts = $this->ApiContacts(); if ($oApiContacts && method_exists($oApiContacts, 'synchronizeExternalContacts')) { $bResult = $oApiContacts->synchronizeExternalContacts($oAccount); } } $oCacher = \CApi::Cacher(); $bDoGC = false; $bDoHepdeskClear = false; if ($oCacher && $oCacher->IsInited()) { $iTime = $oCacher->GetTimer('Cache/ClearFileCache'); if (0 === $iTime || $iTime + 60 * 60 * 24 < time()) { if ($oCacher->SetTimer('Cache/ClearFileCache')) { $bDoGC = true; } } if ($oApiHelpdesk) { $iTime = $oCacher->GetTimer('Cache/ClearHelpdeskUsers'); if (0 === $iTime || $iTime + 60 * 60 * 24 < time()) { if ($oCacher->SetTimer('Cache/ClearHelpdeskUsers')) { $bDoHepdeskClear = true; } } } } if ($bDoGC) { \CApi::Log('GC: FileCache / Start'); $this->ApiFileCache()->gc(); $oCacher->gc(); \CApi::Log('GC: FileCache / End'); } if ($bDoHepdeskClear && $oApiHelpdesk) { \CApi::Log('GC: clear Unregistred Users'); $oApiHelpdesk->clearUnregistredUsers(); \CApi::Log('GC: clear Online'); $oApiHelpdesk->clearAllOnline(); } return $this->DefaultResponse($oAccount, __FUNCTION__, $bResult); }
/** * Downloads message from IMAP and returns it. * * @param CAccount $oAccount Account object. * @param string $sFolderFullNameRaw Raw full name of the Folder. * @param int $iUid UID of the message to download. * @param string $sRfc822SubMimeIndex = ''. Index at which a message is taken to parse. Index is used if the message is another message attachment. * @param bool $bParseICalAndVcard = false. If **true** ical and vcard attachments will be parsed. * @param bool $bParseAsc = false. If **true** attachments with extension .asc will be parsed. * @param int $iBodyTextLimit = 0. If **> 0** will be received only part of the message body. If **= 0** the message body is not limited. * * @return CApiMailMessage * * @throws CApiInvalidArgumentException */ public function getMessage($oAccount, $sFolderFullNameRaw, $iUid, $sRfc822SubMimeIndex = '', $bParseICalAndVcard = false, $bParseAsc = false, $iBodyTextLimit = 0) { if (0 === strlen($sFolderFullNameRaw) || !is_numeric($iUid) || 0 >= (int) $iUid) { throw new CApiInvalidArgumentException(); } $iUid = (int) $iUid; $oImapClient =& $this->_getImapClient($oAccount); $oImapClient->FolderExamine($sFolderFullNameRaw); $oMessage = false; $sICalMimeIndex = ''; $sVCardMimeIndex = ''; $aTextMimeIndexes = array(); $aAscPartsIds = array(); $aFetchResponse = $oImapClient->Fetch(array(\MailSo\Imap\Enumerations\FetchType::BODYSTRUCTURE), $iUid, true); $oBodyStructure = 0 < count($aFetchResponse) ? $aFetchResponse[0]->GetFetchBodyStructure($sRfc822SubMimeIndex) : null; if ($oBodyStructure) { $aTextParts = $oBodyStructure->SearchHtmlOrPlainParts(); if (is_array($aTextParts) && 0 < count($aTextParts)) { foreach ($aTextParts as $oPart) { $aTextMimeIndexes[] = array($oPart->PartID(), $oPart->Size()); } } if ($bParseICalAndVcard) { $aICalPart = $oBodyStructure->SearchByContentType('text/calendar'); $oICalPart = is_array($aICalPart) && 0 < count($aICalPart) ? $aICalPart[0] : null; $sICalMimeIndex = $oICalPart ? $oICalPart->PartID() : ''; $aVCardPart = $oBodyStructure->SearchByContentType('text/vcard'); $aVCardPart = $aVCardPart ? $aVCardPart : $oBodyStructure->SearchByContentType('text/x-vcard'); $oVCardPart = is_array($aVCardPart) && 0 < count($aVCardPart) ? $aVCardPart[0] : null; $sVCardMimeIndex = $oVCardPart ? $oVCardPart->PartID() : ''; } if ($bParseAsc) { $aAscParts = $oBodyStructure->SearchByCallback(function ($oPart) { return '.asc' === \strtolower(\substr(\trim($oPart->FileName()), -4)); }); if (is_array($aAscParts) && 0 < count($aAscParts)) { foreach ($aAscParts as $oPart) { $aAscPartsIds[] = $oPart->PartID(); } } } } $aFetchItems = array(\MailSo\Imap\Enumerations\FetchType::INDEX, \MailSo\Imap\Enumerations\FetchType::UID, \MailSo\Imap\Enumerations\FetchType::RFC822_SIZE, \MailSo\Imap\Enumerations\FetchType::INTERNALDATE, \MailSo\Imap\Enumerations\FetchType::FLAGS, 0 < strlen($sRfc822SubMimeIndex) ? \MailSo\Imap\Enumerations\FetchType::BODY_PEEK . '[' . $sRfc822SubMimeIndex . '.HEADER]' : \MailSo\Imap\Enumerations\FetchType::BODY_HEADER_PEEK); if (0 < count($aTextMimeIndexes)) { if (0 < strlen($sRfc822SubMimeIndex) && is_numeric($sRfc822SubMimeIndex)) { $sLine = \MailSo\Imap\Enumerations\FetchType::BODY_PEEK . '[' . $aTextMimeIndexes[0][0] . '.1]'; if (\is_numeric($iBodyTextLimit) && 0 < $iBodyTextLimit && $iBodyTextLimit < $aTextMimeIndexes[0][1]) { $sLine .= '<0.' . (int) $iBodyTextLimit . '>'; } $aFetchItems[] = $sLine; } else { foreach ($aTextMimeIndexes as $aTextMimeIndex) { $sLine = \MailSo\Imap\Enumerations\FetchType::BODY_PEEK . '[' . $aTextMimeIndex[0] . ']'; if (\is_numeric($iBodyTextLimit) && 0 < $iBodyTextLimit && $iBodyTextLimit < $aTextMimeIndex[1]) { $sLine .= '<0.' . (int) $iBodyTextLimit . '>'; } $aFetchItems[] = $sLine; } } } if (0 < strlen($sICalMimeIndex)) { $aFetchItems[] = \MailSo\Imap\Enumerations\FetchType::BODY_PEEK . '[' . $sICalMimeIndex . ']'; } if (0 < strlen($sVCardMimeIndex)) { $aFetchItems[] = \MailSo\Imap\Enumerations\FetchType::BODY_PEEK . '[' . $sVCardMimeIndex . ']'; } if (0 < count($aAscPartsIds)) { foreach ($aAscPartsIds as $sPartID) { $aFetchItems[] = \MailSo\Imap\Enumerations\FetchType::BODY_PEEK . '[' . $sPartID . ']'; } } if (!$oBodyStructure) { $aFetchItems[] = \MailSo\Imap\Enumerations\FetchType::BODYSTRUCTURE; } $aFetchResponse = $oImapClient->Fetch($aFetchItems, $iUid, true); if (0 < count($aFetchResponse)) { $oMessage = CApiMailMessage::createInstance($sFolderFullNameRaw, $aFetchResponse[0], $oBodyStructure, $sRfc822SubMimeIndex, $aAscPartsIds); } if ($oMessage) { $sFromEmail = ''; $oFromCollection = $oMessage->getFrom(); if ($oFromCollection && 0 < $oFromCollection->Count()) { $oFrom =& $oFromCollection->GetByIndex(0); if ($oFrom) { $sFromEmail = trim($oFrom->GetEmail()); } } if (0 < strlen($sFromEmail)) { $oApiUsersManager = CApi::Manager('users'); $oSettings =& CApi::GetSettings(); $bAlwaysShowImagesInMessage = !!$oSettings->GetConf('WebMail/AlwaysShowImagesInMessage'); $oMessage->setSafety($bAlwaysShowImagesInMessage ? true : $oApiUsersManager->getSafetySender($oAccount->IdUser, $sFromEmail, true)); } /*if ($bParseAsc && 0 < count($aAscPartsIds)) { }*/ if ($bParseICalAndVcard) { $oApiCapa = CApi::Manager('capability'); $oApiFileCache = CApi::Manager('filecache'); // ICAL $sICal = $oMessage->getExtend('ICAL_RAW'); if (!empty($sICal) && $oApiCapa->isCalendarSupported($oAccount)) { $oApiCalendarManager = CApi::Manager('calendar'); if ($oApiCalendarManager) { $mResult = $oApiCalendarManager->processICS($oAccount, trim($sICal), $sFromEmail); if (is_array($mResult) && !empty($mResult['Action']) && !empty($mResult['Body'])) { $sTemptFile = md5($mResult['Body']) . '.ics'; if ($oApiFileCache && $oApiFileCache->put($oAccount, $sTemptFile, $mResult['Body'])) { $oIcs = CApiMailIcs::createInstance(); $oIcs->Uid = $mResult['UID']; $oIcs->Sequence = $mResult['Sequence']; $oIcs->File = $sTemptFile; $oIcs->Attendee = isset($mResult['Attendee']) ? $mResult['Attendee'] : null; $oIcs->Type = $mResult['Action']; $oIcs->Location = !empty($mResult['Location']) ? $mResult['Location'] : ''; $oIcs->Description = !empty($mResult['Description']) ? $mResult['Description'] : ''; $oIcs->When = !empty($mResult['When']) ? $mResult['When'] : ''; $oIcs->CalendarId = !empty($mResult['CalendarId']) ? $mResult['CalendarId'] : ''; if (!$oApiCapa->isCalendarAppointmentsSupported($oAccount)) { $oIcs->Type = 'SAVE'; } // TODO // $oIcs->Calendars = array(); // if (isset($mResult['Calendars']) && is_array($mResult['Calendars']) && 0 < count($mResult['Calendars'])) // { // foreach ($mResult['Calendars'] as $sUid => $sName) // { // $oIcs->Calendars[$sUid] = $sName; // } // } $oMessage->addExtend('ICAL', $oIcs); } else { CApi::Log('Can\'t save temp file "' . $sTemptFile . '"', ELogLevel::Error); } } } } // VCARD $sVCard = $oMessage->getExtend('VCARD_RAW'); if (!empty($sVCard) && $oApiCapa->isContactsSupported($oAccount)) { $oApiContactsManager = CApi::Manager('contacts'); $oContact = new CContact(); $oContact->InitFromVCardStr($oAccount->IdUser, $sVCard); $oContact->initBeforeChange(); $oContact->IdContact = 0; $bContactExists = false; if (0 < strlen($oContact->ViewEmail)) { if ($oApiContactsManager) { $oLocalContact = $oApiContactsManager->getContactByEmail($oAccount->IdUser, $oContact->ViewEmail); if ($oLocalContact) { $oContact->IdContact = $oLocalContact->IdContact; $bContactExists = true; } } } $sTemptFile = md5($sVCard) . '.vcf'; if ($oApiFileCache && $oApiFileCache->put($oAccount, $sTemptFile, $sVCard)) { $oVcard = CApiMailVcard::createInstance(); $oVcard->Uid = $oContact->IdContact; $oVcard->File = $sTemptFile; $oVcard->Exists = !!$bContactExists; $oVcard->Name = $oContact->FullName; $oVcard->Email = $oContact->ViewEmail; $oMessage->addExtend('VCARD', $oVcard); } else { CApi::Log('Can\'t save temp file "' . $sTemptFile . '"', ELogLevel::Error); } } } } return $oMessage; }
/** * @param CAccount $oAccount * @param array $aNumbers * @param bool $bUseCache = true * @return array */ public function getNamesByCallersNumbers($oAccount, $aNumbers, $bUseCache = true) { $mResult = false; $oApiContactsManager = CApi::Manager('contactsmain'); if (is_array($aNumbers) && 0 < count($aNumbers) && $oAccount && $oApiContactsManager) { $bFromCache = false; $sCacheKey = ''; $mNamesResult = null; $oApiFileCache = $bUseCache ? CApi::Manager('filecache') : false; if ($oApiFileCache) { $sCacheKey = $this->_generateCacheFileName($oAccount->IdUser); if (!empty($sCacheKey)) { $sData = $oApiFileCache->get($oAccount, $sCacheKey); if (!empty($sData)) { $mNamesResult = @json_decode($sData, true); if (!is_array($mNamesResult)) { $mNamesResult = null; } else { $bFromCache = true; CApi::Log('Cache: get contacts names from cache (count:' . count($mNamesResult) . ')'); } } } } if (!is_array($mNamesResult)) { $mNamesResult = $oApiContactsManager->GetAllContactsNamesWithPhones($oAccount); } if (is_array($mNamesResult)) { if (!$bFromCache && $oApiFileCache && 0 < strlen($sCacheKey)) { $oApiFileCache->put($oAccount, $sCacheKey, @json_encode($mNamesResult)); CApi::Log('Cache: save contacts names to cache (count:' . count($mNamesResult) . ')'); } $aNormNumbers = array(); foreach ($aNumbers as $sNumber) { $aNormNumbers[$sNumber] = api_Utils::ClearPhone($sNumber); } foreach ($aNormNumbers as $sInputNumber => $sClearNumber) { $aNormNumbers[$sInputNumber] = isset($mNamesResult[$sClearNumber]) ? $mNamesResult[$sClearNumber] : ''; } $mResult = $aNormNumbers; } } else { if (is_array($aNumbers)) { $mResult = array(); } } return $mResult; }
/** * Deletes account from WebMail Pro database. * * @api * * @param CAccount $oAccount Object instance with prepopulated account properties. * * @return bool */ public function deleteAccount($oAccount) { $bResult = false; try { if (!$oAccount) { $this->setLastException(new CApiManagerException(Errs::Main_UnknownError)); return false; } if ($oAccount->IsDefaultAccount) { if (0 === $oAccount->IdTenant && \strtolower($oAccount->Email) === \strtolower($this->oSettings->GetConf('Helpdesk/AdminEmailAccount'))) { $this->setLastException(new CApiManagerException(Errs::HelpdeskManager_AccountCannotBeDeleted)); return false; } else { if (0 < $oAccount->IdTenant) { $oApiTenantsManager = CApi::Manager('tenants'); /* @var $oApiTenantsManager CApiTenantsManager */ if ($oApiTenantsManager) { $oTenant = $oApiTenantsManager->getTenantById($oAccount->IdTenant); /* @var $oTenant CTenant */ if (\strtolower($oAccount->Email) === $oTenant->HelpdeskAdminEmailAccount) { $this->setLastException(new CApiManagerException(Errs::HelpdeskManager_AccountCannotBeDeleted)); return false; } } } } } if ($oAccount && $this->oStorage->deleteAccount($oAccount->IdAccount)) { if ($oAccount->IsInternal) { /* @var $oApiMailSuiteManager CApiMailSuiteManager */ $oApiMailSuiteManager = CApi::Manager('mailsuite'); if ($oApiMailSuiteManager) { $oApiMailSuiteManager->deleteMailAliases($oAccount); $oApiMailSuiteManager->deleteMailForwards($oAccount); $oApiMailSuiteManager->deleteMailDir($oAccount); } } if ($oAccount->IsDefaultAccount) { /* @var $oApiContactsManager CApiContactsManager */ $oApiContactsManager = CApi::Manager('contacts'); if ($oApiContactsManager) { $oApiContactsManager->clearAllContactsAndGroups($oAccount); } /* @var $oApiCalendarManager CApiCalendarManager */ $oApiCalendarManager = CApi::Manager('calendar'); if ($oApiCalendarManager) { $oApiCalendarManager->clearAllCalendars($oAccount); } /* @var $oApiDavManager CApiDavManager */ $oApiDavManager = CApi::Manager('dav'); if ($oApiDavManager) { $oApiDavManager->deletePrincipal($oAccount); } /* @var $oApiFilestorageManager CApiFilestorageManager */ $oApiFilestorageManager = CApi::Manager('filestorage'); if ($oApiFilestorageManager) { $oApiFilestorageManager->clearAllFiles($oAccount); } /* @var $oApiSocialManager CApiSocialManager */ $oApiSocialManager = CApi::Manager('social'); if ($oApiSocialManager) { $oApiSocialManager->deleteSocialByAccountId($oAccount->IdAccount); } if (0 < $oAccount->User->IdHelpdeskUser) { /* @var $oApiHelpdeskManager CApiHelpdeskManager */ $oApiHelpdeskManager = CApi::Manager('helpdesk'); if ($oApiHelpdeskManager) { //$oApiHelpdeskManager->setUserAsBlocked($oAccount->IdTenant, $oAccount->User->IdHelpdeskUser); $oApiHelpdeskManager->deleteUser($oAccount->IdTenant, $oAccount->User->IdHelpdeskUser); } } } CApi::Log('FS: Delete "/mail/" and "/temp/" folders'); // TODO move in storage $sMailRoot = CApi::DataPath() . '/mail/'; $sTmpRoot = CApi::DataPath() . '/temp/'; $sPath = strtolower($oAccount->Email . '.' . $oAccount->IdAccount); $sPath = $sPath[0] . '/' . $sPath; api_Utils::RecRmdir($sMailRoot . $sPath); api_Utils::RecRmdir($sTmpRoot . $sPath); $bResult = true; } else { if (null === $oAccount) { $this->setLastException(new CApiManagerException(Errs::UserManager_AccountDoesNotExist)); } } } catch (CApiBaseException $oException) { $bResult = false; $this->setLastException($oException); } return $bResult; }
/** * @return string $sFileName * @return string */ public static function CsvToArray($sFileName) { if (!file_exists($sFileName) || !is_readable($sFileName)) { return false; } $aHeaders = null; $aData = array(); @setlocale(LC_CTYPE, 'en_US.UTF-8'); \ini_set('auto_detect_line_endings', true); if (false !== ($rHandle = @fopen($sFileName, 'rb'))) { $sDelimiterSearchString = @fread($rHandle, 2000); rewind($rHandle); $sDelimiter = (int) substr_count($sDelimiterSearchString, ',') > (int) substr_count($sDelimiterSearchString, ';') ? ',' : ';'; while (false !== ($mRow = fgetcsv($rHandle, 5000, $sDelimiter, '"'))) { $mRow = preg_replace('/[\\r\\n]+/', "\n", $mRow); if (null === $aHeaders) { if (3 >= count($mRow)) { CApi::Log('Invalid csv headers'); CApi::LogObject($mRow); fclose($rHandle); return $aData; } $aHeaders = $mRow; } else { $aNewItem = array(); foreach ($aHeaders as $iIndex => $sHeaderValue) { $aNewItem[@iconv('utf-8', 'utf-8//IGNORE', $sHeaderValue)] = isset($mRow[$iIndex]) ? $mRow[$iIndex] : ''; } $aData[] = $aNewItem; } } fclose($rHandle); } ini_set('auto_detect_line_endings', false); return $aData; }
/** * @param Exception $oException * @param bool $bLog = true */ protected function setLastException(Exception $oException, $bLog = true) { $this->oLastException = $oException; if ($bLog) { $sFile = str_replace(str_replace('\\', '/', strtolower(realpath(CApi::WebMailPath()))), '~ ', str_replace('\\', '/', strtolower($oException->getFile()))); CApi::Log('Exception[' . $oException->getCode() . ']: ' . $oException->getMessage() . API_CRLF . $sFile . ' (' . $oException->getLine() . ')' . API_CRLF . '----------------------------------------------------------------------' . API_CRLF . $oException->getTraceAsString(), ELogLevel::Error); } }
protected static function _socialError($oClientError, $sSocialName) { \CApi::Log($sSocialName, ' error'); \CApi::LogObject($oClientError); }
/** * Returns the data * * @return resource */ public function get() { \CApi::Log($this->path, \ELogLevel::Full, 'file-'); return fopen($this->path, 'r'); }