_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q256300
ReflectionFunctionAbstract.isVariadic
test
public function isVariadic() : bool { $parameters = $this->getParameters(); foreach ($parameters as $parameter) { if ($parameter->isVariadic()) { return true; } } return false; }
php
{ "resource": "" }
q256301
ReflectionFunctionAbstract.setReturnType
test
public function setReturnType(string $newReturnType) : void { $this->node->returnType = new Node\Name($newReturnType); }
php
{ "resource": "" }
q256302
ReflectionFunctionAbstract.getBodyCode
test
public function getBodyCode(?PrettyPrinterAbstract $printer = null) : string { if ($printer === null) { $printer = new StandardPrettyPrinter(); } return $printer->prettyPrint($this->getBodyAst()); }
php
{ "resource": "" }
q256303
ReflectionFunctionAbstract.getReturnStatementsAst
test
public function getReturnStatementsAst() : array { $visitor = new ReturnNodeVisitor(); $traverser = new NodeTraverser(); $traverser->addVisitor($visitor); $traverser->traverse($this->node->getStmts()); return $visitor->getReturnNodes(); }
php
{ "resource": "" }
q256304
PsrAutoloaderLocator.locateIdentifiersByType
test
public function locateIdentifiersByType(Reflector $reflector, IdentifierType $identifierType) : array { return (new DirectoriesSourceLocator( $this->mapping->directories(), $this->astLocator ))->locateIdentifiersByType($reflector, $identifierType); }
php
{ "resource": "" }
q256305
ReflectionClassConstant.createFromNode
test
public static function createFromNode( Reflector $reflector, ClassConst $node, int $positionInNode, ReflectionClass $owner ) : self { $ref = new self(); $ref->node = $node; $ref->positionInNode = $positionInNode; $ref->owner = $owner; $ref->reflector = $reflector; return $ref; }
php
{ "resource": "" }
q256306
ReflectionClassConstant.getValue
test
public function getValue() { if ($this->valueWasCached !== false) { return $this->value; } $this->value = (new CompileNodeToValue())->__invoke( $this->node->consts[$this->positionInNode]->value, new CompilerContext($this->reflector, $this->getDeclaringClass()) ); $this->valueWasCached = true; return $this->value; }
php
{ "resource": "" }
q256307
ReflectionClassConstant.getModifiers
test
public function getModifiers() : int { $val = 0; $val += $this->isPublic() ? ReflectionProperty::IS_PUBLIC : 0; $val += $this->isProtected() ? ReflectionProperty::IS_PROTECTED : 0; $val += $this->isPrivate() ? ReflectionProperty::IS_PRIVATE : 0; return $val; }
php
{ "resource": "" }
q256308
PhpDocAnnotationGenerator.generateDoc
test
private function generateDoc(string $className, bool $interface = false): array { $resource = $this->classes[$className]['resource']; $annotations = []; if (!$interface && isset($this->classes[$className]['interfaceName'])) { $annotations[] = '{@inheritdoc}'; $annotations[] = ''; } else { $annotations = $this->formatDoc((string) $resource->get('rdfs:comment')); $annotations[] = ''; $annotations[] = sprintf('@see %s %s', $resource->getUri(), 'Documentation on Schema.org'); } if ($this->config['author']) { $annotations[] = sprintf('@author %s', $this->config['author']); } return $annotations; }
php
{ "resource": "" }
q256309
PhpDocAnnotationGenerator.formatDoc
test
private function formatDoc(string $doc, bool $indent = false): array { $doc = explode("\n", $this->htmlToMarkdown->convert($doc)); if ($indent) { $count = count($doc); for ($i = 1; $i < $count; ++$i) { $doc[$i] = self::INDENT.$doc[$i]; } } return $doc; }
php
{ "resource": "" }
q256310
CardinalitiesExtractor.extract
test
public function extract(): array { $properties = []; foreach ($this->graphs as $graph) { foreach ($graph->allOfType('rdf:Property') as $property) { $properties[$property->localName()] = $this->extractForProperty($property); } } return $properties; }
php
{ "resource": "" }
q256311
CardinalitiesExtractor.extractForProperty
test
private function extractForProperty(\EasyRdf_Resource $property): string { $localName = $property->localName(); $fromGoodRelations = $this->goodRelationsBridge->extractCardinality($localName); if (false !== $fromGoodRelations) { return $fromGoodRelations; } $comment = $property->get('rdfs:comment')->getValue(); if ( // http://schema.org/acceptedOffer, http://schema.org/acceptedPaymentMethod, http://schema.org/exerciseType preg_match('/\(s\)/', $comment) || // http://schema.org/follows preg_match('/^The most generic uni-directional social relation./', $comment) || preg_match('/one or more/i', $comment) ) { return self::CARDINALITY_0_N; } if ( preg_match('/^is/', $localName) || preg_match('/^The /', $comment) ) { return self::CARDINALITY_0_1; } return self::CARDINALITY_UNKNOWN; }
php
{ "resource": "" }
q256312
TypesGenerator.isEnum
test
private function isEnum(\EasyRdf_Resource $type): bool { $subClassOf = $type->get('rdfs:subClassOf'); return $subClassOf && self::SCHEMA_ORG_ENUMERATION === $subClassOf->getUri(); }
php
{ "resource": "" }
q256313
TypesGenerator.createPropertiesMap
test
private function createPropertiesMap(array $types) { $typesAsString = []; $map = []; foreach ($types as $type) { // get all parent classes until the root $parentClasses = $this->getParentClasses($type); $typesAsString[] = $parentClasses; $map[$type->getUri()] = []; } foreach ($this->graphs as $graph) { foreach ($graph->allOfType('rdf:Property') as $property) { foreach ($property->all(self::SCHEMA_ORG_DOMAIN) as $domain) { foreach ($typesAsString as $typesAsStringItem) { if (in_array($domain->getUri(), $typesAsStringItem, true)) { $map[$typesAsStringItem[0]][] = $property; } } } } } return $map; }
php
{ "resource": "" }
q256314
TypesGenerator.namespaceToDir
test
private function namespaceToDir(array $config, string $namespace): string { if (null !== ($prefix = $config['namespaces']['prefix'] ?? null) && 0 === strpos($namespace, $prefix)) { $namespace = substr($namespace, strlen($prefix)); } return sprintf('%s/%s/', $config['output'], strtr($namespace, '\\', '/')); }
php
{ "resource": "" }
q256315
TypesGenerator.fixCs
test
private function fixCs(array $files): void { $fileInfos = []; foreach ($files as $file) { $fileInfos[] = new \SplFileInfo($file); } $fixers = (new FixerFactory()) ->registerBuiltInFixers() ->useRuleSet(new RuleSet([ '@Symfony' => true, 'array_syntax' => ['syntax' => 'short'], 'phpdoc_order' => true, 'declare_strict_types' => true, ])) ->getFixers(); $runner = new Runner( new \ArrayIterator($fileInfos), $fixers, new NullDiffer(), null, new ErrorsManager(), new Linter(), false, new NullCacheManager() ); $runner->fix(); }
php
{ "resource": "" }
q256316
GoodRelationsBridge.exist
test
public function exist(string $id): bool { foreach ($this->relations as $relation) { $result = $relation->xpath(sprintf('//*[@rdf:about="%s"]', $this->getPropertyUrl($id))); if (!empty($result)) { return true; } } return false; }
php
{ "resource": "" }
q256317
GoodRelationsBridge.extractCardinality
test
public function extractCardinality(string $id) { foreach ($this->relations as $relation) { $result = $relation->xpath(sprintf('//*[@rdf:about="%s"]/rdfs:label', $this->getPropertyUrl($id))); if (count($result)) { preg_match('/\(.\.\..\)/', $result[0]->asXML(), $matches); return $matches[0]; } } return false; }
php
{ "resource": "" }
q256318
GoodRelationsBridge.getPropertyUrl
test
private function getPropertyUrl(string $id): string { $propertyId = $this->datatypePropertiesTable[$id] ?? $this->objectPropertiesTable[$id] ?? $id; return self::GOOD_RELATIONS_NAMESPACE.$propertyId; }
php
{ "resource": "" }
q256319
AbstractAnnotationGenerator.toPhpType
test
protected function toPhpType(array $field, bool $adderOrRemover = false): string { $range = $field['range']; if ($field['isEnum']) { if ($field['isArray']) { return 'string[]'; } return 'string'; } $data = false; switch ($range) { case 'Boolean': $data = 'bool'; break; case 'Date': case 'DateTime': case 'Time': $data = '\\'.\DateTimeInterface::class; break; case 'Number': case 'Float': $data = 'float'; break; case 'Integer': $data = 'integer'; break; case 'Text': case 'URL': $data = 'string'; break; } if (false !== $data) { if ($field['isArray']) { return sprintf('%s[]', $data); } return $data; } if (isset($this->classes[$field['range']]['interfaceName'])) { $range = $this->classes[$field['range']]['interfaceName']; } if ($field['isArray'] && !$adderOrRemover) { if ($this->config['doctrine']['useCollection']) { return sprintf('Collection<%s>', $range); } return sprintf('%s[]', $range); } return $range; }
php
{ "resource": "" }
q256320
DoctrineOrmAnnotationGenerator.getRelationName
test
private function getRelationName(string $range): string { $class = $this->classes[$range]; if (isset($class['interfaceName'])) { return $class['interfaceName']; } if (isset($this->config['types'][$class['name']]['namespaces']['class'])) { return sprintf('%s\\%s', $this->config['types'][$class['name']]['namespaces']['class'], $class['name']); } if (isset($this->config['namespaces']['entity'])) { return sprintf('%s\\%s', $this->config['namespaces']['entity'], $class['name']); } return $class['name']; }
php
{ "resource": "" }
q256321
Sitemap.finishFile
test
private function finishFile() { if ($this->writer !== null) { $this->writer->endElement(); $this->writer->endDocument(); /* To prevent infinite recursion through flush */ $this->urlsCount = 0; $this->flush(0); $this->writerBackend->finish(); $this->writerBackend = null; $this->byteCount = 0; } }
php
{ "resource": "" }
q256322
Sitemap.flush
test
private function flush($footSize = 10) { $data = $this->writer->flush(true); $dataSize = mb_strlen($data, '8bit'); /* * Limit the file size of each single site map * * We use a heuristic of 10 Bytes for the remainder of the file, * i.e. </urlset> plus a new line. */ if ($this->byteCount + $dataSize + $footSize > $this->maxBytes) { if ($this->urlsCount <= 1) { throw new \OverflowException('The buffer size is too big for the defined file size limit'); } $this->finishFile(); $this->createNewFile(); } $this->writerBackend->append($data); $this->byteCount += $dataSize; }
php
{ "resource": "" }
q256323
Sitemap.addItem
test
public function addItem($location, $lastModified = null, $changeFrequency = null, $priority = null) { if ($this->urlsCount >= $this->maxUrls) { $this->finishFile(); } if ($this->writerBackend === null) { $this->createNewFile(); } if (is_array($location)) { $this->addMultiLanguageItem($location, $lastModified, $changeFrequency, $priority); } else { $this->addSingleLanguageItem($location, $lastModified, $changeFrequency, $priority); } $this->urlsCount++; if ($this->urlsCount % $this->bufferSize === 0) { $this->flush(); } }
php
{ "resource": "" }
q256324
Sitemap.addSingleLanguageItem
test
private function addSingleLanguageItem($location, $lastModified, $changeFrequency, $priority) { $this->validateLocation($location); $this->writer->startElement('url'); $this->writer->writeElement('loc', $location); if ($lastModified !== null) { $this->writer->writeElement('lastmod', date('c', $lastModified)); } if ($changeFrequency !== null) { if (!in_array($changeFrequency, $this->validFrequencies, true)) { throw new \InvalidArgumentException( 'Please specify valid changeFrequency. Valid values are: ' . implode(', ', $this->validFrequencies) . "You have specified: {$changeFrequency}." ); } $this->writer->writeElement('changefreq', $changeFrequency); } if ($priority !== null) { if (!is_numeric($priority) || $priority < 0 || $priority > 1) { throw new \InvalidArgumentException( "Please specify valid priority. Valid values range from 0.0 to 1.0. You have specified: {$priority}." ); } $this->writer->writeElement('priority', number_format($priority, 1, '.', ',')); } $this->writer->endElement(); }
php
{ "resource": "" }
q256325
Sitemap.addMultiLanguageItem
test
private function addMultiLanguageItem($locations, $lastModified, $changeFrequency, $priority) { foreach ($locations as $language => $url) { $this->validateLocation($url); $this->writer->startElement('url'); $this->writer->writeElement('loc', $url); if ($lastModified !== null) { $this->writer->writeElement('lastmod', date('c', $lastModified)); } if ($changeFrequency !== null) { if (!in_array($changeFrequency, $this->validFrequencies, true)) { throw new \InvalidArgumentException( 'Please specify valid changeFrequency. Valid values are: ' . implode(', ', $this->validFrequencies) . "You have specified: {$changeFrequency}." ); } $this->writer->writeElement('changefreq', $changeFrequency); } if ($priority !== null) { if (!is_numeric($priority) || $priority < 0 || $priority > 1) { throw new \InvalidArgumentException( "Please specify valid priority. Valid values range from 0.0 to 1.0. You have specified: {$priority}." ); } $this->writer->writeElement('priority', number_format($priority, 1, '.', ',')); } foreach ($locations as $hreflang => $href) { $this->writer->startElement('xhtml:link'); $this->writer->startAttribute('rel'); $this->writer->text('alternate'); $this->writer->endAttribute(); $this->writer->startAttribute('hreflang'); $this->writer->text($hreflang); $this->writer->endAttribute(); $this->writer->startAttribute('href'); $this->writer->text($href); $this->writer->endAttribute(); $this->writer->endElement(); } $this->writer->endElement(); } }
php
{ "resource": "" }
q256326
Sitemap.getSitemapUrls
test
public function getSitemapUrls($baseUrl) { $urls = array(); foreach ($this->writtenFilePaths as $file) { $urls[] = $baseUrl . pathinfo($file, PATHINFO_BASENAME); } return $urls; }
php
{ "resource": "" }
q256327
Sitemap.setUseGzip
test
public function setUseGzip($value) { if ($value && !extension_loaded('zlib')) { throw new \RuntimeException('Zlib extension must be enabled to gzip the sitemap.'); } if ($this->writerBackend !== null && $value != $this->useGzip) { throw new \RuntimeException('Cannot change the gzip value once items have been added to the sitemap.'); } $this->useGzip = $value; }
php
{ "resource": "" }
q256328
Index.addSitemap
test
public function addSitemap($location, $lastModified = null) { if (false === filter_var($location, FILTER_VALIDATE_URL)) { throw new \InvalidArgumentException( "The location must be a valid URL. You have specified: {$location}." ); } if ($this->writer === null) { $this->createNewFile(); } $this->writer->startElement('sitemap'); $this->writer->writeElement('loc', $location); if ($lastModified !== null) { $this->writer->writeElement('lastmod', date('c', $lastModified)); } $this->writer->endElement(); }
php
{ "resource": "" }
q256329
DeflateWriter.write
test
private function write($data, $flushMode) { assert($this->file !== null); $compressedChunk = deflate_add($this->deflateContext, $data, $flushMode); fwrite($this->file, $compressedChunk); }
php
{ "resource": "" }
q256330
DeflateWriter.finish
test
public function finish() { $this->write('', ZLIB_FINISH); $this->file = null; $this->deflateContext = null; }
php
{ "resource": "" }
q256331
TempFileGZIPWriter.finish
test
public function finish() { assert($this->tempFile !== null); $file = fopen('compress.zlib://' . $this->filename, 'wb'); rewind($this->tempFile); stream_copy_to_stream($this->tempFile, $file); fclose($file); fclose($this->tempFile); $this->tempFile = null; }
php
{ "resource": "" }
q256332
Crypt_GPG_KeyGenerator.setExpirationDate
test
public function setExpirationDate($date) { if (is_int($date) || ctype_digit(strval($date))) { $expirationDate = intval($date); } else { $expirationDate = strtotime($date); } if ($expirationDate === false) { throw new InvalidArgumentException( sprintf( 'Invalid expiration date format: "%s". Please use a ' . 'format compatible with PHP\'s strtotime().', $date ) ); } if ($expirationDate !== 0 && $expirationDate < time() + 86400) { throw new InvalidArgumentException( 'Expiration date must be at least a day in the future.' ); } // GnuPG suffers from the 2038 bug if ($expirationDate > 2147483647) { throw new InvalidArgumentException( 'Expiration date must not be greater than 2038-01-19T03:14:07.' ); } $this->expirationDate = $expirationDate; return $this; }
php
{ "resource": "" }
q256333
Crypt_GPG_KeyGenerator.setKeyParams
test
public function setKeyParams($algorithm, $size = 0, $usage = 0) { $algorithm = intval($algorithm); if ($algorithm === Crypt_GPG_SubKey::ALGORITHM_ELGAMAL_ENC) { throw new Crypt_GPG_InvalidKeyParamsException( 'Primary key algorithm must be capable of signing. The ' . 'Elgamal algorithm can only encrypt.', 0, $algorithm, $size, $usage ); } if ($size != 0) { $size = intval($size); } if ($usage != 0) { $usage = intval($usage); } $usageEncrypt = Crypt_GPG_SubKey::USAGE_ENCRYPT; if ($algorithm === Crypt_GPG_SubKey::ALGORITHM_DSA && ($usage & $usageEncrypt) === $usageEncrypt ) { throw new Crypt_GPG_InvalidKeyParamsException( 'The DSA algorithm is not capable of encrypting. Please ' . 'specify a different algorithm or do not include encryption ' . 'as a usage for the primary key.', 0, $algorithm, $size, $usage ); } $this->keyAlgorithm = $algorithm; if ($size != 0) { $this->keySize = $size; } if ($usage != 0) { $this->keyUsage = $usage; } return $this; }
php
{ "resource": "" }
q256334
Crypt_GPG_KeyGenerator.setSubKeyParams
test
public function setSubKeyParams($algorithm, $size = '', $usage = 0) { $algorithm = intval($algorithm); if ($size != 0) { $size = intval($size); } if ($usage != 0) { $usage = intval($usage); } $usageSign = Crypt_GPG_SubKey::USAGE_SIGN; if ($algorithm === Crypt_GPG_SubKey::ALGORITHM_ELGAMAL_ENC && ($usage & $usageSign) === $usageSign ) { throw new Crypt_GPG_InvalidKeyParamsException( 'The Elgamal algorithm is not capable of signing. Please ' . 'specify a different algorithm or do not include signing ' . 'as a usage for the sub-key.', 0, $algorithm, $size, $usage ); } $usageEncrypt = Crypt_GPG_SubKey::USAGE_ENCRYPT; if ($algorithm === Crypt_GPG_SubKey::ALGORITHM_DSA && ($usage & $usageEncrypt) === $usageEncrypt ) { throw new Crypt_GPG_InvalidKeyParamsException( 'The DSA algorithm is not capable of encrypting. Please ' . 'specify a different algorithm or do not include encryption ' . 'as a usage for the sub-key.', 0, $algorithm, $size, $usage ); } $this->subKeyAlgorithm = $algorithm; if ($size != 0) { $this->subKeySize = $size; } if ($usage != 0) { $this->subKeyUsage = $usage; } return $this; }
php
{ "resource": "" }
q256335
Crypt_GPG_KeyGenerator.getUsage
test
protected function getUsage($usage) { $map = array( Crypt_GPG_SubKey::USAGE_ENCRYPT => 'encrypt', Crypt_GPG_SubKey::USAGE_SIGN => 'sign', Crypt_GPG_SubKey::USAGE_CERTIFY => 'cert', Crypt_GPG_SubKey::USAGE_AUTHENTICATION => 'auth', ); // cert is always used for primary keys and does not need to be // specified $usage &= ~Crypt_GPG_SubKey::USAGE_CERTIFY; $usageArray = array(); foreach ($map as $key => $value) { if (($usage & $key) === $key) { $usageArray[] = $value; } } return implode(',', $usageArray); }
php
{ "resource": "" }
q256336
Crypt_GPG_KeyGenerator.getUserId
test
protected function getUserId($name, $email = '', $comment = '') { if ($name instanceof Crypt_GPG_UserId) { $userId = $name; } else { $userId = new Crypt_GPG_UserId(); $userId->setName($name)->setEmail($email)->setComment($comment); } return $userId; }
php
{ "resource": "" }
q256337
Crypt_GPG_UserId.parse
test
public static function parse($string) { $userId = new Crypt_GPG_UserId(); $name = ''; $email = ''; $comment = ''; // get email address from end of string if it exists $matches = array(); if (preg_match('/^(.*?)<([^>]+)>$/', $string, $matches) === 1) { $string = trim($matches[1]); $email = $matches[2]; } // get comment from end of string if it exists $matches = array(); if (preg_match('/^(.+?) \(([^\)]+)\)$/', $string, $matches) === 1) { $string = $matches[1]; $comment = $matches[2]; } // there can be an email without a name if (!$email && preg_match('/^[\S]+@[\S]+$/', $string, $matches) === 1) { $email = $string; } else { $name = $string; } $userId->setName($name); $userId->setComment($comment); $userId->setEmail($email); return $userId; }
php
{ "resource": "" }
q256338
Crypt_GPG_ProcessControl.isRunning
test
public function isRunning() { $running = false; if (function_exists('posix_getpgid')) { $running = false !== posix_getpgid($this->pid); } elseif (PHP_OS === 'WINNT') { $command = 'tasklist /fo csv /nh /fi ' . escapeshellarg('PID eq ' . $this->pid); $result = exec($command); $parts = explode(',', $result); $running = (count($parts) > 1 && trim($parts[1], '"') == $this->pid); } else { $result = exec('ps -p ' . escapeshellarg($this->pid) . ' -o pid='); $running = (trim($result) == $this->pid); } return $running; }
php
{ "resource": "" }
q256339
Crypt_GPG_ProcessControl.terminate
test
public function terminate() { if (function_exists('posix_kill')) { posix_kill($this->pid, 15); } elseif (PHP_OS === 'WINNT') { exec('taskkill /PID ' . escapeshellarg($this->pid)); } else { exec('kill -15 ' . escapeshellarg($this->pid)); } }
php
{ "resource": "" }
q256340
Crypt_GPG_ProcessHandler.setOperation
test
public function setOperation($operation) { $op = null; $opArg = null; // Regexp matching all GPG "operational" arguments $regexp = '/--(' . 'version|import|list-public-keys|list-secret-keys' . '|list-keys|delete-key|delete-secret-key|encrypt|sign|clearsign' . '|detach-sign|decrypt|verify|export-secret-keys|export|gen-key' . ')/'; if (strpos($operation, ' ') === false) { $op = trim($operation, '- '); } else if (preg_match($regexp, $operation, $matches, PREG_OFFSET_CAPTURE)) { $op = trim($matches[0][0], '-'); $op_len = $matches[0][1] + mb_strlen($op, '8bit') + 3; $command = mb_substr($operation, $op_len, null, '8bit'); // we really need the argument if it is a key ID/fingerprint or email // address se we can use simplified regexp to "revert escapeshellarg()" if (preg_match('/^[\'"]([a-zA-Z0-9:@._-]+)[\'"]/', $command, $matches)) { $opArg = $matches[1]; } } $this->operation = $op; $this->operationArg = $opArg; $this->data['Warnings'] = array(); }
php
{ "resource": "" }
q256341
Crypt_GPG_ProcessHandler.handleError
test
public function handleError($line) { if (stripos($line, 'gpg: WARNING: ') !== false) { $this->data['Warnings'][] = substr($line, 14); } if ($this->errorCode !== Crypt_GPG::ERROR_NONE) { return; } $pattern = '/no valid OpenPGP data found/'; if (preg_match($pattern, $line) === 1) { $this->errorCode = Crypt_GPG::ERROR_NO_DATA; return; } $pattern = '/No secret key|secret key not available/'; if (preg_match($pattern, $line) === 1) { $this->errorCode = Crypt_GPG::ERROR_KEY_NOT_FOUND; return; } $pattern = '/No public key|public key not found/'; if (preg_match($pattern, $line) === 1) { $this->errorCode = Crypt_GPG::ERROR_KEY_NOT_FOUND; return; } $pattern = '/can\'t (?:access|open) `(.*?)\'/'; if (preg_match($pattern, $line, $matches) === 1) { $this->data['ErrorFilename'] = $matches[1]; $this->errorCode = Crypt_GPG::ERROR_FILE_PERMISSIONS; return; } // GnuPG 2.1: It should return MISSING_PASSPHRASE, but it does not // we have to detect it this way. This happens e.g. on private key import $pattern = '/key ([0-9A-F]+).* (Bad|No) passphrase/'; if (preg_match($pattern, $line, $matches) === 1) { $keyId = $matches[1]; // @TODO: Get user name/email if (empty($this->data['BadPassphrases'][$keyId])) { $this->data['BadPassphrases'][$keyId] = $keyId; } if ($matches[2] == 'Bad') { $this->errorCode = Crypt_GPG::ERROR_BAD_PASSPHRASE; } else { $this->errorCode = Crypt_GPG::ERROR_MISSING_PASSPHRASE; if (empty($this->data['MissingPassphrases'][$keyId])) { $this->data['MissingPassphrases'][$keyId] = $keyId; } } return; } if ($this->operation == 'gen-key') { $pattern = '/:([0-9]+): invalid algorithm$/'; if (preg_match($pattern, $line, $matches) === 1) { $this->errorCode = Crypt_GPG::ERROR_BAD_KEY_PARAMS; $this->data['LineNumber'] = intval($matches[1]); } } }
php
{ "resource": "" }
q256342
Crypt_GPG_ProcessHandler.setErrorCode
test
protected function setErrorCode($exitcode) { if ($this->needPassphrase > 0) { return Crypt_GPG::ERROR_MISSING_PASSPHRASE; } if ($this->operation == 'import') { return Crypt_GPG::ERROR_NONE; } if ($this->operation == 'decrypt' && !empty($this->data['DecryptionOkay'])) { if (!empty($this->data['IgnoreVerifyErrors'])) { return Crypt_GPG::ERROR_NONE; } if (!empty($this->data['MissingKeys'])) { return Crypt_GPG::ERROR_KEY_NOT_FOUND; } } return Crypt_GPG::ERROR_UNKNOWN; }
php
{ "resource": "" }
q256343
Crypt_GPG_ProcessHandler.setData
test
public function setData($name, $value) { switch ($name) { case 'Handle': $this->data[$name] = strval($value); break; case 'IgnoreVerifyErrors': $this->data[$name] = (bool) $value; break; } }
php
{ "resource": "" }
q256344
Crypt_GPG_ProcessHandler.badPassException
test
protected function badPassException($code, $message) { $badPassphrases = array_diff_key( isset($this->data['BadPassphrases']) ? $this->data['BadPassphrases'] : array(), isset($this->data['MissingPassphrases']) ? $this->data['MissingPassphrases'] : array() ); $missingPassphrases = array_intersect_key( isset($this->data['BadPassphrases']) ? $this->data['BadPassphrases'] : array(), isset($this->data['MissingPassphrases']) ? $this->data['MissingPassphrases'] : array() ); if (count($badPassphrases) > 0) { $message .= ' Incorrect passphrase provided for keys: "' . implode('", "', $badPassphrases) . '".'; } if (count($missingPassphrases) > 0) { $message .= ' No passphrase provided for keys: "' . implode('", "', $missingPassphrases) . '".'; } return new Crypt_GPG_BadPassphraseException( $message, $code, $badPassphrases, $missingPassphrases ); }
php
{ "resource": "" }
q256345
Crypt_GPG_ProcessHandler.getPin
test
protected function getPin($key) { $passphrase = ''; $keyIdLength = mb_strlen($key, '8bit'); if ($keyIdLength && !empty($_ENV['PINENTRY_USER_DATA'])) { $passphrases = json_decode($_ENV['PINENTRY_USER_DATA'], true); foreach ($passphrases as $_keyId => $pass) { $keyId = $key; $_keyIdLength = mb_strlen($_keyId, '8bit'); // Get last X characters of key identifier to compare if ($keyIdLength < $_keyIdLength) { $_keyId = mb_substr($_keyId, -$keyIdLength, null, '8bit'); } else if ($keyIdLength > $_keyIdLength) { $keyId = mb_substr($keyId, -$_keyIdLength, null, '8bit'); } if ($_keyId === $keyId) { $passphrase = $pass; break; } } } return $passphrase; }
php
{ "resource": "" }
q256346
Crypt_GPG_SignatureCreationInfo.getHashAlgorithmName
test
public function getHashAlgorithmName() { if (!isset(self::$hashAlgorithmNames[$this->hashAlgorithm])) { return null; } return self::$hashAlgorithmNames[$this->hashAlgorithm]; }
php
{ "resource": "" }
q256347
Crypt_GPG_SubKey.setCanSign
test
public function setCanSign($canSign) { if ($canSign) { $this->_usage |= self::USAGE_SIGN; } else { $this->_usage &= ~self::USAGE_SIGN; } return $this; }
php
{ "resource": "" }
q256348
Crypt_GPG_SubKey.setCanEncrypt
test
public function setCanEncrypt($canEncrypt) { if ($canEncrypt) { $this->_usage |= self::USAGE_ENCRYPT; } else { $this->_usage &= ~self::USAGE_ENCRYPT; } return $this; }
php
{ "resource": "" }
q256349
Crypt_GPG_SubKey.parse
test
public static function parse($string) { $tokens = explode(':', $string); $subKey = new Crypt_GPG_SubKey(); $subKey->setId($tokens[4]); $subKey->setLength($tokens[2]); $subKey->setAlgorithm($tokens[3]); $subKey->setCreationDate(self::_parseDate($tokens[5])); $subKey->setExpirationDate(self::_parseDate($tokens[6])); if ($tokens[1] == 'r') { $subKey->setRevoked(true); } $usage = 0; $usage_map = array( 'a' => self::USAGE_AUTHENTICATION, 'c' => self::USAGE_CERTIFY, 'e' => self::USAGE_ENCRYPT, 's' => self::USAGE_SIGN, ); foreach ($usage_map as $key => $flag) { if (strpos($tokens[11], $key) !== false) { $usage |= $flag; } } $subKey->setUsage($usage); return $subKey; }
php
{ "resource": "" }
q256350
Crypt_GPG_SubKey._parseDate
test
private static function _parseDate($string) { if ($string == '') { $timestamp = 0; } else { // all times are in UTC according to GPG documentation $timeZone = new DateTimeZone('UTC'); if (strpos($string, 'T') === false) { // interpret as UNIX timestamp $string = '@' . $string; } $date = new DateTime($string, $timeZone); // convert to UNIX timestamp $timestamp = intval($date->format('U')); } return $timestamp; }
php
{ "resource": "" }
q256351
Crypt_GPG.deletePublicKey
test
public function deletePublicKey($keyId) { $fingerprint = $this->getFingerprint($keyId); if ($fingerprint === null) { throw new Crypt_GPG_KeyNotFoundException( 'Public key not found: ' . $keyId, self::ERROR_KEY_NOT_FOUND, $keyId ); } $operation = '--delete-key ' . escapeshellarg($fingerprint); $arguments = array( '--batch', '--yes' ); $this->engine->reset(); $this->engine->setOperation($operation, $arguments); $this->engine->run(); }
php
{ "resource": "" }
q256352
Crypt_GPG.getFingerprint
test
public function getFingerprint($keyId, $format = self::FORMAT_NONE) { $output = ''; $operation = '--list-keys ' . escapeshellarg($keyId); $arguments = array( '--with-colons', '--with-fingerprint' ); $this->engine->reset(); $this->engine->setOutput($output); $this->engine->setOperation($operation, $arguments); $this->engine->run(); $fingerprint = null; foreach (explode(PHP_EOL, $output) as $line) { if (mb_substr($line, 0, 3, '8bit') == 'fpr') { $lineExp = explode(':', $line); $fingerprint = $lineExp[9]; switch ($format) { case self::FORMAT_CANONICAL: $fingerprintExp = str_split($fingerprint, 4); $format = '%s %s %s %s %s %s %s %s %s %s'; $fingerprint = vsprintf($format, $fingerprintExp); break; case self::FORMAT_X509: $fingerprintExp = str_split($fingerprint, 2); $fingerprint = implode(':', $fingerprintExp); break; } break; } } return $fingerprint; }
php
{ "resource": "" }
q256353
Crypt_GPG.encrypt
test
public function encrypt($data, $armor = self::ARMOR_ASCII) { return $this->_encrypt($data, false, null, $armor); }
php
{ "resource": "" }
q256354
Crypt_GPG.encryptFile
test
public function encryptFile( $filename, $encryptedFile = null, $armor = self::ARMOR_ASCII ) { return $this->_encrypt($filename, true, $encryptedFile, $armor); }
php
{ "resource": "" }
q256355
Crypt_GPG.encryptAndSign
test
public function encryptAndSign($data, $armor = self::ARMOR_ASCII) { return $this->_encryptAndSign($data, false, null, $armor); }
php
{ "resource": "" }
q256356
Crypt_GPG.encryptAndSignFile
test
public function encryptAndSignFile( $filename, $signedFile = null, $armor = self::ARMOR_ASCII ) { return $this->_encryptAndSign($filename, true, $signedFile, $armor); }
php
{ "resource": "" }
q256357
Crypt_GPG.decryptAndVerify
test
public function decryptAndVerify($encryptedData, $ignoreVerifyErrors = false) { return $this->_decryptAndVerify($encryptedData, false, null, $ignoreVerifyErrors); }
php
{ "resource": "" }
q256358
Crypt_GPG.decryptAndVerifyFile
test
public function decryptAndVerifyFile($encryptedFile, $decryptedFile = null, $ignoreVerifyErrors = false) { return $this->_decryptAndVerify($encryptedFile, true, $decryptedFile, $ignoreVerifyErrors); }
php
{ "resource": "" }
q256359
Crypt_GPG.signFile
test
public function signFile( $filename, $signedFile = null, $mode = self::SIGN_MODE_NORMAL, $armor = self::ARMOR_ASCII, $textmode = self::TEXT_RAW ) { return $this->_sign( $filename, true, $signedFile, $mode, $armor, $textmode ); }
php
{ "resource": "" }
q256360
Crypt_GPG.addDecryptKey
test
public function addDecryptKey($key, $passphrase = null) { $this->_addKey($this->decryptKeys, false, false, $key, $passphrase); return $this; }
php
{ "resource": "" }
q256361
Crypt_GPG.addEncryptKey
test
public function addEncryptKey($key) { $this->_addKey($this->encryptKeys, true, false, $key); return $this; }
php
{ "resource": "" }
q256362
Crypt_GPG.addSignKey
test
public function addSignKey($key, $passphrase = null) { $this->_addKey($this->signKeys, false, true, $key, $passphrase); return $this; }
php
{ "resource": "" }
q256363
Crypt_GPG._addKey
test
protected function _addKey(array &$array, $encrypt, $sign, $key, $passphrase = null ) { $subKeys = array(); if (is_scalar($key)) { $keys = $this->getKeys($key); if (count($keys) == 0) { throw new Crypt_GPG_KeyNotFoundException( 'Key not found: ' . $key, self::ERROR_KEY_NOT_FOUND, $key ); } $key = $keys[0]; } if ($key instanceof Crypt_GPG_Key) { if ($encrypt && !$key->canEncrypt()) { throw new InvalidArgumentException( 'Key "' . $key . '" cannot encrypt.' ); } if ($sign && !$key->canSign()) { throw new InvalidArgumentException( 'Key "' . $key . '" cannot sign.' ); } foreach ($key->getSubKeys() as $subKey) { $canEncrypt = $subKey->canEncrypt(); $canSign = $subKey->canSign(); if (($encrypt && $sign && $canEncrypt && $canSign) || ($encrypt && !$sign && $canEncrypt) || (!$encrypt && $sign && $canSign) || (!$encrypt && !$sign) ) { // We add all subkeys that meet the requirements because we // were not told which subkey is required. $subKeys[] = $subKey; } } } elseif ($key instanceof Crypt_GPG_SubKey) { $subKeys[] = $key; } if (count($subKeys) === 0) { throw new InvalidArgumentException( 'Key "' . $key . '" is not in a recognized format.' ); } foreach ($subKeys as $subKey) { if ($encrypt && !$subKey->canEncrypt()) { throw new InvalidArgumentException( 'Key "' . $key . '" cannot encrypt.' ); } if ($sign && !$subKey->canSign()) { throw new InvalidArgumentException( 'Key "' . $key . '" cannot sign.' ); } $array[$subKey->getId()] = array( 'fingerprint' => $subKey->getFingerprint(), 'passphrase' => $passphrase ); } }
php
{ "resource": "" }
q256364
Crypt_GPG._importKey
test
protected function _importKey($key, $isFile) { $result = array(); $arguments = array(); $input = $this->_prepareInput($key, $isFile, false); $version = $this->engine->getVersion(); if (version_compare($version, '1.0.5', 'ge') && version_compare($version, '1.0.7', 'lt') ) { $arguments[] = '--allow-secret-key-import'; } if (empty($this->passphrases)) { $arguments[] = '--batch'; } $this->engine->reset(); $this->engine->setPins($this->passphrases); $this->engine->setOperation('--import', $arguments); $this->engine->setInput($input); $this->engine->run(); return $this->engine->getProcessData('Import'); }
php
{ "resource": "" }
q256365
Crypt_GPG._exportKey
test
protected function _exportKey($keyId, $armor = true, $private = false) { $fingerprint = $this->getFingerprint($keyId); if ($fingerprint === null) { throw new Crypt_GPG_KeyNotFoundException( 'Key not found: ' . $keyId, self::ERROR_KEY_NOT_FOUND, $keyId ); } $keyData = ''; $operation = $private ? '--export-secret-keys' : '--export'; $operation .= ' ' . escapeshellarg($fingerprint); $arguments = $armor ? array('--armor') : array(); $this->engine->reset(); $this->engine->setPins($this->passphrases); $this->engine->setOutput($keyData); $this->engine->setOperation($operation, $arguments); $this->engine->run(); return $keyData; }
php
{ "resource": "" }
q256366
Crypt_GPG._decryptAndVerify
test
protected function _decryptAndVerify($data, $isFile, $outputFile, $ignoreVerifyErrors = false) { $input = $this->_prepareInput($data, $isFile, false); $output = $this->_prepareOutput($outputFile, $input); $this->engine->reset(); $this->engine->setPins($this->decryptKeys); $this->engine->setInput($input); $this->engine->setOutput($output); $this->engine->setOperation('--decrypt'); $this->engine->setProcessData('IgnoreVerifyErrors', $ignoreVerifyErrors); $this->engine->run(); $return = array( 'data' => null, 'signatures' => $this->engine->getProcessData('Signatures') ); if ($outputFile === null) { $return['data'] = $output; } return $return; }
php
{ "resource": "" }
q256367
Crypt_GPG._prepareInput
test
protected function _prepareInput($data, $isFile = false, $allowEmpty = true) { if ($isFile) { $input = @fopen($data, 'rb'); if ($input === false) { throw new Crypt_GPG_FileException( 'Could not open input file "' . $data . '"', 0, $data ); } } else { $input = strval($data); if (!$allowEmpty && $input === '') { throw new Crypt_GPG_NoDataException( 'No valid input data found.', self::ERROR_NO_DATA ); } } return $input; }
php
{ "resource": "" }
q256368
Crypt_GPG._prepareOutput
test
protected function _prepareOutput($outputFile, $input = null) { if ($outputFile === null) { $output = ''; } else { $output = @fopen($outputFile, 'wb'); if ($output === false) { if (is_resource($input)) { fclose($input); } throw new Crypt_GPG_FileException( 'Could not open output file "' . $outputFile . '"', 0, $outputFile ); } } return $output; }
php
{ "resource": "" }
q256369
Crypt_GPGAbstract._getKeys
test
protected function _getKeys($keyId = '') { // get private key fingerprints if ($keyId == '') { $operation = '--list-secret-keys'; } else { $operation = '--utf8-strings --list-secret-keys ' . escapeshellarg($keyId); } // According to The file 'doc/DETAILS' in the GnuPG distribution, using // double '--with-fingerprint' also prints the fingerprint for subkeys. $arguments = array( '--with-colons', '--with-fingerprint', '--with-fingerprint', '--fixed-list-mode' ); $output = ''; $this->engine->reset(); $this->engine->setOutput($output); $this->engine->setOperation($operation, $arguments); $this->engine->run(); $privateKeyFingerprints = array(); foreach (explode(PHP_EOL, $output) as $line) { $lineExp = explode(':', $line); if ($lineExp[0] == 'fpr') { $privateKeyFingerprints[] = $lineExp[9]; } } // get public keys if ($keyId == '') { $operation = '--list-public-keys'; } else { $operation = '--utf8-strings --list-public-keys ' . escapeshellarg($keyId); } $output = ''; $this->engine->reset(); $this->engine->setOutput($output); $this->engine->setOperation($operation, $arguments); $this->engine->run(); $keys = array(); $key = null; // current key $subKey = null; // current sub-key foreach (explode(PHP_EOL, $output) as $line) { $lineExp = explode(':', $line); if ($lineExp[0] == 'pub') { // new primary key means last key should be added to the array if ($key !== null) { $keys[] = $key; } $key = new Crypt_GPG_Key(); $subKey = Crypt_GPG_SubKey::parse($line); $key->addSubKey($subKey); } elseif ($lineExp[0] == 'sub') { $subKey = Crypt_GPG_SubKey::parse($line); $key->addSubKey($subKey); } elseif ($lineExp[0] == 'fpr') { $fingerprint = $lineExp[9]; // set current sub-key fingerprint $subKey->setFingerprint($fingerprint); // if private key exists, set has private to true if (in_array($fingerprint, $privateKeyFingerprints)) { $subKey->setHasPrivate(true); } } elseif ($lineExp[0] == 'uid') { $string = stripcslashes($lineExp[9]); // as per documentation $userId = new Crypt_GPG_UserId($string); if ($lineExp[1] == 'r') { $userId->setRevoked(true); } $key->addUserId($userId); } } // add last key if ($key !== null) { $keys[] = $key; } return $keys; }
php
{ "resource": "" }
q256370
Crypt_GPG_Engine.sendCommand
test
public function sendCommand($command) { if (array_key_exists(self::FD_COMMAND, $this->_openPipes)) { $this->_commandBuffer .= $command . PHP_EOL; } }
php
{ "resource": "" }
q256371
Crypt_GPG_Engine.reset
test
public function reset() { $this->_operation = ''; $this->_arguments = array(); $this->_input = null; $this->_message = null; $this->_output = ''; $this->_commandBuffer = ''; $this->_statusHandlers = array(); $this->_errorHandlers = array(); if ($this->_debug) { $this->addStatusHandler(array($this, '_handleDebugStatus')); $this->addErrorHandler(array($this, '_handleDebugError')); } $this->_processHandler = new Crypt_GPG_ProcessHandler($this); $this->addStatusHandler(array($this->_processHandler, 'handleStatus')); $this->addErrorHandler(array($this->_processHandler, 'handleError')); }
php
{ "resource": "" }
q256372
Crypt_GPG_Engine.run
test
public function run() { if ($this->_operation === '') { throw new Crypt_GPG_InvalidOperationException( 'No GPG operation specified. Use Crypt_GPG_Engine::setOperation() ' . 'before calling Crypt_GPG_Engine::run().' ); } $this->_openSubprocess(); $this->_process(); $this->_closeSubprocess(); }
php
{ "resource": "" }
q256373
Crypt_GPG_Engine.setOperation
test
public function setOperation($operation, array $arguments = array()) { $this->_operation = $operation; $this->_arguments = $arguments; $this->_processHandler->setOperation($operation); }
php
{ "resource": "" }
q256374
Crypt_GPG_Engine.setPins
test
public function setPins(array $keys) { $envKeys = array(); foreach ($keys as $keyId => $key) { $envKeys[$keyId] = is_array($key) ? $key['passphrase'] : $key; } $_ENV['PINENTRY_USER_DATA'] = json_encode($envKeys); }
php
{ "resource": "" }
q256375
Crypt_GPG_Engine.getVersion
test
public function getVersion() { if ($this->_version == '') { $options = array( 'homedir' => $this->_homedir, 'binary' => $this->_binary, 'debug' => $this->_debug, 'agent' => $this->_agent, ); $engine = new self($options); $info = ''; // Set a garbage version so we do not end up looking up the version // recursively. $engine->_version = '1.0.0'; $engine->reset(); $engine->setOutput($info); $engine->setOperation('--version'); $engine->run(); $matches = array(); $expression = '#gpg \(GnuPG[A-Za-z0-9/]*?\) (\S+)#'; if (preg_match($expression, $info, $matches) === 1) { $this->_version = $matches[1]; } else { throw new Crypt_GPG_Exception( 'No GnuPG version information provided by the binary "' . $this->_binary . '". Are you sure it is GnuPG?' ); } if (version_compare($this->_version, self::MIN_VERSION, 'lt')) { throw new Crypt_GPG_Exception( 'The version of GnuPG being used (' . $this->_version . ') is not supported by Crypt_GPG. The minimum version ' . 'required by Crypt_GPG is ' . self::MIN_VERSION ); } } return $this->_version; }
php
{ "resource": "" }
q256376
Crypt_GPG_Engine.getProcessData
test
public function getProcessData($name) { if ($this->_processHandler) { switch ($name) { case 'SignatureInfo': if ($data = $this->_processHandler->getData('SigCreated')) { return new Crypt_GPG_SignatureCreationInfo($data); } break; case 'Signatures': case 'Warnings': return (array) $this->_processHandler->getData($name); default: return $this->_processHandler->getData($name); } } }
php
{ "resource": "" }
q256377
Crypt_GPG_Engine.setProcessData
test
public function setProcessData($name, $value) { if ($this->_processHandler) { $this->_processHandler->setData($name, $value); } }
php
{ "resource": "" }
q256378
Crypt_GPG_Engine._closeSubprocess
test
private function _closeSubprocess() { // clear PINs from environment if they were set $_ENV['PINENTRY_USER_DATA'] = null; if (is_resource($this->_process)) { $this->_debug('CLOSING GPG SUBPROCESS'); // close remaining open pipes foreach (array_keys($this->_openPipes) as $pipeNumber) { $this->_closePipe($pipeNumber); } $status = proc_get_status($this->_process); $exitCode = proc_close($this->_process); // proc_close() can return -1 in some cases, // get the real exit code from the process status if ($exitCode < 0 && $status && !$status['running']) { $exitCode = $status['exitcode']; } if ($exitCode > 0) { $this->_debug( '=> subprocess returned an unexpected exit code: ' . $exitCode ); } $this->_process = null; $this->_pipes = array(); // close file handles before throwing an exception if (is_resource($this->_input)) { fclose($this->_input); } if (is_resource($this->_output)) { fclose($this->_output); } $this->_processHandler->throwException($exitCode); } $this->_closeAgentLaunchProcess(); if ($this->_agentInfo !== null) { $parts = explode(':', $this->_agentInfo, 3); if (!empty($parts[1])) { $this->_debug('STOPPING GPG-AGENT DAEMON'); $process = new Crypt_GPG_ProcessControl($parts[1]); // terminate agent daemon $process->terminate(); while ($process->isRunning()) { usleep(10000); // 10 ms $process->terminate(); } $this->_debug('GPG-AGENT DAEMON STOPPED'); } $this->_agentInfo = null; } }
php
{ "resource": "" }
q256379
Crypt_GPG_Engine._closeAgentLaunchProcess
test
private function _closeAgentLaunchProcess() { if (is_resource($this->_agentProcess)) { $this->_debug('CLOSING GPG-AGENT LAUNCH PROCESS'); // close agent pipes foreach ($this->_agentPipes as $pipe) { fflush($pipe); fclose($pipe); } // close agent launching process proc_close($this->_agentProcess); $this->_agentProcess = null; $this->_agentPipes = array(); $this->_debug('GPG-AGENT LAUNCH PROCESS CLOSED'); } }
php
{ "resource": "" }
q256380
Crypt_GPG_Engine._closePipe
test
private function _closePipe($pipeNumber) { $pipeNumber = intval($pipeNumber); if (array_key_exists($pipeNumber, $this->_openPipes)) { fflush($this->_openPipes[$pipeNumber]); fclose($this->_openPipes[$pipeNumber]); unset($this->_openPipes[$pipeNumber]); } }
php
{ "resource": "" }
q256381
Crypt_GPG_Engine._closeIdleAgents
test
private function _closeIdleAgents() { if ($this->_gpgconf) { // before 2.1.13 --homedir wasn't supported, use env variable $env = array('GNUPGHOME' => $this->_homedir); $cmd = $this->_gpgconf . ' --kill gpg-agent'; if ($process = proc_open($cmd, array(), $pipes, null, $env)) { proc_close($process); } } }
php
{ "resource": "" }
q256382
Crypt_GPG_Engine._findBinary
test
private function _findBinary($name) { $binary = ''; if ($this->_isDarwin) { $locations = array( '/opt/local/bin/', // MacPorts '/usr/local/bin/', // Mac GPG '/sw/bin/', // Fink '/usr/bin/' ); } else { $locations = array( '/usr/bin/', '/usr/local/bin/' ); } foreach ($locations as $location) { if (is_executable($location . $name)) { $binary = $location . $name; break; } } return $binary; }
php
{ "resource": "" }
q256383
Crypt_GPG_Engine._getPinEntry
test
private function _getPinEntry() { // Find PinEntry program depending on the way how the package is installed $ds = DIRECTORY_SEPARATOR; $root = __DIR__ . $ds . '..' . $ds . '..' . $ds; $paths = array( '@bin-dir@', // PEAR $root . 'scripts', // Git $root . 'bin', // Composer ); foreach ($paths as $path) { if (file_exists($path . $ds . 'crypt-gpg-pinentry')) { return $path . $ds . 'crypt-gpg-pinentry'; } } }
php
{ "resource": "" }
q256384
Crypt_GPG_Engine._debug
test
private function _debug($text) { if ($this->_debug) { if (php_sapi_name() === 'cli') { foreach (explode(PHP_EOL, $text) as $line) { echo "Crypt_GPG DEBUG: ", $line, PHP_EOL; } } else if (is_callable($this->_debug)) { call_user_func($this->_debug, $text); } else { // running on a web server, format debug output nicely foreach (explode(PHP_EOL, $text) as $line) { echo "Crypt_GPG DEBUG: <strong>", htmlspecialchars($line), '</strong><br />', PHP_EOL; } } } }
php
{ "resource": "" }
q256385
Crypt_GPG_Key.getPrimaryKey
test
public function getPrimaryKey() { $primary_key = null; if (count($this->_subKeys) > 0) { $primary_key = $this->_subKeys[0]; } return $primary_key; }
php
{ "resource": "" }
q256386
Crypt_GPG_Key.canSign
test
public function canSign() { $canSign = false; foreach ($this->_subKeys as $subKey) { if ($subKey->canSign()) { $canSign = true; break; } } return $canSign; }
php
{ "resource": "" }
q256387
Crypt_GPG_Key.canEncrypt
test
public function canEncrypt() { $canEncrypt = false; foreach ($this->_subKeys as $subKey) { if ($subKey->canEncrypt()) { $canEncrypt = true; break; } } return $canEncrypt; }
php
{ "resource": "" }
q256388
Crypt_GPG_PinEntry.setLogFilename
test
public function setLogFilename($filename) { if (is_resource($this->logFile)) { fflush($this->logFile); fclose($this->logFile); $this->logFile = null; } if ($filename != '') { if (($this->logFile = fopen($filename, 'w')) === false) { $this->log( 'Unable to open log file "' . $filename . '" ' . 'for writing.' . PHP_EOL, self::VERBOSITY_ERRORS ); exit(1); } else { stream_set_write_buffer($this->logFile, 0); } } return $this; }
php
{ "resource": "" }
q256389
Crypt_GPG_PinEntry.log
test
protected function log($data, $level) { if ($this->verbosity >= $level) { if (is_resource($this->logFile)) { fwrite($this->logFile, $data); fflush($this->logFile); } else { $this->parser->outputter->stderr($data); } } return $this; }
php
{ "resource": "" }
q256390
Crypt_GPG_PinEntry.connect
test
protected function connect() { // Binary operations will not work on Windows with PHP < 5.2.6. $rb = (version_compare(PHP_VERSION, '5.2.6') < 0) ? 'r' : 'rb'; $wb = (version_compare(PHP_VERSION, '5.2.6') < 0) ? 'w' : 'wb'; $this->stdin = fopen('php://stdin', $rb); $this->stdout = fopen('php://stdout', $wb); if (function_exists('stream_set_read_buffer')) { stream_set_read_buffer($this->stdin, 0); } stream_set_write_buffer($this->stdout, 0); // initial handshake $this->send($this->getOK('Crypt_GPG pinentry ready and waiting')); return $this; }
php
{ "resource": "" }
q256391
Crypt_GPG_PinEntry.parseCommand
test
protected function parseCommand($line) { $this->log('<- ' . $line . PHP_EOL, self::VERBOSITY_ALL); $parts = explode(' ', $line, 2); $command = $parts[0]; if (count($parts) === 2) { $data = $parts[1]; } else { $data = null; } switch ($command) { case 'SETDESC': return $this->sendSetDescription($data); case 'MESSAGE': return $this->sendMessage(); case 'CONFIRM': return $this->sendConfirm(); case 'GETINFO': return $this->sendGetInfo($data); case 'GETPIN': return $this->sendGetPin($data); case 'RESET': return $this->sendReset(); case 'BYE': return $this->sendBye(); default: return $this->sendNotImplementedOK(); } }
php
{ "resource": "" }
q256392
Crypt_GPG_PinEntry.initPinsFromENV
test
protected function initPinsFromENV() { if (($userData = getenv('PINENTRY_USER_DATA')) !== false) { $pins = json_decode($userData, true); if ($pins === null) { $this->log( '-- failed to parse user data' . PHP_EOL, self::VERBOSITY_ERRORS ); } else { $this->pins = $pins; $this->log( '-- got user data [not showing passphrases]' . PHP_EOL, self::VERBOSITY_ALL ); } } return $this; }
php
{ "resource": "" }
q256393
Crypt_GPG_PinEntry.disconnect
test
protected function disconnect() { $this->log('-- disconnecting' . PHP_EOL, self::VERBOSITY_ALL); fflush($this->stdout); fclose($this->stdout); fclose($this->stdin); $this->stdin = null; $this->stdout = null; $this->log('-- disconnected' . PHP_EOL, self::VERBOSITY_ALL); if (is_resource($this->logFile)) { fflush($this->logFile); fclose($this->logFile); $this->logFile = null; } return $this; }
php
{ "resource": "" }
q256394
Crypt_GPG_PinEntry.sendSetDescription
test
protected function sendSetDescription($text) { $text = rawurldecode($text); $matches = array(); // TODO: handle user id with quotation marks $exp = '/\n"(.+)"\n.*\sID ([A-Z0-9]+),\n/mu'; if (preg_match($exp, $text, $matches) === 1) { $userId = $matches[1]; $keyId = $matches[2]; if ($this->currentPin === null || $this->currentPin['keyId'] !== $keyId) { $this->currentPin = array( 'userId' => $userId, 'keyId' => $keyId ); $this->log( '-- looking for PIN for ' . $keyId . PHP_EOL, self::VERBOSITY_ALL ); } } return $this->send($this->getOK()); }
php
{ "resource": "" }
q256395
Crypt_GPG_PinEntry.sendGetPin
test
protected function sendGetPin() { $foundPin = ''; if (is_array($this->currentPin)) { $keyIdLength = mb_strlen($this->currentPin['keyId'], '8bit'); // search for the pin foreach ($this->pins as $_keyId => $pin) { // Warning: GnuPG 2.1 asks 3 times for passphrase if it is invalid $keyId = $this->currentPin['keyId']; $_keyIdLength = mb_strlen($_keyId, '8bit'); // Get last X characters of key identifier to compare // Most GnuPG versions use 8 characters, but recent ones can use 16, // We support 8 for backward compatibility if ($keyIdLength < $_keyIdLength) { $_keyId = mb_substr($_keyId, -$keyIdLength, $keyIdLength, '8bit'); } else if ($keyIdLength > $_keyIdLength) { $keyId = mb_substr($keyId, -$_keyIdLength, $_keyIdLength, '8bit'); } if ($_keyId === $keyId) { $foundPin = $pin; break; } } } return $this ->send($this->getData($foundPin)) ->send($this->getOK()); }
php
{ "resource": "" }
q256396
Crypt_GPG_PinEntry.sendGetInfo
test
protected function sendGetInfo($data) { $parts = explode(' ', $data, 2); $command = reset($parts); switch ($command) { case 'pid': return $this->sendGetInfoPID(); default: return $this->send($this->getOK()); } return $this; }
php
{ "resource": "" }
q256397
Crypt_GPG_PinEntry.getData
test
protected function getData($data) { // Escape data. Only %, \n and \r need to be escaped but other // values are allowed to be escaped. See // http://www.gnupg.org/documentation/manuals/assuan/Server-responses.html $data = rawurlencode($data); $data = $this->getWordWrappedData($data, 'D'); return $data; }
php
{ "resource": "" }
q256398
Crypt_GPG_PinEntry.getWordWrappedData
test
protected function getWordWrappedData($data, $prefix) { $lines = array(); do { if (mb_strlen($data, '8bit') > 997) { $line = $prefix . ' ' . mb_strcut($data, 0, 996, 'utf-8') . "\\\n"; $lines[] = $line; $lineLength = mb_strlen($line, '8bit') - 1; $dataLength = mb_substr($data, '8bit'); $data = mb_substr( $data, $lineLength, $dataLength - $lineLength, '8bit' ); } else { $lines[] = $prefix . ' ' . $data . "\n"; $data = ''; } } while ($data != ''); return implode('', $lines); }
php
{ "resource": "" }
q256399
Crypt_GPG_PinEntry.send
test
protected function send($data) { $this->log('-> ' . $data, self::VERBOSITY_ALL); fwrite($this->stdout, $data); fflush($this->stdout); return $this; }
php
{ "resource": "" }