Exemplo n.º 1
1
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $path = $input->getArgument('path');
     if (!file_exists($path)) {
         $output->writeln("{$path} is not a file or a path");
     }
     $filePaths = [];
     if (is_file($path)) {
         $filePaths = [realpath($path)];
     } elseif (is_dir($path)) {
         $filePaths = array_diff(scandir($path), array('..', '.'));
     } else {
         $output->writeln("{$path} is not known.");
     }
     $generator = new StopwordGenerator($filePaths);
     if ($input->getArgument('type') === 'json') {
         echo json_encode($this->toArray($generator->getStopwords()), JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
         echo json_last_error_msg();
         die;
         $output->write(json_encode($this->toArray($generator->getStopwords())));
     } else {
         $stopwords = $generator->getStopwords();
         $stdout = fopen('php://stdout', 'w');
         echo 'token,freq' . PHP_EOL;
         foreach ($stopwords as $token => $freq) {
             fputcsv($stdout, [utf8_encode($token), $freq]) . PHP_EOL;
         }
         fclose($stdout);
     }
 }
 public function actionRun()
 {
     $queueName = Yii::$app->apnsGcm->queueName;
     $amqp = Yii::$app->amqp;
     $channel = $amqp->getChannel();
     $channel->queue_declare($queueName, false, true, false, false);
     $message = $channel->basic_get($queueName);
     if (empty($message) || !isset($message->body)) {
         return Controller::EXIT_CODE_NORMAL;
     }
     $body = json_decode($message->body);
     if (!$body) {
         $channel->basic_ack($message->delivery_info['delivery_tag']);
         Yii::error('Has no body. json: ' . json_last_error_msg(), 'ApnsGcm');
         return Controller::EXIT_CODE_ERROR;
     }
     // Log data
     Yii::info($message->body, 'ApnsGcm');
     /* @var $apnsGcm \bryglen\apnsgcm\ApnsGcm */
     Yii::$app->apnsGcm->sendMulti($body->type, (array) $body->tokens, $body->text, $body->payloadData, $body->args);
     if (!Yii::$app->apnsGcm->success) {
         Yii::error('Error send push: ' . var_export(Yii::$app->apnsGcm->error, true), 'ApnsGcm');
         return Controller::EXIT_CODE_ERROR;
     }
     $channel->basic_ack($message->delivery_info['delivery_tag']);
     $channel->close();
     return Controller::EXIT_CODE_NORMAL;
 }
Exemplo n.º 3
0
 public function __construct($configFile, $env = '@')
 {
     $this->config = new \stdClass();
     if (!file_exists($configFile)) {
         throw new ConfigException('Configruation file not found: ' . $configFile);
     }
     $config = json_decode(file_get_contents($configFile));
     if ($config === null) {
         $msg = 'Configruation file failed to parse: ' . $configFile . ', with error: ' . json_last_error_msg();
         throw new ConfigException($msg);
     }
     if (!isset($config->{'@'})) {
         throw new ConfigException('Missing "@" section in parsed config: ' . $configFile);
     }
     // If modules is defined, copy to own variable
     if (isset($config->__modules__)) {
         $this->modules = $config->__modules__;
     }
     // Att default values to config
     $this->addValue('tmpConfig', $config->{'@'}, $this);
     if (isset($config->{$env})) {
         $config = [$env => $config->{$env}];
     }
     foreach ($config as $key => $value) {
         if (fnmatch($key, $env)) {
             $this->addValue('tmpConfig', $value, $this);
         }
     }
     $this->loadConfigModules();
     $this->addValue('config', $this->tmpConfig, $this);
     unset($this->tmpConfig);
 }
Exemplo n.º 4
0
 /**
  * Load language pack resources from the given directory.
  *
  * @param string $directory
  */
 public function loadLanguagePackFrom($directory)
 {
     $name = $title = basename($directory);
     if (file_exists($manifest = $directory . '/composer.json')) {
         $json = json_decode(file_get_contents($manifest), true);
         if (empty($json)) {
             throw new RuntimeException("Error parsing composer.json in {$name}: " . json_last_error_msg());
         }
         $locale = array_get($json, 'extra.flarum-locale.code');
         $title = array_get($json, 'extra.flarum-locale.title', $title);
     }
     if (!isset($locale)) {
         throw new RuntimeException("Language pack {$name} must define \"extra.flarum-locale.code\" in composer.json.");
     }
     $this->locales->addLocale($locale, $title);
     if (!is_dir($localeDir = $directory . '/locale')) {
         throw new RuntimeException("Language pack {$name} must have a \"locale\" subdirectory.");
     }
     if (file_exists($file = $localeDir . '/config.js')) {
         $this->locales->addJsFile($locale, $file);
     }
     if (file_exists($file = $localeDir . '/config.css')) {
         $this->locales->addCssFile($locale, $file);
     }
     foreach (new DirectoryIterator($localeDir) as $file) {
         if ($file->isFile() && in_array($file->getExtension(), ['yml', 'yaml'])) {
             $this->locales->addTranslations($locale, $file->getPathname());
         }
     }
 }
Exemplo n.º 5
0
 /**
  * Retrieve the current version available remotely.
  *
  * @param Updater $updater
  * @return string|bool
  */
 public function getCurrentRemoteVersion(Updater $updater)
 {
     /** Switch remote request errors to HttpRequestExceptions */
     set_error_handler(array($updater, 'throwHttpRequestException'));
     $packageUrl = $this->getApiUrl();
     $package = json_decode(humbug_get_contents($packageUrl), true);
     restore_error_handler();
     if (null === $package || json_last_error() !== JSON_ERROR_NONE) {
         throw new JsonParsingException('Error parsing JSON package data' . (function_exists('json_last_error_msg') ? ': ' . json_last_error_msg() : ''));
     }
     $versions = array_keys($package['package']['versions']);
     $versionParser = new VersionParser($versions);
     if ($this->getStability() === self::STABLE) {
         $this->remoteVersion = $versionParser->getMostRecentStable();
     } elseif ($this->getStability() === self::UNSTABLE) {
         $this->remoteVersion = $versionParser->getMostRecentUnstable();
     } else {
         $this->remoteVersion = $versionParser->getMostRecentAll();
     }
     /**
      * Setup remote URL if there's an actual version to download
      */
     if (!empty($this->remoteVersion)) {
         $this->remoteUrl = $this->getDownloadUrl($package);
     }
     return $this->remoteVersion;
 }
Exemplo n.º 6
0
 public function postJson($url, array $data = [], array $headers = [], $decode_flags = 0)
 {
     $curlHeaders = [];
     if (!isset($headers['content-type'])) {
         $headers['content-type'] = 'application/json';
     }
     foreach ($headers as $k => $v) {
         $curlHeaders[] = $k . ': ' . $v;
     }
     $ch = $this->getHandle($url, [CURLOPT_POSTFIELDS => json_encode($data), CURLOPT_HTTPHEADER => $curlHeaders]);
     $res = curl_exec($ch);
     if (!$res) {
         throw new \RuntimeException('Empty response; ' . json_encode(curl_getinfo($ch)));
     }
     // discard sets of headers prior to the final one...and make sure the body doesn't
     // include stray headers (e.g. if running through a proxy that emits an initial 200
     // on-connect)
     $body = $res;
     do {
         list($rawHeaders, $body) = explode("\r\n\r\n", $body, 2);
     } while (strpos($body, 'HTTP/') === 0 && strpos($body, "\r\n\r\n") !== false);
     $resHeaders = [];
     foreach (array_slice(explode("\r\n", $rawHeaders), 1) as $rawHeader) {
         list($key, $value) = explode(': ', $rawHeader, 2);
         $resHeaders[$key] = $value;
     }
     $decoded = json_decode($body, $decode_flags);
     if ($decoded === false || $decoded === null) {
         throw new \RuntimeException('JSON decoding error: ' . json_last_error_msg());
     }
     return new HttpResponse($decoded, $resHeaders, curl_getinfo($ch, CURLINFO_HTTP_CODE));
 }
Exemplo n.º 7
0
 public function __construct($jsonString, $check = true)
 {
     if ($check && false !== @json_decode($jsonString) && (bool) json_last_error()) {
         throw new \InvalidArgumentException(sprintf("Invalid JSON provided: %s", json_last_error_msg()));
     }
     $this->jsonString = $jsonString;
 }
Exemplo n.º 8
0
 public function submit()
 {
     check_ajax_referer('ninja_forms_display_nonce', 'security');
     register_shutdown_function(array($this, 'shutdown'));
     if (!$this->_form_data) {
         if (function_exists('json_last_error') && function_exists('json_last_error_msg') && json_last_error()) {
             $this->_errors[] = json_last_error_msg();
         } else {
             $this->_errors[] = __('An unexpected error occurred.', 'ninja-forms');
         }
         $this->_respond();
     }
     $this->_form_id = $this->_data['form_id'] = $this->_form_data['id'];
     if (isset($this->_form_data['settings']['is_preview']) && $this->_form_data['settings']['is_preview']) {
         $this->_preview_data = get_user_option('nf_form_preview_' . $this->_form_id);
         // Add preview field keys to form data.
         foreach ($this->_form_data['fields'] as $key => $field) {
             $field_id = $field['id'];
             $this->_form_data['fields'][$key]['key'] = $this->_preview_data['fields'][$field_id]['settings']['key'];
         }
         if (!$this->_preview_data) {
             $this->_errors['preview'] = __('Preview does not exist.', 'ninja-forms');
             $this->_respond();
         }
     }
     $this->_data['settings'] = $this->_form_data['settings'];
     $this->_data['extra'] = $this->_form_data['extra'];
     $this->_data['fields'] = $this->_form_data['fields'];
     $this->_data = apply_filters('ninja_forms_submit_data', $this->_data);
     $this->validate_fields();
     $this->process_fields();
     $this->process();
 }
Exemplo n.º 9
0
 /**
  * Parses the command from string
  *
  * @param string $commandString Raw command string
  *
  * @return Command
  * @throws ProtocolException If parsing fails
  */
 public function parseCommand($commandString)
 {
     $data = json_decode($commandString, true);
     if (json_last_error() !== JSON_ERROR_NONE) {
         throw new ProtocolException('Json decode fail: ' . json_last_error_msg());
     }
     if (!is_array($data)) {
         throw new ProtocolException('Command data is not an array');
     }
     if (!isset($data['type']) || !$data['type']) {
         throw new ProtocolException('Command type not given');
     }
     $class = 'Bttw\\Infrastructure\\Command\\' . $data['type'];
     if (!class_exists($class)) {
         throw new ProtocolException('Command class does not exist');
     }
     switch ($class) {
         case GetBaskets::class:
             return new GetBaskets();
         case GetSolution::class:
             return new GetSolution();
         case PutBall::class:
             if (!isset($data['ballNumber'])) {
                 throw new ProtocolException('Ball number not given');
             }
             return new PutBall($data['ballNumber']);
         default:
             throw new ProtocolException('Unknown command type given');
     }
 }
Exemplo n.º 10
0
 /**
  * @param string $file
  * @param bool $assoc
  * @param int $depth
  * @param int $options
  *
  * @throws RuntimeException
  * @throws LogicException
  *
  * @return mixed
  */
 protected function loadJsonFile($file, $assoc = false, $depth = 512, $options = 0)
 {
     $base_error = 'Can\'t find load JSON in file: ' . $file . ', ';
     if (!file_exists($file)) {
         throw new LogicException($base_error . 'does not exist.');
     }
     $file_content = file_get_contents($file);
     /**
      * Support iso to UTF-8
      */
     if (!mb_detect_encoding($file_content, 'UTF-8', true)) {
         $file_content = mb_convert_encoding($file_content, 'UTF-8', mb_detect_encoding($file_content, 'auto'));
         if (!mb_detect_encoding($file_content, 'UTF-8', true)) {
             throw new \RuntimeException($base_error . ' is not UTF-8 compatible or can not be converted to UTF-8.');
         }
     }
     /**
      * support for different parameters.
      */
     if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
         $data = json_decode($file_content, $assoc, $depth, $options);
     } elseif (version_compare(PHP_VERSION, '5.3.0') >= 0) {
         $data = json_decode($file_content, $assoc, $depth);
     } else {
         $data = json_decode($file_content, $assoc);
     }
     if (json_last_error()) {
         throw new RuntimeException($base_error . 'json error:' . json_last_error_msg(), json_last_error());
     }
     return $data;
 }
Exemplo n.º 11
0
 function data()
 {
     // Sanitize the GET variables here.
     $cfg = array('columns' => array(), 'order' => array(), 'start' => 0, 'length' => -1, 'draw' => 0, 'search' => '', 'where' => '', 'mrColNotEmpty' => '');
     //echo '<pre>';print_r($_GET);return;
     $searchcols = array();
     // Process $_POST array
     foreach ($_POST as $k => $v) {
         if ($k == 'search') {
             $cfg['search'] = $v['value'];
         } elseif (isset($cfg[$k])) {
             $cfg[$k] = $v;
         }
     }
     // endforeach
     // Add columns to config
     $cfg['search_cols'] = $searchcols;
     //echo '<pre>';print_r($cfg);
     try {
         // Get model
         $obj = new Tablequery($cfg);
         //echo '<pre>';print_r($obj->fetch($cfg));
         echo json_encode($obj->fetch($cfg));
         // If there is an encoding error, show it
         if (json_last_error() != JSON_ERROR_NONE) {
             echo json_last_error_msg();
             print_r($obj->fetch($cfg));
         }
     } catch (Exception $e) {
         echo json_encode(array('error' => $e->getMessage(), 'draw' => intval($cfg['draw'])));
     }
 }
Exemplo n.º 12
0
 private function configureResponseHandler(HandlerStack $handlerStack)
 {
     $handlerStack->remove('wechatClient:response');
     $handlerStack->push(function (callable $handler) {
         return function (RequestInterface $request, array $options = []) use($handler) {
             return $handler($request, $options)->then(function (ResponseInterface $response) use($request) {
                 // Non-success page, so we won't attempt to parse.
                 if ($response->getStatusCode() >= 300) {
                     return $response;
                 }
                 // Check if the response should be JSON decoded
                 $parse = ['application/json', 'text/json', 'text/plain'];
                 if (preg_match('#' . implode('|', $parse) . '#', $response->getHeaderLine('Content-Type')) < 1) {
                     return $response;
                 }
                 // Begin parsing JSON body.
                 $body = (string) $response->getBody();
                 $json = json_decode($body);
                 if (json_last_error() !== JSON_ERROR_NONE) {
                     throw new BadResponseFormatException(json_last_error_msg(), json_last_error());
                 }
                 if (isset($json->errcode) && $json->errcode != 0) {
                     $message = isset($json->errmsg) ? $json->errmsg : '';
                     $code = $json->errcode;
                     throw new APIErrorException($message, $code, $request, $response);
                 }
                 return $response;
             });
         };
     }, 'wechatClient:response');
 }
Exemplo n.º 13
0
 function query($path, $content = array(), $method = 'GET')
 {
     @ini_set('track_errors', 1);
     // @ - may be disabled
     $file = @file_get_contents($this->_url . ($this->_db != "" ? "{$this->_db}/" : "") . $path, false, stream_context_create(array('http' => array('method' => $method, 'content' => json_encode($content), 'ignore_errors' => 1))));
     if (!$file) {
         $this->error = $php_errormsg;
         return $file;
     }
     if (!preg_match('~^HTTP/[0-9.]+ 2~i', $http_response_header[0])) {
         $this->error = $file;
         return false;
     }
     $return = json_decode($file, true);
     if (!$return) {
         $this->errno = json_last_error();
         if (function_exists('json_last_error_msg')) {
             $this->error = json_last_error_msg();
         } else {
             $constants = get_defined_constants(true);
             foreach ($constants['json'] as $name => $value) {
                 if ($value == $this->errno && preg_match('~^JSON_ERROR_~', $name)) {
                     $this->error = $name;
                     break;
                 }
             }
         }
     }
     return $return;
 }
Exemplo n.º 14
0
 /**
  * Create an exception based on error codes returned by json_last_error function
  *
  * @param int $error A JSON error constant, as returned by json_last_error()
  * @see http://www.php.net/manual/en/function.json-last-error.php
  */
 public function __construct($error)
 {
     $message = 'Error while parsing Json configuration file: ';
     if (!function_exists('json_last_error_msg')) {
         switch ($error) {
             case JSON_ERROR_DEPTH:
                 $message .= 'maximum stack depth exceeded';
                 break;
             case JSON_ERROR_STATE_MISMATCH:
                 $message .= 'underflow or the modes mismatch';
                 break;
             case JSON_ERROR_CTRL_CHAR:
                 $message .= 'unexpected control character found';
                 break;
             case JSON_ERROR_SYNTAX:
                 $message .= 'syntax error, malformed JSON';
                 break;
             case JSON_ERROR_UTF8:
                 $message .= 'malformed UTF-8 characters, possibly incorrectly encoded';
                 break;
             default:
                 $message .= 'unknown error';
                 break;
         }
     } else {
         $message .= json_last_error_msg();
     }
     parent::__construct($message);
 }
Exemplo n.º 15
0
 /**
  * @param Request $request
  *
  * @throws ValidationException
  * @throws MalformedContentException
  */
 public function process(Request $request)
 {
     if (!$request->attributes->has(RequestMeta::ATTRIBUTE_URI)) {
         throw new \UnexpectedValueException("Missing document URI");
     }
     $description = $this->repository->get($request->attributes->get(RequestMeta::ATTRIBUTE_URI));
     $operation = $description->getPath($request->attributes->get(RequestMeta::ATTRIBUTE_PATH))->getOperation($request->getMethod());
     $body = null;
     if ($request->getContent()) {
         $body = json_decode($request->getContent());
         if (json_last_error() !== JSON_ERROR_NONE) {
             throw new MalformedContentException(json_last_error_msg());
         }
     }
     $result = $this->validator->validate($operation->getRequestSchema(), $coercedParams = $this->parametersAssembler->assemble($operation, $request->query->all(), $request->attributes->all(), $request->headers->all(), $body));
     foreach ($coercedParams as $attribute => $value) {
         /** @var ScalarSchema  $schema*/
         if (($schema = $operation->getParameter($attribute)->getSchema()) instanceof ScalarSchema) {
             if ($schema->isDateTime()) {
                 $value = $this->dateTimeSerializer->deserialize($value, $schema);
             }
         }
         $request->attributes->set($attribute, $value);
     }
     if ($this->hydrator && ($bodyParam = $description->getRequestBodyParameter($operation->getPath(), $operation->getMethod()))) {
         $body = $this->hydrator->hydrate($body, $bodyParam->getSchema());
         $request->attributes->set($bodyParam->getName(), $body);
     }
     $request->attributes->set(RequestMeta::ATTRIBUTE, new RequestMeta($description, $operation));
     if (!$result->isValid()) {
         throw new ValidationException($result->getErrorMessages());
     }
 }
Exemplo n.º 16
0
 /**
  * Запрос к API
  *
  * @param array $params
  * @return mixed|string
  */
 protected function sendRequest($params = array())
 {
     try {
         $curl = curl_init($this->endpoint);
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($curl, CURLOPT_POST, true);
         curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
         $response = curl_exec($curl);
         if ($response === false) {
             throw new \Exception(curl_errno($curl) . ': ' . curl_error($curl));
         }
         curl_close($curl);
         $result = json_decode($response);
         if (json_last_error()) {
             throw new \Exception(json_last_error() . ': ' . json_last_error_msg());
         }
         if ($result->code) {
             throw new \Exception($result->code . ': ' . $result->msg);
         }
         return $result;
     } catch (\Exception $e) {
         $this->error = true;
         return $e->getMessage();
     }
 }
Exemplo n.º 17
0
 /**
  * @inheritdoc
  * @throws Api_Exception_ParserError
  */
 public function getRate($targetIso, $sourceIso)
 {
     try {
         $url = $this->_getApiUrl($targetIso, $sourceIso);
         $data = json_decode(file_get_contents($url), true);
     } catch (\Exception $e) {
         $data = null;
     }
     if (!$data) {
         throw new Api_Exception_ParserError('No API request');
     }
     if (json_last_error()) {
         throw new Api_Exception_ParserError(json_last_error_msg());
     }
     if (!isset($data['query'])) {
         throw new Api_Exception_ParserError('Wrong APIs request: no body');
     }
     $data = $data['query'];
     if (!isset($data['results']) || empty($data['results']['rate'])) {
         return null;
     }
     $rate = $data['results']['rate'];
     if (!isset($rate['Rate'])) {
         throw new Api_Exception_ParserError('Wrong APIs request: wrong structure, no rate');
     }
     return (double) $rate['Rate'];
 }
Exemplo n.º 18
0
 protected function execute($uri, array $parameters)
 {
     $parameters['key'] = YANDEX_TRANSLATE_KEY;
     curl_setopt($this->handler, CURLOPT_URL, static::BASE_URL . $uri);
     curl_setopt($this->handler, CURLOPT_POST, true);
     curl_setopt($this->handler, CURLOPT_POSTFIELDS, http_build_query($parameters));
     $remoteResult = curl_exec($this->handler);
     if ($remoteResult === false) {
         throw new \Exception(curl_error($this->handler), curl_errno($this->handler));
     }
     $result = json_decode($remoteResult, true);
     if (!$result) {
         $errorMessage = self::MESSAGE_UNKNOWN_ERROR;
         if (version_compare(PHP_VERSION, '5.3', '>=')) {
             if (json_last_error() !== JSON_ERROR_NONE) {
                 if (version_compare(PHP_VERSION, '5.5', '>=')) {
                     $errorMessage = json_last_error_msg();
                 } else {
                     $errorMessage = self::MESSAGE_JSON_ERROR;
                 }
             }
         }
         throw new \Exception(sprintf('%s: %s', self::MESSAGE_INVALID_RESPONSE, $errorMessage));
     } elseif (isset($result['code']) && $result['code'] > 200) {
         throw new \Exception($result['message'], $result['code']);
     }
     return $result;
 }
Exemplo n.º 19
0
 public function respondError($msg, $code = 500)
 {
     switch ($code) {
         case 400:
             header("HTTP/1.0 400 Bad Request");
             break;
             break;
         case 401:
             header("HTTP/1.0 401 Unauthorized");
             break;
             break;
         default:
         case 500:
             header("HTTP/1.0 500 Internal Server Error.");
             break;
     }
     $json = json_encode(array("error" => true, "error_code" => $code, "error_msg" => $msg));
     if ($json === false) {
         header("HTTP/1.0 500 Internal Server Error.");
         $msg = 'JSON encoding error ' . json_last_error() . ': ' . json_last_error_msg();
         echo json_encode(array("error" => true, "error_code" => 500, "error_msg" => $msg));
         exit;
     }
     echo $json;
     exit;
 }
Exemplo n.º 20
0
 public function run()
 {
     $reqId = (int) $this->httpRequest->postData('id');
     $reqsData = json_decode($this->httpRequest->postData('data'), true);
     if (json_last_error() !== JSON_ERROR_NONE) {
         //Try with stripslashes()
         $reqsData = json_decode(stripslashes($this->httpRequest->postData('data')), true);
         if (json_last_error() !== JSON_ERROR_NONE) {
             $errMsg = '#' . json_last_error();
             if (function_exists('json_last_error_msg')) {
                 $errMsg .= ' ' . json_last_error_msg();
             }
             throw new \RuntimeException('Malformed JSON-encoded request (' . $errMsg . ')', 400);
         }
     }
     $responses = array();
     foreach ($reqsData as $requestData) {
         $apiCall = new Api();
         $apiCall->emulate($requestData, $this->httpRequest);
         $apiCall->run();
         $responses[] = $apiCall->httpResponse()->content();
     }
     $resp = new ApiGroupResponse();
     $resp->setResponses($responses);
     $resp->setId($reqId);
     $this->httpResponse->addHeader('Content-Type: application/json');
     if ($resp->cacheable()) {
         $this->httpResponse->setCacheable();
     }
     $this->httpResponse->setContent($resp);
 }
Exemplo n.º 21
0
 /**
  * @param Request     $request
  * @param Application $app
  *
  * @return Response
  *
  * @throws \Exception
  */
 public function installAction(Request $request, Application $app)
 {
     $installer = json_decode($request->getContent(), true);
     $app['logger']->info('Install Callback');
     if (json_last_error()) {
         $app['logger']->error('Install JSON Error: ' . json_last_error_msg());
         throw new \Exception('JSON Error');
     }
     $oauthId = $this->getInstallValue($installer, 'oauthId');
     $oauthSecret = $this->getInstallValue($installer, 'oauthSecret');
     $groupId = $this->getInstallValue($installer, 'groupId', true);
     $roomId = $this->getInstallValue($installer, 'roomId', true);
     if ($oauthId === null || $oauthSecret === null || $groupId === null) {
         throw new \Exception('Invalid installation request');
     }
     $app['logger']->debug(sprintf('Got oauthId "%s" and oauthSecret "%s"', $oauthId, $oauthSecret));
     /* @var Registry $registry */
     $registry = $app['hc.api_registry'];
     $registry->install($oauthId, $oauthSecret, $groupId, $roomId);
     /** @var \Venyii\HipChatCommander\Api\Client $client */
     $client = $app['hc.api_client']($oauthId);
     try {
         // fetch auth token
         $authToken = $client->renewAuthToken($oauthId, $oauthSecret);
         $app['logger']->debug(sprintf('Got authToken "%s"', $authToken));
     } catch (\Exception $e) {
         $registry->uninstall($oauthId);
         throw $e;
     }
     return new Response(null, 200);
 }
Exemplo n.º 22
0
 public function encode($value)
 {
     if (false === ($encoded = json_encode($value, $this->options, $this->depth))) {
         throw new JsonEncodingException(json_last_error_msg(), json_last_error());
     }
     return $encoded;
 }
Exemplo n.º 23
0
 public function load($json, \Dice\Dice $dice = null)
 {
     if ($dice === null) {
         $dice = new \Dice\Dice();
     }
     if (trim($json)[0] != '{') {
         $path = dirname(realpath($json));
         $json = str_replace('__DIR__', $path, file_get_contents($json));
     }
     $map = json_decode($json, true);
     if (!is_array($map)) {
         throw new \Exception('Could not decode json: ' . json_last_error_msg());
     }
     if (isset($map['rules'])) {
         foreach ($map['rules'] as $rule) {
             $name = $rule['name'];
             unset($rule['name']);
             $dice->addRule($name, $rule);
         }
     } else {
         foreach ($map as $name => $rule) {
             $dice->addRule($name, $rule);
         }
     }
     return $dice;
 }
Exemplo n.º 24
0
 /** constructor */
 public function __construct()
 {
     $this->error_code = json_last_error();
     if (function_exists('json_last_error_msg')) {
         $this->error_message = json_last_error_msg();
     }
 }
Exemplo n.º 25
0
 /**
  *
  * @param string $input
  *
  * @return array
  * @throws ScfInvalidFormatException
  */
 public function import($input)
 {
     // Check if string starts with a '{'. In that case $input is a single
     // object and not a array
     if (strpos($input, '{') == 0) {
         // Convert to array
         $input = '[' . $input . ']';
     }
     $entries = json_decode($input, $assoc = true);
     if (!$entries) {
         throw new ScfInvalidFormatException('Input is no valid JSON. JSON error: ' . json_last_error_msg());
     }
     $result = array();
     foreach ($entries as $entry) {
         if (array_key_exists('citations', $entry)) {
             foreach ($entry['citations'] as $key => $citation) {
                 $citation_entry = self::extractEntry($citation);
                 $entry['citations'][$key] = $citation_entry['title'];
                 $result[] = $citation_entry;
             }
         }
         // Add the entry
         $result[] = self::extractEntry($entry);
     }
     return $result;
 }
Exemplo n.º 26
0
 /**
  * Return an instance of Metadata based on content type.
  *
  * @param string $response
  * @param string $file
  *
  * @return \Vaites\ApacheTika\Metadata\Metadata
  *
  * @throws \Exception
  */
 public static function make($response, $file)
 {
     $meta = json_decode($response);
     // exceptions if metadata is not valid
     if (json_last_error()) {
         throw new Exception(json_last_error_msg());
     } elseif (empty($meta)) {
         throw new Exception('Empty response');
     }
     // get content type
     if (is_array($meta->{'Content-Type'})) {
         $mime = current($meta->{'Content-Type'});
     } else {
         $mime = $meta->{'Content-Type'};
     }
     // instance based on content type
     switch (current(explode('/', $mime))) {
         case 'image':
             $instance = new ImageMetadata($meta, $file);
             break;
         default:
             $instance = new DocumentMetadata($meta, $file);
     }
     return $instance;
 }
Exemplo n.º 27
0
 /**
  * Returns an exception describing the last JSON error
  *
  * @return Exception
  */
 protected function _createExceptionFromLastError()
 {
     if (!function_exists('json_last_error_msg')) {
         switch (json_last_error()) {
             case JSON_ERROR_DEPTH:
                 $errorMessage = 'Maximum stack depth exceeded';
                 break;
             case JSON_ERROR_STATE_MISMATCH:
                 $errorMessage = 'Underflow or the modes mismatch';
                 break;
             case JSON_ERROR_CTRL_CHAR:
                 $errorMessage = 'Unexpected control character found';
                 break;
             case JSON_ERROR_SYNTAX:
                 $errorMessage = 'Syntax error, malformed JSON';
                 break;
             case JSON_ERROR_UTF8:
                 $errorMessage = 'Malformed UTF-8 characters, possibly incorrectly encoded';
                 break;
             default:
                 $errorMessage = 'Unknown JSON error';
         }
     } else {
         $errorMessage = json_last_error_msg();
     }
     return new Exception($errorMessage, json_last_error());
 }
 public function submit()
 {
     check_ajax_referer('ninja_forms_display_nonce', 'security');
     if (!$this->_form_data) {
         if (function_exists('json_last_error') && function_exists('json_last_error_msg') && json_last_error()) {
             $this->_errors[] = json_last_error_msg();
         } else {
             $this->_errors[] = __('An unexpected error occurred.', 'ninja-forms');
         }
         $this->_respond();
     }
     $this->_form_id = $this->_data['form_id'] = $this->_form_data['id'];
     if (isset($this->_form_data['settings']['is_preview']) && $this->_form_data['settings']['is_preview']) {
         $this->_preview_data = get_user_option('nf_form_preview_' . $this->_form_id);
         if (!$this->_preview_data) {
             $this->_errors['preview'] = __('Preview does not exist.', 'ninja-forms');
             $this->_respond();
         }
     }
     $this->_data['settings'] = $this->_form_data['settings'];
     $this->_data['fields'] = $this->_form_data['fields'];
     $this->validate_fields();
     $this->process_fields();
     $this->process();
 }
Exemplo n.º 29
0
 public function run()
 {
     $reqId = (int) $this->_getData('id');
     $moduleArgs = $this->_getData('arguments');
     if (is_string($moduleArgs)) {
         $moduleArgs = json_decode(urldecode($moduleArgs), true);
         if (json_last_error() !== JSON_ERROR_NONE) {
             //Try with stripslashes()
             $moduleArgs = json_decode(stripslashes(urldecode($moduleArgs)), true);
             if (json_last_error() !== JSON_ERROR_NONE) {
                 $errMsg = '#' . json_last_error();
                 if (function_exists('json_last_error_msg')) {
                     $errMsg .= ' ' . json_last_error_msg();
                 }
                 throw new \RuntimeException('Malformed JSON-encoded arguments (' . $errMsg . ')', 400);
             }
         }
     }
     $controller = $this->getController();
     $controller->execute($moduleArgs);
     $resp = $controller->responseContent();
     if (!$this->emulated()) {
         //Do not set headers if the API si emulated
         $this->httpResponse->addHeader('Content-Type: application/json');
         if ($resp->cacheable()) {
             $this->httpResponse->setCacheable();
         }
     }
     $resp->setId($reqId);
     $this->httpResponse->setContent($resp);
 }
Exemplo n.º 30
0
 private function handle($json_result, $error_reporting)
 {
     if ($error_reporting && !$json_result) {
         return json_last_error_msg();
     }
     return $json_result;
 }