Example #1
0
 /**
  * @return void
  */
 protected function matchRoute()
 {
     if (isset($this->routeCollection)) {
         $context = new WebRequestContext();
         $context->fromWebRequest($this->request);
         $matcher = new RouteMatcher($this->routeCollection, $context);
         try {
             Logger::debug('Looking for route match: ' . $this->request->getPathInfo());
             $parameters = $matcher->match($this->request->getPathInfo());
             if (is_array($matcher->getRouteOption('parameters'))) {
                 $this->parameters = array_merge($this->parameters, $matcher->getRouteOption('parameters'));
             }
         } catch (ResourceNotFoundException $ex) {
             // Use our DefaultController
             $parameters = $this->getDefaultController();
         }
     } else {
         // no route to match against, so use the DefaultController
         $parameters = $this->getDefaultController();
     }
     if (!isset($parameters)) {
         Logger::alert('Route not found');
     } else {
         $this->parseRouteParameters($parameters);
         Logger::debug('Route matched: ' . $this->route);
     }
 }
Example #2
0
 /**
  * Tries to match a URL with a set of routes.
  * Will always return the first route that matches.
  *
  * @param string          $pathinfo The path info to be parsed
  * @param RouteCollection $routes   The set of routes
  *
  * @return array An array of parameters
  *
  * @throws ResourceNotFoundException If the resource could not be found
  * @throws MethodNotAllowedException method is not allowed
  */
 protected function matchCollection($pathinfo, RouteCollection $routes)
 {
     /**
      * @var $route \Symfony\Component\Routing\Route
      */
     foreach ($routes as $name => $route) {
         $compiledRoute = $route->compile();
         // check the static prefix of the URL first.
         // Only use the more expensive preg_match when it matches
         if ('' !== $compiledRoute->getStaticPrefix() && 0 !== strpos($pathinfo, $compiledRoute->getStaticPrefix())) {
             continue;
         }
         if (!preg_match($compiledRoute->getRegex(), $pathinfo, $matches)) {
             continue;
         }
         $hostMatches = array();
         if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
             continue;
         }
         // check HTTP method requirement
         if ($req = $route->getRequirement('_method')) {
             // HEAD and GET are equivalent as per RFC
             if ('HEAD' === ($method = $this->context->getMethod())) {
                 $method = 'GET';
             }
             if (!in_array($method, $req = explode('|', strtoupper($req)))) {
                 $this->allow = array_merge($this->allow, $req);
                 continue;
             }
         }
         // check device
         if (class_exists('\\Mobile_Detect') && $this->context->getDevice() instanceof \Mobile_Detect) {
             /**
              * @var $device \Mobile_Detect
              */
             $device = $this->context->getDevice();
             $deviceType = $device->isMobile() ? $device->isTablet() ? 'tablet' : 'mobile' : 'computer';
             if ($route->getOption('device') && $route->getOption('device') != $deviceType) {
                 continue;
             }
             /**
              * Test for a specific mobile OS
              */
             if ($routeOS = $route->getOption('os')) {
                 $deviceOS = $this->matchDeviceOS($routeOS, $device);
                 if ($deviceOS) {
                     Logger::info("Matched RouteOS: " . $deviceOS);
                 } else {
                     continue;
                 }
             }
             /**
              * Test for a specific mobile/tablet type (brand)
              * eg iPhone, BlackBerry, HTC, Dell, etc
              */
             if ($device->isMobile() && !$device->isTablet() && ($routeType = $route->getOption('type'))) {
                 $phoneType = $this->matchPhoneType($routeType, $device);
                 if ($phoneType) {
                     Logger::info("Matched RouteType: " . $phoneType);
                 } else {
                     continue;
                 }
             } elseif ($device->isTablet() && ($routeType = $route->getOption('type'))) {
                 $tabletType = $this->matchTabletType($routeType, $device);
                 if ($tabletType) {
                     Logger::info("Matched RouteType: " . $tabletType);
                 } else {
                     continue;
                 }
             }
         }
         $status = $this->handleRouteRequirements($pathinfo, $name, $route);
         if (self::ROUTE_MATCH === $status[0]) {
             return $status[1];
         }
         if (self::REQUIREMENT_MISMATCH === $status[0]) {
             continue;
         }
         return $this->getAttributes($route, $name, array_replace($matches, $hostMatches));
     }
     return false;
 }
Example #3
0
 /**
  * Exits this process if there is already one running (this one makes 2)
  *
  * @return void
  */
 protected function thereCanBeOnlyOne()
 {
     $controller = $this->__toString();
     $parts = preg_split('/[^a-zA-Z0-9]{1,}/', $controller);
     $regex = join('[^a-zA-Z0-9]{1,2}', $parts);
     $cmd = 'ps ax | grep -v grep | egrep -c "' . $regex . '"';
     $res = `{$cmd}`;
     if (intval($res) > 1) {
         Logger::critical('Unable to launch : Process already running');
         exit(1);
     }
 }
 public function testWebFactory()
 {
     $project = ProjectFactory::build('synergy-test', ProjectType::WEB, Logger::getLogger());
     $this->assertInstanceOf('Synergy\\Project\\Web\\WebProject', $project);
     $project->run();
 }
Example #5
0
 /**
  * Run our CLI Project
  *
  * @return void
  */
 protected function launch()
 {
     $this->loadBootstrap();
     $router = new CliRouter($this->request);
     $router->match();
     /**
      * Get the ControllerEntity
      */
     $this->controller = $router->getController();
     Logger::notice('Calling: ' . $this->controller->getClassName() . '::' . $this->controller->getMethodName());
     // pass the parameters
     $this->controller->setParameters($this->parameters);
     // Call the action
     $response = $this->controller->callControllerAction();
 }
Example #6
0
 /**
  * Save a cached file of the output
  *
  * @param $content
  */
 protected function writeCacheFile($content)
 {
     $dir = $this->temp_dir . DIRECTORY_SEPARATOR . 'synergy';
     Logger::debug('Synergy cache dir: ' . $dir);
     if (!is_dir($dir)) {
         Tools::mkdir($dir);
     }
     $file = $dir . DIRECTORY_SEPARATOR . md5($this->request->getUri()) . '.syn';
     $fh = fopen($file, 'w');
     fputs($fh, $content, strlen($content));
     @fclose($fh);
     if (!$this->isDev && $this->useGzip()) {
         Logger::info('Compressing response');
         $zp = gzopen($file . '.gz', 'w9');
         gzwrite($zp, $content);
         gzclose($zp);
         // remove gzip file if it's bigger than the unzipped file
         if (filesize($file . '.gz') > filesize($file)) {
             unlink($file . '.gz');
         }
     }
 }
Example #7
0
 /**
  * Daemonises the process
  */
 protected function fork_to_bg()
 {
     $daemon_pid = pcntl_fork();
     switch ($daemon_pid) {
         case -1:
             Logger::emergency('Unable to fork daemon process');
             exit(1);
             // fork failed
         // fork failed
         case 0:
             // this child is our daemon
             $this->process_pid = getmypid();
             break;
         default:
             // we are the parent - the one from the FG command line
             // return control to command line by exiting...
             \Cli\line('Daemon process running : pid=%y' . $daemon_pid . '%n');
             exit(0);
     }
     // promote the daemon process so it doesn't die because the parent has
     if (posix_setsid() === -1) {
         Logger::critical('Error creating daemon as session leader');
         exit(1);
     }
     fclose(STDIN);
     fclose(STDOUT);
     fclose(STDERR);
     $this->_stdIn = fopen('/dev/null', 'r');
     // set fd/0
     $this->_stdOut = fopen('/dev/null', 'w');
     // set fd/1
     $this->_stdErr = fopen('php://stdout', 'w');
     // a hack to duplicate fd/1 to 2
     // Silence any console output from the logger
     Logger::setSilentConsole(true);
     Logger::notice('Daemon process running : pid=' . getmypid());
 }
Example #8
0
 /**
  * Location of the template cache directory
  *
  * @param string $dir absolute location of the template cache directory
  *
  * @return void
  */
 public function setCacheDir($dir)
 {
     $dir .= DIRECTORY_SEPARATOR . 'smarty';
     Logger::debug("Smarty cache dir set to: " . $dir);
     parent::setCacheDir($dir);
 }
Example #9
0
 /**
  * Try to match an asset file in our templateDir
  *
  * @param string $matchDir
  * @param string $file
  *
  * @return WebAsset|void
  */
 protected function matchAsset($matchDir, $file)
 {
     if (strpos($file, '_synergy_')) {
         // internal asset request
         $matchDir = SYNERGY_LIBRARY_PATH . DIRECTORY_SEPARATOR . 'View' . DIRECTORY_SEPARATOR . '_synergy_';
         $file = substr($file, 10);
     }
     $testfile = $matchDir . $file;
     if (file_exists($testfile) && is_readable($testfile)) {
         $asset = new WebAsset($testfile);
         Logger::debug("Asset found: {$file}");
         return $asset;
     }
 }
Example #10
0
 /**
  * An alias for Synergy\Logger\Logger::getLogger()
  *
  * @return LoggerInterface
  */
 public static function getLogger()
 {
     return Logger::getLogger();
 }
Example #11
0
 /**
  * filename of the main config file
  *
  * @param string $filename filename of the main config file
  *
  * @return void
  * @throws InvalidArgumentException
  */
 public function setConfigFilename($filename)
 {
     if (!file_exists($filename)) {
         throw new InvalidArgumentException(sprintf("Missing file %s", $filename));
     } else {
         if (!is_readable($filename)) {
             throw new InvalidArgumentException(sprintf("File %s not readable", $filename));
         } else {
             $extension = pathinfo($filename, PATHINFO_EXTENSION);
             switch (strtolower($extension)) {
                 case 'yml':
                     $this->configFilename = $filename;
                     $this->options = \Spyc::YAMLLoad($filename);
                     Logger::debug('Config file: ' . $filename);
                     break;
                 default:
                     throw new InvalidArgumentException(sprintf("Config file format is not supported", $filename));
             }
         }
     }
 }
Example #12
0
 /**
  * Sends the error to our Debug object
  *
  * @static
  */
 protected static function handler($LogLevel = null)
 {
     if (isset(self::$errNum)) {
         $text = '';
         if (isset(self::$trace)) {
             foreach (self::$trace as $traceItem) {
                 // Look for a BREAK file
                 if (self::$trace[count(self::$trace) - 1]['class'] == 'Synergy\\Project\\ProjectAbstract' || self::$trace[count(self::$trace) - 2]['class'] == 'Synergy\\Project\\ProjectAbstract') {
                     if (defined('SYNERGY_LIBRARY_PATH') && isset($traceItem['file']) && ($file = str_ireplace(realpath(SYNERGY_LIBRARY_PATH) . DIRECTORY_SEPARATOR, '', $traceItem['file']))) {
                         if (in_array($file, self::$_aBreakFiles)) {
                             break;
                             // stop iterating through the trace
                         }
                     }
                 }
                 // Clean up the filename to make it relative
                 if (defined('SYNERGY_ROOT_DIR') && isset($traceItem['file'])) {
                     $traceItem['file'] = str_ireplace(realpath(SYNERGY_ROOT_DIR) . DIRECTORY_SEPARATOR, '', $traceItem['file']);
                 }
                 foreach ($traceItem as $key => $val) {
                     if ($key == 'type' && ($val == '::' || $val == '->')) {
                         continue;
                     }
                     $text .= sprintf(" [%s] => %s\n", $key, $val);
                 }
                 $text .= "\n";
             }
             if ($text != '') {
                 $text = sprintf("%s\n\nTrace:\n\n", self::$errMsg) . $text;
             }
         } else {
             $text = sprintf("%s", self::$errMsg);
         }
         if ($LogLevel === null) {
             /**
              * Convert the PHP error number to a Psr compatible LogLevel
              */
             switch (self::$errNum) {
                 case 1:
                 case 256:
                     $dbgLevel = LogLevel::CRITICAL;
                     break;
                 case 2:
                 case 512:
                     $dbgLevel = LogLevel::WARNING;
                     break;
                 case 8:
                 case 1024:
                     $dbgLevel = LogLevel::NOTICE;
                     break;
                 case 2048:
                 case 8192:
                     $dbgLevel = LogLevel::ALERT;
                     break;
                 case 16:
                     $dbgLevel = LogLevel::CRITICAL;
                     break;
                 default:
                     $dbgLevel = LogLevel::ERROR;
             }
         } else {
             $dbgLevel = $LogLevel;
         }
         // Log it through our Project Logger
         Logger::log($dbgLevel, $text, array('filename' => self::$fileName, 'linenum' => self::$lineNum, 'level' => $dbgLevel));
     }
 }