Ejemplo n.º 1
0
 /**
  * @param \RainLoop\Account|null $oAccount = null
  *
  * @return \RainLoop\Common\RainLoopFacebookRedirectLoginHelper|null
  */
 public function FacebookConnector($oAccount = null)
 {
     $oFacebook = false;
     $oConfig = $this->oActions->Config();
     $sAppID = \trim($oConfig->Get('social', 'fb_app_id', ''));
     if (\version_compare(PHP_VERSION, '5.4.0', '>=') && $oConfig->Get('social', 'fb_enable', false) && '' !== $sAppID && '' !== \trim($oConfig->Get('social', 'fb_app_secret', ''))) {
         \Facebook\FacebookSession::setDefaultApplication($sAppID, \trim($oConfig->Get('social', 'fb_app_secret', '')));
         $sRedirectUrl = $this->oHttp->GetFullUrl() . '?SocialFacebook';
         if (0 < \strlen($this->oActions->GetSpecAuthToken())) {
             $sRedirectUrl .= '&rlah=' . $this->oActions->GetSpecAuthToken();
         } else {
             if ($this->oHttp->HasQuery('rlah')) {
                 $this->oActions->SetSpecAuthToken($this->oHttp->GetQuery('rlah', ''));
                 $sRedirectUrl .= '&rlah=' . $this->oActions->GetSpecAuthToken();
             }
         }
         try {
             $oAccount = $this->oActions->GetAccount();
             $oFacebook = new \RainLoop\Common\RainLoopFacebookRedirectLoginHelper($sRedirectUrl);
             $oFacebook->initRainLoopData(array('rlAppId' => $sAppID, 'rlAccount' => $oAccount, 'rlUserHash' => \RainLoop\Utils::GetConnectionToken(), 'rlStorageProvaider' => $this->oActions->StorageProvider()));
         } catch (\Exception $oException) {
             $this->oActions->Logger()->WriteException($oException, \MailSo\Log\Enumerations\Type::ERROR);
         }
     }
     return false === $oFacebook ? null : $oFacebook;
 }
Ejemplo n.º 2
0
 /**
  * @param bool $bAdmin = true
  *
  * @return string
  */
 private function localAppData($bAdmin = false)
 {
     @\header('Content-Type: application/javascript; charset=utf-8');
     $this->oHttp->ServerNoCache();
     $sAuthAccountHash = '';
     if (!$bAdmin && 0 === \strlen($this->oActions->GetSpecAuthLogoutTokenWithDeletion())) {
         $sAuthAccountHash = $this->oActions->GetSpecAuthTokenWithDeletion();
         if (empty($sAuthAccountHash)) {
             $sAuthAccountHash = $this->oActions->GetSpecAuthToken();
         }
         if (empty($sAuthAccountHash)) {
             $oAccount = $this->oActions->GetAccountFromSignMeToken();
             if ($oAccount) {
                 try {
                     $this->oActions->CheckMailConnection($oAccount);
                     $this->oActions->AuthToken($oAccount);
                     $sAuthAccountHash = $this->oActions->GetSpecAuthToken();
                 } catch (\Exception $oException) {
                     $oException = null;
                     $this->oActions->ClearSignMeData($oAccount);
                 }
             }
         }
         $this->oActions->SetSpecAuthToken($sAuthAccountHash);
     }
     $sResult = $this->compileAppData($this->oActions->AppData($bAdmin, $sAuthAccountHash), false);
     $this->Logger()->Write($sResult, \MailSo\Log\Enumerations\Type::INFO, 'APPDATA');
     return $sResult;
 }
Ejemplo n.º 3
0
 public static function Run()
 {
     include_once self::LibrariesPath() . 'MailSo/MailSo.php';
     CApi::$aI18N = null;
     CApi::$aClientI18N = array();
     if (!is_object(CApi::$oManager)) {
         CApi::Inc('common.functions');
         CApi::Inc('common.constants');
         CApi::Inc('common.enum');
         CApi::Inc('common.exception');
         CApi::Inc('common.utils');
         CApi::Inc('common.crypt');
         CApi::Inc('common.container');
         CApi::Inc('common.manager');
         CApi::Inc('common.xml');
         CApi::Inc('common.plugin');
         CApi::Inc('common.utils.get');
         CApi::Inc('common.utils.post');
         CApi::Inc('common.utils.session');
         CApi::Inc('common.http');
         CApi::Inc('common.social');
         CApi::Inc('common.twilio');
         CApi::Inc('common.db.storage');
         $sSalt = '';
         $sSaltFile = CApi::DataPath() . '/salt.php';
         if (!@file_exists($sSaltFile)) {
             $sSaltDesc = '<?php #' . md5(microtime(true) . rand(1000, 9999)) . md5(microtime(true) . rand(1000, 9999));
             @file_put_contents($sSaltFile, $sSaltDesc);
         } else {
             $sSalt = md5(file_get_contents($sSaltFile));
         }
         CApi::$sSalt = $sSalt;
         CApi::$aConfig = (include CApi::RootPath() . 'common/config.php');
         $sSettingsFile = CApi::DataPath() . '/settings/config.php';
         if (@file_exists($sSettingsFile)) {
             $aAppConfig = (include $sSettingsFile);
             if (is_array($aAppConfig)) {
                 CApi::$aConfig = array_merge(CApi::$aConfig, $aAppConfig);
             }
         }
         $oHtml = \MailSo\Base\Http::SingletonInstance();
         $sHost = $oHtml->GetHost();
         if (0 < \strlen($sHost)) {
             $sDomainSettingsFile = CApi::DataPath() . '/settings/' . $sHost . '.config.php';
             if (@file_exists($sDomainSettingsFile)) {
                 $aDomainAppConfig = (include $sDomainSettingsFile);
                 if (is_array($aDomainAppConfig)) {
                     CApi::$aConfig = array_merge(CApi::$aConfig, $aDomainAppConfig);
                 }
             }
         }
         CApi::$oManager = new CApiGlobalManager();
         CApi::$oPlugin = new CApiPluginManager(CApi::$oManager);
         CApi::$bIsValid = CApi::validateApi();
         CApi::$oManager->PrepareStorageMap();
         require_once CApi::RootPath() . 'DAV/autoload.php';
     }
 }
Ejemplo n.º 4
0
 /**
  * @return bool
  */
 public function RawContactsCsv()
 {
     $oAccount = $this->getAccountFromToken();
     \header('Content-Type: text/csv; charset=UTF-8');
     \header('Content-Disposition: attachment; filename="contacts.csv"', true);
     \header('Accept-Ranges: none', true);
     \header('Content-Transfer-Encoding: binary');
     $this->oHttp->ServerNoCache();
     return $this->AddressBookProvider($oAccount)->IsActive() ? $this->AddressBookProvider($oAccount)->Export($oAccount->ParentEmailHelper(), 'csv') : false;
 }
Ejemplo n.º 5
0
 /**
  * @return string
  */
 private function helpdeskLink()
 {
     $sPath = rtrim(\MailSo\Base\Http::SingletonInstance()->GetFullUrl(), '\\/ ');
     if ('/crons' === substr($sPath, -6)) {
         $sPath = substr($sPath, 0, -6);
     }
     $sPath .= '/?helpdesk';
     if (0 < $this->IdTenant) {
         $sPath .= '=' . substr(md5($this->IdTenant . CApi::$sSalt), 0, 8);
     }
     return $sPath;
 }
Ejemplo n.º 6
0
 public static function CreateClient($oTenant)
 {
     $oClient = null;
     $oSocial = $oTenant->getSocialByName(self::$ConnectorName);
     if (isset($oSocial) && $oSocial->SocialAllow) {
         $sRedirectUrl = rtrim(\MailSo\Base\Http::SingletonInstance()->GetFullUrl(), '\\/ ') . '/?external-services=' . self::$ConnectorName;
         require PSEVEN_APP_ROOT_PATH . 'libraries/OAuthClient/http.php';
         require PSEVEN_APP_ROOT_PATH . 'libraries/OAuthClient/oauth_client.php';
         $oClient = new \oauth_client_class();
         $oClient->debug = self::$Debug;
         $oClient->debug_http = self::$Debug;
         $oClient->server = 'Facebook';
         $oClient->redirect_uri = $sRedirectUrl;
         $oClient->client_id = $oSocial->SocialId;
         $oClient->client_secret = $oSocial->SocialSecret;
         $oClient->scope = 'email';
     }
     return $oClient;
 }
Ejemplo n.º 7
0
 public static function CreateClient($oTenant)
 {
     $oClient = null;
     $oSocial = $oTenant->getSocialByName(self::$ConnectorName);
     if (isset($oSocial) && $oSocial->SocialAllow) {
         $sRedirectUrl = rtrim(\MailSo\Base\Http::SingletonInstance()->GetFullUrl(), '\\/ ') . '/?external-services=' . self::$ConnectorName;
         if (!strpos($sRedirectUrl, '://localhost')) {
             $sRedirectUrl = str_replace('http:', 'https:', $sRedirectUrl);
         }
         require PSEVEN_APP_ROOT_PATH . 'libraries/OAuthClient/http.php';
         require PSEVEN_APP_ROOT_PATH . 'libraries/OAuthClient/oauth_client.php';
         $oClient = new \oauth_client_class();
         $oClient->debug = self::$Debug;
         $oClient->debug_http = self::$Debug;
         $oClient->server = 'Dropbox2';
         $oClient->redirect_uri = $sRedirectUrl;
         $oClient->client_id = $oSocial->SocialId;
         $oClient->client_secret = $oSocial->SocialSecret;
         $oClient->configuration_file = PSEVEN_APP_ROOT_PATH . 'libraries/OAuthClient/' . $oClient->configuration_file;
     }
     return $oClient;
 }
Ejemplo n.º 8
0
 public static function CreateClient($oTenant = null)
 {
     $oClient = null;
     $oSocial = $oTenant->getSocialByName(self::$ConnectorName);
     if (isset($oSocial) && $oSocial->SocialAllow) {
         $sRedirectUrl = rtrim(\MailSo\Base\Http::SingletonInstance()->GetFullUrl(), '\\/ ') . '/?external-services=' . self::$ConnectorName;
         require PSEVEN_APP_ROOT_PATH . 'libraries/OAuthClient/http.php';
         require PSEVEN_APP_ROOT_PATH . 'libraries/OAuthClient/oauth_client.php';
         $oClient = new \oauth_client_class();
         $oClient->offline = true;
         $oClient->debug = self::$Debug;
         $oClient->debug_http = self::$Debug;
         $oClient->server = 'Google';
         $oClient->redirect_uri = $sRedirectUrl;
         $oClient->client_id = $oSocial->SocialId;
         $oClient->client_secret = $oSocial->SocialSecret;
         $oClient->scope = 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile';
         if (in_array('filestorage', self::$Scopes)) {
             $oClient->scope = $oClient->scope . ' https://www.googleapis.com/auth/drive';
         }
     }
     return $oClient;
 }
Ejemplo n.º 9
0
 /**
  * 
  * @return mixed
  */
 public function EntryDownload()
 {
     $mResult = false;
     $aPaths = \System\Service::GetPaths();
     $sMethod = empty($aPaths[2]) ? '' : $aPaths[2];
     try {
         if (!empty($sMethod)) {
             $sRawKey = empty($aPaths[3]) ? '' : $aPaths[3];
             $aParameters = CApi::DecodeKeyValues($sRawKey);
             $aParameters['AuthToken'] = empty($aPaths[4]) ? '' : $aPaths[4];
             $aParameters['SharedHash'] = empty($aPaths[5]) ? '' : $aPaths[5];
             $mResult = $this->CallMethod($sMethod, $aParameters, true);
         }
     } catch (\Exception $oException) {
         \CApi::LogException($oException);
         $this->oHttp->StatusHeader(404);
     }
     return $mResult;
 }
Ejemplo n.º 10
0
 /**
  * @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;
 }
Ejemplo n.º 11
0
 /**
  * @return \RainLoop\Service
  */
 private function localHandle()
 {
     if (!\class_exists('MailSo\\Version')) {
         return $this;
     }
     $this->oActions->BootStart();
     $sResult = '';
     $bCached = false;
     $sQuery = $this->oActions->ParseQueryAuthString();
     $this->oActions->Plugins()->RunHook('filter.http-query', array(&$sQuery));
     $aPaths = \explode('/', $sQuery);
     $this->oActions->Plugins()->RunHook('filter.http-paths', array(&$aPaths));
     $bAdmin = false;
     $sAdminPanelHost = $this->oActions->Config()->Get('security', 'admin_panel_host', '');
     if (empty($sAdminPanelHost)) {
         $bAdmin = !empty($aPaths[0]) && \in_array(\strtolower($aPaths[0]), array('admin', 'cp'));
     } else {
         if (empty($aPaths[0]) && \MailSo\Base\Utils::StrToLowerIfAscii($sAdminPanelHost) === \MailSo\Base\Utils::StrToLowerIfAscii($this->oHttp->GetHost())) {
             $bAdmin = true;
         }
     }
     if ($this->oHttp->IsPost()) {
         $this->oHttp->ServerNoCache();
     }
     if ($bAdmin && !$this->oActions->Config()->Get('security', 'allow_admin_panel', true)) {
         echo $this->oServiceActions->ErrorTemplates('Access Denied.', 'Access to the RainLoop Webmail Admin Panel is not allowed!', true);
         return $this;
     }
     $bIndex = true;
     if (0 < \count($aPaths) && !empty($aPaths[0]) && !$bAdmin && 'index' !== $aPaths[0]) {
         $bIndex = false;
         $sMethodName = 'Service' . $aPaths[0];
         if (\method_exists($this->oServiceActions, $sMethodName) && \is_callable(array($this->oServiceActions, $sMethodName))) {
             $this->oServiceActions->SetQuery($sQuery)->SetPaths($aPaths);
             $sResult = \call_user_func(array($this->oServiceActions, $sMethodName));
         } else {
             if (!$this->oActions->Plugins()->RunAdditionalPart($aPaths[0], $aPaths)) {
                 $bIndex = true;
             }
         }
     }
     if ($bIndex) {
         @\header('Content-Security-Policy:');
         @\header_remove('Content-Security-Policy');
         @header('Content-Type: text/html; charset=utf-8');
         $this->oHttp->ServerNoCache();
         if (!@\is_dir(APP_DATA_FOLDER_PATH) || !@\is_writable(APP_DATA_FOLDER_PATH)) {
             echo $this->oServiceActions->ErrorTemplates('Permission denied!', 'RainLoop Webmail cannot access to the data folder "' . APP_DATA_FOLDER_PATH . '"');
             return $this;
         }
         $aTemplateParameters = $this->indexTemplateParameters($bAdmin);
         $sCacheFileName = '';
         if ($this->oActions->Config()->Get('labs', 'cache_system_data', true)) {
             $sCacheFileName = 'TMPL:' . $aTemplateParameters['{{BaseHash}}'];
             $sResult = $this->oActions->Cacher()->Get($sCacheFileName);
         }
         if (0 === \strlen($sResult)) {
             //				$aTemplateParameters['{{BaseTemplates}}'] = $this->oServiceActions->compileTemplates($bAdmin, false);
             $sResult = \strtr(\file_get_contents(APP_VERSION_ROOT_PATH . 'app/templates/Index.html'), $aTemplateParameters);
             $sResult = \RainLoop\Utils::ClearHtmlOutput($sResult);
             if (0 < \strlen($sCacheFileName)) {
                 $this->oActions->Cacher()->Set($sCacheFileName, $sResult);
             }
         } else {
             $bCached = true;
         }
         $sResult .= '<!--';
         $sResult .= ' [time:' . \substr(\microtime(true) - APP_START, 0, 6);
         //			$sResult .= '][version:'.APP_VERSION;
         if ($this->oActions->IsOpen()) {
             $sResult .= '][AGPLv3';
         }
         $sResult .= '][cached:' . ($bCached ? 'true' : 'false');
         //			$sResult .= '][hash:'.$aTemplateParameters['{{BaseHash}}'];
         //			$sResult .= '][session:'.\md5(\RainLoop\Utils::GetShortToken());
         if (\RainLoop\Utils::IsOwnCloud()) {
             $sResult .= '][owncloud:true';
         }
         $sResult .= '] //-->';
     }
     // Output result
     echo $sResult;
     unset($sResult);
     $this->oActions->BootEnd();
     return $this;
 }
Ejemplo n.º 12
0
 /**
  * @param string $sUrl
  * @param resource $rFile
  * @param string $sCustomUserAgent = 'MailSo Http User Agent (v1)'
  * @param string $sContentType = ''
  * @param int $iCode = 0
  * @param \MailSo\Log\Logger $oLogger = null
  * @param int $iTimeout = 10
  * @param string $sProxy = ''
  * @param string $sProxyAuth = ''
  * @param array $aHttpHeaders = array()
  * @param bool $bFollowLocation = true
  *
  * @return bool
  */
 public function SaveUrlToFile($sUrl, $rFile, $sCustomUserAgent = 'MailSo Http User Agent (v1)', &$sContentType = '', &$iCode = 0, $oLogger = null, $iTimeout = 10, $sProxy = '', $sProxyAuth = '', $aHttpHeaders = array(), $bFollowLocation = true)
 {
     if (null === $sCustomUserAgent) {
         $sCustomUserAgent = 'MailSo Http User Agent (v1)';
     }
     if (!is_resource($rFile)) {
         if ($oLogger) {
             $oLogger->Write('cURL: input resource invalid.', \MailSo\Log\Enumerations\Type::WARNING);
         }
         return false;
     }
     $aOptions = array(CURLOPT_URL => $sUrl, CURLOPT_HEADER => false, CURLOPT_FAILONERROR => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => !!$bFollowLocation, CURLOPT_MAXREDIRS => 7, CURLOPT_FILE => $rFile, CURLOPT_TIMEOUT => (int) $iTimeout);
     if (0 < \strlen($sCustomUserAgent)) {
         $aOptions[CURLOPT_USERAGENT] = $sCustomUserAgent;
     }
     if (0 < \strlen($sProxy)) {
         $aOptions[CURLOPT_PROXY] = $sProxy;
         if (0 < \strlen($sProxyAuth)) {
             $aOptions[CURLOPT_PROXYUSERPWD] = $sProxyAuth;
         }
     }
     if (\is_array($aHttpHeaders) && 0 < \count($aHttpHeaders)) {
         $aOptions[CURLOPT_HTTPHEADER] = $aHttpHeaders;
     }
     if ($oLogger) {
         $oLogger->Write('cUrl: URL: ' . $sUrl);
         if (isset($aOptions[CURLOPT_HTTPHEADER]) && \is_array($aOptions[CURLOPT_HTTPHEADER]) && 0 < \count($aOptions[CURLOPT_HTTPHEADER])) {
             $oLogger->Write('cUrl: Headers: ' . \print_r($aOptions[CURLOPT_HTTPHEADER], true));
         }
     }
     \MailSo\Base\Http::DetectAndHackFollowLocationUrl($sUrl, $aOptions, $oLogger);
     $oCurl = \curl_init();
     \curl_setopt_array($oCurl, $aOptions);
     $bResult = \curl_exec($oCurl);
     $iCode = (int) \curl_getinfo($oCurl, CURLINFO_HTTP_CODE);
     $sContentType = (string) \curl_getinfo($oCurl, CURLINFO_CONTENT_TYPE);
     if ($oLogger) {
         $oLogger->Write('cUrl: Request result: ' . ($bResult ? 'true' : 'false') . ' (Status: ' . $iCode . ', ContentType: ' . $sContentType . ')');
         if (!$bResult || 200 !== $iCode) {
             $oLogger->Write('cUrl: Error: ' . \curl_error($oCurl), \MailSo\Log\Enumerations\Type::WARNING);
         }
     }
     if (\is_resource($oCurl)) {
         \curl_close($oCurl);
     }
     return $bResult;
 }
Ejemplo n.º 13
0
 /**
  * @return bool
  */
 public static function IsFilesPubModule()
 {
     $oHttp = \MailSo\Base\Http::NewInstance();
     return $oHttp->HasQuery('files-pub') && 0 < strlen($oHttp->GetQuery('files-pub'));
 }
 /**
  * @param \RainLoop\Account $oAccount
  * @param string $sPrevPassword
  * @param string $sNewPassword
  *
  * @return bool
  */
 public function ChangePassword(\RainLoop\Account $oAccount, $sPrevPassword, $sNewPassword)
 {
     if ($this->oLogger) {
         $this->oLogger->Write('DirectAdmin: Try to change password for ' . $oAccount->Email());
     }
     $bResult = false;
     if (!empty($this->sHost) && 0 < $this->iPort && $oAccount) {
         $sEmail = \trim(\strtolower($oAccount->Email()));
         $sHost = \trim($this->sHost);
         $sHost = \str_replace('{user:host-imap}', $oAccount->Domain()->IncHost(), $sHost);
         $sHost = \str_replace('{user:host-smtp}', $oAccount->Domain()->OutHost(), $sHost);
         $sHost = \str_replace('{user:domain}', \MailSo\Base\Utils::GetDomainFromEmail($sEmail), $sHost);
         $sHost = \rtrim($this->sHost, '/\\');
         if (!\preg_match('/^http[s]?:\\/\\//i', $sHost)) {
             $sHost = 'http://' . $sHost;
         }
         $sUrl = $sHost . ':' . $this->iPort . '/CMD_CHANGE_EMAIL_PASSWORD';
         $iCode = 0;
         $oHttp = \MailSo\Base\Http::SingletonInstance();
         if ($this->oLogger) {
             $this->oLogger->Write('DirectAdmin[Api Request]:' . $sUrl);
         }
         $mResult = $oHttp->SendPostRequest($sUrl, array('email' => $sEmail, 'oldpassword' => $sPrevPassword, 'password1' => $sNewPassword, 'password2' => $sNewPassword, 'api' => '1'), 'MailSo Http User Agent (v1)', $iCode, $this->oLogger);
         if (false !== $mResult && 200 === $iCode) {
             $aRes = null;
             @\parse_str($mResult, $aRes);
             if (is_array($aRes) && (!isset($aRes['error']) || (int) $aRes['error'] !== 1)) {
                 $bResult = true;
             } else {
                 if ($this->oLogger) {
                     $this->oLogger->Write('DirectAdmin[Error]: Response: ' . $mResult);
                 }
             }
         } else {
             if ($this->oLogger) {
                 $this->oLogger->Write('DirectAdmin[Error]: Empty Response: Code:' . $iCode);
             }
         }
     }
     return $bResult;
 }
Ejemplo n.º 15
0
 /**
  * @param string $sKey
  *
  * @return void
  */
 public static function verifyCacheByKey($sKey)
 {
     if (!empty($sKey)) {
         $oHttp = \MailSo\Base\Http::NewInstance();
         $sIfModifiedSince = $oHttp->GetHeader('If-Modified-Since', '');
         if (!empty($sIfModifiedSince)) {
             $oHttp->StatusHeader(304);
             self::cacheByKey($sKey);
             exit;
         }
     }
 }
Ejemplo n.º 16
0
 /**
  * @return void
  */
 public function Handle()
 {
     $mResult = '';
     $bError = false;
     $bIsHtml = false;
     $this->GetVersion();
     $this->CheckApi();
     $this->RedirectToHttps();
     $aPaths = self::GetPaths();
     $aModules = array();
     if (0 < count($aPaths) && !empty($aPaths[0])) {
         $sEntry = strtolower($aPaths[0]);
         $oModule = $this->oModuleManager->GetModuleFromRequest();
         if ($oModule instanceof \AApiModule) {
             if ($oModule->HasEntry($sEntry)) {
                 $aModules[] = $oModule;
             } else {
                 $mResult = '\'' . $sEntry . '\' entry not found in \'' . $oModule->GetName() . '\' module.';
                 $bError = true;
             }
         } else {
             if ($sEntry === 'api') {
                 $oCoreModule = \CApi::GetModule('Core');
                 if ($oCoreModule instanceof \AApiModule) {
                     $aModules[] = $oCoreModule;
                 }
             } else {
                 $aModules = $this->oModuleManager->GetModulesByEntry($sEntry);
             }
         }
         if (!$bError) {
             if (count($aModules) > 0) {
                 foreach ($aModules as $oModule) {
                     $mEntryResult = $oModule->RunEntry($sEntry);
                     if ($mEntryResult !== 'null') {
                         $mResult .= $mEntryResult;
                     }
                 }
             } else {
                 $bIsHtml = true;
             }
         }
     } else {
         $bIsHtml = true;
     }
     if ($bIsHtml) {
         $mResult = $this->generateHTML();
     }
     $oHttp = \MailSo\Base\Http::SingletonInstance();
     if ($oHttp->GetRequest('Format') !== 'Raw') {
         echo $mResult;
     }
 }
Ejemplo n.º 17
0
 /**
  * @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');
     /* @var $oApiCapability \CApiCapabilityManager */
     $oApiCapability = \CApi::Manager('capability');
     $sResult = '';
     $sQuery = \trim(\trim($this->oHttp->GetServer('QUERY_STRING', '')), ' /');
     $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 ('ajax' === $sFirstPart) {
                 @ob_start();
                 $aResponseItem = null;
                 $sAction = $this->oHttp->GetPost('Action', null);
                 try {
                     \CApi::Log('AJAX: Action: ' . $sAction);
                     if ('AppData' !== $sAction && \CApi::GetConf('labs.webmail.csrftoken-protection', true) && !$this->validateToken()) {
                         throw new \ProjectSeven\Exceptions\ClientException(\ProjectSeven\Notifications::InvalidToken);
                     } else {
                         if (!empty($sAction)) {
                             $sMethodName = 'Ajax' . $sAction;
                             if (method_exists($this->oActions, $sMethodName) && is_callable(array($this->oActions, $sMethodName))) {
                                 $this->oActions->SetActionParams($this->oHttp->GetPostAsArray());
                                 $aResponseItem = call_user_func(array($this->oActions, $sMethodName));
                             } else {
                                 if (\CApi::Plugin()->JsonHookExists($sMethodName)) {
                                     $this->oActions->SetActionParams($this->oHttp->GetPostAsArray());
                                     $aResponseItem = \CApi::Plugin()->RunJsonHook($this->oActions, $sMethodName);
                                 }
                             }
                         }
                     }
                     if (!is_array($aResponseItem)) {
                         throw new \ProjectSeven\Exceptions\ClientException(\ProjectSeven\Notifications::UnknownError);
                     }
                 } catch (\Exception $oException) {
                     //					if ($oException instanceof \ProjectSeven\Exceptions\ClientException &&
                     //						\ProjectSeven\Notifications::AuthError === $oException->getCode())
                     //					{
                     //						$oApiIntegrator = /* @var $oApiIntegrator \CApiIntegratorManager */ \CApi::Manager('integrator');
                     //						$oApiIntegrator->SetLastErrorCode(\ProjectSeven\Notifications::AuthError);
                     //						$oApiIntegrator->LogoutAccount();
                     //					}
                     \CApi::LogException($oException);
                     $sAction = empty($sAction) ? 'Unknown' : $sAction;
                     $aResponseItem = $this->oActions->ExceptionResponse(null, $sAction, $oException);
                 }
                 @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];
                     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', '')));
                                     \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 \ProjectSeven\Exceptions\ClientException(\ProjectSeven\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();
                     if ('iframe' === $this->oHttp->GetPost('jua-post-type', '')) {
                         @header('Content-Type: text/html; charset=utf-8');
                     } else {
                         @header('Content-Type: application/json; 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');
                                 //$sInput = '<?'.'xml version="1.0" encoding="utf-8"?'.'><Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006"><Request><EMailAddress>test@afterlogic.com</EMailAddress><AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a</AcceptableResponseSchema></Request></Autodiscover>';
                                 \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 = $oSettings->GetConf('WebMail/ExternalHostNameOfLocalImap');
                                     $sOutMailServer = $oSettings->GetConf('WebMail/ExternalHostNameOfLocalSmtp');
                                     if (0 < \strlen($sIncMailServer) && 0 < \strlen($sOutMailServer)) {
                                         $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>143</Port>', '				<SSL>off</SSL>', '				<SPA>off</SPA>', '				<AuthRequired>on</AuthRequired>', '			</Protocol>', '			<Protocol>', '				<Type>SMTP</Type>', '				<Server>' . $sOutMailServer . '</Server>', '				<LoginName>' . $aEmailAddress[1] . '</LoginName>', '				<Port>25</Port>', '				<SSL>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::I18N('IOS/HELLO'), '{{IOS/DESC_P1}}' => \CApi::I18N('IOS/DESC_P1'), '{{IOS/DESC_P2}}' => \CApi::I18N('IOS/DESC_P2'), '{{IOS/DESC_P3}}' => \CApi::I18N('IOS/DESC_P3'), '{{IOS/DESC_P4}}' => \CApi::I18N('IOS/DESC_P4'), '{{IOS/DESC_P5}}' => \CApi::I18N('IOS/DESC_P5'), '{{IOS/DESC_P6}}' => \CApi::I18N('IOS/DESC_P6'), '{{IOS/DESC_P7}}' => \CApi::I18N('IOS/DESC_P7'), '{{IOS/DESC_BUTTON_YES}}' => \CApi::I18N('IOS/DESC_BUTTON_YES'), '{{IOS/DESC_BUTTON_SKIP}}' => \CApi::I18N('IOS/DESC_BUTTON_SKIP'), '{{IOS/DESC_BUTTON_OPEN}}' => \CApi::I18N('IOS/DESC_BUTTON_OPEN'), '{{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]));
                                                         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 ('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 ($this->oHttp->HasQuery('facebook')) {
                                                     $mResult = \api_Social::Facebook(\api_Social::GetTenantFromCookieByHash());
                                                     if (false !== $mResult && is_array($mResult)) {
                                                         \api_Social::Process($mResult);
                                                     }
                                                 } else {
                                                     if ($this->oHttp->HasQuery('google')) {
                                                         $mResult = \api_Social::Google(\api_Social::GetTenantFromCookieByHash());
                                                         if (false !== $mResult && is_array($mResult)) {
                                                             \api_Social::Process($mResult);
                                                         }
                                                     } else {
                                                         if ($this->oHttp->HasQuery('twitter')) {
                                                             $mResult = \api_Social::Twitter(\api_Social::GetTenantFromCookieByHash());
                                                             if (false !== $mResult && is_array($mResult)) {
                                                                 \api_Social::Process($mResult);
                                                             }
                                                         } else {
                                                             if ($this->oHttp->HasQuery('dropbox')) {
                                                                 $mResult = \api_Social::Dropbox(\api_Social::GetTenantFromCookieByHash());
                                                                 if (false !== $mResult && is_array($mResult)) {
                                                                     \api_Social::Process($mResult);
                                                                 }
                                                             } else {
                                                                 if ($this->oHttp->HasQuery('helpdesk')) {
                                                                     $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->GetAccountOnLogin($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/InviteExternal.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 ($this->oHttp->HasQuery('calendar-pub') && 0 < strlen($this->oHttp->GetQuery('calendar-pub'))) {
                                                                             $sResult = $this->indexHTML(false, '', $this->oHttp->GetQuery('calendar-pub'));
                                                                         } else {
                                                                             if ($this->oHttp->HasQuery('files-pub') && 0 < strlen($this->oHttp->GetQuery('files-pub'))) {
                                                                                 $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->Init($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 ('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)) {
                                                                                                     $oAccount = $oApiIntegrator->LoginToAccount($sEmail, $sPassword, $sLogin);
                                                                                                     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;
 }
Ejemplo n.º 18
0
 public static function Dropbox($oTenant)
 {
     $bResult = false;
     $oUser = null;
     $bDropboxAllow = $oTenant->SocialDropboxAllow;
     $sDropboxId = $oTenant->SocialDropboxKey;
     $sDropboxSecret = $oTenant->SocialDropboxSecret;
     $sRedirectUrl = rtrim(\MailSo\Base\Http::SingletonInstance()->GetFullUrl(), '\\/ ') . '/?dropbox';
     if (!strpos($sRedirectUrl, '://localhost')) {
         $sRedirectUrl = str_replace('http:', 'https:', $sRedirectUrl);
     }
     if ($bDropboxAllow) {
         require PSEVEN_APP_ROOT_PATH . 'libraries/OAuthClient/http.php';
         require PSEVEN_APP_ROOT_PATH . 'libraries/OAuthClient/oauth_client.php';
         $oClient = new \oauth_client_class();
         $oClient->debug = self::$Debug;
         $oClient->debug_http = self::$Debug;
         $oClient->server = 'Dropbox2';
         $oClient->redirect_uri = $sRedirectUrl;
         $oClient->client_id = $sDropboxId;
         $application_line = __LINE__;
         $oClient->client_secret = $sDropboxSecret;
         $oClient->configuration_file = PSEVEN_APP_ROOT_PATH . 'libraries/OAuthClient/' . $oClient->configuration_file;
         if (strlen($oClient->client_id) == 0 || strlen($oClient->client_secret) == 0) {
             $bResult = false;
             exit('Please go to Dropbox Apps page https://www.dropbox.com/developers/apps , ' . 'create an application, and in the line ' . $application_line . ' set the client_id to Consumer key and client_secret with Consumer secret. ' . 'The Callback URL must be ' . $oClient->redirect_uri) . ' Make sure this URL is ' . 'not in a private network and accessible to the Dropbox site.';
         }
         if ($success = $oClient->Initialize()) {
             if ($success = $oClient->Process()) {
                 if (strlen($oClient->access_token)) {
                     $success = $oClient->CallAPI('https://api.dropbox.com/1/account/info', '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' => 'dropbox', 'id' => $oUser->uid, 'name' => $oUser->display_name, 'email' => isset($oUser->email) ? $oUser->email : '', 'access_token' => $oClient->access_token);
             \CApi::Log('social_user_dropbox');
             \CApi::LogObject($oUser);
             $bResult = $aSocial;
         } else {
             $bResult = false;
             $oClient->ResetAccessToken();
             self::_socialError($oClient->error, 'dropbox');
         }
     }
     return $bResult;
 }
Ejemplo n.º 19
0
 public static function validateAuthToken()
 {
     $bResult = true;
     if (isset($_COOKIE[\System\Service::AUTH_TOKEN_KEY])) {
         $oHttp = \MailSo\Base\Http::SingletonInstance();
         $sAuthToken = $oHttp->GetPost('AuthToken', '');
         $bResult = $sAuthToken === $_COOKIE[\System\Service::AUTH_TOKEN_KEY];
     }
     return $bResult;
 }
Ejemplo n.º 20
0
 /**
  * @return string
  */
 public static function WebPath()
 {
     $sAppPath = '';
     if (\RainLoop\Utils::IsOwnCloud()) {
         if (\class_exists('OC_App')) {
             $sAppPath = \rtrim(\trim(\OC_App::getAppWebPath('rainloop')), '\\/') . '/app/';
         }
         if (empty($sAppPath)) {
             $sUrl = \MailSo\Base\Http::SingletonInstance()->GetUrl();
             if ($sUrl && \preg_match('/\\/index\\.php\\/apps\\/rainloop/', $sUrl)) {
                 $sAppPath = \preg_replace('/\\/index\\.php\\/apps\\/rainloop.+$/', '/apps/rainloop/app/', $sUrl);
             }
         }
     }
     return $sAppPath;
 }
Ejemplo n.º 21
0
 public static function GetGoogleUserInfo($sGoogleAPIKey, $sAccessToken = null)
 {
     $mResult = false;
     $sUrl = "https://www.googleapis.com/plus/v1/people/me?key=" . $sGoogleAPIKey;
     $aHeaders = $sAccessToken ? array('Authorization: Bearer ' . $sAccessToken) : array();
     $sContentType = '';
     $iCode = 0;
     $mResult = \MailSo\Base\Http::SingletonInstance()->GetUrlAsString($sUrl, '', $sContentType, $iCode, null, 10, '', '', $aHeaders);
     return $iCode === 200 ? json_decode($mResult) : false;
 }
Ejemplo n.º 22
0
 /**
  * @return string
  */
 public function ForgotLink()
 {
     $sPath = rtrim(\MailSo\Base\Http::SingletonInstance()->GetFullUrl(), '\\/ ');
     if ('/crons' === substr($sPath, -6)) {
         $sPath = substr($sPath, 0, -6);
     }
     $sPath .= '/?helpdesk';
     if (0 < $this->IdTenant) {
         $sHash = substr(md5($this->IdTenant . CApi::$sSalt), 0, 8);
         $sPath .= '=' . $sHash;
     }
     $sPath .= '&forgot=' . $this->ActivateHash;
     return $sPath;
 }
Ejemplo n.º 23
0
 /**
  * @param bool $bHelpdesk Default value is **false**.
  * @param int $iHelpdeskIdTenant Default value is **null**.
  * @param string $sHelpdeskTenantHash Default value is empty string.
  * @param string $sCalendarPubHash Default value is empty string.
  * @param string $sFileStoragePubHash Default value is empty string.
  * @param string $sAuthToken Default value is empty string.
  *
  * @return array
  */
 public function appData($bHelpdesk = false, $iHelpdeskIdTenant = null, $sHelpdeskTenantHash = '', $sCalendarPubHash = '', $sFileStoragePubHash = '', $sAuthToken = '')
 {
     $aAppData = array('Auth' => false, 'User' => null, 'TenantHash' => $sHelpdeskTenantHash, 'IsMobile' => 0, 'AllowMobile' => false, 'IsMailsuite' => false, 'HelpdeskSiteName' => '', 'HelpdeskIframeUrl' => '', 'HelpdeskRedirect' => false, 'HelpdeskThreadId' => 0, 'HelpdeskActivatedEmail' => '', 'HelpdeskForgotHash' => '', 'ClientDebug' => \CApi::GetConf('labs.webmail-client-debug', false), 'MailExpandFolders' => \CApi::GetConf('labs.mail-expand-folders', false), 'HtmlEditorDefaultFontName' => \CApi::GetConf('labs.htmleditor-default-font-name', ''), 'HtmlEditorDefaultFontSize' => \CApi::GetConf('labs.htmleditor-default-font-size', ''), 'AllowSaveAsPdf' => !!\CApi::GetConf('labs.allow-save-as-pdf', false), 'LastErrorCode' => $this->getLastErrorCode(), 'Token' => $this->getCsrfToken(), 'ZipAttachments' => !!class_exists('ZipArchive'), 'AllowIdentities' => !!$this->oSettings->GetConf('WebMail/AllowIdentities'), 'SocialEmail' => '', 'SocialIsLoggedIn' => false, 'Links' => array('ImportingContacts' => \CApi::GetConf('links.importing-contacts', ''), 'OutlookSyncPlugin32' => \CApi::GetConf('links.outlook-sync-plugin-32', ''), 'OutlookSyncPlugin64' => \CApi::GetConf('links.outlook-sync-plugin-64', ''), 'OutlookSyncPluginReadMore' => \CApi::GetConf('links.outlook-sync-read-more', '')));
     CApi::Plugin()->RunHook('api-pre-app-data', array(&$aAppData));
     $oApiCapability = \CApi::Manager('capability');
     if ($oApiCapability) {
         if ($oApiCapability->isNotLite()) {
             $aAppData['IsMobile'] = $this->isMobile();
             $aAppData['AllowMobile'] = true;
         }
         $aAppData['IsMailsuite'] = $oApiCapability->isMailsuite();
     }
     $iIdTenant = 0;
     /*		TODO: sash
     		if (\CApi::GetConf('labs.allow-social-integration', true))
     		{
     			\api_Social::init($aAppData, $sHelpdeskTenantHash);
     		}
     */
     if (0 < $aAppData['LastErrorCode']) {
         $this->clearLastErrorCode();
     }
     $oAccount = null;
     if (!empty($sCalendarPubHash)) {
         $oAccount = $this->getLogginedDefaultAccount();
         if ($oAccount) {
             $aAppData['Auth'] = true;
             $aAppData['User'] = $this->appDataUserSettings($oAccount);
         }
         $aAppData['CalendarPubHash'] = $sCalendarPubHash;
         $aAppData['IsMobile'] = 0;
         return $aAppData;
     }
     if (!empty($sFileStoragePubHash)) {
         $aAppData['FileStoragePubHash'] = $sFileStoragePubHash;
         $oMin = \CApi::Manager('min');
         $mMin = $oMin->getMinByHash($sFileStoragePubHash);
         $aAppData['FileStoragePubParams'] = array();
         if (!empty($mMin['__hash__'])) {
             $aAppData['FileStoragePubParams'] = $mMin;
         }
         $aAppData['IsMobile'] = 0;
         return $aAppData;
     }
     $oApiHelpdeskManager = CApi::Manager('helpdesk');
     /* @var $oApiHelpdeskManager CApiHelpdeskManager */
     $oApiTenant = CApi::Manager('tenants');
     /* @var $oApiTenant CApiTenantsManager */
     $oTenant = $oApiTenant ? $oApiTenant->getDefaultGlobalTenant() : null;
     $aAppData['LoginStyleImage'] = '';
     $aAppData['AppStyleImage'] = '';
     $aAppData['HelpdeskSiteName'] = '';
     $aAppData['HelpdeskStyleImage'] = '';
     if ($oTenant) {
         $aAppData['LoginStyleImage'] = $oTenant->LoginStyleImage;
         $aAppData['AppStyleImage'] = $oTenant->AppStyleImage;
     }
     $aThreadId = $this->getThreadIdFromRequestAndClear();
     $mThreadId = isset($aThreadId['id']) ? $aThreadId['id'] : null;
     $sThreadAction = isset($aThreadId['action']) ? $aThreadId['action'] : '';
     if ($bHelpdesk) {
         $aHelpdeskMainData = null;
         $aAppData['TenantHash'] = $sHelpdeskTenantHash;
         $aAppData['IsMobile'] = 0;
         $iUserId = $this->getLogginedHelpdeskUserId();
         if (0 < $iUserId && $oApiHelpdeskManager) {
             $oHelpdeskUser = $oApiHelpdeskManager->getUserById($iHelpdeskIdTenant, $iUserId);
             if ($oHelpdeskUser) {
                 $aHelpdeskMainData = $oApiHelpdeskManager->getHelpdeskMainSettings($oHelpdeskUser->IdTenant);
                 $aAppData['Auth'] = true;
                 $aAppData['HelpdeskIframeUrl'] = $oHelpdeskUser->IsAgent ? $aHelpdeskMainData['AgentIframeUrl'] : $aHelpdeskMainData['ClientIframeUrl'];
                 $aAppData['HelpdeskSiteName'] = isset($aHelpdeskMainData['SiteName']) ? $aHelpdeskMainData['SiteName'] : '';
                 $aAppData['User'] = $this->appDataHelpdeskUserSettings($oHelpdeskUser);
             }
         }
         if (!$aHelpdeskMainData && $oApiHelpdeskManager) {
             $iIdTenant = $this->getTenantIdByHash($sHelpdeskTenantHash);
             $aHelpdeskMainData = $oApiHelpdeskManager->getHelpdeskMainSettings($iIdTenant);
             $aAppData['HelpdeskSiteName'] = isset($aHelpdeskMainData['SiteName']) ? $aHelpdeskMainData['SiteName'] : '';
             $aAppData['HelpdeskStyleImage'] = isset($aHelpdeskMainData['StyleImage']) && isset($aHelpdeskMainData['StyleAllow']) ? $aHelpdeskMainData['StyleImage'] : '';
         }
         $oHttp = \MailSo\Base\Http::SingletonInstance();
         $aAppData['HelpdeskForgotHash'] = $oHttp->GetRequest('forgot', '');
         if (0 === strlen($aAppData['HelpdeskForgotHash'])) {
             $aAppData['HelpdeskThreadId'] = null === $mThreadId ? 0 : $mThreadId;
             $aAppData['HelpdeskActivatedEmail'] = $this->getActivatedUserEmailAndClear();
         }
         $aAppData['App'] = array();
         $aAppData['App']['DateFormats'] = array();
         foreach (array(EDateFormat::MMDDYYYY, EDateFormat::DDMMYYYY, EDateFormat::DD_MONTH_YYYY) as $sDateFmtName) {
             $aAppData['App']['DateFormats'][] = $sDateFmtName;
         }
         return $aAppData;
     } else {
         $aAppData['HelpdeskRedirect'] = is_int($mThreadId);
         $aAppData['HelpdeskThreadId'] = null === $mThreadId ? 0 : $mThreadId;
         $aAppData['HelpdeskThreadAction'] = $sThreadAction ? $sThreadAction : '';
     }
     $oDefaultAccount = null;
     $oDomain = null;
     $iUserId = $this->getLogginedUserId($sAuthToken);
     if (0 < $iUserId) {
         /* @var $oApiUsersManager CApiUsersManager */
         $oApiUsersManager = CApi::Manager('users');
         $aInfo = $oApiUsersManager->getUserAccounts($iUserId);
         if (is_array($aInfo) && 0 < count($aInfo)) {
             $aAppData['Auth'] = true;
             $iDefault = 0;
             $iDefaultIndex = 0;
             $aAccounts = array();
             $aDefaultAccount = array();
             foreach ($aInfo as $iAccountId => $aData) {
                 if (is_array($aData) && !empty($aData[1])) {
                     $aAccount = array('AccountID' => $iAccountId, 'Email' => $aData[1], 'FriendlyName' => $aData[2], 'Signature' => array('Signature' => $aData[3], 'Type' => $aData[4], 'Options' => $aData[5]), 'IsPasswordSpecified' => $aData[6], 'AllowMail' => $aData[7]);
                     if ($aData[0]) {
                         $aDefaultAccount = $aAccount;
                         $iDefault = $iAccountId;
                         $iDefaultIndex = count($aAccounts);
                     } else {
                         $aAccounts[] = $aAccount;
                     }
                 }
             }
             $aAppData['Default'] = $iDefault;
             $oDefaultAccount = $oApiUsersManager->getAccountById($iDefault);
             if ($oDefaultAccount) {
                 $aAppData['User'] = $this->appDataUserSettings($oDefaultAccount);
                 if ($oApiHelpdeskManager) {
                     $aData = $oApiHelpdeskManager->getHelpdeskMainSettings($oDefaultAccount->IdTenant);
                     $aAppData['HelpdeskIframeUrl'] = isset($aAppData['User']['IsHelpdeskAgent']) && $aAppData['User']['IsHelpdeskAgent'] ? $aData['AgentIframeUrl'] : $aData['ClientIframeUrl'];
                 }
             }
         }
     }
     if ($aAppData['Auth']) {
         if (0 < $oDefaultAccount->IdTenant) {
             $aAppData['AppStyleImage'] = '';
             $oAccountTenant = $oApiTenant ? 0 < $oDefaultAccount->IdTenant ? $oApiTenant->getTenantById($oDefaultAccount->IdTenant) : $oApiTenant->getDefaultGlobalTenant() : null;
             if ($oAccountTenant) {
                 $aAppData['AppStyleImage'] = $oAccountTenant->AppStyleImage;
             }
         }
     }
     $oDomain = $this->getDefaultAccountDomain($oDefaultAccount);
     if ($oDefaultAccount) {
         array_splice($aAccounts, $iDefaultIndex, 0, array($aDefaultAccount));
         $aAppData['Accounts'] = $aAccounts;
     }
     $aAppData['App'] = $this->appDataDomainSettings($oDomain, $oDefaultAccount);
     if (!isset($aAppData['Plugins'])) {
         $aAppData['Plugins'] = array();
     }
     $aAppData['HelpdeskThreadId'] = null === $aAppData['HelpdeskThreadId'] ? 0 : $aAppData['HelpdeskThreadId'];
     CApi::Plugin()->RunHook('api-app-data', array($oDefaultAccount, &$aAppData));
     return $aAppData;
 }
Ejemplo n.º 24
0
 public static function GetGoogleDriveFileInfo($sLink, $sGoogleAPIKey, $sAccessToken = null, $bLinkAsId = false)
 {
     $mResult = false;
     $sGDId = '';
     if ($bLinkAsId) {
         $sGDId = $sLink;
     } else {
         $matches = array();
         preg_match("%https://\\w+\\.google\\.com/\\w+/d/(.*?)/.*%", $sLink, $matches);
         if (!isset($matches[1])) {
             preg_match("%https://\\w+\\.google\\.com/open\\?id=(.*)%", $sLink, $matches);
         }
         $sGDId = isset($matches[1]) ? $matches[1] : '';
     }
     if ($sGDId !== '') {
         $sUrl = "https://www.googleapis.com/drive/v2/files/" . $sGDId . '?key=' . $sGoogleAPIKey;
         $aHeaders = $sAccessToken ? array('Authorization: Bearer ' . $sAccessToken) : array();
         $sContentType = '';
         $iCode = 0;
         $mResult = \MailSo\Base\Http::SingletonInstance()->GetUrlAsString($sUrl, '', $sContentType, $iCode, null, 10, '', '', $aHeaders);
         if ($iCode === 200) {
             $mResult = json_decode($mResult);
             self::PopulateGoogleDriveFileInfo($mResult);
         } else {
             $mResult = false;
         }
     } else {
         $mResult = false;
     }
     return $mResult;
 }
Ejemplo n.º 25
0
 /**
  * @return \RainLoop\Service
  */
 public function Handle()
 {
     if (!\class_exists('MailSo\\Version')) {
         return $this;
     }
     $this->oActions->BootStart();
     $this->oActions->ParseQueryAuthString();
     $bCached = false;
     $sResult = '';
     $sQuery = \trim(\trim($this->oHttp->GetServer('QUERY_STRING', '')), ' /');
     $iPos = \strpos($sQuery, '&');
     if (0 < $iPos) {
         $sQuery = \substr($sQuery, 0, $iPos);
     }
     $this->oActions->Plugins()->RunHook('filter.http-query', array(&$sQuery));
     $aPaths = \explode('/', $sQuery);
     $this->oActions->Plugins()->RunHook('filter.http-paths', array(&$aPaths));
     $bAdmin = false;
     $sAdminPanelHost = $this->oActions->Config()->Get('security', 'admin_panel_host', '');
     if (empty($sAdminPanelHost)) {
         $bAdmin = !empty($aPaths[0]) && \in_array(\strtolower($aPaths[0]), array('admin', 'cp'));
     } else {
         if (empty($aPaths[0]) && \MailSo\Base\Utils::StrToLowerIfAscii($sAdminPanelHost) === \MailSo\Base\Utils::StrToLowerIfAscii($this->oHttp->GetHost())) {
             $bAdmin = true;
         }
     }
     if ($bAdmin && !$this->oActions->Config()->Get('security', 'allow_admin_panel', true)) {
         echo $this->oActions->ErrorTemplates('Access Denied.', 'Access to the RainLoop Webmail Admin Panel is not allowed!', true);
         return $this;
     }
     $bIndex = true;
     if (0 < \count($aPaths) && !empty($aPaths[0]) && !$bAdmin && 'index' !== $aPaths[0]) {
         $bIndex = false;
         $sMethodName = 'Service' . $aPaths[0];
         if (\method_exists($this->oServiceActions, $sMethodName) && \is_callable(array($this->oServiceActions, $sMethodName))) {
             $this->oServiceActions->SetQuery($sQuery)->SetPaths($aPaths);
             $sResult = \call_user_func(array($this->oServiceActions, $sMethodName));
         } else {
             if (!$this->oActions->Plugins()->RunAdditionalPart($aPaths[0], $aPaths)) {
                 $bIndex = true;
             }
         }
     }
     if ($bIndex) {
         @header('Content-Type: text/html; charset=utf-8');
         $this->oHttp->ServerNoCache();
         $aData = $this->startUpData($bAdmin);
         $sCacheFileName = '';
         if ($this->oActions->Config()->Get('labs', 'cache_system_data', true)) {
             $sCacheFileName = 'TMPL:' . $aData['Hash'];
             $sResult = $this->oActions->Cacher()->Get($sCacheFileName);
         }
         if (0 === \strlen($sResult)) {
             $sJsBoot = \file_get_contents(APP_VERSION_ROOT_PATH . 'static/js/boot.js');
             $sResult = \strtr(\file_get_contents(APP_VERSION_ROOT_PATH . 'app/templates/Index.html'), array('{{BaseRandHash}}' => \md5(\rand(1000, 9000) . \microtime(true)), '{{BaseAppDataScriptLink}}' => $bAdmin ? './?/AdminAppData/' : './?/AppData/', '{{BaseAppFaviconIcoFile}}' => $aData['FaviconIcoLink'], '{{BaseAppFaviconPngFile}}' => $aData['FaviconPngLink'], '{{BaseAppAppleTouchFile}}' => $aData['AppleTouchLink'], '{{BaseAppMainCssLink}}' => $aData['AppCssLink'], '{{BaseAppBootScriptSource}}' => $sJsBoot, '{{BaseAppLibsScriptLink}}' => $aData['LibJsLink'], '{{BaseAppEditorScriptLink}}' => $aData['EditorJsLink'], '{{BaseAppMainScriptLink}}' => $aData['AppJsLink'], '{{BaseAppLoadingDescription}}' => \htmlspecialchars($aData['LoadingDescription'], ENT_QUOTES | ENT_IGNORE, 'UTF-8'), '{{BaseDir}}' => \in_array($aData['Language'], array('ar', 'he', 'ur')) ? 'rtl' : 'ltr'));
             $sResult = \RainLoop\Utils::ClearHtmlOutput($sResult);
             if (0 < \strlen($sCacheFileName)) {
                 $this->oActions->Cacher()->Set($sCacheFileName, $sResult);
             }
         } else {
             $bCached = true;
         }
         $sResult .= '<!--';
         $sResult .= ' [version:' . APP_VERSION;
         $sResult .= '][time:' . \substr(\microtime(true) - APP_START, 0, 6);
         $sResult .= '][cached:' . ($bCached ? 'true' : 'false');
         $sResult .= '][session:' . \md5(\RainLoop\Utils::GetShortToken());
         $sResult .= '] -->';
     }
     // Output result
     echo $sResult;
     unset($sResult);
     $this->oActions->BootEnd();
     return $this;
 }