public function testGetSetRuntime() { $defaultTimeZoneBackup = date_default_timezone_get(); $interval = '1 day'; $timezone = new DateTimeZone('Europe/Berlin'); $event1 = new CM_Clockwork_Event('foo', $interval); $event2 = new CM_Clockwork_Event('bar', $interval); $date1 = new DateTime('2014-10-31 08:00:00', $timezone); $date2 = new DateTime('2014-10-31 08:02:03', $timezone); $context = 'persistence-test'; $storage = new CM_Clockwork_Storage_FileSystem($context); $serviceManager = CM_Service_Manager::getInstance(); $storage->setServiceManager($serviceManager); $filepath = 'clockwork/' . md5($context) . '.json'; $file = new CM_File($filepath, $serviceManager->getFilesystems()->getData()); $this->assertFalse($file->exists()); $this->assertFalse($file->getParentDirectory()->exists()); $storage->setRuntime($event1, $date1); $this->assertTrue($file->getParentDirectory()->exists()); $this->assertTrue($file->exists()); $storage->setRuntime($event2, $date2); date_default_timezone_set('Antarctica/Vostok'); $storage = new CM_Clockwork_Storage_FileSystem($context); $storage->setServiceManager($serviceManager); $this->assertEquals($date1, $storage->getLastRuntime($event1)); $this->assertEquals($date2, $storage->getLastRuntime($event2)); date_default_timezone_set($defaultTimeZoneBackup); }
public function testImportVideoThumbnail() { $testFile1 = CM_File::create('test1.png', 'foo1', CM_Service_Manager::getInstance()->getFilesystems()->getTmp()); $testFile2 = CM_File::create('test2.png', 'foo2', CM_Service_Manager::getInstance()->getFilesystems()->getTmp()); $cli = new CM_MediaStreams_Cli(); // streamchannel exists /** @var CM_Model_StreamChannel_Media $streamChannel */ $streamChannel = CMTest_TH::createStreamChannel(null, null, 'foobar'); $this->assertCount(0, $streamChannel->getThumbnails()); $cli->importVideoThumbnail('foobar', $testFile1, 1234); $this->assertCount(1, $streamChannel->getThumbnails()); /** @var CM_StreamChannel_Thumbnail $thumbnail */ $thumbnail = $streamChannel->getThumbnails()->getItem(0); $this->assertSame(1234, $thumbnail->getCreateStamp()); $this->assertSame('foo1', $thumbnail->getFile()->read()); // archive exists $archive = CM_Model_StreamChannelArchive_Media::createStatic(['streamChannel' => $streamChannel]); $streamChannel->delete(); $cli->importVideoThumbnail('foobar', $testFile2, 1235); $this->assertCount(2, $streamChannel->getThumbnails()); /** @var CM_StreamChannel_Thumbnail $thumbnail */ $thumbnail = $archive->getThumbnails()->getItem(1); $this->assertSame(1235, $thumbnail->getCreateStamp()); $this->assertSame('foo2', $thumbnail->getFile()->read()); }
/** * @param array|null $parameters * @param bool|null $disableQueryBuffering * @throws CM_Db_Exception * @return CM_Db_Result */ public function execute(array $parameters = null, $disableQueryBuffering = null) { $disableQueryBuffering = (bool) $disableQueryBuffering; $retryCount = 1; for ($try = 0; true; $try++) { try { if ($disableQueryBuffering) { $this->_client->setBuffered(false); } @$this->_pdoStatement->execute($parameters); if ($disableQueryBuffering) { $this->_client->setBuffered(true); } CM_Service_Manager::getInstance()->getDebug()->incStats('mysql', $this->getQueryString()); return new CM_Db_Result($this->_pdoStatement); } catch (PDOException $e) { if ($try < $retryCount && $this->_client->isConnectionLossError($e)) { $this->_client->disconnect(); $this->_client->connect(); $this->_reCreatePdoStatement(); continue; } throw new CM_Db_Exception('Cannot execute SQL statement', null, ['tries' => $try, 'originalExceptionMessage' => $e->getMessage(), 'query' => $this->_pdoStatement->queryString]); } } throw new CM_Db_Exception('Line should never be reached'); }
/** * @return CM_Service_EmailVerification_ClientInterface */ protected function _getEmailVerification() { if ($this->getParams()->getBoolean('disable-email-verification', false)) { return new CM_Service_EmailVerification_Standard(); } return CM_Service_Manager::getInstance()->get('email-verification', 'CM_Service_EmailVerification_ClientInterface'); }
public function testWithoutWhere() { $client = CM_Service_Manager::getInstance()->getDatabases()->getMaster(); $query = new CM_Db_Query_UpdateSequence($client, 't`est', 's`ort', -1, null, 4, 9); $this->assertSame('UPDATE `t``est` SET `s``ort` = `s``ort` + ? WHERE `s``ort` BETWEEN ? AND ?', $query->getSqlTemplate()); $this->assertEquals(array(-1, 4, 9), $query->getParameters()); }
/** * @param string $name * @param CM_Service_Manager $serviceManager */ public function __construct($name, CM_Service_Manager $serviceManager = null) { $this->_construct(array('name' => $name)); if (null === $serviceManager) { $serviceManager = CM_Service_Manager::getInstance(); } $this->setServiceManager($serviceManager); }
protected function _execute(CM_Params $params) { $indexClassName = $params->getString('indexClassName'); $id = $params->getString('id'); $client = CM_Service_Manager::getInstance()->getElasticsearch()->getClient(); /** @var CM_Elasticsearch_Type_Abstract $index */ $index = new $indexClassName($client); $index->updateDocuments(array($id)); $index->refreshIndex(); }
/** * @param int $age */ protected function _deleteOlderThan($age) { $age = (int) $age; $deleteOlderThan = time() - $age; $criteria = $this->_getCriteria(); $criteria['createdAt'] = ['$lt' => new MongoDate($deleteOlderThan)]; $mongoDb = CM_Service_Manager::getInstance()->getMongoDb(); $mongoDb->remove(self::COLLECTION_NAME, $criteria, ['socketTimeoutMS' => 50000]); $this->_change(); }
public function prepare(CM_Frontend_Environment $environment, CM_Frontend_ViewResponse $viewResponse) { $debug = CM_Service_Manager::getInstance()->getDebug(); $stats = $debug->getStats(); ksort($stats); $viewResponse->set('stats', $stats); $cacheNames = array('CM_Cache_Storage_Memcache', 'CM_Cache_Storage_Apc', 'CM_Cache_Storage_File'); $viewResponse->getJs()->setProperty('cacheNames', $cacheNames); $viewResponse->set('cacheNames', $cacheNames); }
public function onUnsubscribe(CM_Model_Stream_Subscribe $streamSubscribe) { if ($this->hasUser()) { $user = $streamSubscribe->getUser(); if ($user && !$this->isSubscriber($user, $streamSubscribe)) { $delayedJobQueue = CM_Service_Manager::getInstance()->getDelayedJobQueue(); $delayedJobQueue->addJob(new CM_User_OfflineJob(), ['user' => $user], CM_Model_User::OFFLINE_DELAY); } } }
protected function _execute(CM_Params $params) { CM_Service_Manager::getInstance()->getMailer()->send($params->getMailMessage('message')); if ($params->has('recipient') && $params->has('mailType')) { $recipient = $params->getUser('recipient'); $mailType = $params->getInt('mailType'); $action = new CM_Action_Email(CM_Action_Abstract::SEND, $recipient, $mailType); $action->prepare($recipient); $action->notify($recipient); } }
/** * @param CM_Params $params * @return mixed * @throws Exception */ private function _executeJob(CM_Params $params) { CM_Service_Manager::getInstance()->getNewrelic()->startTransaction('CM Job: ' . $this->_getClassName()); try { $return = $this->_execute($params); CM_Service_Manager::getInstance()->getNewrelic()->endTransaction(); return $return; } catch (Exception $ex) { CM_Service_Manager::getInstance()->getNewrelic()->endTransaction(); throw $ex; } }
/** * @param string $message */ public static function log($message) { $message = (string) $message; $trace = debug_backtrace(); $className = 'none'; $functionName = 'none'; if (isset($trace[1])) { $className = isset($trace[1]['class']) ? $trace[1]['class'] : $className; $functionName = isset($trace[1]['function']) ? $trace[1]['function'] : $functionName; } CM_Service_Manager::getInstance()->getLogger()->debug(sprintf('%s:%s - %s', $className, $functionName, $message)); }
public function setUp() { CM_Db_Db::exec('ALTER TABLE cm_model_location_ip AUTO_INCREMENT = 1'); CM_Db_Db::exec('ALTER TABLE cm_model_location_zip AUTO_INCREMENT = 1'); CM_Db_Db::exec('ALTER TABLE cm_model_location_city AUTO_INCREMENT = 1'); CM_Db_Db::exec('ALTER TABLE cm_model_location_state AUTO_INCREMENT = 1'); CM_Db_Db::exec('ALTER TABLE cm_model_location_country AUTO_INCREMENT = 1'); $this->_errorStream = new CM_OutputStream_Null(); $file = new CM_File('/CM_OutputStream_File-' . uniqid(), CM_Service_Manager::getInstance()->getFilesystems()->getTmp()); $file->truncate(); $this->_outputStream = new CM_OutputStream_File($file); }
/** * @param CM_Frontend_Environment|null $environment * @param boolean|null $languageRewrite * @param CM_Service_Manager|null $serviceManager */ public function __construct(CM_Frontend_Environment $environment = null, $languageRewrite = null, CM_Service_Manager $serviceManager = null) { if (!$environment) { $environment = new CM_Frontend_Environment(); } $this->_environment = $environment; $this->_languageRewrite = (bool) $languageRewrite; if (null === $serviceManager) { $serviceManager = CM_Service_Manager::getInstance(); } $this->setServiceManager($serviceManager); }
/** * @param string $verbName * @param CM_Model_User|int $actor * @param int $typeEmail */ public function __construct($verbName, $actor, $typeEmail) { parent::__construct($verbName, $actor); $typeEmail = (int) $typeEmail; try { $className = CM_Mail_Mailable::_getClassName($typeEmail); $this->_nameEmail = ucwords(CM_Util::uncamelize(str_replace('_', '', preg_replace('#\\A[^_]++_[^_]++_#', '', $className)), ' ')); } catch (CM_Class_Exception_TypeNotConfiguredException $exception) { CM_Service_Manager::getInstance()->getLogger()->warning('Unrecognized mail type when creating mail action', (new CM_Log_Context())->setException($exception)); $this->_nameEmail = (string) $typeEmail; } }
public function testGetModules() { $filesystemTmp = CM_Service_Manager::getInstance()->getFilesystems()->getTmp(); $dirRoot = $filesystemTmp->getAdapter()->getPathPrefix() . '/foo-app/'; $composerFile = new \Composer\Json\JsonFile($dirRoot . 'composer.json'); $composerFile->write(array('name' => 'foo/bar', 'require' => array('cargomedia/cm' => '*'), 'extra' => ['cm-modules' => ['Package' => ['path' => 'package/']]])); $filesystemTmp->ensureDirectory('foo-app/vendor/composer/'); $installedFile = new \Composer\Json\JsonFile($dirRoot . 'vendor/composer/installed.json'); $installedFile->write([['name' => 'cargomedia/cm', 'version' => '1.3.10', 'type' => 'library', 'extra' => ['cm-modules' => ['CM' => ['path' => '']]], 'autoload' => ['psr-0' => ['CM_' => 'library/']]]]); $installation = new CM_App_Installation($dirRoot); $expectedModules = [new CM_App_Module('CM', 'vendor/cargomedia/cm/'), new CM_App_Module('Package', 'package/')]; $this->assertEquals($expectedModules, $installation->getModules()); }
/** * @param string|null $filterIndexName * @throws CM_Exception_Invalid * @return CM_Elasticsearch_Type_Abstract[] */ protected function _getTypes($filterIndexName = null) { $types = CM_Service_Manager::getInstance()->getElasticsearch()->getTypes(); if (null !== $filterIndexName) { $types = \Functional\filter($types, function (CM_Elasticsearch_Type_Abstract $type) use($filterIndexName) { return $type->getIndex()->getName() === $filterIndexName; }); if (count($types) === 0) { throw new CM_Exception_Invalid('No type with such index name: ' . $filterIndexName); } } return $types; }
public function testDisableEmailVerification() { $emailVerificationMock = $this->getMock('CM_Service_EmailVerification_Standard', ['isValid']); $emailVerificationMock->expects($this->never())->method('isValid'); $serviceManager = CM_Service_Manager::getInstance(); $emailVerificationDefault = $serviceManager->get('email-verification'); $serviceManager->unregister('email-verification'); $serviceManager->registerInstance('email-verification', $emailVerificationMock); $field = new CM_FormField_Email(['name' => 'email', 'disable-email-verification' => true]); $environment = new CM_Frontend_Environment(); $this->assertSame('*****@*****.**', $field->validate($environment, '*****@*****.**')); $serviceManager->unregister('email-verification'); $serviceManager->registerInstance('email-verification', $emailVerificationDefault); }
public function testReconnectTimeout() { $config = CM_Service_Manager::getInstance()->getDatabases()->getMaster()->getConfig(); $config['reconnectTimeout'] = 5; $client = new CM_Db_Client($config); $client->connect(); $firstTime = $client->getLastConnect(); $timeForward = 100; CMTest_TH::timeForward($timeForward); $client->createStatement('SELECT 1')->execute(); $this->assertSameTime($firstTime + $timeForward, $client->getLastConnect(), 5); CMTest_TH::timeForward($timeForward); $client->createStatement('SELECT 1')->execute(); $this->assertSameTime($firstTime + 2 * $timeForward, $client->getLastConnect(), 5); }
/** * @param string $namespace * @param string $filename * @param int|null $sequence * @param CM_Service_Manager|null $serviceManager */ public function __construct($namespace, $filename, $sequence = null, CM_Service_Manager $serviceManager = null) { $namespace = (string) $namespace; $filename = (string) $filename; if (null !== $sequence) { $sequence = (int) $sequence; } if (null === $serviceManager) { $serviceManager = CM_Service_Manager::getInstance(); } $this->_pathRelative = $this->_calculateRelativeDir($namespace, $filename, $sequence); $this->_namespace = $namespace; $this->setServiceManager($serviceManager); $filesystem = $serviceManager->getUserContent()->getFilesystem($this->getNamespace()); parent::__construct($this->getPathRelative(), $filesystem); }
/** * @param int|null $offset * @param int|null $count * @return array */ private function _getResult($offset = null, $count = null) { $cacheKey = array($this->_query->getSort(), $offset, $count); if (($result = $this->_cacheGet($cacheKey)) === false) { $data = array('query' => $this->_query->getQuery(), 'sort' => $this->_query->getSort()); if ($this->_fields) { $data['fields'] = $this->_fields; } if ($offset !== null) { $data['from'] = $offset; } if ($count !== null) { $data['size'] = $count; } $searchResult = CM_Service_Manager::getInstance()->getElasticsearch()->query($this->_types, $data); $result = array('items' => array(), 'total' => 0); if (isset($searchResult['hits'])) { foreach ($searchResult['hits']['hits'] as $hit) { if ($this->_fields && array_key_exists('fields', $hit)) { if ($this->_returnType) { $idArray = array('id' => $hit['_id'], 'type' => $hit['_type']); } else { $idArray = array('id' => $hit['_id']); } $fields = $hit['fields']; $fields = Functional\map($fields, function ($field) { if (is_array($field) && 1 == count($field)) { $field = reset($field); } return $field; }); $result['items'][] = array_merge($idArray, $fields); } else { if ($this->_returnType) { $item = array('id' => $hit['_id'], 'type' => $hit['_type']); } else { $item = $hit['_id']; } $result['items'][] = $item; } } $result['total'] = $searchResult['hits']['total']; } $this->_cacheSet($cacheKey, $result); } return $result; }
/** * @param CM_InputStream_Interface|null $streamInput * @param CM_OutputStream_Interface|null $streamOutput * @param CM_OutputStream_Interface|null $streamError */ public function __construct(CM_InputStream_Interface $streamInput = null, CM_OutputStream_Interface $streamOutput = null, CM_OutputStream_Interface $streamError = null) { if (null === $streamInput) { $streamInput = new CM_InputStream_Null(); } $this->_streamInput = $streamInput; if (null === $streamOutput) { $streamOutput = new CM_OutputStream_Null(); } $this->_streamOutput = $streamOutput; if (null === $streamError) { $streamError = new CM_OutputStream_Null(); } $this->_streamError = $streamError; $this->setServiceManager(CM_Service_Manager::getInstance()); $this->_initialize(); }
/** * @return string */ public function fetch() { $page = $this->_getPage(); $layout = $this->_getLayout(); $page->checkAccessible($this->getRender()->getEnvironment()); $frontend = $this->getRender()->getGlobalResponse(); $viewResponse = new CM_Frontend_ViewResponse($layout); $viewResponse->setTemplateName('default'); $layout->prepare($this->getRender()->getEnvironment(), $viewResponse); $viewResponse->set('viewResponse', $viewResponse); $viewResponse->set('page', $page); $viewResponse->set('pageTitle', $this->fetchTitle()); $viewResponse->set('pageDescription', $this->fetchDescription()); $viewResponse->set('pageKeywords', $this->fetchKeywords()); $viewResponse->set('renderAdapter', $this); $environmentDefault = new CM_Frontend_Environment($this->getRender()->getEnvironment()->getSite()); $renderDefault = new CM_Frontend_Render($environmentDefault); $viewResponse->set('renderDefault', $renderDefault); $viewResponse->set('languageList', new CM_Paging_Language_Enabled()); $serviceManager = CM_Service_Manager::getInstance(); $options = array(); $options['deployVersion'] = CM_App::getInstance()->getDeployVersion(); $options['renderStamp'] = floor(microtime(true) * 1000); $options['site'] = CM_Params::encode($this->getRender()->getSite()); $options['url'] = $this->getRender()->getSite()->getUrl(); $options['urlCdn'] = $this->getRender()->getSite()->getUrlCdn(); $options['urlUserContentList'] = $serviceManager->getUserContent()->getUrlList(); $options['language'] = $this->getRender()->getLanguage(); $options['debug'] = CM_Bootloader::getInstance()->isDebug(); $options['stream'] = $serviceManager->getStreamMessage()->getClientOptions(); if ($viewer = $this->getRender()->getViewer()) { $options['stream']['channel']['key'] = CM_Model_StreamChannel_Message_User::getKeyByUser($viewer); $options['stream']['channel']['type'] = CM_Model_StreamChannel_Message_User::getTypeStatic(); } $frontend->getOnloadHeaderJs()->append('cm.options = ' . CM_Params::encode($options, true)); if ($viewer = $this->getRender()->getViewer()) { $frontend->getOnloadHeaderJs()->append('cm.viewer = ' . CM_Params::encode($viewer, true)); } $frontend->treeExpand($viewResponse); $frontend->getOnloadReadyJs()->append('cm.getLayout()._ready();'); $frontend->getOnloadHeaderJs()->append('cm.ready();'); $html = $this->getRender()->fetchViewResponse($viewResponse); $frontend->treeCollapse(); return $html; }
/** * @param string[] $keys * @return mixed[] */ public final function getMulti(array $keys) { CM_Service_Manager::getInstance()->getDebug()->incStats(strtolower($this->_getName()) . '-getMulti', $keys); foreach ($keys as &$key) { $key = self::_getKeyArmored($key); } $values = $this->_getMulti($keys); $result = array(); $runtime = $this->_getRuntime(); foreach ($values as $armoredKey => $value) { $key = $this->_extractKeyArmored($armoredKey); $result[$key] = $value; if ($runtime) { $runtime->set($key, $value); } } return $result; }
/** * @param string $method * @param CM_Janus_Server $server * @param string $path * @param array|null $body * @return string * @throws CM_Exception_Invalid */ protected function _request($method, CM_Janus_Server $server, $path, array $body = null) { $context = CM_Service_Manager::getInstance()->getLogger()->getContext(); $appContext = $this->_contextFormatter->formatAppContext($context); $url = $server->getHttpAddress() . $path; $body = (array) $body; $options = ['query' => ['context' => CM_Util::jsonEncode($appContext)], 'body' => $body, 'headers' => ['Server-Key' => $server->getKey()]]; $request = $this->_httpClient->createRequest($method, $url, $options); try { $response = $this->_httpClient->send($request); } catch (GuzzleHttp\Exception\TransferException $e) { throw new CM_Exception_Invalid('Fetching contents from url failed', null, ['url' => $url, 'originalExceptionMessage' => $e->getMessage()]); } $body = $response->getBody(); if (null === $body) { throw new CM_Exception_Invalid('Empty response body'); } return $body->getContents(); }
/** * @throws CM_Db_Exception */ public function connect() { if ($this->isConnected()) { return; } $dsnOptions = array('host=' . $this->_host, 'port=' . $this->_port); if (null !== $this->_db) { $dsnOptions[] = 'dbname=' . $this->_db; } $dsn = 'mysql:' . implode(';', $dsnOptions); try { $time = microtime(true) * 1000; $this->_pdo = new PDO($dsn, $this->_username, $this->_password, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "UTF8"')); CM_Service_Manager::getInstance()->getNewrelic()->setCustomMetric('DB connect', microtime(true) * 1000 - $time); $this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { throw new CM_Db_Exception('Database connection failed', null, ['originalExceptionMessage' => $e->getMessage()]); } $this->_lastConnect = time(); }
public function process() { $this->_process(); if ($this->getRequest()->hasSession()) { $session = $this->getRequest()->getSession(); if (!$session->isEmpty()) { $sessionExpiration = $session->hasLifetime() ? time() + $session->getLifetime() : null; $this->setCookie('sessionId', $session->getId(), $sessionExpiration); } elseif ($this->getRequest()->getCookie('sessionId')) { $this->deleteCookie('sessionId'); } } if ($this->getRequest()->hasClientId()) { $requestClientId = $this->getRequest()->getClientId(); if ($this->getRequest()->getCookie('clientId') != $requestClientId) { $this->setCookie('clientId', (string) $requestClientId, time() + 20 * 365 * 24 * 60 * 60); } } $name = $this->_getStringRepresentation(); CM_Service_Manager::getInstance()->getNewrelic()->setNameTransaction($name); }
/** * @param string $namespace */ private function _dbToFileMongo($namespace) { $mongo = CM_Service_Manager::getInstance()->getMongoDb(); $collectionList = \Functional\select($mongo->listCollectionNames(), function ($collection) use($namespace) { return preg_match('/^' . strtolower($namespace) . '_/', $collection); }); sort($collectionList); $optionsValid = ['unique', 'name', 'dropDups', 'sparse', 'expireAfterSeconds']; $indexes = []; foreach ($collectionList as $collection) { $indexList = $mongo->getIndexInfo($collection); foreach ($indexList as $indexInfo) { $key = $indexInfo['key']; $options = array_intersect_key($indexInfo, array_flip($optionsValid)); $indexes[$collection][] = ['key' => $key, 'options' => $options]; } } $dump = CM_Params::jsonEncode($indexes, true); $dirPath = CM_Util::getModulePath($namespace) . '/resources/mongo/'; CM_File::getFilesystemDefault()->ensureDirectory($dirPath); CM_File::create($dirPath . 'collections.json', $dump); }
/** * @param int|null $offset * @param int|null $count * @return array */ public function getItems($offset = null, $count = null) { $cacheKey = array('items', $offset, $count, $this->_sort); if (($items = $this->_cacheGet($cacheKey)) === false) { $mongoDb = CM_Service_Manager::getInstance()->getMongoDb(); $aggregation = null; if ($this->_aggregation) { $aggregation = $this->_aggregation; if (null !== $this->_sort) { array_push($aggregation, ['$sort' => $this->_sort]); } if (null !== $offset) { array_push($aggregation, ['$skip' => $offset]); } if (null !== $count) { array_push($aggregation, ['$limit' => $count]); } } $cursor = $mongoDb->find($this->_collection, $this->_criteria, $this->_projection, $aggregation); if (null === $this->_aggregation) { /** @var MongoCursor $cursor */ if (null !== $this->_sort) { $cursor->sort($this->_sort); } if (null !== $offset) { $cursor->skip($offset); } if (null !== $count) { $cursor->limit($count); } } $items = array(); foreach ($cursor as $item) { $items[] = $item; } $this->_cacheSet($cacheKey, $items); } return $items; }