예제 #1
0
파일: cache.php 프로젝트: mpcmf/mpcmf-core
 public static function setCached($key, $value, $expire = 0)
 {
     profiler::addStack('file_cache');
     $cachePath = self::getPath($key);
     $dirname = dirname($cachePath);
     if (file_exists($cachePath) && !@chmod($cachePath, 0777)) {
         @unlink($cachePath);
     } elseif (!file_exists($dirname)) {
         @mkdir($dirname, 0777, true);
     }
     $storeData = ['e' => $expire > 0 ? time() + $expire : 0, 'v' => $value];
     $attempts = 5;
     do {
         $result = file_put_contents($cachePath, serialize($storeData));
         if ($result !== false) {
             break;
         }
         usleep(10000);
     } while ($result === false && --$attempts > 0);
 }
예제 #2
0
 public function checkActionAccessByGroups(action $action, array $groups)
 {
     static $groupMapper;
     profiler::addStack('acl::check');
     $actionAclGroups = $action->getAcl();
     $actionAclGroups[] = $action->getAclGroupName();
     $actionAclGroups[] = aclManager::ACL__GROUP_ROOT;
     $actionAclGroups = array_unique($actionAclGroups, SORT_ASC);
     $actionGroupsCacheKey = 'acl/groups/' . md5(implode(',', $actionAclGroups));
     $actionGroups = cache::getCached($actionGroupsCacheKey);
     if (!$actionGroups) {
         if ($groupMapper === null) {
             $groupMapper = groupMapper::getInstance();
         }
         $cursor = $groupMapper->getAllBy([groupMapper::FIELD__GROUP_ALIAS => ['$in' => $actionAclGroups]]);
         $actionGroups = $this->expandGroupsByCursor($cursor);
         cache::setCached($actionGroupsCacheKey, $actionGroups, 3600);
     }
     $groups = array_unique($groups, SORT_ASC);
     $userGroupsCacheKey = 'acl/groups/' . md5(implode(',', $groups));
     $userGroups = cache::getCached($userGroupsCacheKey);
     if (!$userGroups) {
         if ($groupMapper === null) {
             $groupMapper = groupMapper::getInstance();
         }
         $cursor = $groupMapper->getAllBy([groupMapper::FIELD__GROUP_ALIAS => ['$in' => $groups]]);
         $userGroups = $this->expandGroupsByCursor($cursor);
         cache::setCached($userGroupsCacheKey, $userGroups, 3600);
     }
     $found = array_intersect($userGroups, $actionGroups);
     if (count($found) > 0) {
         return self::success($found, self::ACL__OK);
     } else {
         return self::error(['message' => 'Forbidden'], self::ACL__FORBIDDEN);
     }
 }
예제 #3
0
 /**
  * Render page by template file path
  *
  * @param string $template Path to template
  * @param bool $asString Return result as string
  * @param null|string $cache_id ID of template cache
  *
  * @return bool|string
  * @throws \Exception
  * @throws \SmartyException
  */
 public function render($template, $asString = true, $cache_id = null)
 {
     profiler::addStack('view::render');
     if ($asString) {
         return $this->fetch($template, $cache_id);
     } else {
         $this->display($template, $cache_id);
         return true;
     }
 }
예제 #4
0
 /**
  * WARNING! Clear all cache!
  *
  * @return bool
  */
 public function clear()
 {
     profiler::addStack('memcached::w');
     return $this->memcached->flush();
 }
예제 #5
0
 public function render($path, $params, $method = 'GET')
 {
     profiler::addStack('app::render');
     MPCMF_LL_DEBUG && self::log()->addDebug(__METHOD__ . '(' . json_encode(func_get_args(), 320) . ')');
     MPCMF_DEBUG && self::log()->addDebug('Rendering: ' . json_encode(func_get_args()));
     $matchedRoutes = $this->slim()->router()->getMatchedRoutes($method, $path . ($params ? '?' . http_build_query($params) : ''), true);
     /** @var Route $route */
     $route = reset($matchedRoutes);
     return $route->dispatch();
 }
예제 #6
0
파일: run.php 프로젝트: mpcmf/mpcmf-web
 public function childServer($addr)
 {
     $output = $this->output;
     $bindTo = json_decode($addr, true);
     $this->childHost = $bindTo['host'];
     $this->port = $bindTo['port'];
     cli_set_process_title("mpcmf/console server:run/child -b {$this->childHost} -p {$this->port}");
     posix_setgid(99);
     posix_setuid(99);
     posix_seteuid(99);
     posix_setegid(99);
     $loop = Factory::create();
     $socket = new reactSocketServer($loop);
     $http = new reactHttpServer($socket);
     $http->on('request', function (reactRequest $request, reactResponse $response) use($output) {
         //MPCMF_DEBUG && $output->writeln("<info>[CHILD:{$this->port}]</info> New connection");
         //MPCMF_DEBUG && $clientName = $request->getRemoteAddress() . '#' . spl_object_hash($request);
         //MPCMF_DEBUG && $output->writeln("<info>[{$clientName}] Client connected");
         profiler::resetStack();
         if (!$this->prepare($request, $response, $output)) {
             return;
         }
         //MPCMF_DEBUG && $output->writeln("<info>[{$clientName}] Starting application</info>");
         try {
             $app = $this->app();
             $slim = $app->slim();
             $originApplication = $this->applicationInstance->getCurrentApplication();
             $this->applicationInstance->setApplication($app);
             $slim->call();
         } catch (\Exception $e) {
             $response->writeHead(500);
             $response->end("Exception: {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}\n{$e->getTraceAsString()}");
             return;
         }
         /** @var int[]|Headers[]|string[] $content */
         $content = $slim->response->finalize();
         Util::serializeCookies($content[1], $slim->response->cookies, $slim->settings);
         $content[1] = $content[1]->all();
         $this->applicationInstance->setApplication($originApplication);
         //MPCMF_DEBUG && $output->writeln("<info>[{$clientName}] Ending application</info>");
         //MPCMF_DEBUG && $output->writeln("<info>[CHILD:{$this->port}]</info> Writing data and closing connection");
         static $serverSoftware;
         if ($serverSoftware === null) {
             $serverSoftware = 'MPCMF Async PHP ' . phpversion();
         }
         if (array_key_exists('HTTP_ACCEPT_ENCODING', $_SERVER) && strpos($_SERVER["HTTP_ACCEPT_ENCODING"], 'gzip') !== false) {
             $content[1]['Content-Encoding'] = 'gzip';
             $content[2] = gzencode($content[2], 9);
         }
         $content[1]['X-PHP-Server'] = $serverSoftware;
         $content[1]['X-PHP-Server-Addr'] = "{$this->childHost}:{$this->port}";
         $response->writeHead($content[0], $content[1]);
         $response->end($content[2]);
         //MPCMF_DEBUG && $output->writeln("<info>[CHILD:{$this->port}]</info> Connection closed");
     });
     $output->writeln("<error>[CHILD]</error> Starting child server on {$this->childHost}:{$this->port}");
     $socket->listen($this->port, $this->childHost);
     $loop->run();
 }
예제 #7
0
 /**
  * (PHP 5 &gt;= 5.1.0)<br/>
  * Construct the exception. Note: The message is NOT binary safe.
  * @link http://php.net/manual/en/exception.construct.php
  * @param string $message [optional] The Exception message to throw.
  * @param int $code [optional] The Exception code.
  * @param \Exception $previous [optional] The previous exception used for the exception chaining. Since 5.3.0
  *
  * @see \Exception
  */
 public function __construct($message = '', $code = 0, \Exception $previous = null)
 {
     profiler::addStack('mpcmf::exception');
     parent::__construct($message, $code, $previous);
 }
예제 #8
0
 /**
  * Check and create indexes by params
  *
  * @param string $db
  * @param string $collection
  * @param array  $indexes
  *
  * @throws \MongoConnectionException
  * @throws configurationException
  * @throws \InvalidArgumentException
  * @throws \Exception
  */
 public function checkIndexes($db, $collection, $indexes)
 {
     $log = self::log();
     $log->addDebug("Checking indexes for `{$collection}`");
     $collectionObject = $this->getMongo()->selectDB($db)->selectCollection($collection);
     $dbIndexes = $collectionObject->getIndexInfo();
     $needToCreate = [];
     $indexCount = count($dbIndexes);
     $needCreateAllIndexes = $indexCount <= 1;
     foreach ($indexes as $key => $index) {
         $log->addDebug('Checking index ' . json_encode($index));
         if ($needCreateAllIndexes) {
             $log->addInfo('NOT found index ' . json_encode($index));
             $needToCreate[$key] = true;
         } else {
             foreach ($dbIndexes as $dbIndex) {
                 if (json_encode($dbIndex['key']) === json_encode($index['keys'])) {
                     $log->addDebug('Found index ' . json_encode($index['keys']) . ', checking options...');
                     if (!empty($index['options'])) {
                         $log->addDebug('Options in cfg found');
                         $ok = true;
                         foreach ($index['options'] as $option => $optionValue) {
                             if (!isset($dbIndex[$option]) || $dbIndex[$option] !== $optionValue) {
                                 $log->addInfo('Option not found in dbIndex, need to create!');
                                 $ok = false;
                                 $needToCreate[$key] = true;
                             }
                         }
                         if ($ok) {
                             $log->addDebug('Index OK, skipping...');
                             unset($needToCreate[$key]);
                             break;
                         }
                     } else {
                         $log->addDebug('Options in cfg not found, Index OK, skipping...');
                         unset($needToCreate[$key]);
                         break;
                     }
                 } else {
                     $log->addInfo('Not found index ' . json_encode($index));
                     $needToCreate[$key] = true;
                 }
             }
         }
     }
     $log->addInfo('Need to create indexes: ' . count($needToCreate));
     foreach ($needToCreate as $key => $v) {
         profiler::addStack('mongo::i');
         $log->addInfo('Creating index ' . json_encode($indexes[$key]) . '...');
         if (array_key_exists('options', $indexes[$key])) {
             $collectionObject->ensureIndex($indexes[$key]['keys'], $indexes[$key]['options']);
         } else {
             $collectionObject->ensureIndex($indexes[$key]['keys']);
         }
         $log->addInfo('Index created ' . json_encode($indexes[$key]));
     }
 }
예제 #9
0
파일: config.php 프로젝트: mpcmf/mpcmf-core
 public static function getConfig($name, $environment = null)
 {
     static $currentEnvironment, $baseEnvironment;
     profiler::addStack('config::get');
     if ($currentEnvironment === null) {
         $currentEnvironment = environment::getCurrentEnvironment();
         MPCMF_LL_DEBUG && error_log("Initialize config current environment: {$currentEnvironment}");
     }
     if ($baseEnvironment === null) {
         $baseEnvironment = environment::getBaseEnvironment();
         MPCMF_LL_DEBUG && error_log("Initialize config base environment: {$baseEnvironment}");
     }
     if ($environment === null) {
         $environment = $currentEnvironment;
     }
     MPCMF_LL_DEBUG && error_log("Input environment: {$environment}");
     $packageName = self::getPackageName($name);
     class_exists('log') && log::factory()->addDebug("Loading config for {$packageName}");
     if (!isset(self::$loaded[$packageName])) {
         self::loadPackageConfig($packageName);
     }
     class_exists('log') && log::factory()->addDebug("Set by name: {$name} / env: {$environment}");
     if ($environment !== environment::ENV_DEFAULT) {
         if (isset(self::$loaded[$packageName][$currentEnvironment])) {
             MPCMF_LL_DEBUG && error_log("Return requested config [{$packageName}] {$currentEnvironment}");
             return self::$loaded[$packageName][$currentEnvironment];
         } elseif ($baseEnvironment !== environment::ENV_DEFAULT && isset(self::$loaded[$packageName][$baseEnvironment])) {
             MPCMF_LL_DEBUG && error_log("Use base config [{$packageName}] {$baseEnvironment}");
             return self::$loaded[$packageName][$baseEnvironment];
         } else {
             MPCMF_LL_DEBUG && error_log("Return default config [{$packageName}] {$currentEnvironment}");
             return self::$loaded[$packageName][environment::ENV_DEFAULT];
         }
     }
     MPCMF_LL_DEBUG && error_log("Return config [{$packageName}] " . environment::ENV_DEFAULT);
     return self::$loaded[$packageName][environment::ENV_DEFAULT];
 }