#!/usr/bin/env php '/lib/aws-sdk/Aws/Common/Aws.php', 'aws\\common\\client\\abstractclient' => '/lib/aws-sdk/Aws/Common/Client/AbstractClient.php', 'aws\\common\\client\\awsclientinterface' => '/lib/aws-sdk/Aws/Common/Client/AwsClientInterface.php', 'aws\\common\\client\\clientbuilder' => '/lib/aws-sdk/Aws/Common/Client/ClientBuilder.php', 'aws\\common\\client\\defaultclient' => '/lib/aws-sdk/Aws/Common/Client/DefaultClient.php', 'aws\\common\\client\\expiredcredentialschecker' => '/lib/aws-sdk/Aws/Common/Client/ExpiredCredentialsChecker.php', 'aws\\common\\client\\throttlingerrorchecker' => '/lib/aws-sdk/Aws/Common/Client/ThrottlingErrorChecker.php', 'aws\\common\\client\\uploadbodylistener' => '/lib/aws-sdk/Aws/Common/Client/UploadBodyListener.php', 'aws\\common\\client\\useragentlistener' => '/lib/aws-sdk/Aws/Common/Client/UserAgentListener.php', 'aws\\common\\command\\awsqueryvisitor' => '/lib/aws-sdk/Aws/Common/Command/AwsQueryVisitor.php', 'aws\\common\\command\\jsoncommand' => '/lib/aws-sdk/Aws/Common/Command/JsonCommand.php', 'aws\\common\\command\\querycommand' => '/lib/aws-sdk/Aws/Common/Command/QueryCommand.php', 'aws\\common\\command\\xmlresponselocationvisitor' => '/lib/aws-sdk/Aws/Common/Command/XmlResponseLocationVisitor.php', 'aws\\common\\credentials\\abstractcredentialsdecorator' => '/lib/aws-sdk/Aws/Common/Credentials/AbstractCredentialsDecorator.php', 'aws\\common\\credentials\\abstractrefreshablecredentials' => '/lib/aws-sdk/Aws/Common/Credentials/AbstractRefreshableCredentials.php', 'aws\\common\\credentials\\cacheablecredentials' => '/lib/aws-sdk/Aws/Common/Credentials/CacheableCredentials.php', 'aws\\common\\credentials\\credentials' => '/lib/aws-sdk/Aws/Common/Credentials/Credentials.php', 'aws\\common\\credentials\\credentialsinterface' => '/lib/aws-sdk/Aws/Common/Credentials/CredentialsInterface.php', 'aws\\common\\credentials\\nullcredentials' => '/lib/aws-sdk/Aws/Common/Credentials/NullCredentials.php', 'aws\\common\\credentials\\refreshableinstanceprofilecredentials' => '/lib/aws-sdk/Aws/Common/Credentials/RefreshableInstanceProfileCredentials.php', 'aws\\common\\enum' => '/lib/aws-sdk/Aws/Common/Enum.php', 'aws\\common\\enum\\clientoptions' => '/lib/aws-sdk/Aws/Common/Enum/ClientOptions.php', 'aws\\common\\enum\\dateformat' => '/lib/aws-sdk/Aws/Common/Enum/DateFormat.php', 'aws\\common\\enum\\region' => '/lib/aws-sdk/Aws/Common/Enum/Region.php', 'aws\\common\\enum\\size' => '/lib/aws-sdk/Aws/Common/Enum/Size.php', 'aws\\common\\enum\\time' => '/lib/aws-sdk/Aws/Common/Enum/Time.php', 'aws\\common\\enum\\uastring' => '/lib/aws-sdk/Aws/Common/Enum/UaString.php', 'aws\\common\\exception\\awsexceptioninterface' => '/lib/aws-sdk/Aws/Common/Exception/AwsExceptionInterface.php', 'aws\\common\\exception\\badmethodcallexception' => '/lib/aws-sdk/Aws/Common/Exception/BadMethodCallException.php', 'aws\\common\\exception\\domainexception' => '/lib/aws-sdk/Aws/Common/Exception/DomainException.php', 'aws\\common\\exception\\exceptionfactoryinterface' => '/lib/aws-sdk/Aws/Common/Exception/ExceptionFactoryInterface.php', 'aws\\common\\exception\\exceptionlistener' => '/lib/aws-sdk/Aws/Common/Exception/ExceptionListener.php', 'aws\\common\\exception\\instanceprofilecredentialsexception' => '/lib/aws-sdk/Aws/Common/Exception/InstanceProfileCredentialsException.php', 'aws\\common\\exception\\invalidargumentexception' => '/lib/aws-sdk/Aws/Common/Exception/InvalidArgumentException.php', 'aws\\common\\exception\\logicexception' => '/lib/aws-sdk/Aws/Common/Exception/LogicException.php', 'aws\\common\\exception\\multipartuploadexception' => '/lib/aws-sdk/Aws/Common/Exception/MultipartUploadException.php', 'aws\\common\\exception\\namespaceexceptionfactory' => '/lib/aws-sdk/Aws/Common/Exception/NamespaceExceptionFactory.php', 'aws\\common\\exception\\outofboundsexception' => '/lib/aws-sdk/Aws/Common/Exception/OutOfBoundsException.php', 'aws\\common\\exception\\overflowexception' => '/lib/aws-sdk/Aws/Common/Exception/OverflowException.php', 'aws\\common\\exception\\parser\\abstractjsonexceptionparser' => '/lib/aws-sdk/Aws/Common/Exception/Parser/AbstractJsonExceptionParser.php', 'aws\\common\\exception\\parser\\defaultxmlexceptionparser' => '/lib/aws-sdk/Aws/Common/Exception/Parser/DefaultXmlExceptionParser.php', 'aws\\common\\exception\\parser\\exceptionparserinterface' => '/lib/aws-sdk/Aws/Common/Exception/Parser/ExceptionParserInterface.php', 'aws\\common\\exception\\parser\\jsonqueryexceptionparser' => '/lib/aws-sdk/Aws/Common/Exception/Parser/JsonQueryExceptionParser.php', 'aws\\common\\exception\\parser\\jsonrestexceptionparser' => '/lib/aws-sdk/Aws/Common/Exception/Parser/JsonRestExceptionParser.php', 'aws\\common\\exception\\requiredextensionnotloadedexception' => '/lib/aws-sdk/Aws/Common/Exception/RequiredExtensionNotLoadedException.php', 'aws\\common\\exception\\runtimeexception' => '/lib/aws-sdk/Aws/Common/Exception/RuntimeException.php', 'aws\\common\\exception\\serviceresponseexception' => '/lib/aws-sdk/Aws/Common/Exception/ServiceResponseException.php', 'aws\\common\\exception\\transferexception' => '/lib/aws-sdk/Aws/Common/Exception/TransferException.php', 'aws\\common\\exception\\unexpectedvalueexception' => '/lib/aws-sdk/Aws/Common/Exception/UnexpectedValueException.php', 'aws\\common\\facade\\autoscaling' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\cloudformation' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\cloudfront' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\cloudsearch' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\cloudtrail' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\cloudwatch' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\datapipeline' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\directconnect' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\dynamodb' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\ec2' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\elasticache' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\elasticbeanstalk' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\elasticloadbalancing' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\elastictranscoder' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\emr' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\facade' => '/lib/aws-sdk/Aws/Common/Facade/Facade.php', 'aws\\common\\facade\\facadeinterface' => '/lib/aws-sdk/Aws/Common/Facade/FacadeInterface.php', 'aws\\common\\facade\\glacier' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\iam' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\importexport' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\kinesis' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\opsworks' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\rds' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\redshift' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\route53' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\s3' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\ses' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\simpledb' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\sns' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\sqs' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\storagegateway' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\sts' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\support' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\facade\\swf' => '/lib/aws-sdk/Aws/Common/Facade/facade-classes.php', 'aws\\common\\hash\\chunkhash' => '/lib/aws-sdk/Aws/Common/Hash/ChunkHash.php', 'aws\\common\\hash\\chunkhashinterface' => '/lib/aws-sdk/Aws/Common/Hash/ChunkHashInterface.php', 'aws\\common\\hash\\hashutils' => '/lib/aws-sdk/Aws/Common/Hash/HashUtils.php', 'aws\\common\\hash\\treehash' => '/lib/aws-sdk/Aws/Common/Hash/TreeHash.php', 'aws\\common\\hostnameutils' => '/lib/aws-sdk/Aws/Common/HostNameUtils.php', 'aws\\common\\instancemetadata\\instancemetadataclient' => '/lib/aws-sdk/Aws/Common/InstanceMetadata/InstanceMetadataClient.php', 'aws\\common\\instancemetadata\\waiter\\serviceavailable' => '/lib/aws-sdk/Aws/Common/InstanceMetadata/Waiter/ServiceAvailable.php', 'aws\\common\\iterator\\awsresourceiterator' => '/lib/aws-sdk/Aws/Common/Iterator/AwsResourceIterator.php', 'aws\\common\\iterator\\awsresourceiteratorfactory' => '/lib/aws-sdk/Aws/Common/Iterator/AwsResourceIteratorFactory.php', 'aws\\common\\model\\multipartupload\\abstracttransfer' => '/lib/aws-sdk/Aws/Common/Model/MultipartUpload/AbstractTransfer.php', 'aws\\common\\model\\multipartupload\\abstracttransferstate' => '/lib/aws-sdk/Aws/Common/Model/MultipartUpload/AbstractTransferState.php', 'aws\\common\\model\\multipartupload\\abstractuploadbuilder' => '/lib/aws-sdk/Aws/Common/Model/MultipartUpload/AbstractUploadBuilder.php', 'aws\\common\\model\\multipartupload\\abstractuploadid' => '/lib/aws-sdk/Aws/Common/Model/MultipartUpload/AbstractUploadId.php', 'aws\\common\\model\\multipartupload\\abstractuploadpart' => '/lib/aws-sdk/Aws/Common/Model/MultipartUpload/AbstractUploadPart.php', 'aws\\common\\model\\multipartupload\\transferinterface' => '/lib/aws-sdk/Aws/Common/Model/MultipartUpload/TransferInterface.php', 'aws\\common\\model\\multipartupload\\transferstateinterface' => '/lib/aws-sdk/Aws/Common/Model/MultipartUpload/TransferStateInterface.php', 'aws\\common\\model\\multipartupload\\uploadidinterface' => '/lib/aws-sdk/Aws/Common/Model/MultipartUpload/UploadIdInterface.php', 'aws\\common\\model\\multipartupload\\uploadpartinterface' => '/lib/aws-sdk/Aws/Common/Model/MultipartUpload/UploadPartInterface.php', 'aws\\common\\rulesendpointprovider' => '/lib/aws-sdk/Aws/Common/RulesEndpointProvider.php', 'aws\\common\\signature\\abstractsignature' => '/lib/aws-sdk/Aws/Common/Signature/AbstractSignature.php', 'aws\\common\\signature\\endpointsignatureinterface' => '/lib/aws-sdk/Aws/Common/Signature/EndpointSignatureInterface.php', 'aws\\common\\signature\\signatureinterface' => '/lib/aws-sdk/Aws/Common/Signature/SignatureInterface.php', 'aws\\common\\signature\\signaturelistener' => '/lib/aws-sdk/Aws/Common/Signature/SignatureListener.php', 'aws\\common\\signature\\signaturev2' => '/lib/aws-sdk/Aws/Common/Signature/SignatureV2.php', 'aws\\common\\signature\\signaturev3https' => '/lib/aws-sdk/Aws/Common/Signature/SignatureV3Https.php', 'aws\\common\\signature\\signaturev4' => '/lib/aws-sdk/Aws/Common/Signature/SignatureV4.php', 'aws\\common\\waiter\\abstractresourcewaiter' => '/lib/aws-sdk/Aws/Common/Waiter/AbstractResourceWaiter.php', 'aws\\common\\waiter\\abstractwaiter' => '/lib/aws-sdk/Aws/Common/Waiter/AbstractWaiter.php', 'aws\\common\\waiter\\callablewaiter' => '/lib/aws-sdk/Aws/Common/Waiter/CallableWaiter.php', 'aws\\common\\waiter\\compositewaiterfactory' => '/lib/aws-sdk/Aws/Common/Waiter/CompositeWaiterFactory.php', 'aws\\common\\waiter\\configresourcewaiter' => '/lib/aws-sdk/Aws/Common/Waiter/ConfigResourceWaiter.php', 'aws\\common\\waiter\\resourcewaiterinterface' => '/lib/aws-sdk/Aws/Common/Waiter/ResourceWaiterInterface.php', 'aws\\common\\waiter\\waiterclassfactory' => '/lib/aws-sdk/Aws/Common/Waiter/WaiterClassFactory.php', 'aws\\common\\waiter\\waiterconfig' => '/lib/aws-sdk/Aws/Common/Waiter/WaiterConfig.php', 'aws\\common\\waiter\\waiterconfigfactory' => '/lib/aws-sdk/Aws/Common/Waiter/WaiterConfigFactory.php', 'aws\\common\\waiter\\waiterfactoryinterface' => '/lib/aws-sdk/Aws/Common/Waiter/WaiterFactoryInterface.php', 'aws\\common\\waiter\\waiterinterface' => '/lib/aws-sdk/Aws/Common/Waiter/WaiterInterface.php', 'aws\\s3\\acplistener' => '/lib/aws-sdk/Aws/S3/AcpListener.php', 'aws\\s3\\bucketstylelistener' => '/lib/aws-sdk/Aws/S3/BucketStyleListener.php', 'aws\\s3\\command\\s3command' => '/lib/aws-sdk/Aws/S3/Command/S3Command.php', 'aws\\s3\\enum\\cannedacl' => '/lib/aws-sdk/Aws/S3/Enum/CannedAcl.php', 'aws\\s3\\enum\\encodingtype' => '/lib/aws-sdk/Aws/S3/Enum/EncodingType.php', 'aws\\s3\\enum\\event' => '/lib/aws-sdk/Aws/S3/Enum/Event.php', 'aws\\s3\\enum\\granteetype' => '/lib/aws-sdk/Aws/S3/Enum/GranteeType.php', 'aws\\s3\\enum\\group' => '/lib/aws-sdk/Aws/S3/Enum/Group.php', 'aws\\s3\\enum\\metadatadirective' => '/lib/aws-sdk/Aws/S3/Enum/MetadataDirective.php', 'aws\\s3\\enum\\mfadelete' => '/lib/aws-sdk/Aws/S3/Enum/MFADelete.php', 'aws\\s3\\enum\\payer' => '/lib/aws-sdk/Aws/S3/Enum/Payer.php', 'aws\\s3\\enum\\permission' => '/lib/aws-sdk/Aws/S3/Enum/Permission.php', 'aws\\s3\\enum\\protocol' => '/lib/aws-sdk/Aws/S3/Enum/Protocol.php', 'aws\\s3\\enum\\serversideencryption' => '/lib/aws-sdk/Aws/S3/Enum/ServerSideEncryption.php', 'aws\\s3\\enum\\status' => '/lib/aws-sdk/Aws/S3/Enum/Status.php', 'aws\\s3\\enum\\storage' => '/lib/aws-sdk/Aws/S3/Enum/Storage.php', 'aws\\s3\\enum\\storageclass' => '/lib/aws-sdk/Aws/S3/Enum/StorageClass.php', 'aws\\s3\\exception\\accessdeniedexception' => '/lib/aws-sdk/Aws/S3/Exception/AccessDeniedException.php', 'aws\\s3\\exception\\accountproblemexception' => '/lib/aws-sdk/Aws/S3/Exception/AccountProblemException.php', 'aws\\s3\\exception\\ambiguousgrantbyemailaddressexception' => '/lib/aws-sdk/Aws/S3/Exception/AmbiguousGrantByEmailAddressException.php', 'aws\\s3\\exception\\baddigestexception' => '/lib/aws-sdk/Aws/S3/Exception/BadDigestException.php', 'aws\\s3\\exception\\bucketalreadyexistsexception' => '/lib/aws-sdk/Aws/S3/Exception/BucketAlreadyExistsException.php', 'aws\\s3\\exception\\bucketalreadyownedbyyouexception' => '/lib/aws-sdk/Aws/S3/Exception/BucketAlreadyOwnedByYouException.php', 'aws\\s3\\exception\\bucketnotemptyexception' => '/lib/aws-sdk/Aws/S3/Exception/BucketNotEmptyException.php', 'aws\\s3\\exception\\credentialsnotsupportedexception' => '/lib/aws-sdk/Aws/S3/Exception/CredentialsNotSupportedException.php', 'aws\\s3\\exception\\crosslocationloggingprohibitedexception' => '/lib/aws-sdk/Aws/S3/Exception/CrossLocationLoggingProhibitedException.php', 'aws\\s3\\exception\\deletemultipleobjectsexception' => '/lib/aws-sdk/Aws/S3/Exception/DeleteMultipleObjectsException.php', 'aws\\s3\\exception\\entitytoolargeexception' => '/lib/aws-sdk/Aws/S3/Exception/EntityTooLargeException.php', 'aws\\s3\\exception\\entitytoosmallexception' => '/lib/aws-sdk/Aws/S3/Exception/EntityTooSmallException.php', 'aws\\s3\\exception\\expiredtokenexception' => '/lib/aws-sdk/Aws/S3/Exception/ExpiredTokenException.php', 'aws\\s3\\exception\\illegalversioningconfigurationexception' => '/lib/aws-sdk/Aws/S3/Exception/IllegalVersioningConfigurationException.php', 'aws\\s3\\exception\\incompletebodyexception' => '/lib/aws-sdk/Aws/S3/Exception/IncompleteBodyException.php', 'aws\\s3\\exception\\incorrectnumberoffilesinpostrequestexception' => '/lib/aws-sdk/Aws/S3/Exception/IncorrectNumberOfFilesInPostRequestException.php', 'aws\\s3\\exception\\inlinedatatoolargeexception' => '/lib/aws-sdk/Aws/S3/Exception/InlineDataTooLargeException.php', 'aws\\s3\\exception\\internalerrorexception' => '/lib/aws-sdk/Aws/S3/Exception/InternalErrorException.php', 'aws\\s3\\exception\\invalidaccesskeyidexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidAccessKeyIdException.php', 'aws\\s3\\exception\\invalidaddressingheaderexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidAddressingHeaderException.php', 'aws\\s3\\exception\\invalidargumentexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidArgumentException.php', 'aws\\s3\\exception\\invalidbucketnameexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidBucketNameException.php', 'aws\\s3\\exception\\invalidbucketstateexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidBucketStateException.php', 'aws\\s3\\exception\\invaliddigestexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidDigestException.php', 'aws\\s3\\exception\\invalidlocationconstraintexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidLocationConstraintException.php', 'aws\\s3\\exception\\invalidpartexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidPartException.php', 'aws\\s3\\exception\\invalidpartorderexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidPartOrderException.php', 'aws\\s3\\exception\\invalidpayerexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidPayerException.php', 'aws\\s3\\exception\\invalidpolicydocumentexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidPolicyDocumentException.php', 'aws\\s3\\exception\\invalidrangeexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidRangeException.php', 'aws\\s3\\exception\\invalidrequestexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidRequestException.php', 'aws\\s3\\exception\\invalidsecurityexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidSecurityException.php', 'aws\\s3\\exception\\invalidsoaprequestexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidSOAPRequestException.php', 'aws\\s3\\exception\\invalidstorageclassexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidStorageClassException.php', 'aws\\s3\\exception\\invalidtagerrorexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidTagErrorException.php', 'aws\\s3\\exception\\invalidtargetbucketforloggingexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidTargetBucketForLoggingException.php', 'aws\\s3\\exception\\invalidtokenexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidTokenException.php', 'aws\\s3\\exception\\invaliduriexception' => '/lib/aws-sdk/Aws/S3/Exception/InvalidURIException.php', 'aws\\s3\\exception\\keytoolongexception' => '/lib/aws-sdk/Aws/S3/Exception/KeyTooLongException.php', 'aws\\s3\\exception\\malformedaclerrorexception' => '/lib/aws-sdk/Aws/S3/Exception/MalformedACLErrorException.php', 'aws\\s3\\exception\\malformedpostrequestexception' => '/lib/aws-sdk/Aws/S3/Exception/MalformedPOSTRequestException.php', 'aws\\s3\\exception\\malformedxmlexception' => '/lib/aws-sdk/Aws/S3/Exception/MalformedXMLException.php', 'aws\\s3\\exception\\maxmessagelengthexceededexception' => '/lib/aws-sdk/Aws/S3/Exception/MaxMessageLengthExceededException.php', 'aws\\s3\\exception\\maxpostpredatalengthexceedederrorexception' => '/lib/aws-sdk/Aws/S3/Exception/MaxPostPreDataLengthExceededErrorException.php', 'aws\\s3\\exception\\metadatatoolargeexception' => '/lib/aws-sdk/Aws/S3/Exception/MetadataTooLargeException.php', 'aws\\s3\\exception\\methodnotallowedexception' => '/lib/aws-sdk/Aws/S3/Exception/MethodNotAllowedException.php', 'aws\\s3\\exception\\missingattachmentexception' => '/lib/aws-sdk/Aws/S3/Exception/MissingAttachmentException.php', 'aws\\s3\\exception\\missingcontentlengthexception' => '/lib/aws-sdk/Aws/S3/Exception/MissingContentLengthException.php', 'aws\\s3\\exception\\missingrequestbodyerrorexception' => '/lib/aws-sdk/Aws/S3/Exception/MissingRequestBodyErrorException.php', 'aws\\s3\\exception\\missingsecurityelementexception' => '/lib/aws-sdk/Aws/S3/Exception/MissingSecurityElementException.php', 'aws\\s3\\exception\\missingsecurityheaderexception' => '/lib/aws-sdk/Aws/S3/Exception/MissingSecurityHeaderException.php', 'aws\\s3\\exception\\nologgingstatusforkeyexception' => '/lib/aws-sdk/Aws/S3/Exception/NoLoggingStatusForKeyException.php', 'aws\\s3\\exception\\nosuchbucketexception' => '/lib/aws-sdk/Aws/S3/Exception/NoSuchBucketException.php', 'aws\\s3\\exception\\nosuchbucketpolicyexception' => '/lib/aws-sdk/Aws/S3/Exception/NoSuchBucketPolicyException.php', 'aws\\s3\\exception\\nosuchcorsconfigurationexception' => '/lib/aws-sdk/Aws/S3/Exception/NoSuchCORSConfigurationException.php', 'aws\\s3\\exception\\nosuchkeyexception' => '/lib/aws-sdk/Aws/S3/Exception/NoSuchKeyException.php', 'aws\\s3\\exception\\nosuchlifecycleconfigurationexception' => '/lib/aws-sdk/Aws/S3/Exception/NoSuchLifecycleConfigurationException.php', 'aws\\s3\\exception\\nosuchtagseterrorexception' => '/lib/aws-sdk/Aws/S3/Exception/NoSuchTagSetErrorException.php', 'aws\\s3\\exception\\nosuchuploadexception' => '/lib/aws-sdk/Aws/S3/Exception/NoSuchUploadException.php', 'aws\\s3\\exception\\nosuchversionexception' => '/lib/aws-sdk/Aws/S3/Exception/NoSuchVersionException.php', 'aws\\s3\\exception\\nosuchwebsiteconfigurationexception' => '/lib/aws-sdk/Aws/S3/Exception/NoSuchWebsiteConfigurationException.php', 'aws\\s3\\exception\\notimplementedexception' => '/lib/aws-sdk/Aws/S3/Exception/NotImplementedException.php', 'aws\\s3\\exception\\notsignedupexception' => '/lib/aws-sdk/Aws/S3/Exception/NotSignedUpException.php', 'aws\\s3\\exception\\notsuchbucketpolicyexception' => '/lib/aws-sdk/Aws/S3/Exception/NotSuchBucketPolicyException.php', 'aws\\s3\\exception\\objectalreadyinactivetiererrorexception' => '/lib/aws-sdk/Aws/S3/Exception/ObjectAlreadyInActiveTierErrorException.php', 'aws\\s3\\exception\\objectnotinactivetiererrorexception' => '/lib/aws-sdk/Aws/S3/Exception/ObjectNotInActiveTierErrorException.php', 'aws\\s3\\exception\\operationabortedexception' => '/lib/aws-sdk/Aws/S3/Exception/OperationAbortedException.php', 'aws\\s3\\exception\\parser\\s3exceptionparser' => '/lib/aws-sdk/Aws/S3/Exception/Parser/S3ExceptionParser.php', 'aws\\s3\\exception\\permanentredirectexception' => '/lib/aws-sdk/Aws/S3/Exception/PermanentRedirectException.php', 'aws\\s3\\exception\\preconditionfailedexception' => '/lib/aws-sdk/Aws/S3/Exception/PreconditionFailedException.php', 'aws\\s3\\exception\\redirectexception' => '/lib/aws-sdk/Aws/S3/Exception/RedirectException.php', 'aws\\s3\\exception\\requestisnotmultipartcontentexception' => '/lib/aws-sdk/Aws/S3/Exception/RequestIsNotMultiPartContentException.php', 'aws\\s3\\exception\\requesttimeoutexception' => '/lib/aws-sdk/Aws/S3/Exception/RequestTimeoutException.php', 'aws\\s3\\exception\\requesttimetooskewedexception' => '/lib/aws-sdk/Aws/S3/Exception/RequestTimeTooSkewedException.php', 'aws\\s3\\exception\\requesttorrentofbucketerrorexception' => '/lib/aws-sdk/Aws/S3/Exception/RequestTorrentOfBucketErrorException.php', 'aws\\s3\\exception\\s3exception' => '/lib/aws-sdk/Aws/S3/Exception/S3Exception.php', 'aws\\s3\\exception\\serviceunavailableexception' => '/lib/aws-sdk/Aws/S3/Exception/ServiceUnavailableException.php', 'aws\\s3\\exception\\signaturedoesnotmatchexception' => '/lib/aws-sdk/Aws/S3/Exception/SignatureDoesNotMatchException.php', 'aws\\s3\\exception\\slowdownexception' => '/lib/aws-sdk/Aws/S3/Exception/SlowDownException.php', 'aws\\s3\\exception\\temporaryredirectexception' => '/lib/aws-sdk/Aws/S3/Exception/TemporaryRedirectException.php', 'aws\\s3\\exception\\tokenrefreshrequiredexception' => '/lib/aws-sdk/Aws/S3/Exception/TokenRefreshRequiredException.php', 'aws\\s3\\exception\\toomanybucketsexception' => '/lib/aws-sdk/Aws/S3/Exception/TooManyBucketsException.php', 'aws\\s3\\exception\\unexpectedcontentexception' => '/lib/aws-sdk/Aws/S3/Exception/UnexpectedContentException.php', 'aws\\s3\\exception\\unresolvablegrantbyemailaddressexception' => '/lib/aws-sdk/Aws/S3/Exception/UnresolvableGrantByEmailAddressException.php', 'aws\\s3\\exception\\userkeymustbespecifiedexception' => '/lib/aws-sdk/Aws/S3/Exception/UserKeyMustBeSpecifiedException.php', 'aws\\s3\\iterator\\listbucketsiterator' => '/lib/aws-sdk/Aws/S3/Iterator/ListBucketsIterator.php', 'aws\\s3\\iterator\\listmultipartuploadsiterator' => '/lib/aws-sdk/Aws/S3/Iterator/ListMultipartUploadsIterator.php', 'aws\\s3\\iterator\\listobjectsiterator' => '/lib/aws-sdk/Aws/S3/Iterator/ListObjectsIterator.php', 'aws\\s3\\iterator\\listobjectversionsiterator' => '/lib/aws-sdk/Aws/S3/Iterator/ListObjectVersionsIterator.php', 'aws\\s3\\iterator\\opendiriterator' => '/lib/aws-sdk/Aws/S3/Iterator/OpendirIterator.php', 'aws\\s3\\model\\acp' => '/lib/aws-sdk/Aws/S3/Model/Acp.php', 'aws\\s3\\model\\acpbuilder' => '/lib/aws-sdk/Aws/S3/Model/AcpBuilder.php', 'aws\\s3\\model\\clearbucket' => '/lib/aws-sdk/Aws/S3/Model/ClearBucket.php', 'aws\\s3\\model\\deleteobjectsbatch' => '/lib/aws-sdk/Aws/S3/Model/DeleteObjectsBatch.php', 'aws\\s3\\model\\deleteobjectstransfer' => '/lib/aws-sdk/Aws/S3/Model/DeleteObjectsTransfer.php', 'aws\\s3\\model\\grant' => '/lib/aws-sdk/Aws/S3/Model/Grant.php', 'aws\\s3\\model\\grantee' => '/lib/aws-sdk/Aws/S3/Model/Grantee.php', 'aws\\s3\\model\\multipartupload\\abstracttransfer' => '/lib/aws-sdk/Aws/S3/Model/MultipartUpload/AbstractTransfer.php', 'aws\\s3\\model\\multipartupload\\paralleltransfer' => '/lib/aws-sdk/Aws/S3/Model/MultipartUpload/ParallelTransfer.php', 'aws\\s3\\model\\multipartupload\\serialtransfer' => '/lib/aws-sdk/Aws/S3/Model/MultipartUpload/SerialTransfer.php', 'aws\\s3\\model\\multipartupload\\transferstate' => '/lib/aws-sdk/Aws/S3/Model/MultipartUpload/TransferState.php', 'aws\\s3\\model\\multipartupload\\uploadbuilder' => '/lib/aws-sdk/Aws/S3/Model/MultipartUpload/UploadBuilder.php', 'aws\\s3\\model\\multipartupload\\uploadid' => '/lib/aws-sdk/Aws/S3/Model/MultipartUpload/UploadId.php', 'aws\\s3\\model\\multipartupload\\uploadpart' => '/lib/aws-sdk/Aws/S3/Model/MultipartUpload/UploadPart.php', 'aws\\s3\\model\\postobject' => '/lib/aws-sdk/Aws/S3/Model/PostObject.php', 'aws\\s3\\resumabledownload' => '/lib/aws-sdk/Aws/S3/ResumableDownload.php', 'aws\\s3\\s3client' => '/lib/aws-sdk/Aws/S3/S3Client.php', 'aws\\s3\\s3md5listener' => '/lib/aws-sdk/Aws/S3/S3Md5Listener.php', 'aws\\s3\\s3signature' => '/lib/aws-sdk/Aws/S3/S3Signature.php', 'aws\\s3\\s3signatureinterface' => '/lib/aws-sdk/Aws/S3/S3SignatureInterface.php', 'aws\\s3\\s3signaturev4' => '/lib/aws-sdk/Aws/S3/S3SignatureV4.php', 'aws\\s3\\sockettimeoutchecker' => '/lib/aws-sdk/Aws/S3/SocketTimeoutChecker.php', 'aws\\s3\\ssecpklistener' => '/lib/aws-sdk/Aws/S3/SseCpkListener.php', 'aws\\s3\\streamwrapper' => '/lib/aws-sdk/Aws/S3/StreamWrapper.php', 'aws\\s3\\sync\\abstractsync' => '/lib/aws-sdk/Aws/S3/Sync/AbstractSync.php', 'aws\\s3\\sync\\abstractsyncbuilder' => '/lib/aws-sdk/Aws/S3/Sync/AbstractSyncBuilder.php', 'aws\\s3\\sync\\changedfilesiterator' => '/lib/aws-sdk/Aws/S3/Sync/ChangedFilesIterator.php', 'aws\\s3\\sync\\downloadsync' => '/lib/aws-sdk/Aws/S3/Sync/DownloadSync.php', 'aws\\s3\\sync\\downloadsyncbuilder' => '/lib/aws-sdk/Aws/S3/Sync/DownloadSyncBuilder.php', 'aws\\s3\\sync\\filenameconverterinterface' => '/lib/aws-sdk/Aws/S3/Sync/FilenameConverterInterface.php', 'aws\\s3\\sync\\keyconverter' => '/lib/aws-sdk/Aws/S3/Sync/KeyConverter.php', 'aws\\s3\\sync\\uploadsync' => '/lib/aws-sdk/Aws/S3/Sync/UploadSync.php', 'aws\\s3\\sync\\uploadsyncbuilder' => '/lib/aws-sdk/Aws/S3/Sync/UploadSyncBuilder.php', 'barracuda\\copy\\api' => '/lib/copy/API.php', 'dropbox\\appinfo' => '/lib/dropbox/AppInfo.php', 'dropbox\\appinfoloadexception' => '/lib/dropbox/AppInfoLoadException.php', 'dropbox\\arrayentrystore' => '/lib/dropbox/ArrayEntryStore.php', 'dropbox\\authbase' => '/lib/dropbox/AuthBase.php', 'dropbox\\authinfo' => '/lib/dropbox/AuthInfo.php', 'dropbox\\authinfoloadexception' => '/lib/dropbox/AuthInfoLoadException.php', 'dropbox\\checker' => '/lib/dropbox/Checker.php', 'dropbox\\client' => '/lib/dropbox/Client.php', 'dropbox\\curl' => '/lib/dropbox/Curl.php', 'dropbox\\curlstreamrelay' => '/lib/dropbox/CurlStreamRelay.php', 'dropbox\\deserializeexception' => '/lib/dropbox/DeserializeException.php', 'dropbox\\dropboxmetadataheadercatcher' => '/lib/dropbox/DropboxMetadataHeaderCatcher.php', 'dropbox\\exception' => '/lib/dropbox/Exception.php', 'dropbox\\exception_badrequest' => '/lib/dropbox/Exception/BadRequest.php', 'dropbox\\exception_badresponse' => '/lib/dropbox/Exception/BadResponse.php', 'dropbox\\exception_badresponsecode' => '/lib/dropbox/Exception/BadResponseCode.php', 'dropbox\\exception_invalidaccesstoken' => '/lib/dropbox/Exception/InvalidAccessToken.php', 'dropbox\\exception_networkio' => '/lib/dropbox/Exception/NetworkIO.php', 'dropbox\\exception_protocolerror' => '/lib/dropbox/Exception/ProtocolError.php', 'dropbox\\exception_retrylater' => '/lib/dropbox/Exception/RetryLater.php', 'dropbox\\exception_servererror' => '/lib/dropbox/Exception/ServerError.php', 'dropbox\\host' => '/lib/dropbox/Host.php', 'dropbox\\httpresponse' => '/lib/dropbox/HttpResponse.php', 'dropbox\\oauth1accesstoken' => '/lib/dropbox/OAuth1AccessToken.php', 'dropbox\\oauth1upgrader' => '/lib/dropbox/OAuth1Upgrader.php', 'dropbox\\path' => '/lib/dropbox/Path.php', 'dropbox\\requestutil' => '/lib/dropbox/RequestUtil.php', 'dropbox\\rootcertificates' => '/lib/dropbox/RootCertificates.php', 'dropbox\\security' => '/lib/dropbox/Security.php', 'dropbox\\ssltester' => '/lib/dropbox/SSLTester.php', 'dropbox\\streamreadexception' => '/lib/dropbox/StreamReadException.php', 'dropbox\\util' => '/lib/dropbox/Util.php', 'dropbox\\valuestore' => '/lib/dropbox/ValueStore.php', 'dropbox\\webauth' => '/lib/dropbox/WebAuth.php', 'dropbox\\webauthbase' => '/lib/dropbox/WebAuthBase.php', 'dropbox\\webauthexception_badrequest' => '/lib/dropbox/WebAuthException/BadRequest.php', 'dropbox\\webauthexception_badstate' => '/lib/dropbox/WebAuthException/BadState.php', 'dropbox\\webauthexception_csrf' => '/lib/dropbox/WebAuthException/Csrf.php', 'dropbox\\webauthexception_notapproved' => '/lib/dropbox/WebAuthException/NotApproved.php', 'dropbox\\webauthexception_provider' => '/lib/dropbox/WebAuthException/Provider.php', 'dropbox\\webauthnoredirect' => '/lib/dropbox/WebAuthNoRedirect.php', 'dropbox\\writemode' => '/lib/dropbox/WriteMode.php', 'eher\\oauth\\consumer' => '/lib/eher/Eher/OAuth/Consumer.php', 'eher\\oauth\\hmacsha1' => '/lib/eher/Eher/OAuth/HmacSha1.php', 'eher\\oauth\\oauthdatastore' => '/lib/eher/Eher/OAuth/OAuthDataStore.php', 'eher\\oauth\\oauthexception' => '/lib/eher/Eher/OAuth/OAuthException.php', 'eher\\oauth\\oauthserver' => '/lib/eher/Eher/OAuth/OAuthServer.php', 'eher\\oauth\\plaintext' => '/lib/eher/Eher/OAuth/PlainText.php', 'eher\\oauth\\request' => '/lib/eher/Eher/OAuth/Request.php', 'eher\\oauth\\signaturemethod' => '/lib/eher/Eher/OAuth/SignatureMethod.php', 'eher\\oauth\\signaturemethod\\rsasha1' => '/lib/eher/Eher/OAuth/RsaSha1.php', 'eher\\oauth\\token' => '/lib/eher/Eher/OAuth/Token.php', 'eher\\oauth\\util' => '/lib/eher/Eher/OAuth/Util.php', 'guzzle\\batch\\abstractbatchdecorator' => '/lib/guzzle/Guzzle/Batch/AbstractBatchDecorator.php', 'guzzle\\batch\\batch' => '/lib/guzzle/Guzzle/Batch/Batch.php', 'guzzle\\batch\\batchbuilder' => '/lib/guzzle/Guzzle/Batch/BatchBuilder.php', 'guzzle\\batch\\batchclosuredivisor' => '/lib/guzzle/Guzzle/Batch/BatchClosureDivisor.php', 'guzzle\\batch\\batchclosuretransfer' => '/lib/guzzle/Guzzle/Batch/BatchClosureTransfer.php', 'guzzle\\batch\\batchcommandtransfer' => '/lib/guzzle/Guzzle/Batch/BatchCommandTransfer.php', 'guzzle\\batch\\batchdivisorinterface' => '/lib/guzzle/Guzzle/Batch/BatchDivisorInterface.php', 'guzzle\\batch\\batchinterface' => '/lib/guzzle/Guzzle/Batch/BatchInterface.php', 'guzzle\\batch\\batchrequesttransfer' => '/lib/guzzle/Guzzle/Batch/BatchRequestTransfer.php', 'guzzle\\batch\\batchsizedivisor' => '/lib/guzzle/Guzzle/Batch/BatchSizeDivisor.php', 'guzzle\\batch\\batchtransferinterface' => '/lib/guzzle/Guzzle/Batch/BatchTransferInterface.php', 'guzzle\\batch\\exception\\batchtransferexception' => '/lib/guzzle/Guzzle/Batch/Exception/BatchTransferException.php', 'guzzle\\batch\\exceptionbufferingbatch' => '/lib/guzzle/Guzzle/Batch/ExceptionBufferingBatch.php', 'guzzle\\batch\\flushingbatch' => '/lib/guzzle/Guzzle/Batch/FlushingBatch.php', 'guzzle\\batch\\historybatch' => '/lib/guzzle/Guzzle/Batch/HistoryBatch.php', 'guzzle\\batch\\notifyingbatch' => '/lib/guzzle/Guzzle/Batch/NotifyingBatch.php', 'guzzle\\cache\\abstractcacheadapter' => '/lib/guzzle/Guzzle/Cache/AbstractCacheAdapter.php', 'guzzle\\cache\\cacheadapterfactory' => '/lib/guzzle/Guzzle/Cache/CacheAdapterFactory.php', 'guzzle\\cache\\cacheadapterinterface' => '/lib/guzzle/Guzzle/Cache/CacheAdapterInterface.php', 'guzzle\\cache\\closurecacheadapter' => '/lib/guzzle/Guzzle/Cache/ClosureCacheAdapter.php', 'guzzle\\cache\\doctrinecacheadapter' => '/lib/guzzle/Guzzle/Cache/DoctrineCacheAdapter.php', 'guzzle\\cache\\nullcacheadapter' => '/lib/guzzle/Guzzle/Cache/NullCacheAdapter.php', 'guzzle\\cache\\zf1cacheadapter' => '/lib/guzzle/Guzzle/Cache/Zf1CacheAdapter.php', 'guzzle\\cache\\zf2cacheadapter' => '/lib/guzzle/Guzzle/Cache/Zf2CacheAdapter.php', 'guzzle\\common\\abstracthasdispatcher' => '/lib/guzzle/Guzzle/Common/AbstractHasDispatcher.php', 'guzzle\\common\\collection' => '/lib/guzzle/Guzzle/Common/Collection.php', 'guzzle\\common\\event' => '/lib/guzzle/Guzzle/Common/Event.php', 'guzzle\\common\\exception\\badmethodcallexception' => '/lib/guzzle/Guzzle/Common/Exception/BadMethodCallException.php', 'guzzle\\common\\exception\\exceptioncollection' => '/lib/guzzle/Guzzle/Common/Exception/ExceptionCollection.php', 'guzzle\\common\\exception\\guzzleexception' => '/lib/guzzle/Guzzle/Common/Exception/GuzzleException.php', 'guzzle\\common\\exception\\invalidargumentexception' => '/lib/guzzle/Guzzle/Common/Exception/InvalidArgumentException.php', 'guzzle\\common\\exception\\runtimeexception' => '/lib/guzzle/Guzzle/Common/Exception/RuntimeException.php', 'guzzle\\common\\exception\\unexpectedvalueexception' => '/lib/guzzle/Guzzle/Common/Exception/UnexpectedValueException.php', 'guzzle\\common\\fromconfiginterface' => '/lib/guzzle/Guzzle/Common/FromConfigInterface.php', 'guzzle\\common\\hasdispatcherinterface' => '/lib/guzzle/Guzzle/Common/HasDispatcherInterface.php', 'guzzle\\common\\toarrayinterface' => '/lib/guzzle/Guzzle/Common/ToArrayInterface.php', 'guzzle\\common\\version' => '/lib/guzzle/Guzzle/Common/Version.php', 'guzzle\\http\\abstractentitybodydecorator' => '/lib/guzzle/Guzzle/Http/AbstractEntityBodyDecorator.php', 'guzzle\\http\\cachingentitybody' => '/lib/guzzle/Guzzle/Http/CachingEntityBody.php', 'guzzle\\http\\client' => '/lib/guzzle/Guzzle/Http/Client.php', 'guzzle\\http\\clientinterface' => '/lib/guzzle/Guzzle/Http/ClientInterface.php', 'guzzle\\http\\curl\\curlhandle' => '/lib/guzzle/Guzzle/Http/Curl/CurlHandle.php', 'guzzle\\http\\curl\\curlmulti' => '/lib/guzzle/Guzzle/Http/Curl/CurlMulti.php', 'guzzle\\http\\curl\\curlmultiinterface' => '/lib/guzzle/Guzzle/Http/Curl/CurlMultiInterface.php', 'guzzle\\http\\curl\\curlmultiproxy' => '/lib/guzzle/Guzzle/Http/Curl/CurlMultiProxy.php', 'guzzle\\http\\curl\\curlversion' => '/lib/guzzle/Guzzle/Http/Curl/CurlVersion.php', 'guzzle\\http\\curl\\requestmediator' => '/lib/guzzle/Guzzle/Http/Curl/RequestMediator.php', 'guzzle\\http\\entitybody' => '/lib/guzzle/Guzzle/Http/EntityBody.php', 'guzzle\\http\\entitybodyinterface' => '/lib/guzzle/Guzzle/Http/EntityBodyInterface.php', 'guzzle\\http\\exception\\badresponseexception' => '/lib/guzzle/Guzzle/Http/Exception/BadResponseException.php', 'guzzle\\http\\exception\\clienterrorresponseexception' => '/lib/guzzle/Guzzle/Http/Exception/ClientErrorResponseException.php', 'guzzle\\http\\exception\\couldnotrewindstreamexception' => '/lib/guzzle/Guzzle/Http/Exception/CouldNotRewindStreamException.php', 'guzzle\\http\\exception\\curlexception' => '/lib/guzzle/Guzzle/Http/Exception/CurlException.php', 'guzzle\\http\\exception\\httpexception' => '/lib/guzzle/Guzzle/Http/Exception/HttpException.php', 'guzzle\\http\\exception\\multitransferexception' => '/lib/guzzle/Guzzle/Http/Exception/MultiTransferException.php', 'guzzle\\http\\exception\\requestexception' => '/lib/guzzle/Guzzle/Http/Exception/RequestException.php', 'guzzle\\http\\exception\\servererrorresponseexception' => '/lib/guzzle/Guzzle/Http/Exception/ServerErrorResponseException.php', 'guzzle\\http\\exception\\toomanyredirectsexception' => '/lib/guzzle/Guzzle/Http/Exception/TooManyRedirectsException.php', 'guzzle\\http\\ioemittingentitybody' => '/lib/guzzle/Guzzle/Http/IoEmittingEntityBody.php', 'guzzle\\http\\message\\abstractmessage' => '/lib/guzzle/Guzzle/Http/Message/AbstractMessage.php', 'guzzle\\http\\message\\entityenclosingrequest' => '/lib/guzzle/Guzzle/Http/Message/EntityEnclosingRequest.php', 'guzzle\\http\\message\\entityenclosingrequestinterface' => '/lib/guzzle/Guzzle/Http/Message/EntityEnclosingRequestInterface.php', 'guzzle\\http\\message\\header' => '/lib/guzzle/Guzzle/Http/Message/Header.php', 'guzzle\\http\\message\\header\\cachecontrol' => '/lib/guzzle/Guzzle/Http/Message/Header/CacheControl.php', 'guzzle\\http\\message\\header\\headercollection' => '/lib/guzzle/Guzzle/Http/Message/Header/HeaderCollection.php', 'guzzle\\http\\message\\header\\headerfactory' => '/lib/guzzle/Guzzle/Http/Message/Header/HeaderFactory.php', 'guzzle\\http\\message\\header\\headerfactoryinterface' => '/lib/guzzle/Guzzle/Http/Message/Header/HeaderFactoryInterface.php', 'guzzle\\http\\message\\header\\headerinterface' => '/lib/guzzle/Guzzle/Http/Message/Header/HeaderInterface.php', 'guzzle\\http\\message\\header\\link' => '/lib/guzzle/Guzzle/Http/Message/Header/Link.php', 'guzzle\\http\\message\\messageinterface' => '/lib/guzzle/Guzzle/Http/Message/MessageInterface.php', 'guzzle\\http\\message\\postfile' => '/lib/guzzle/Guzzle/Http/Message/PostFile.php', 'guzzle\\http\\message\\postfileinterface' => '/lib/guzzle/Guzzle/Http/Message/PostFileInterface.php', 'guzzle\\http\\message\\request' => '/lib/guzzle/Guzzle/Http/Message/Request.php', 'guzzle\\http\\message\\requestfactory' => '/lib/guzzle/Guzzle/Http/Message/RequestFactory.php', 'guzzle\\http\\message\\requestfactoryinterface' => '/lib/guzzle/Guzzle/Http/Message/RequestFactoryInterface.php', 'guzzle\\http\\message\\requestinterface' => '/lib/guzzle/Guzzle/Http/Message/RequestInterface.php', 'guzzle\\http\\message\\response' => '/lib/guzzle/Guzzle/Http/Message/Response.php', 'guzzle\\http\\mimetypes' => '/lib/guzzle/Guzzle/Http/Mimetypes.php', 'guzzle\\http\\queryaggregator\\commaaggregator' => '/lib/guzzle/Guzzle/Http/QueryAggregator/CommaAggregator.php', 'guzzle\\http\\queryaggregator\\duplicateaggregator' => '/lib/guzzle/Guzzle/Http/QueryAggregator/DuplicateAggregator.php', 'guzzle\\http\\queryaggregator\\phpaggregator' => '/lib/guzzle/Guzzle/Http/QueryAggregator/PhpAggregator.php', 'guzzle\\http\\queryaggregator\\queryaggregatorinterface' => '/lib/guzzle/Guzzle/Http/QueryAggregator/QueryAggregatorInterface.php', 'guzzle\\http\\querystring' => '/lib/guzzle/Guzzle/Http/QueryString.php', 'guzzle\\http\\readlimitentitybody' => '/lib/guzzle/Guzzle/Http/ReadLimitEntityBody.php', 'guzzle\\http\\redirectplugin' => '/lib/guzzle/Guzzle/Http/RedirectPlugin.php', 'guzzle\\http\\staticclient' => '/lib/guzzle/Guzzle/Http/StaticClient.php', 'guzzle\\http\\url' => '/lib/guzzle/Guzzle/Http/Url.php', 'guzzle\\inflection\\inflector' => '/lib/guzzle/Guzzle/Inflection/Inflector.php', 'guzzle\\inflection\\inflectorinterface' => '/lib/guzzle/Guzzle/Inflection/InflectorInterface.php', 'guzzle\\inflection\\memoizinginflector' => '/lib/guzzle/Guzzle/Inflection/MemoizingInflector.php', 'guzzle\\inflection\\precomputedinflector' => '/lib/guzzle/Guzzle/Inflection/PreComputedInflector.php', 'guzzle\\iterator\\appenditerator' => '/lib/guzzle/Guzzle/Iterator/AppendIterator.php', 'guzzle\\iterator\\chunkediterator' => '/lib/guzzle/Guzzle/Iterator/ChunkedIterator.php', 'guzzle\\iterator\\filteriterator' => '/lib/guzzle/Guzzle/Iterator/FilterIterator.php', 'guzzle\\iterator\\mapiterator' => '/lib/guzzle/Guzzle/Iterator/MapIterator.php', 'guzzle\\iterator\\methodproxyiterator' => '/lib/guzzle/Guzzle/Iterator/MethodProxyIterator.php', 'guzzle\\log\\abstractlogadapter' => '/lib/guzzle/Guzzle/Log/AbstractLogAdapter.php', 'guzzle\\log\\arraylogadapter' => '/lib/guzzle/Guzzle/Log/ArrayLogAdapter.php', 'guzzle\\log\\closurelogadapter' => '/lib/guzzle/Guzzle/Log/ClosureLogAdapter.php', 'guzzle\\log\\logadapterinterface' => '/lib/guzzle/Guzzle/Log/LogAdapterInterface.php', 'guzzle\\log\\messageformatter' => '/lib/guzzle/Guzzle/Log/MessageFormatter.php', 'guzzle\\log\\monologlogadapter' => '/lib/guzzle/Guzzle/Log/MonologLogAdapter.php', 'guzzle\\log\\psrlogadapter' => '/lib/guzzle/Guzzle/Log/PsrLogAdapter.php', 'guzzle\\log\\zf1logadapter' => '/lib/guzzle/Guzzle/Log/Zf1LogAdapter.php', 'guzzle\\log\\zf2logadapter' => '/lib/guzzle/Guzzle/Log/Zf2LogAdapter.php', 'guzzle\\parser\\cookie\\cookieparser' => '/lib/guzzle/Guzzle/Parser/Cookie/CookieParser.php', 'guzzle\\parser\\cookie\\cookieparserinterface' => '/lib/guzzle/Guzzle/Parser/Cookie/CookieParserInterface.php', 'guzzle\\parser\\message\\abstractmessageparser' => '/lib/guzzle/Guzzle/Parser/Message/AbstractMessageParser.php', 'guzzle\\parser\\message\\messageparser' => '/lib/guzzle/Guzzle/Parser/Message/MessageParser.php', 'guzzle\\parser\\message\\messageparserinterface' => '/lib/guzzle/Guzzle/Parser/Message/MessageParserInterface.php', 'guzzle\\parser\\message\\peclhttpmessageparser' => '/lib/guzzle/Guzzle/Parser/Message/PeclHttpMessageParser.php', 'guzzle\\parser\\parserregistry' => '/lib/guzzle/Guzzle/Parser/ParserRegistry.php', 'guzzle\\parser\\uritemplate\\pecluritemplate' => '/lib/guzzle/Guzzle/Parser/UriTemplate/PeclUriTemplate.php', 'guzzle\\parser\\uritemplate\\uritemplate' => '/lib/guzzle/Guzzle/Parser/UriTemplate/UriTemplate.php', 'guzzle\\parser\\uritemplate\\uritemplateinterface' => '/lib/guzzle/Guzzle/Parser/UriTemplate/UriTemplateInterface.php', 'guzzle\\parser\\url\\urlparser' => '/lib/guzzle/Guzzle/Parser/Url/UrlParser.php', 'guzzle\\parser\\url\\urlparserinterface' => '/lib/guzzle/Guzzle/Parser/Url/UrlParserInterface.php', 'guzzle\\plugin\\async\\asyncplugin' => '/lib/guzzle/Guzzle/Plugin/Async/AsyncPlugin.php', 'guzzle\\plugin\\backoff\\abstractbackoffstrategy' => '/lib/guzzle/Guzzle/Plugin/Backoff/AbstractBackoffStrategy.php', 'guzzle\\plugin\\backoff\\abstracterrorcodebackoffstrategy' => '/lib/guzzle/Guzzle/Plugin/Backoff/AbstractErrorCodeBackoffStrategy.php', 'guzzle\\plugin\\backoff\\backofflogger' => '/lib/guzzle/Guzzle/Plugin/Backoff/BackoffLogger.php', 'guzzle\\plugin\\backoff\\backoffplugin' => '/lib/guzzle/Guzzle/Plugin/Backoff/BackoffPlugin.php', 'guzzle\\plugin\\backoff\\backoffstrategyinterface' => '/lib/guzzle/Guzzle/Plugin/Backoff/BackoffStrategyInterface.php', 'guzzle\\plugin\\backoff\\callbackbackoffstrategy' => '/lib/guzzle/Guzzle/Plugin/Backoff/CallbackBackoffStrategy.php', 'guzzle\\plugin\\backoff\\constantbackoffstrategy' => '/lib/guzzle/Guzzle/Plugin/Backoff/ConstantBackoffStrategy.php', 'guzzle\\plugin\\backoff\\curlbackoffstrategy' => '/lib/guzzle/Guzzle/Plugin/Backoff/CurlBackoffStrategy.php', 'guzzle\\plugin\\backoff\\exponentialbackoffstrategy' => '/lib/guzzle/Guzzle/Plugin/Backoff/ExponentialBackoffStrategy.php', 'guzzle\\plugin\\backoff\\httpbackoffstrategy' => '/lib/guzzle/Guzzle/Plugin/Backoff/HttpBackoffStrategy.php', 'guzzle\\plugin\\backoff\\linearbackoffstrategy' => '/lib/guzzle/Guzzle/Plugin/Backoff/LinearBackoffStrategy.php', 'guzzle\\plugin\\backoff\\reasonphrasebackoffstrategy' => '/lib/guzzle/Guzzle/Plugin/Backoff/ReasonPhraseBackoffStrategy.php', 'guzzle\\plugin\\backoff\\truncatedbackoffstrategy' => '/lib/guzzle/Guzzle/Plugin/Backoff/TruncatedBackoffStrategy.php', 'guzzle\\plugin\\cache\\cachekeyproviderinterface' => '/lib/guzzle/Guzzle/Plugin/Cache/CacheKeyProviderInterface.php', 'guzzle\\plugin\\cache\\cacheplugin' => '/lib/guzzle/Guzzle/Plugin/Cache/CachePlugin.php', 'guzzle\\plugin\\cache\\cachestorageinterface' => '/lib/guzzle/Guzzle/Plugin/Cache/CacheStorageInterface.php', 'guzzle\\plugin\\cache\\callbackcancachestrategy' => '/lib/guzzle/Guzzle/Plugin/Cache/CallbackCanCacheStrategy.php', 'guzzle\\plugin\\cache\\cancachestrategyinterface' => '/lib/guzzle/Guzzle/Plugin/Cache/CanCacheStrategyInterface.php', 'guzzle\\plugin\\cache\\defaultcachekeyprovider' => '/lib/guzzle/Guzzle/Plugin/Cache/DefaultCacheKeyProvider.php', 'guzzle\\plugin\\cache\\defaultcachestorage' => '/lib/guzzle/Guzzle/Plugin/Cache/DefaultCacheStorage.php', 'guzzle\\plugin\\cache\\defaultcancachestrategy' => '/lib/guzzle/Guzzle/Plugin/Cache/DefaultCanCacheStrategy.php', 'guzzle\\plugin\\cache\\defaultrevalidation' => '/lib/guzzle/Guzzle/Plugin/Cache/DefaultRevalidation.php', 'guzzle\\plugin\\cache\\denyrevalidation' => '/lib/guzzle/Guzzle/Plugin/Cache/DenyRevalidation.php', 'guzzle\\plugin\\cache\\revalidationinterface' => '/lib/guzzle/Guzzle/Plugin/Cache/RevalidationInterface.php', 'guzzle\\plugin\\cache\\skiprevalidation' => '/lib/guzzle/Guzzle/Plugin/Cache/SkipRevalidation.php', 'guzzle\\plugin\\cookie\\cookie' => '/lib/guzzle/Guzzle/Plugin/Cookie/Cookie.php', 'guzzle\\plugin\\cookie\\cookiejar\\arraycookiejar' => '/lib/guzzle/Guzzle/Plugin/Cookie/CookieJar/ArrayCookieJar.php', 'guzzle\\plugin\\cookie\\cookiejar\\cookiejarinterface' => '/lib/guzzle/Guzzle/Plugin/Cookie/CookieJar/CookieJarInterface.php', 'guzzle\\plugin\\cookie\\cookiejar\\filecookiejar' => '/lib/guzzle/Guzzle/Plugin/Cookie/CookieJar/FileCookieJar.php', 'guzzle\\plugin\\cookie\\cookieplugin' => '/lib/guzzle/Guzzle/Plugin/Cookie/CookiePlugin.php', 'guzzle\\plugin\\cookie\\exception\\invalidcookieexception' => '/lib/guzzle/Guzzle/Plugin/Cookie/Exception/InvalidCookieException.php', 'guzzle\\plugin\\curlauth\\curlauthplugin' => '/lib/guzzle/Guzzle/Plugin/CurlAuth/CurlAuthPlugin.php', 'guzzle\\plugin\\errorresponse\\errorresponseexceptioninterface' => '/lib/guzzle/Guzzle/Plugin/ErrorResponse/ErrorResponseExceptionInterface.php', 'guzzle\\plugin\\errorresponse\\errorresponseplugin' => '/lib/guzzle/Guzzle/Plugin/ErrorResponse/ErrorResponsePlugin.php', 'guzzle\\plugin\\errorresponse\\exception\\errorresponseexception' => '/lib/guzzle/Guzzle/Plugin/ErrorResponse/Exception/ErrorResponseException.php', 'guzzle\\plugin\\history\\historyplugin' => '/lib/guzzle/Guzzle/Plugin/History/HistoryPlugin.php', 'guzzle\\plugin\\log\\logplugin' => '/lib/guzzle/Guzzle/Plugin/Log/LogPlugin.php', 'guzzle\\plugin\\md5\\commandcontentmd5plugin' => '/lib/guzzle/Guzzle/Plugin/Md5/CommandContentMd5Plugin.php', 'guzzle\\plugin\\md5\\md5validatorplugin' => '/lib/guzzle/Guzzle/Plugin/Md5/Md5ValidatorPlugin.php', 'guzzle\\plugin\\mock\\mockplugin' => '/lib/guzzle/Guzzle/Plugin/Mock/MockPlugin.php', 'guzzle\\plugin\\oauth\\oauthplugin' => '/lib/guzzle/Guzzle/Plugin/Oauth/OauthPlugin.php', 'guzzle\\service\\abstractconfigloader' => '/lib/guzzle/Guzzle/Service/AbstractConfigLoader.php', 'guzzle\\service\\builder\\servicebuilder' => '/lib/guzzle/Guzzle/Service/Builder/ServiceBuilder.php', 'guzzle\\service\\builder\\servicebuilderinterface' => '/lib/guzzle/Guzzle/Service/Builder/ServiceBuilderInterface.php', 'guzzle\\service\\builder\\servicebuilderloader' => '/lib/guzzle/Guzzle/Service/Builder/ServiceBuilderLoader.php', 'guzzle\\service\\cachingconfigloader' => '/lib/guzzle/Guzzle/Service/CachingConfigLoader.php', 'guzzle\\service\\client' => '/lib/guzzle/Guzzle/Service/Client.php', 'guzzle\\service\\clientinterface' => '/lib/guzzle/Guzzle/Service/ClientInterface.php', 'guzzle\\service\\command\\abstractcommand' => '/lib/guzzle/Guzzle/Service/Command/AbstractCommand.php', 'guzzle\\service\\command\\closurecommand' => '/lib/guzzle/Guzzle/Service/Command/ClosureCommand.php', 'guzzle\\service\\command\\commandinterface' => '/lib/guzzle/Guzzle/Service/Command/CommandInterface.php', 'guzzle\\service\\command\\createresponseclassevent' => '/lib/guzzle/Guzzle/Service/Command/CreateResponseClassEvent.php', 'guzzle\\service\\command\\defaultrequestserializer' => '/lib/guzzle/Guzzle/Service/Command/DefaultRequestSerializer.php', 'guzzle\\service\\command\\defaultresponseparser' => '/lib/guzzle/Guzzle/Service/Command/DefaultResponseParser.php', 'guzzle\\service\\command\\factory\\aliasfactory' => '/lib/guzzle/Guzzle/Service/Command/Factory/AliasFactory.php', 'guzzle\\service\\command\\factory\\compositefactory' => '/lib/guzzle/Guzzle/Service/Command/Factory/CompositeFactory.php', 'guzzle\\service\\command\\factory\\concreteclassfactory' => '/lib/guzzle/Guzzle/Service/Command/Factory/ConcreteClassFactory.php', 'guzzle\\service\\command\\factory\\factoryinterface' => '/lib/guzzle/Guzzle/Service/Command/Factory/FactoryInterface.php', 'guzzle\\service\\command\\factory\\mapfactory' => '/lib/guzzle/Guzzle/Service/Command/Factory/MapFactory.php', 'guzzle\\service\\command\\factory\\servicedescriptionfactory' => '/lib/guzzle/Guzzle/Service/Command/Factory/ServiceDescriptionFactory.php', 'guzzle\\service\\command\\locationvisitor\\request\\abstractrequestvisitor' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/AbstractRequestVisitor.php', 'guzzle\\service\\command\\locationvisitor\\request\\bodyvisitor' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/BodyVisitor.php', 'guzzle\\service\\command\\locationvisitor\\request\\headervisitor' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/HeaderVisitor.php', 'guzzle\\service\\command\\locationvisitor\\request\\jsonvisitor' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/JsonVisitor.php', 'guzzle\\service\\command\\locationvisitor\\request\\postfieldvisitor' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/PostFieldVisitor.php', 'guzzle\\service\\command\\locationvisitor\\request\\postfilevisitor' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/PostFileVisitor.php', 'guzzle\\service\\command\\locationvisitor\\request\\queryvisitor' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/QueryVisitor.php', 'guzzle\\service\\command\\locationvisitor\\request\\requestvisitorinterface' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/RequestVisitorInterface.php', 'guzzle\\service\\command\\locationvisitor\\request\\responsebodyvisitor' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/ResponseBodyVisitor.php', 'guzzle\\service\\command\\locationvisitor\\request\\xmlvisitor' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/XmlVisitor.php', 'guzzle\\service\\command\\locationvisitor\\response\\abstractresponsevisitor' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/Response/AbstractResponseVisitor.php', 'guzzle\\service\\command\\locationvisitor\\response\\bodyvisitor' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/Response/BodyVisitor.php', 'guzzle\\service\\command\\locationvisitor\\response\\headervisitor' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/Response/HeaderVisitor.php', 'guzzle\\service\\command\\locationvisitor\\response\\jsonvisitor' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/Response/JsonVisitor.php', 'guzzle\\service\\command\\locationvisitor\\response\\reasonphrasevisitor' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/Response/ReasonPhraseVisitor.php', 'guzzle\\service\\command\\locationvisitor\\response\\responsevisitorinterface' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/Response/ResponseVisitorInterface.php', 'guzzle\\service\\command\\locationvisitor\\response\\statuscodevisitor' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/Response/StatusCodeVisitor.php', 'guzzle\\service\\command\\locationvisitor\\response\\xmlvisitor' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/Response/XmlVisitor.php', 'guzzle\\service\\command\\locationvisitor\\visitorflyweight' => '/lib/guzzle/Guzzle/Service/Command/LocationVisitor/VisitorFlyweight.php', 'guzzle\\service\\command\\operationcommand' => '/lib/guzzle/Guzzle/Service/Command/OperationCommand.php', 'guzzle\\service\\command\\operationresponseparser' => '/lib/guzzle/Guzzle/Service/Command/OperationResponseParser.php', 'guzzle\\service\\command\\requestserializerinterface' => '/lib/guzzle/Guzzle/Service/Command/RequestSerializerInterface.php', 'guzzle\\service\\command\\responseclassinterface' => '/lib/guzzle/Guzzle/Service/Command/ResponseClassInterface.php', 'guzzle\\service\\command\\responseparserinterface' => '/lib/guzzle/Guzzle/Service/Command/ResponseParserInterface.php', 'guzzle\\service\\configloaderinterface' => '/lib/guzzle/Guzzle/Service/ConfigLoaderInterface.php', 'guzzle\\service\\description\\operation' => '/lib/guzzle/Guzzle/Service/Description/Operation.php', 'guzzle\\service\\description\\operationinterface' => '/lib/guzzle/Guzzle/Service/Description/OperationInterface.php', 'guzzle\\service\\description\\parameter' => '/lib/guzzle/Guzzle/Service/Description/Parameter.php', 'guzzle\\service\\description\\schemaformatter' => '/lib/guzzle/Guzzle/Service/Description/SchemaFormatter.php', 'guzzle\\service\\description\\schemavalidator' => '/lib/guzzle/Guzzle/Service/Description/SchemaValidator.php', 'guzzle\\service\\description\\servicedescription' => '/lib/guzzle/Guzzle/Service/Description/ServiceDescription.php', 'guzzle\\service\\description\\servicedescriptioninterface' => '/lib/guzzle/Guzzle/Service/Description/ServiceDescriptionInterface.php', 'guzzle\\service\\description\\servicedescriptionloader' => '/lib/guzzle/Guzzle/Service/Description/ServiceDescriptionLoader.php', 'guzzle\\service\\description\\validatorinterface' => '/lib/guzzle/Guzzle/Service/Description/ValidatorInterface.php', 'guzzle\\service\\exception\\commandexception' => '/lib/guzzle/Guzzle/Service/Exception/CommandException.php', 'guzzle\\service\\exception\\commandtransferexception' => '/lib/guzzle/Guzzle/Service/Exception/CommandTransferException.php', 'guzzle\\service\\exception\\descriptionbuilderexception' => '/lib/guzzle/Guzzle/Service/Exception/DescriptionBuilderException.php', 'guzzle\\service\\exception\\inconsistentclienttransferexception' => '/lib/guzzle/Guzzle/Service/Exception/InconsistentClientTransferException.php', 'guzzle\\service\\exception\\responseclassexception' => '/lib/guzzle/Guzzle/Service/Exception/ResponseClassException.php', 'guzzle\\service\\exception\\servicebuilderexception' => '/lib/guzzle/Guzzle/Service/Exception/ServiceBuilderException.php', 'guzzle\\service\\exception\\servicenotfoundexception' => '/lib/guzzle/Guzzle/Service/Exception/ServiceNotFoundException.php', 'guzzle\\service\\exception\\validationexception' => '/lib/guzzle/Guzzle/Service/Exception/ValidationException.php', 'guzzle\\service\\resource\\abstractresourceiteratorfactory' => '/lib/guzzle/Guzzle/Service/Resource/AbstractResourceIteratorFactory.php', 'guzzle\\service\\resource\\compositeresourceiteratorfactory' => '/lib/guzzle/Guzzle/Service/Resource/CompositeResourceIteratorFactory.php', 'guzzle\\service\\resource\\mapresourceiteratorfactory' => '/lib/guzzle/Guzzle/Service/Resource/MapResourceIteratorFactory.php', 'guzzle\\service\\resource\\model' => '/lib/guzzle/Guzzle/Service/Resource/Model.php', 'guzzle\\service\\resource\\resourceiterator' => '/lib/guzzle/Guzzle/Service/Resource/ResourceIterator.php', 'guzzle\\service\\resource\\resourceiteratorapplybatched' => '/lib/guzzle/Guzzle/Service/Resource/ResourceIteratorApplyBatched.php', 'guzzle\\service\\resource\\resourceiteratorclassfactory' => '/lib/guzzle/Guzzle/Service/Resource/ResourceIteratorClassFactory.php', 'guzzle\\service\\resource\\resourceiteratorfactoryinterface' => '/lib/guzzle/Guzzle/Service/Resource/ResourceIteratorFactoryInterface.php', 'guzzle\\service\\resource\\resourceiteratorinterface' => '/lib/guzzle/Guzzle/Service/Resource/ResourceIteratorInterface.php', 'guzzle\\stream\\phpstreamrequestfactory' => '/lib/guzzle/Guzzle/Stream/PhpStreamRequestFactory.php', 'guzzle\\stream\\stream' => '/lib/guzzle/Guzzle/Stream/Stream.php', 'guzzle\\stream\\streaminterface' => '/lib/guzzle/Guzzle/Stream/StreamInterface.php', 'guzzle\\stream\\streamrequestfactoryinterface' => '/lib/guzzle/Guzzle/Stream/StreamRequestFactoryInterface.php', 'objectstorage' => '/lib/softlayer-os/ObjectStorage.php', 'objectstorage_abstract' => '/lib/softlayer-os/ObjectStorage/Abstract.php', 'objectstorage_authdata' => '/lib/softlayer-os/ObjectStorage/AuthData.php', 'objectstorage_container' => '/lib/softlayer-os/ObjectStorage/Container.php', 'objectstorage_exception' => '/lib/softlayer-os/ObjectStorage/Exception.php', 'objectstorage_exception_authentication' => '/lib/softlayer-os/ObjectStorage/Exception/Authentication.php', 'objectstorage_exception_container' => '/lib/softlayer-os/ObjectStorage/Exception/Container.php', 'objectstorage_exception_http' => '/lib/softlayer-os/ObjectStorage/Exception/Http.php', 'objectstorage_exception_http_badgateway' => '/lib/softlayer-os/ObjectStorage/Exception/Http/BadGateway.php', 'objectstorage_exception_http_badrequest' => '/lib/softlayer-os/ObjectStorage/Exception/Http/BadRequest.php', 'objectstorage_exception_http_conflict' => '/lib/softlayer-os/ObjectStorage/Exception/Http/Conflict.php', 'objectstorage_exception_http_forbidden' => '/lib/softlayer-os/ObjectStorage/Exception/Http/Forbidden.php', 'objectstorage_exception_http_interface' => '/lib/softlayer-os/ObjectStorage/Exception/Http/Interface.php', 'objectstorage_exception_http_internalservererror' => '/lib/softlayer-os/ObjectStorage/Exception/Http/InternalServerError.php', 'objectstorage_exception_http_methodnotallowed' => '/lib/softlayer-os/ObjectStorage/Exception/Http/MethodNotAllowed.php', 'objectstorage_exception_http_notacceptable' => '/lib/softlayer-os/ObjectStorage/Exception/Http/NotAcceptable.php', 'objectstorage_exception_http_notfound' => '/lib/softlayer-os/ObjectStorage/Exception/Http/NotFound.php', 'objectstorage_exception_http_notimplemented' => '/lib/softlayer-os/ObjectStorage/Exception/Http/NotImplemented.php', 'objectstorage_exception_http_proxyauthenticationrequired' => '/lib/softlayer-os/ObjectStorage/Exception/Http/ProxyAuthenticationRequired.php', 'objectstorage_exception_http_requesttimeout' => '/lib/softlayer-os/ObjectStorage/Exception/Http/RequestTimeout.php', 'objectstorage_exception_http_unauthorized' => '/lib/softlayer-os/ObjectStorage/Exception/Http/Unauthorized.php', 'objectstorage_exception_object' => '/lib/softlayer-os/ObjectStorage/Exception/Object.php', 'objectstorage_exception_tokenstore' => '/lib/softlayer-os/ObjectStorage/Exception/TokenStore.php', 'objectstorage_http_abstract' => '/lib/softlayer-os/ObjectStorage/Http/Abstract.php', 'objectstorage_http_adapter_curl' => '/lib/softlayer-os/ObjectStorage/Http/Adapter/Curl.php', 'objectstorage_http_adapter_interface' => '/lib/softlayer-os/ObjectStorage/Http/Adapter/Interface.php', 'objectstorage_http_adapter_socket' => '/lib/softlayer-os/ObjectStorage/Http/Adapter/Socket.php', 'objectstorage_http_adapter_zend' => '/lib/softlayer-os/ObjectStorage/Http/Adapter/Zend.php', 'objectstorage_http_client' => '/lib/softlayer-os/ObjectStorage/Http/Client.php', 'objectstorage_http_request' => '/lib/softlayer-os/ObjectStorage/Http/Request.php', 'objectstorage_http_response' => '/lib/softlayer-os/ObjectStorage/Http/Response.php', 'objectstorage_object' => '/lib/softlayer-os/ObjectStorage/Object.php', 'objectstorage_tokenstore' => '/lib/softlayer-os/ObjectStorage/TokenStore.php', 'objectstorage_tokenstore_file' => '/lib/softlayer-os/ObjectStorage/TokenStore/File.php', 'objectstorage_tokenstore_interface' => '/lib/softlayer-os/ObjectStorage/TokenStore/Interface.php', 'objectstorage_tokenstore_memory' => '/lib/softlayer-os/ObjectStorage/TokenStore/Memory.php', 'objectstorage_util' => '/lib/softlayer-os/ObjectStorage/Util.php', 'php_timer' => '/lib/php-timer/Timer.php', 'phpbu\\app\\backup\\check' => '/Backup/Check.php', 'phpbu\\app\\backup\\check\\exception' => '/Backup/Check/Exception.php', 'phpbu\\app\\backup\\check\\sizediffpreviouspercent' => '/Backup/Check/SizeDiffPreviousPercent.php', 'phpbu\\app\\backup\\check\\sizemin' => '/Backup/Check/SizeMin.php', 'phpbu\\app\\backup\\cleaner' => '/Backup/Cleaner.php', 'phpbu\\app\\backup\\cleaner\\capacity' => '/Backup/Cleaner/Capacity.php', 'phpbu\\app\\backup\\cleaner\\exception' => '/Backup/Cleaner/Exception.php', 'phpbu\\app\\backup\\cleaner\\outdated' => '/Backup/Cleaner/Outdated.php', 'phpbu\\app\\backup\\cleaner\\quantity' => '/Backup/Cleaner/Quantity.php', 'phpbu\\app\\backup\\cli\\cmd' => '/Backup/Cli/Cmd.php', 'phpbu\\app\\backup\\cli\\exec' => '/Backup/Cli/Exec.php', 'phpbu\\app\\backup\\cli\\result' => '/Backup/Cli/Result.php', 'phpbu\\app\\backup\\collector' => '/Backup/Collector.php', 'phpbu\\app\\backup\\compressor' => '/Backup/Compressor.php', 'phpbu\\app\\backup\\file' => '/Backup/File.php', 'phpbu\\app\\backup\\source' => '/Backup/Source.php', 'phpbu\\app\\backup\\source\\cli' => '/Backup/Source/Cli.php', 'phpbu\\app\\backup\\source\\mongodump' => '/Backup/Source/Mongodump.php', 'phpbu\\app\\backup\\source\\mysqldump' => '/Backup/Source/Mysqldump.php', 'phpbu\\app\\backup\\source\\tar' => '/Backup/Source/Tar.php', 'phpbu\\app\\backup\\sync' => '/Backup/Sync.php', 'phpbu\\app\\backup\\sync\\amazons3' => '/Backup/Sync/AmazonS3.php', 'phpbu\\app\\backup\\sync\\cli' => '/Backup/Sync/Cli.php', 'phpbu\\app\\backup\\sync\\copycom' => '/Backup/Sync/Copycom.php', 'phpbu\\app\\backup\\sync\\dropbox' => '/Backup/Sync/Dropbox.php', 'phpbu\\app\\backup\\sync\\exception' => '/Backup/Sync/Exception.php', 'phpbu\\app\\backup\\sync\\ftp' => '/Backup/Sync/Ftp.php', 'phpbu\\app\\backup\\sync\\rsync' => '/Backup/Sync/Rsync.php', 'phpbu\\app\\backup\\sync\\sftp' => '/Backup/Sync/Sftp.php', 'phpbu\\app\\backup\\sync\\softlayer' => '/Backup/Sync/SoftLayer.php', 'phpbu\\app\\backup\\target' => '/Backup/Target.php', 'phpbu\\app\\cmd' => '/Cmd.php', 'phpbu\\app\\cmd\\args' => '/Cmd/Args.php', 'phpbu\\app\\configuration' => '/Configuration.php', 'phpbu\\app\\exception' => '/Exception.php', 'phpbu\\app\\factory' => '/Factory.php', 'phpbu\\app\\listener' => '/Listener.php', 'phpbu\\app\\log\\json' => '/Log/Json.php', 'phpbu\\app\\log\\logger' => '/Log/Logger.php', 'phpbu\\app\\log\\mail' => '/Log/Mail.php', 'phpbu\\app\\log\\printer' => '/Log/Printer.php', 'phpbu\\app\\result' => '/Result.php', 'phpbu\\app\\result\\backup' => '/Result/Backup.php', 'phpbu\\app\\result\\printercli' => '/Result/PrinterCli.php', 'phpbu\\app\\runner' => '/Runner.php', 'phpbu\\app\\util\\arr' => '/Util/Arr.php', 'phpbu\\app\\util\\cli' => '/Util/Cli.php', 'phpbu\\app\\util\\math' => '/Util/Math.php', 'phpbu\\app\\util\\string' => '/Util/String.php', 'phpbu\\app\\version' => '/Version.php', 'phpseclib\\crypt\\aes' => '/lib/phpseclib/Crypt/AES.php', 'phpseclib\\crypt\\base' => '/lib/phpseclib/Crypt/Base.php', 'phpseclib\\crypt\\blowfish' => '/lib/phpseclib/Crypt/Blowfish.php', 'phpseclib\\crypt\\des' => '/lib/phpseclib/Crypt/DES.php', 'phpseclib\\crypt\\hash' => '/lib/phpseclib/Crypt/Hash.php', 'phpseclib\\crypt\\random' => '/lib/phpseclib/Crypt/Random.php', 'phpseclib\\crypt\\rc2' => '/lib/phpseclib/Crypt/RC2.php', 'phpseclib\\crypt\\rc4' => '/lib/phpseclib/Crypt/RC4.php', 'phpseclib\\crypt\\rijndael' => '/lib/phpseclib/Crypt/Rijndael.php', 'phpseclib\\crypt\\rsa' => '/lib/phpseclib/Crypt/RSA.php', 'phpseclib\\crypt\\tripledes' => '/lib/phpseclib/Crypt/TripleDES.php', 'phpseclib\\crypt\\twofish' => '/lib/phpseclib/Crypt/Twofish.php', 'phpseclib\\file\\ansi' => '/lib/phpseclib/File/ANSI.php', 'phpseclib\\file\\asn1' => '/lib/phpseclib/File/ASN1.php', 'phpseclib\\file\\asn1\\element' => '/lib/phpseclib/File/ASN1/Element.php', 'phpseclib\\file\\x509' => '/lib/phpseclib/File/X509.php', 'phpseclib\\math\\biginteger' => '/lib/phpseclib/Math/BigInteger.php', 'phpseclib\\net\\scp' => '/lib/phpseclib/Net/SCP.php', 'phpseclib\\net\\sftp' => '/lib/phpseclib/Net/SFTP.php', 'phpseclib\\net\\sftp\\stream' => '/lib/phpseclib/Net/SFTP/Stream.php', 'phpseclib\\net\\ssh1' => '/lib/phpseclib/Net/SSH1.php', 'phpseclib\\net\\ssh2' => '/lib/phpseclib/Net/SSH2.php', 'phpseclib\\system\\ssh\\agent' => '/lib/phpseclib/System/SSH/Agent.php', 'phpseclib\\system\\ssh\\agent\\identity' => '/lib/phpseclib/System/SSH/Agent/Identity.php', 'sebastianbergmann\\environment\\console' => '/lib/sebastian-environment/Console.php', 'sebastianbergmann\\environment\\runtime' => '/lib/sebastian-environment/Runtime.php', 'sebastianbergmann\\version' => '/lib/sebastian-version/Version.php', 'swift' => '/lib/swiftmailer/classes/Swift.php', 'swift_attachment' => '/lib/swiftmailer/classes/Swift/Attachment.php', 'swift_bytestream_abstractfilterableinputstream' => '/lib/swiftmailer/classes/Swift/ByteStream/AbstractFilterableInputStream.php', 'swift_bytestream_arraybytestream' => '/lib/swiftmailer/classes/Swift/ByteStream/ArrayByteStream.php', 'swift_bytestream_filebytestream' => '/lib/swiftmailer/classes/Swift/ByteStream/FileByteStream.php', 'swift_bytestream_temporaryfilebytestream' => '/lib/swiftmailer/classes/Swift/ByteStream/TemporaryFileByteStream.php', 'swift_characterreader' => '/lib/swiftmailer/classes/Swift/CharacterReader.php', 'swift_characterreader_genericfixedwidthreader' => '/lib/swiftmailer/classes/Swift/CharacterReader/GenericFixedWidthReader.php', 'swift_characterreader_usasciireader' => '/lib/swiftmailer/classes/Swift/CharacterReader/UsAsciiReader.php', 'swift_characterreader_utf8reader' => '/lib/swiftmailer/classes/Swift/CharacterReader/Utf8Reader.php', 'swift_characterreaderfactory' => '/lib/swiftmailer/classes/Swift/CharacterReaderFactory.php', 'swift_characterreaderfactory_simplecharacterreaderfactory' => '/lib/swiftmailer/classes/Swift/CharacterReaderFactory/SimpleCharacterReaderFactory.php', 'swift_characterstream' => '/lib/swiftmailer/classes/Swift/CharacterStream.php', 'swift_characterstream_arraycharacterstream' => '/lib/swiftmailer/classes/Swift/CharacterStream/ArrayCharacterStream.php', 'swift_characterstream_ngcharacterstream' => '/lib/swiftmailer/classes/Swift/CharacterStream/NgCharacterStream.php', 'swift_configurablespool' => '/lib/swiftmailer/classes/Swift/ConfigurableSpool.php', 'swift_dependencycontainer' => '/lib/swiftmailer/classes/Swift/DependencyContainer.php', 'swift_dependencyexception' => '/lib/swiftmailer/classes/Swift/DependencyException.php', 'swift_embeddedfile' => '/lib/swiftmailer/classes/Swift/EmbeddedFile.php', 'swift_encoder' => '/lib/swiftmailer/classes/Swift/Encoder.php', 'swift_encoder_base64encoder' => '/lib/swiftmailer/classes/Swift/Encoder/Base64Encoder.php', 'swift_encoder_qpencoder' => '/lib/swiftmailer/classes/Swift/Encoder/QpEncoder.php', 'swift_encoder_rfc2231encoder' => '/lib/swiftmailer/classes/Swift/Encoder/Rfc2231Encoder.php', 'swift_encoding' => '/lib/swiftmailer/classes/Swift/Encoding.php', 'swift_events_commandevent' => '/lib/swiftmailer/classes/Swift/Events/CommandEvent.php', 'swift_events_commandlistener' => '/lib/swiftmailer/classes/Swift/Events/CommandListener.php', 'swift_events_event' => '/lib/swiftmailer/classes/Swift/Events/Event.php', 'swift_events_eventdispatcher' => '/lib/swiftmailer/classes/Swift/Events/EventDispatcher.php', 'swift_events_eventlistener' => '/lib/swiftmailer/classes/Swift/Events/EventListener.php', 'swift_events_eventobject' => '/lib/swiftmailer/classes/Swift/Events/EventObject.php', 'swift_events_responseevent' => '/lib/swiftmailer/classes/Swift/Events/ResponseEvent.php', 'swift_events_responselistener' => '/lib/swiftmailer/classes/Swift/Events/ResponseListener.php', 'swift_events_sendevent' => '/lib/swiftmailer/classes/Swift/Events/SendEvent.php', 'swift_events_sendlistener' => '/lib/swiftmailer/classes/Swift/Events/SendListener.php', 'swift_events_simpleeventdispatcher' => '/lib/swiftmailer/classes/Swift/Events/SimpleEventDispatcher.php', 'swift_events_transportchangeevent' => '/lib/swiftmailer/classes/Swift/Events/TransportChangeEvent.php', 'swift_events_transportchangelistener' => '/lib/swiftmailer/classes/Swift/Events/TransportChangeListener.php', 'swift_events_transportexceptionevent' => '/lib/swiftmailer/classes/Swift/Events/TransportExceptionEvent.php', 'swift_events_transportexceptionlistener' => '/lib/swiftmailer/classes/Swift/Events/TransportExceptionListener.php', 'swift_failovertransport' => '/lib/swiftmailer/classes/Swift/FailoverTransport.php', 'swift_filespool' => '/lib/swiftmailer/classes/Swift/FileSpool.php', 'swift_filestream' => '/lib/swiftmailer/classes/Swift/FileStream.php', 'swift_filterable' => '/lib/swiftmailer/classes/Swift/Filterable.php', 'swift_image' => '/lib/swiftmailer/classes/Swift/Image.php', 'swift_inputbytestream' => '/lib/swiftmailer/classes/Swift/InputByteStream.php', 'swift_ioexception' => '/lib/swiftmailer/classes/Swift/IoException.php', 'swift_keycache' => '/lib/swiftmailer/classes/Swift/KeyCache.php', 'swift_keycache_arraykeycache' => '/lib/swiftmailer/classes/Swift/KeyCache/ArrayKeyCache.php', 'swift_keycache_diskkeycache' => '/lib/swiftmailer/classes/Swift/KeyCache/DiskKeyCache.php', 'swift_keycache_keycacheinputstream' => '/lib/swiftmailer/classes/Swift/KeyCache/KeyCacheInputStream.php', 'swift_keycache_nullkeycache' => '/lib/swiftmailer/classes/Swift/KeyCache/NullKeyCache.php', 'swift_keycache_simplekeycacheinputstream' => '/lib/swiftmailer/classes/Swift/KeyCache/SimpleKeyCacheInputStream.php', 'swift_loadbalancedtransport' => '/lib/swiftmailer/classes/Swift/LoadBalancedTransport.php', 'swift_mailer' => '/lib/swiftmailer/classes/Swift/Mailer.php', 'swift_mailer_arrayrecipientiterator' => '/lib/swiftmailer/classes/Swift/Mailer/ArrayRecipientIterator.php', 'swift_mailer_recipientiterator' => '/lib/swiftmailer/classes/Swift/Mailer/RecipientIterator.php', 'swift_mailtransport' => '/lib/swiftmailer/classes/Swift/MailTransport.php', 'swift_memoryspool' => '/lib/swiftmailer/classes/Swift/MemorySpool.php', 'swift_message' => '/lib/swiftmailer/classes/Swift/Message.php', 'swift_mime_attachment' => '/lib/swiftmailer/classes/Swift/Mime/Attachment.php', 'swift_mime_charsetobserver' => '/lib/swiftmailer/classes/Swift/Mime/CharsetObserver.php', 'swift_mime_contentencoder' => '/lib/swiftmailer/classes/Swift/Mime/ContentEncoder.php', 'swift_mime_contentencoder_base64contentencoder' => '/lib/swiftmailer/classes/Swift/Mime/ContentEncoder/Base64ContentEncoder.php', 'swift_mime_contentencoder_nativeqpcontentencoder' => '/lib/swiftmailer/classes/Swift/Mime/ContentEncoder/NativeQpContentEncoder.php', 'swift_mime_contentencoder_plaincontentencoder' => '/lib/swiftmailer/classes/Swift/Mime/ContentEncoder/PlainContentEncoder.php', 'swift_mime_contentencoder_qpcontentencoder' => '/lib/swiftmailer/classes/Swift/Mime/ContentEncoder/QpContentEncoder.php', 'swift_mime_contentencoder_qpcontentencoderproxy' => '/lib/swiftmailer/classes/Swift/Mime/ContentEncoder/QpContentEncoderProxy.php', 'swift_mime_contentencoder_rawcontentencoder' => '/lib/swiftmailer/classes/Swift/Mime/ContentEncoder/RawContentEncoder.php', 'swift_mime_embeddedfile' => '/lib/swiftmailer/classes/Swift/Mime/EmbeddedFile.php', 'swift_mime_encodingobserver' => '/lib/swiftmailer/classes/Swift/Mime/EncodingObserver.php', 'swift_mime_grammar' => '/lib/swiftmailer/classes/Swift/Mime/Grammar.php', 'swift_mime_header' => '/lib/swiftmailer/classes/Swift/Mime/Header.php', 'swift_mime_headerencoder' => '/lib/swiftmailer/classes/Swift/Mime/HeaderEncoder.php', 'swift_mime_headerencoder_base64headerencoder' => '/lib/swiftmailer/classes/Swift/Mime/HeaderEncoder/Base64HeaderEncoder.php', 'swift_mime_headerencoder_qpheaderencoder' => '/lib/swiftmailer/classes/Swift/Mime/HeaderEncoder/QpHeaderEncoder.php', 'swift_mime_headerfactory' => '/lib/swiftmailer/classes/Swift/Mime/HeaderFactory.php', 'swift_mime_headers_abstractheader' => '/lib/swiftmailer/classes/Swift/Mime/Headers/AbstractHeader.php', 'swift_mime_headers_dateheader' => '/lib/swiftmailer/classes/Swift/Mime/Headers/DateHeader.php', 'swift_mime_headers_identificationheader' => '/lib/swiftmailer/classes/Swift/Mime/Headers/IdentificationHeader.php', 'swift_mime_headers_mailboxheader' => '/lib/swiftmailer/classes/Swift/Mime/Headers/MailboxHeader.php', 'swift_mime_headers_opendkimheader' => '/lib/swiftmailer/classes/Swift/Mime/Headers/OpenDKIMHeader.php', 'swift_mime_headers_parameterizedheader' => '/lib/swiftmailer/classes/Swift/Mime/Headers/ParameterizedHeader.php', 'swift_mime_headers_pathheader' => '/lib/swiftmailer/classes/Swift/Mime/Headers/PathHeader.php', 'swift_mime_headers_unstructuredheader' => '/lib/swiftmailer/classes/Swift/Mime/Headers/UnstructuredHeader.php', 'swift_mime_headerset' => '/lib/swiftmailer/classes/Swift/Mime/HeaderSet.php', 'swift_mime_message' => '/lib/swiftmailer/classes/Swift/Mime/Message.php', 'swift_mime_mimeentity' => '/lib/swiftmailer/classes/Swift/Mime/MimeEntity.php', 'swift_mime_mimepart' => '/lib/swiftmailer/classes/Swift/Mime/MimePart.php', 'swift_mime_parameterizedheader' => '/lib/swiftmailer/classes/Swift/Mime/ParameterizedHeader.php', 'swift_mime_simpleheaderfactory' => '/lib/swiftmailer/classes/Swift/Mime/SimpleHeaderFactory.php', 'swift_mime_simpleheaderset' => '/lib/swiftmailer/classes/Swift/Mime/SimpleHeaderSet.php', 'swift_mime_simplemessage' => '/lib/swiftmailer/classes/Swift/Mime/SimpleMessage.php', 'swift_mime_simplemimeentity' => '/lib/swiftmailer/classes/Swift/Mime/SimpleMimeEntity.php', 'swift_mimepart' => '/lib/swiftmailer/classes/Swift/MimePart.php', 'swift_nulltransport' => '/lib/swiftmailer/classes/Swift/NullTransport.php', 'swift_outputbytestream' => '/lib/swiftmailer/classes/Swift/OutputByteStream.php', 'swift_plugins_antifloodplugin' => '/lib/swiftmailer/classes/Swift/Plugins/AntiFloodPlugin.php', 'swift_plugins_bandwidthmonitorplugin' => '/lib/swiftmailer/classes/Swift/Plugins/BandwidthMonitorPlugin.php', 'swift_plugins_decorator_replacements' => '/lib/swiftmailer/classes/Swift/Plugins/Decorator/Replacements.php', 'swift_plugins_decoratorplugin' => '/lib/swiftmailer/classes/Swift/Plugins/DecoratorPlugin.php', 'swift_plugins_impersonateplugin' => '/lib/swiftmailer/classes/Swift/Plugins/ImpersonatePlugin.php', 'swift_plugins_logger' => '/lib/swiftmailer/classes/Swift/Plugins/Logger.php', 'swift_plugins_loggerplugin' => '/lib/swiftmailer/classes/Swift/Plugins/LoggerPlugin.php', 'swift_plugins_loggers_arraylogger' => '/lib/swiftmailer/classes/Swift/Plugins/Loggers/ArrayLogger.php', 'swift_plugins_loggers_echologger' => '/lib/swiftmailer/classes/Swift/Plugins/Loggers/EchoLogger.php', 'swift_plugins_messagelogger' => '/lib/swiftmailer/classes/Swift/Plugins/MessageLogger.php', 'swift_plugins_pop_pop3connection' => '/lib/swiftmailer/classes/Swift/Plugins/Pop/Pop3Connection.php', 'swift_plugins_pop_pop3exception' => '/lib/swiftmailer/classes/Swift/Plugins/Pop/Pop3Exception.php', 'swift_plugins_popbeforesmtpplugin' => '/lib/swiftmailer/classes/Swift/Plugins/PopBeforeSmtpPlugin.php', 'swift_plugins_redirectingplugin' => '/lib/swiftmailer/classes/Swift/Plugins/RedirectingPlugin.php', 'swift_plugins_reporter' => '/lib/swiftmailer/classes/Swift/Plugins/Reporter.php', 'swift_plugins_reporterplugin' => '/lib/swiftmailer/classes/Swift/Plugins/ReporterPlugin.php', 'swift_plugins_reporters_hitreporter' => '/lib/swiftmailer/classes/Swift/Plugins/Reporters/HitReporter.php', 'swift_plugins_reporters_htmlreporter' => '/lib/swiftmailer/classes/Swift/Plugins/Reporters/HtmlReporter.php', 'swift_plugins_sleeper' => '/lib/swiftmailer/classes/Swift/Plugins/Sleeper.php', 'swift_plugins_throttlerplugin' => '/lib/swiftmailer/classes/Swift/Plugins/ThrottlerPlugin.php', 'swift_plugins_timer' => '/lib/swiftmailer/classes/Swift/Plugins/Timer.php', 'swift_preferences' => '/lib/swiftmailer/classes/Swift/Preferences.php', 'swift_replacementfilterfactory' => '/lib/swiftmailer/classes/Swift/ReplacementFilterFactory.php', 'swift_rfccomplianceexception' => '/lib/swiftmailer/classes/Swift/RfcComplianceException.php', 'swift_sendmailtransport' => '/lib/swiftmailer/classes/Swift/SendmailTransport.php', 'swift_signedmessage' => '/lib/swiftmailer/classes/Swift/SignedMessage.php', 'swift_signer' => '/lib/swiftmailer/classes/Swift/Signer.php', 'swift_signers_bodysigner' => '/lib/swiftmailer/classes/Swift/Signers/BodySigner.php', 'swift_signers_dkimsigner' => '/lib/swiftmailer/classes/Swift/Signers/DKIMSigner.php', 'swift_signers_domainkeysigner' => '/lib/swiftmailer/classes/Swift/Signers/DomainKeySigner.php', 'swift_signers_headersigner' => '/lib/swiftmailer/classes/Swift/Signers/HeaderSigner.php', 'swift_signers_opendkimsigner' => '/lib/swiftmailer/classes/Swift/Signers/OpenDKIMSigner.php', 'swift_signers_smimesigner' => '/lib/swiftmailer/classes/Swift/Signers/SMimeSigner.php', 'swift_smtptransport' => '/lib/swiftmailer/classes/Swift/SmtpTransport.php', 'swift_spool' => '/lib/swiftmailer/classes/Swift/Spool.php', 'swift_spooltransport' => '/lib/swiftmailer/classes/Swift/SpoolTransport.php', 'swift_streamfilter' => '/lib/swiftmailer/classes/Swift/StreamFilter.php', 'swift_streamfilters_bytearrayreplacementfilter' => '/lib/swiftmailer/classes/Swift/StreamFilters/ByteArrayReplacementFilter.php', 'swift_streamfilters_stringreplacementfilter' => '/lib/swiftmailer/classes/Swift/StreamFilters/StringReplacementFilter.php', 'swift_streamfilters_stringreplacementfilterfactory' => '/lib/swiftmailer/classes/Swift/StreamFilters/StringReplacementFilterFactory.php', 'swift_swiftexception' => '/lib/swiftmailer/classes/Swift/SwiftException.php', 'swift_transport' => '/lib/swiftmailer/classes/Swift/Transport.php', 'swift_transport_abstractsmtptransport' => '/lib/swiftmailer/classes/Swift/Transport/AbstractSmtpTransport.php', 'swift_transport_esmtp_auth_crammd5authenticator' => '/lib/swiftmailer/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php', 'swift_transport_esmtp_auth_loginauthenticator' => '/lib/swiftmailer/classes/Swift/Transport/Esmtp/Auth/LoginAuthenticator.php', 'swift_transport_esmtp_auth_ntlmauthenticator' => '/lib/swiftmailer/classes/Swift/Transport/Esmtp/Auth/NTLMAuthenticator.php', 'swift_transport_esmtp_auth_plainauthenticator' => '/lib/swiftmailer/classes/Swift/Transport/Esmtp/Auth/PlainAuthenticator.php', 'swift_transport_esmtp_auth_xoauth2authenticator' => '/lib/swiftmailer/classes/Swift/Transport/Esmtp/Auth/XOAuth2Authenticator.php', 'swift_transport_esmtp_authenticator' => '/lib/swiftmailer/classes/Swift/Transport/Esmtp/Authenticator.php', 'swift_transport_esmtp_authhandler' => '/lib/swiftmailer/classes/Swift/Transport/Esmtp/AuthHandler.php', 'swift_transport_esmtphandler' => '/lib/swiftmailer/classes/Swift/Transport/EsmtpHandler.php', 'swift_transport_esmtptransport' => '/lib/swiftmailer/classes/Swift/Transport/EsmtpTransport.php', 'swift_transport_failovertransport' => '/lib/swiftmailer/classes/Swift/Transport/FailoverTransport.php', 'swift_transport_iobuffer' => '/lib/swiftmailer/classes/Swift/Transport/IoBuffer.php', 'swift_transport_loadbalancedtransport' => '/lib/swiftmailer/classes/Swift/Transport/LoadBalancedTransport.php', 'swift_transport_mailinvoker' => '/lib/swiftmailer/classes/Swift/Transport/MailInvoker.php', 'swift_transport_mailtransport' => '/lib/swiftmailer/classes/Swift/Transport/MailTransport.php', 'swift_transport_nulltransport' => '/lib/swiftmailer/classes/Swift/Transport/NullTransport.php', 'swift_transport_sendmailtransport' => '/lib/swiftmailer/classes/Swift/Transport/SendmailTransport.php', 'swift_transport_simplemailinvoker' => '/lib/swiftmailer/classes/Swift/Transport/SimpleMailInvoker.php', 'swift_transport_smtpagent' => '/lib/swiftmailer/classes/Swift/Transport/SmtpAgent.php', 'swift_transport_spooltransport' => '/lib/swiftmailer/classes/Swift/Transport/SpoolTransport.php', 'swift_transport_streambuffer' => '/lib/swiftmailer/classes/Swift/Transport/StreamBuffer.php', 'swift_transportexception' => '/lib/swiftmailer/classes/Swift/TransportException.php', 'swift_validate' => '/lib/swiftmailer/classes/Swift/Validate.php', 'symfony\\component\\eventdispatcher\\containerawareeventdispatcher' => '/lib/symfony/event-dispatcher/ContainerAwareEventDispatcher.php', 'symfony\\component\\eventdispatcher\\debug\\traceableeventdispatcher' => '/lib/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php', 'symfony\\component\\eventdispatcher\\debug\\traceableeventdispatcherinterface' => '/lib/symfony/event-dispatcher/Debug/TraceableEventDispatcherInterface.php', 'symfony\\component\\eventdispatcher\\debug\\wrappedlistener' => '/lib/symfony/event-dispatcher/Debug/WrappedListener.php', 'symfony\\component\\eventdispatcher\\dependencyinjection\\registerlistenerspass' => '/lib/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.php', 'symfony\\component\\eventdispatcher\\event' => '/lib/symfony/event-dispatcher/Event.php', 'symfony\\component\\eventdispatcher\\eventdispatcher' => '/lib/symfony/event-dispatcher/EventDispatcher.php', 'symfony\\component\\eventdispatcher\\eventdispatcherinterface' => '/lib/symfony/event-dispatcher/EventDispatcherInterface.php', 'symfony\\component\\eventdispatcher\\eventsubscriberinterface' => '/lib/symfony/event-dispatcher/EventSubscriberInterface.php', 'symfony\\component\\eventdispatcher\\genericevent' => '/lib/symfony/event-dispatcher/GenericEvent.php', 'symfony\\component\\eventdispatcher\\immutableeventdispatcher' => '/lib/symfony/event-dispatcher/ImmutableEventDispatcher.php', 'symfony\\component\\eventdispatcher\\tests\\abstracteventdispatchertest' => '/lib/symfony/event-dispatcher/Tests/AbstractEventDispatcherTest.php', 'symfony\\component\\eventdispatcher\\tests\\callableclass' => '/lib/symfony/event-dispatcher/Tests/AbstractEventDispatcherTest.php', 'symfony\\component\\eventdispatcher\\tests\\containerawareeventdispatchertest' => '/lib/symfony/event-dispatcher/Tests/ContainerAwareEventDispatcherTest.php', 'symfony\\component\\eventdispatcher\\tests\\debug\\eventsubscriber' => '/lib/symfony/event-dispatcher/Tests/Debug/TraceableEventDispatcherTest.php', 'symfony\\component\\eventdispatcher\\tests\\debug\\traceableeventdispatchertest' => '/lib/symfony/event-dispatcher/Tests/Debug/TraceableEventDispatcherTest.php', 'symfony\\component\\eventdispatcher\\tests\\dependencyinjection\\registerlistenerspasstest' => '/lib/symfony/event-dispatcher/Tests/DependencyInjection/RegisterListenersPassTest.php', 'symfony\\component\\eventdispatcher\\tests\\dependencyinjection\\subscriberservice' => '/lib/symfony/event-dispatcher/Tests/DependencyInjection/RegisterListenersPassTest.php', 'symfony\\component\\eventdispatcher\\tests\\eventdispatchertest' => '/lib/symfony/event-dispatcher/Tests/EventDispatcherTest.php', 'symfony\\component\\eventdispatcher\\tests\\eventtest' => '/lib/symfony/event-dispatcher/Tests/EventTest.php', 'symfony\\component\\eventdispatcher\\tests\\genericeventtest' => '/lib/symfony/event-dispatcher/Tests/GenericEventTest.php', 'symfony\\component\\eventdispatcher\\tests\\immutableeventdispatchertest' => '/lib/symfony/event-dispatcher/Tests/ImmutableEventDispatcherTest.php', 'symfony\\component\\eventdispatcher\\tests\\service' => '/lib/symfony/event-dispatcher/Tests/ContainerAwareEventDispatcherTest.php', 'symfony\\component\\eventdispatcher\\tests\\subscriberservice' => '/lib/symfony/event-dispatcher/Tests/ContainerAwareEventDispatcherTest.php', 'symfony\\component\\eventdispatcher\\tests\\testeventlistener' => '/lib/symfony/event-dispatcher/Tests/AbstractEventDispatcherTest.php', 'symfony\\component\\eventdispatcher\\tests\\testeventsubscriber' => '/lib/symfony/event-dispatcher/Tests/AbstractEventDispatcherTest.php', 'symfony\\component\\eventdispatcher\\tests\\testeventsubscriberwithmultiplelisteners' => '/lib/symfony/event-dispatcher/Tests/AbstractEventDispatcherTest.php', 'symfony\\component\\eventdispatcher\\tests\\testeventsubscriberwithpriorities' => '/lib/symfony/event-dispatcher/Tests/AbstractEventDispatcherTest.php', 'symfony\\component\\eventdispatcher\\tests\\testwithdispatcher' => '/lib/symfony/event-dispatcher/Tests/AbstractEventDispatcherTest.php' ); } $class = strtolower($class); if (isset($classes[$class])) { require __PHPBU_PHAR_ROOT__ . $classes[$class]; } } ); Phar::mapPhar('phpbu-1.2.0.phar'); if ($execute) { if (isset($_SERVER['argv'][1]) && $_SERVER['argv'][1] == '--manifest') { print file_get_contents(__PHPBU_PHAR_ROOT__ . '/manifest.txt'); exit; } require __PHPBU_PHAR_ROOT__ . '/lib/swiftmailer/swift_init.php'; phpbu\App\Cmd::main(); } __HALT_COMPILER(); ?> *ÿHphpbu-1.2.0.pharBackup/Check/Exception.phpÖdUÖág±‡¶(Backup/Check/SizeDiffPreviousPercent.phpdU¨Ÿ¶Backup/Check/SizeMin.phpÎdUÎô SN¶Backup/Check.phpdUÿIWѶBackup/Cleaner/Capacity.phpØ dUØ ùJ.ɶBackup/Cleaner/Exception.phpÙdUÙ{æ¶Backup/Cleaner/Outdated.phpš dUš ”E;¶Backup/Cleaner/Quantity.php dU ººª‹¶Backup/Cleaner.phpwdUwl¤Ïê¶Backup/Cli/Cmd.phpá dUá íJ†®¶Backup/Cli/Exec.php dU  j@H¶Backup/Cli/Result.phpìdUìh€j²¶Backup/Collector.phpc dUc éw-¶Backup/Compressor.php° dU° qîá¶Backup/File.phpôdUôŽÑ x¶Backup/Source/Cli.phpŒdUŒ)Ž¾é¶Backup/Source/Mongodump.phpy dUy :¾éê¶Backup/Source/Mysqldump.phpÑ dUÑ Z<à(¶Backup/Source/Tar.phpUdUUV6ç¶Backup/Source.phpýdUýã|v—¶Backup/Sync/AmazonS3.phpË dUË !d]º¶Backup/Sync/Cli.phpdU©&±¶Backup/Sync/Copycom.phpÎ dUÎ UÃ>-¶Backup/Sync/Dropbox.php, dU, |H¹¶Backup/Sync/Exception.phpÓdUÓ¢«ö ¶Backup/Sync/Ftp.phpdU/OÁ ¶Backup/Sync/Rsync.php&dU&ärsM¶Backup/Sync/Sftp.phpÒdUÒ¨#Gd¶Backup/Sync/SoftLayer.php(dU(ŽBªÁ¶Backup/Sync.php+dU+áÚý¶Backup/Target.php?*dU?*¯·M†¶ Cmd/Args.phpdUN ð¶Cmd.phpŒ3dUŒ3âf㦶Configuration.phpA1dUA1\Ov¶ Exception.php¸dU¸\! ¶ Factory.phpêdUê…)¶lib/aws-sdk/Aws/Common/Aws.phpWdUWBÖ^u¶0lib/aws-sdk/Aws/Common/Client/AbstractClient.phpÐ%dUÐ%ׂ_â¶4lib/aws-sdk/Aws/Common/Client/AwsClientInterface.phpº dUº ®¡wƒ¶/lib/aws-sdk/Aws/Common/Client/ClientBuilder.php¥EdU¥E%¹Q¶/lib/aws-sdk/Aws/Common/Client/DefaultClient.phpÆ dUÆ Ƕ;lib/aws-sdk/Aws/Common/Client/ExpiredCredentialsChecker.php” dU” n·–¶8lib/aws-sdk/Aws/Common/Client/ThrottlingErrorChecker.phpZ dUZ ^t>,¶4lib/aws-sdk/Aws/Common/Client/UploadBodyListener.php; dU; ¹V(ù¶3lib/aws-sdk/Aws/Common/Client/UserAgentListener.php£dU£1=å<¶2lib/aws-sdk/Aws/Common/Command/AwsQueryVisitor.phpÃdUÃã1ò¶.lib/aws-sdk/Aws/Common/Command/JsonCommand.phpUdUUiáÒ¶/lib/aws-sdk/Aws/Common/Command/QueryCommand.phpÃdUÃ¶=lib/aws-sdk/Aws/Common/Command/XmlResponseLocationVisitor.phpcdUc“Tü¶Clib/aws-sdk/Aws/Common/Credentials/AbstractCredentialsDecorator.php dU ~(ò¶Elib/aws-sdk/Aws/Common/Credentials/AbstractRefreshableCredentials.phpdUÂ뵶;lib/aws-sdk/Aws/Common/Credentials/CacheableCredentials.php€ dU€ ¢µš=¶2lib/aws-sdk/Aws/Common/Credentials/Credentials.phpƒ-dUƒ-ïb¶;lib/aws-sdk/Aws/Common/Credentials/CredentialsInterface.php¨ dU¨ Âò¬/¶6lib/aws-sdk/Aws/Common/Credentials/NullCredentials.phpÚdUÚÜB¶Llib/aws-sdk/Aws/Common/Credentials/RefreshableInstanceProfileCredentials.php5dU5"EE–¶-lib/aws-sdk/Aws/Common/Enum/ClientOptions.php¹dU¹ÃöA¶¶*lib/aws-sdk/Aws/Common/Enum/DateFormat.php­dU­f:oC¶&lib/aws-sdk/Aws/Common/Enum/Region.phpþdUþŠúƒƒ¶$lib/aws-sdk/Aws/Common/Enum/Size.phpždUžv06Ž¶$lib/aws-sdk/Aws/Common/Enum/Time.phpEdUE!ª±u¶(lib/aws-sdk/Aws/Common/Enum/UaString.phpGdUG6õX*¶lib/aws-sdk/Aws/Common/Enum.php‘dU‘d|£K¶:lib/aws-sdk/Aws/Common/Exception/AwsExceptionInterface.php£dU£Û(´¶;lib/aws-sdk/Aws/Common/Exception/BadMethodCallException.phpdUXš«°¶4lib/aws-sdk/Aws/Common/Exception/DomainException.phpdU²…ÿe¶>lib/aws-sdk/Aws/Common/Exception/ExceptionFactoryInterface.phpzdUzV a׶6lib/aws-sdk/Aws/Common/Exception/ExceptionListener.php—dU—ä»»¶Hlib/aws-sdk/Aws/Common/Exception/InstanceProfileCredentialsException.phpdU Àò¶=lib/aws-sdk/Aws/Common/Exception/InvalidArgumentException.php!dU!/®- ¶3lib/aws-sdk/Aws/Common/Exception/LogicException.phpdU”Xg¶=lib/aws-sdk/Aws/Common/Exception/MultipartUploadException.phpgdUgO̓¶>lib/aws-sdk/Aws/Common/Exception/NamespaceExceptionFactory.phpù dUù Á0‡¶9lib/aws-sdk/Aws/Common/Exception/OutOfBoundsException.phpdU$}X̶6lib/aws-sdk/Aws/Common/Exception/OverflowException.php dU ÿ¢ç׶Glib/aws-sdk/Aws/Common/Exception/Parser/AbstractJsonExceptionParser.phpdUì9µ¶Elib/aws-sdk/Aws/Common/Exception/Parser/DefaultXmlExceptionParser.phpú dUú W`gá¶Dlib/aws-sdk/Aws/Common/Exception/Parser/ExceptionParserInterface.phpqdUq7 ¶Dlib/aws-sdk/Aws/Common/Exception/Parser/JsonQueryExceptionParser.phpîdUî“ ú>¶Clib/aws-sdk/Aws/Common/Exception/Parser/JsonRestExceptionParser.phpÐdUЙÀ¶Hlib/aws-sdk/Aws/Common/Exception/RequiredExtensionNotLoadedException.php3dU3–ï}¶5lib/aws-sdk/Aws/Common/Exception/RuntimeException.php dU ø…³\¶=lib/aws-sdk/Aws/Common/Exception/ServiceResponseException.phpIdUI~×µ&¶6lib/aws-sdk/Aws/Common/Exception/TransferException.phpdUó%dÒ¶=lib/aws-sdk/Aws/Common/Exception/UnexpectedValueException.php!dU!‹ )¶0lib/aws-sdk/Aws/Common/Facade/facade-classes.php€dU€ö’6‘¶(lib/aws-sdk/Aws/Common/Facade/Facade.php dU …þØè¶1lib/aws-sdk/Aws/Common/Facade/FacadeInterface.phpLdULHgza¶)lib/aws-sdk/Aws/Common/Hash/ChunkHash.phpPdUP½(£×¶2lib/aws-sdk/Aws/Common/Hash/ChunkHashInterface.phpÌdUÌobÇs¶)lib/aws-sdk/Aws/Common/Hash/HashUtils.phpMdUMeÞð¶(lib/aws-sdk/Aws/Common/Hash/TreeHash.phpdUwÒâÕ¶(lib/aws-sdk/Aws/Common/HostNameUtils.php­ dU­ RRü¶Blib/aws-sdk/Aws/Common/InstanceMetadata/InstanceMetadataClient.php»dU»sXa®¶Clib/aws-sdk/Aws/Common/InstanceMetadata/Waiter/ServiceAvailable.phpÃdUÃ`=ƒà¶7lib/aws-sdk/Aws/Common/Iterator/AwsResourceIterator.phpBdUB°¶>lib/aws-sdk/Aws/Common/Iterator/AwsResourceIteratorFactory.phpždUžå!²¡¶Alib/aws-sdk/Aws/Common/Model/MultipartUpload/AbstractTransfer.php=dU= Så·¶Flib/aws-sdk/Aws/Common/Model/MultipartUpload/AbstractTransferState.php5dU5 ñ×u¶Flib/aws-sdk/Aws/Common/Model/MultipartUpload/AbstractUploadBuilder.phpÕdUÕ.S ½¶Alib/aws-sdk/Aws/Common/Model/MultipartUpload/AbstractUploadId.phpîdUîn$ŶClib/aws-sdk/Aws/Common/Model/MultipartUpload/AbstractUploadPart.phpá dUá gÐ $¶Blib/aws-sdk/Aws/Common/Model/MultipartUpload/TransferInterface.phpOdUOí\þç¶Glib/aws-sdk/Aws/Common/Model/MultipartUpload/TransferStateInterface.php‡ dU‡ ÍÙó;¶Blib/aws-sdk/Aws/Common/Model/MultipartUpload/UploadIdInterface.phpidUißv¬¶Dlib/aws-sdk/Aws/Common/Model/MultipartUpload/UploadPartInterface.phpédUésÕ£¶/lib/aws-sdk/Aws/Common/Resources/aws-config.php¤$dU¤$W3Ô›¶5lib/aws-sdk/Aws/Common/Resources/public-endpoints.phpŠ dUŠ `13d¶0lib/aws-sdk/Aws/Common/Resources/sdk1-config.php(dU(‡„%¶0lib/aws-sdk/Aws/Common/RulesEndpointProvider.phpdU—JJC¶6lib/aws-sdk/Aws/Common/Signature/AbstractSignature.phpêdUêcÒü§¶?lib/aws-sdk/Aws/Common/Signature/EndpointSignatureInterface.phpðdUðÑ?Mí¶7lib/aws-sdk/Aws/Common/Signature/SignatureInterface.phpjdUj ¾p¶6lib/aws-sdk/Aws/Common/Signature/SignatureListener.phpT dUT vÐض0lib/aws-sdk/Aws/Common/Signature/SignatureV2.php5dU5&FŶ5lib/aws-sdk/Aws/Common/Signature/SignatureV3Https.phpAdUA9‘© ¶0lib/aws-sdk/Aws/Common/Signature/SignatureV4.phpù=dUù=hÜö*¶8lib/aws-sdk/Aws/Common/Waiter/AbstractResourceWaiter.php:dU:G5H˜¶0lib/aws-sdk/Aws/Common/Waiter/AbstractWaiter.php‘dU‘-&ø¶0lib/aws-sdk/Aws/Common/Waiter/CallableWaiter.phpHdUH‚è ¶8lib/aws-sdk/Aws/Common/Waiter/CompositeWaiterFactory.php¥dU¥ °y|¶6lib/aws-sdk/Aws/Common/Waiter/ConfigResourceWaiter.phptdUt±«g]¶9lib/aws-sdk/Aws/Common/Waiter/ResourceWaiterInterface.phpdU–`Y¶4lib/aws-sdk/Aws/Common/Waiter/WaiterClassFactory.php« dU« qÙìà¶.lib/aws-sdk/Aws/Common/Waiter/WaiterConfig.php7dU7æö œ¶5lib/aws-sdk/Aws/Common/Waiter/WaiterConfigFactory.phpž dUž ¥ Ë׶8lib/aws-sdk/Aws/Common/Waiter/WaiterFactoryInterface.phpjdUjç.IÁ¶1lib/aws-sdk/Aws/Common/Waiter/WaiterInterface.phpEdUEÛTfz¶"lib/aws-sdk/Aws/S3/AcpListener.phpò dUò ¹µá¶*lib/aws-sdk/Aws/S3/BucketStyleListener.php± dU± År˜w¶(lib/aws-sdk/Aws/S3/Command/S3Command.phpÚdUÚ¯°¸;¶%lib/aws-sdk/Aws/S3/Enum/CannedAcl.phpúdUúH¿¶(lib/aws-sdk/Aws/S3/Enum/EncodingType.phpìdUìcN¶!lib/aws-sdk/Aws/S3/Enum/Event.phpdU1ìÁX¶'lib/aws-sdk/Aws/S3/Enum/GranteeType.php;dU;?‹Ñ·¶!lib/aws-sdk/Aws/S3/Enum/Group.phpådUåG ”y¶-lib/aws-sdk/Aws/S3/Enum/MetadataDirective.phpdU[™.Ò¶%lib/aws-sdk/Aws/S3/Enum/MFADelete.phpdUب3¶!lib/aws-sdk/Aws/S3/Enum/Payer.phpdU‹”¡¶&lib/aws-sdk/Aws/S3/Enum/Permission.phprdUr´†Ro¶$lib/aws-sdk/Aws/S3/Enum/Protocol.phpdU{Eý¶0lib/aws-sdk/Aws/S3/Enum/ServerSideEncryption.phpdUò[äo¶"lib/aws-sdk/Aws/S3/Enum/Status.php dU :>ˆß¶#lib/aws-sdk/Aws/S3/Enum/Storage.phpAdUAZå¢ã¶(lib/aws-sdk/Aws/S3/Enum/StorageClass.php+dU+ÉêP¶6lib/aws-sdk/Aws/S3/Exception/AccessDeniedException.php¹dU¹K¬nü¶8lib/aws-sdk/Aws/S3/Exception/AccountProblemException.php'dU'É’í¶Flib/aws-sdk/Aws/S3/Exception/AmbiguousGrantByEmailAddressException.phpdU#×v¶3lib/aws-sdk/Aws/S3/Exception/BadDigestException.phpædUæuv¶=lib/aws-sdk/Aws/S3/Exception/BucketAlreadyExistsException.phpGdUGŸF‚F¶Alib/aws-sdk/Aws/S3/Exception/BucketAlreadyOwnedByYouException.php dU Y8jÚ¶8lib/aws-sdk/Aws/S3/Exception/BucketNotEmptyException.phpÚdUÚÚÈ5¶Alib/aws-sdk/Aws/S3/Exception/CredentialsNotSupportedException.phpádUáR1´¿¶Hlib/aws-sdk/Aws/S3/Exception/CrossLocationLoggingProhibitedException.php<dU<À÷¶¶?lib/aws-sdk/Aws/S3/Exception/DeleteMultipleObjectsException.phpedUeÔ¬¸µ¶8lib/aws-sdk/Aws/S3/Exception/EntityTooLargeException.phpëdUëÿ(ꑶ8lib/aws-sdk/Aws/S3/Exception/EntityTooSmallException.phpódUó•^€¶6lib/aws-sdk/Aws/S3/Exception/ExpiredTokenException.phpËdUËߘø¼¶Hlib/aws-sdk/Aws/S3/Exception/IllegalVersioningConfigurationException.phpdU¿‡›¶8lib/aws-sdk/Aws/S3/Exception/IncompleteBodyException.phpdU0˜¶Mlib/aws-sdk/Aws/S3/Exception/IncorrectNumberOfFilesInPostRequestException.phpõdUõì£á ¶<lib/aws-sdk/Aws/S3/Exception/InlineDataTooLargeException.phpßdUßÑ u¶7lib/aws-sdk/Aws/S3/Exception/InternalErrorException.phpàdUà·wÙœ¶<lib/aws-sdk/Aws/S3/Exception/InvalidAccessKeyIdException.phpódUóªÌ¤³¶Alib/aws-sdk/Aws/S3/Exception/InvalidAddressingHeaderException.phpÛdUÛ¨`O¶9lib/aws-sdk/Aws/S3/Exception/InvalidArgumentException.php¿dU¿&4y¶;lib/aws-sdk/Aws/S3/Exception/InvalidBucketNameException.phpÓdUÓQºÚ–¶<lib/aws-sdk/Aws/S3/Exception/InvalidBucketStateException.phpðdUðÿQ‚<¶7lib/aws-sdk/Aws/S3/Exception/InvalidDigestException.phpÚdUÚÜòhj¶Clib/aws-sdk/Aws/S3/Exception/InvalidLocationConstraintException.php9dU9"Ly~¶5lib/aws-sdk/Aws/S3/Exception/InvalidPartException.phpRdUR°Ú†¶:lib/aws-sdk/Aws/S3/Exception/InvalidPartOrderException.phpdU¦¶6lib/aws-sdk/Aws/S3/Exception/InvalidPayerException.phpØdUØ̓—<¶?lib/aws-sdk/Aws/S3/Exception/InvalidPolicyDocumentException.php dU g… "¶6lib/aws-sdk/Aws/S3/Exception/InvalidRangeException.phpÔdUÔÁ/䡶8lib/aws-sdk/Aws/S3/Exception/InvalidRequestException.phpâdUâíæ¶9lib/aws-sdk/Aws/S3/Exception/InvalidSecurityException.phpßdUß}ß ¶<lib/aws-sdk/Aws/S3/Exception/InvalidSOAPRequestException.phpÓdUÓÇB¢¶=lib/aws-sdk/Aws/S3/Exception/InvalidStorageClassException.phpàdUàEò¯¶9lib/aws-sdk/Aws/S3/Exception/InvalidTagErrorException.phpMdUMû¶Glib/aws-sdk/Aws/S3/Exception/InvalidTargetBucketForLoggingException.phpCdUC«›¤¶6lib/aws-sdk/Aws/S3/Exception/InvalidTokenException.phpádUá /Ò¤¶4lib/aws-sdk/Aws/S3/Exception/InvalidURIException.phpËdUËêx¸¶4lib/aws-sdk/Aws/S3/Exception/KeyTooLongException.php¿dU¿Lò ¶;lib/aws-sdk/Aws/S3/Exception/MalformedACLErrorException.php dU ¶yš¶>lib/aws-sdk/Aws/S3/Exception/MalformedPOSTRequestException.phpùdUù44€¾¶6lib/aws-sdk/Aws/S3/Exception/MalformedXMLException.php–dU–hWJ¶Blib/aws-sdk/Aws/S3/Exception/MaxMessageLengthExceededException.phpÑdUÑf!׶Klib/aws-sdk/Aws/S3/Exception/MaxPostPreDataLengthExceededErrorException.phpdU•¯ª ¶:lib/aws-sdk/Aws/S3/Exception/MetadataTooLargeException.phpïdUï™"¶:lib/aws-sdk/Aws/S3/Exception/MethodNotAllowedException.phpêdUê#‹aÓ¶;lib/aws-sdk/Aws/S3/Exception/MissingAttachmentException.phpådUåh òa¶>lib/aws-sdk/Aws/S3/Exception/MissingContentLengthException.phpädUä®… R¶Alib/aws-sdk/Aws/S3/Exception/MissingRequestBodyErrorException.php*dU*W§Š¶@lib/aws-sdk/Aws/S3/Exception/MissingSecurityElementException.phpédUén„mG¶?lib/aws-sdk/Aws/S3/Exception/MissingSecurityHeaderException.phpàdUà³±Þ¶?lib/aws-sdk/Aws/S3/Exception/NoLoggingStatusForKeyException.php÷dU÷R̶6lib/aws-sdk/Aws/S3/Exception/NoSuchBucketException.phpÐdUÐ*¡O.¶<lib/aws-sdk/Aws/S3/Exception/NoSuchBucketPolicyException.phpÝdUÝ^œ_Õ¶Alib/aws-sdk/Aws/S3/Exception/NoSuchCORSConfigurationException.phpïdUï[:7¶3lib/aws-sdk/Aws/S3/Exception/NoSuchKeyException.phpÊdUÊ¢ƒ¶Flib/aws-sdk/Aws/S3/Exception/NoSuchLifecycleConfigurationException.phpçdUç‚Ð@¶;lib/aws-sdk/Aws/S3/Exception/NoSuchTagSetErrorException.phpßdUßýk`¶6lib/aws-sdk/Aws/S3/Exception/NoSuchUploadException.phpÚdUÚy¹ÃY¶7lib/aws-sdk/Aws/S3/Exception/NoSuchVersionException.phpdUJ–Å—¶Dlib/aws-sdk/Aws/S3/Exception/NoSuchWebsiteConfigurationException.phpõdUõº*¶8lib/aws-sdk/Aws/S3/Exception/NotImplementedException.phpòdUòØÐm¶5lib/aws-sdk/Aws/S3/Exception/NotSignedUpException.phpQdUQÃFð¶=lib/aws-sdk/Aws/S3/Exception/NotSuchBucketPolicyException.phpædUækÞ·¶Hlib/aws-sdk/Aws/S3/Exception/ObjectAlreadyInActiveTierErrorException.phpõdUõTb¶Dlib/aws-sdk/Aws/S3/Exception/ObjectNotInActiveTierErrorException.php!dU!ãä'¦¶:lib/aws-sdk/Aws/S3/Exception/OperationAbortedException.phpdU•´l-¶9lib/aws-sdk/Aws/S3/Exception/Parser/S3ExceptionParser.phpñdUñÙéšã¶;lib/aws-sdk/Aws/S3/Exception/PermanentRedirectException.php:dU:u}©Ž¶<lib/aws-sdk/Aws/S3/Exception/PreconditionFailedException.phpïdUïsŠÂP¶2lib/aws-sdk/Aws/S3/Exception/RedirectException.php»dU»öc¶Flib/aws-sdk/Aws/S3/Exception/RequestIsNotMultiPartContentException.phpúdUúÐ1ÿa¶8lib/aws-sdk/Aws/S3/Exception/RequestTimeoutException.php dU øì¶>lib/aws-sdk/Aws/S3/Exception/RequestTimeTooSkewedException.phpÿdUÿ`ˆs·¶Elib/aws-sdk/Aws/S3/Exception/RequestTorrentOfBucketErrorException.phpôdUôïƬ¶,lib/aws-sdk/Aws/S3/Exception/S3Exception.phpdU™ññ¶<lib/aws-sdk/Aws/S3/Exception/ServiceUnavailableException.phpÒdUÒÓÙ6¶?lib/aws-sdk/Aws/S3/Exception/SignatureDoesNotMatchException.php‹dU‹nsí¤¶2lib/aws-sdk/Aws/S3/Exception/SlowDownException.phpÈdUȤj½¶;lib/aws-sdk/Aws/S3/Exception/TemporaryRedirectException.phpêdUê‹Å©¶>lib/aws-sdk/Aws/S3/Exception/TokenRefreshRequiredException.phpÙdUÙDfŒ¶8lib/aws-sdk/Aws/S3/Exception/TooManyBucketsException.phpådUå Ÿ¶;lib/aws-sdk/Aws/S3/Exception/UnexpectedContentException.php×dU×Ö mݶIlib/aws-sdk/Aws/S3/Exception/UnresolvableGrantByEmailAddressException.phpdU³ýð­¶@lib/aws-sdk/Aws/S3/Exception/UserKeyMustBeSpecifiedException.php&dU&À8º¶3lib/aws-sdk/Aws/S3/Iterator/ListBucketsIterator.php\dU\M¢>¶<lib/aws-sdk/Aws/S3/Iterator/ListMultipartUploadsIterator.php‰dU‰@÷@¶3lib/aws-sdk/Aws/S3/Iterator/ListObjectsIterator.phpœ dUœ ¬_:Á¶:lib/aws-sdk/Aws/S3/Iterator/ListObjectVersionsIterator.phpdU»Y@¶/lib/aws-sdk/Aws/S3/Iterator/OpendirIterator.php6dU6@ñǶ lib/aws-sdk/Aws/S3/Model/Acp.php*dU*‹ L¶'lib/aws-sdk/Aws/S3/Model/AcpBuilder.phpO dUO LfÓk¶(lib/aws-sdk/Aws/S3/Model/ClearBucket.php­dU­ø@’¶/lib/aws-sdk/Aws/S3/Model/DeleteObjectsBatch.phpÙ dUÙ £å=T¶2lib/aws-sdk/Aws/S3/Model/DeleteObjectsTransfer.phpvdUvR–â°¶"lib/aws-sdk/Aws/S3/Model/Grant.php1 dU1 _¥˜Ü¶$lib/aws-sdk/Aws/S3/Model/Grantee.php€dU€£‰®¤¶=lib/aws-sdk/Aws/S3/Model/MultipartUpload/AbstractTransfer.php dU mþ›¶=lib/aws-sdk/Aws/S3/Model/MultipartUpload/ParallelTransfer.phpdU•4f›¶;lib/aws-sdk/Aws/S3/Model/MultipartUpload/SerialTransfer.phpu dUu šÝY¶:lib/aws-sdk/Aws/S3/Model/MultipartUpload/TransferState.phpùdUùã‹„»¶:lib/aws-sdk/Aws/S3/Model/MultipartUpload/UploadBuilder.phpÑ!dUÑ!rs{Œ¶5lib/aws-sdk/Aws/S3/Model/MultipartUpload/UploadId.phpødUø·ëî¶7lib/aws-sdk/Aws/S3/Model/MultipartUpload/UploadPart.php„dU„¯’l¶'lib/aws-sdk/Aws/S3/Model/PostObject.phpŠ#dUŠ##T¶.lib/aws-sdk/Aws/S3/Resources/s3-2006-03-01.phpÆÖdUÆÖy#!¶(lib/aws-sdk/Aws/S3/ResumableDownload.phpkdUkñƒÖS¶lib/aws-sdk/Aws/S3/S3Client.php×wdU×w*÷¢}¶$lib/aws-sdk/Aws/S3/S3Md5Listener.php+ dU+ 눶"lib/aws-sdk/Aws/S3/S3Signature.phpL$dUL$¥¤FZ¶+lib/aws-sdk/Aws/S3/S3SignatureInterface.phpådUåF<ð^¶$lib/aws-sdk/Aws/S3/S3SignatureV4.php3dU37dËɶ+lib/aws-sdk/Aws/S3/SocketTimeoutChecker.phpÑdUÑÃ"|A¶%lib/aws-sdk/Aws/S3/SseCpkListener.phphdUhƒmǶ$lib/aws-sdk/Aws/S3/StreamWrapper.phpÂodUÂo+)*C¶(lib/aws-sdk/Aws/S3/Sync/AbstractSync.phpådUå{_®¶/lib/aws-sdk/Aws/S3/Sync/AbstractSyncBuilder.php"1dU"1p;W¶0lib/aws-sdk/Aws/S3/Sync/ChangedFilesIterator.phpodUo6ºü¶(lib/aws-sdk/Aws/S3/Sync/DownloadSync.php: dU: 6¥‘¶/lib/aws-sdk/Aws/S3/Sync/DownloadSyncBuilder.phpJdUJü¶6lib/aws-sdk/Aws/S3/Sync/FilenameConverterInterface.php•dU•söxQ¶(lib/aws-sdk/Aws/S3/Sync/KeyConverter.php dU ò„]¶&lib/aws-sdk/Aws/S3/Sync/UploadSync.phpº dUº \ù«q¶-lib/aws-sdk/Aws/S3/Sync/UploadSyncBuilder.php’dU’ké–%¶lib/aws-sdk/LICENSEò#dUò#©élµ¶lib/copy/API.php‡odU‡oá ´J¶lib/copy/ca.crtp dUp £¶‡â¶lib/copy/LICENSECdUCšaFì¶lib/dropbox/AppInfo.phpEdUEœ[v¶$lib/dropbox/AppInfoLoadException.phpFdUFc7¬¶lib/dropbox/ArrayEntryStore.php‚dU‚BœÏ¶lib/dropbox/AuthBase.php dU ëõá?¶lib/dropbox/AuthInfo.php dU Ô=æ(¶%lib/dropbox/AuthInfoLoadException.phpHdUH)„g¶#lib/dropbox/certs/trusted-certs.crt8dU8€YJ˶lib/dropbox/Checker.phpà dUà ÅÓB¶lib/dropbox/Client.phpÖdUÖY[¶lib/dropbox/Curl.phprdUr)s¶lib/dropbox/CurlStreamRelay.php-dU-‘âu†¶$lib/dropbox/DeserializeException.php…dU….`ç¶,lib/dropbox/DropboxMetadataHeaderCatcher.php´dU´à2x,¶$lib/dropbox/Exception/BadRequest.phpgdUgL×ÊN¶%lib/dropbox/Exception/BadResponse.phpqdUq™¶)lib/dropbox/Exception/BadResponseCode.php›dU›íò•Ÿ¶,lib/dropbox/Exception/InvalidAccessToken.php¢dU¢­£¨W¶#lib/dropbox/Exception/NetworkIO.php dU ²“õü¶'lib/dropbox/Exception/ProtocolError.phpWdUWm?J¶$lib/dropbox/Exception/RetryLater.php<dU<ôð @¶%lib/dropbox/Exception/ServerError.php^dU^•èè¶lib/dropbox/Exception.php dU Ef'.¶lib/dropbox/Host.php& dU& ×f¾Ê¶lib/dropbox/HttpResponse.phpödUöoIŽÐ¶lib/dropbox/LICENSE9dU9Œ G¶!lib/dropbox/OAuth1AccessToken.phpÆdUÆw§Ƕlib/dropbox/OAuth1Upgrader.php dU g­½É¶lib/dropbox/Path.phpudUu(s&¶lib/dropbox/RequestUtil.phpã&dUã&‹ˆÐy¶ lib/dropbox/RootCertificates.phpdU§½±¿¶lib/dropbox/Security.phpQdUQ/6B¶lib/dropbox/SSLTester.phpódUóGæ¶#lib/dropbox/StreamReadException.php<dU<tKË7¶lib/dropbox/Util.phpdU^£¶lib/dropbox/ValueStore.phpdUùÜ㛶lib/dropbox/WebAuth.php§(dU§(âŽ}•¶lib/dropbox/WebAuthBase.php$ dU$ .ܳ½¶+lib/dropbox/WebAuthException/BadRequest.php—dU—„¬[¶)lib/dropbox/WebAuthException/BadState.phpËdUË ö² ¶%lib/dropbox/WebAuthException/Csrf.phpÆdUÆ_Rq¶,lib/dropbox/WebAuthException/NotApproved.phpKdUKàNÕ ¶)lib/dropbox/WebAuthException/Provider.phpDdUD°olp¶!lib/dropbox/WebAuthNoRedirect.phpÈ dUÈ s¼”ضlib/dropbox/WriteMode.php¢dU¢ÝÞË[¶ lib/eher/Eher/OAuth/Consumer.phpLdULš%‡ü¶ lib/eher/Eher/OAuth/HmacSha1.php¡dU¡ºPÞ=¶&lib/eher/Eher/OAuth/OAuthDataStore.php¬dU¬½lÄ·¶&lib/eher/Eher/OAuth/OAuthException.phpsdUsÕP¶#lib/eher/Eher/OAuth/OAuthServer.phpƒdUƒÍOÑÚ¶!lib/eher/Eher/OAuth/PlainText.php!dU!yõMu¶lib/eher/Eher/OAuth/Request.php>dU>.îÐ¥¶lib/eher/Eher/OAuth/RsaSha1.php¥ dU¥ ;ÊZ5¶'lib/eher/Eher/OAuth/SignatureMethod.php"dU"Ê ú¶lib/eher/Eher/OAuth/Token.phpªdUªG‰.¶lib/eher/Eher/OAuth/Util.phpcdUc?Ÿ¼)¶2lib/guzzle/Guzzle/Batch/AbstractBatchDecorator.phpßdUßš?¶!lib/guzzle/Guzzle/Batch/Batch.phpÓ dUÓ Ôs‰¶(lib/guzzle/Guzzle/Batch/BatchBuilder.phpëdUëÎ;Ͷ/lib/guzzle/Guzzle/Batch/BatchClosureDivisor.phptdUtzHFê¶0lib/guzzle/Guzzle/Batch/BatchClosureTransfer.php¾dU¾»ÂúÖ¶0lib/guzzle/Guzzle/Batch/BatchCommandTransfer.php®dU®ì¹ß2¶1lib/guzzle/Guzzle/Batch/BatchDivisorInterface.phpþdUþÁ¢~ü¶*lib/guzzle/Guzzle/Batch/BatchInterface.phpMdUMÆ¿s|¶0lib/guzzle/Guzzle/Batch/BatchRequestTransfer.php‚dU‚ïq;¶,lib/guzzle/Guzzle/Batch/BatchSizeDivisor.phpkdUkdÌj•¶2lib/guzzle/Guzzle/Batch/BatchTransferInterface.phpdUÉÄ#T¶<lib/guzzle/Guzzle/Batch/Exception/BatchTransferException.php‹ dU‹ &œä¶3lib/guzzle/Guzzle/Batch/ExceptionBufferingBatch.php×dU×ñE$¥¶)lib/guzzle/Guzzle/Batch/FlushingBatch.php¿dU¿Û†ƒP¶(lib/guzzle/Guzzle/Batch/HistoryBatch.phpödUö`B2î¶*lib/guzzle/Guzzle/Batch/NotifyingBatch.php½dU½Šj¬¶0lib/guzzle/Guzzle/Cache/AbstractCacheAdapter.phpGdUG!Ŷ/lib/guzzle/Guzzle/Cache/CacheAdapterFactory.phpdU:îÜö1lib/guzzle/Guzzle/Cache/CacheAdapterInterface.phpëdU뎚ó¶/lib/guzzle/Guzzle/Cache/ClosureCacheAdapter.php^dU^ÇáÛζ0lib/guzzle/Guzzle/Cache/DoctrineCacheAdapter.phpKdUKÇ;#Œ¶,lib/guzzle/Guzzle/Cache/NullCacheAdapter.phpdUà½Ââ¶+lib/guzzle/Guzzle/Cache/Zf1CacheAdapter.phpúdUúZ㼶+lib/guzzle/Guzzle/Cache/Zf2CacheAdapter.php—dU—ÊIõ̶2lib/guzzle/Guzzle/Common/AbstractHasDispatcher.php«dU«%ƒ;þ¶'lib/guzzle/Guzzle/Common/Collection.php-dU-—ÃE¶"lib/guzzle/Guzzle/Common/Event.php(dU(÷÷kÛ¶=lib/guzzle/Guzzle/Common/Exception/BadMethodCallException.php†dU†‚qS”¶:lib/guzzle/Guzzle/Common/Exception/ExceptionCollection.php dU ÍA˲¶6lib/guzzle/Guzzle/Common/Exception/GuzzleException.phpddUdà’ض?lib/guzzle/Guzzle/Common/Exception/InvalidArgumentException.phpŠdUŠùVǶ7lib/guzzle/Guzzle/Common/Exception/RuntimeException.phpzdUzh^Üw¶?lib/guzzle/Guzzle/Common/Exception/UnexpectedValueException.phpŠdUŠ¢eˆ£¶0lib/guzzle/Guzzle/Common/FromConfigInterface.phpçdUç½Ù1r¶3lib/guzzle/Guzzle/Common/HasDispatcherInterface.phpNdUNÔ3®¶-lib/guzzle/Guzzle/Common/ToArrayInterface.phpõdUõü—N¶$lib/guzzle/Guzzle/Common/Version.phpdU Š,¶6lib/guzzle/Guzzle/Http/AbstractEntityBodyDecorator.php»dU»ža“¶,lib/guzzle/Guzzle/Http/CachingEntityBody.phpzdUz×õb¶!lib/guzzle/Guzzle/Http/Client.phpþAdUþAFø¹ˆ¶*lib/guzzle/Guzzle/Http/ClientInterface.phpÁ&dUÁ&P g5¶*lib/guzzle/Guzzle/Http/Curl/CurlHandle.phpj=dUj=ën q¶)lib/guzzle/Guzzle/Http/Curl/CurlMulti.phpÉ8dUÉ8ßÎ{@¶2lib/guzzle/Guzzle/Http/Curl/CurlMultiInterface.php=dU=ÂÑšO¶.lib/guzzle/Guzzle/Http/Curl/CurlMultiProxy.phpdUˆÁ¤D¶+lib/guzzle/Guzzle/Http/Curl/CurlVersion.php·dU·¡¡\¶/lib/guzzle/Guzzle/Http/Curl/RequestMediator.php]dU]TÇš¶%lib/guzzle/Guzzle/Http/EntityBody.php‚dU‚Ùáî¶.lib/guzzle/Guzzle/Http/EntityBodyInterface.phps dUs ™Ûí¶9lib/guzzle/Guzzle/Http/Exception/BadResponseException.php4dU4´É= ¶Alib/guzzle/Guzzle/Http/Exception/ClientErrorResponseException.php°dU°5"ùÚ¶Blib/guzzle/Guzzle/Http/Exception/CouldNotRewindStreamException.php±dU±„n—ð¶2lib/guzzle/Guzzle/Http/Exception/CurlException.phpCdUC&Y˜à¶2lib/guzzle/Guzzle/Http/Exception/HttpException.php®dU®ˆ ¶;lib/guzzle/Guzzle/Http/Exception/MultiTransferException.phpƒ dUƒ [Ú’œ¶5lib/guzzle/Guzzle/Http/Exception/RequestException.phpdUÀo~¶Alib/guzzle/Guzzle/Http/Exception/ServerErrorResponseException.php°dU°Wpñ¶>lib/guzzle/Guzzle/Http/Exception/TooManyRedirectsException.phpidUiǸ–¶/lib/guzzle/Guzzle/Http/IoEmittingEntityBody.phpðdUðcÒ"¶2lib/guzzle/Guzzle/Http/Message/AbstractMessage.php#dU#ÙC}#¶9lib/guzzle/Guzzle/Http/Message/EntityEnclosingRequest.php­dU­—'DU¶Blib/guzzle/Guzzle/Http/Message/EntityEnclosingRequestInterface.phpëdUë ¶6lib/guzzle/Guzzle/Http/Message/Header/CacheControl.phpö dUö ¬æO¶:lib/guzzle/Guzzle/Http/Message/Header/HeaderCollection.php dU …òhɶ7lib/guzzle/Guzzle/Http/Message/Header/HeaderFactory.php†dU†®┶@lib/guzzle/Guzzle/Http/Message/Header/HeaderFactoryInterface.php£dU£‰´Œ›¶9lib/guzzle/Guzzle/Http/Message/Header/HeaderInterface.phpPdUPì(™¶.lib/guzzle/Guzzle/Http/Message/Header/Link.phpådU噳“µ¶)lib/guzzle/Guzzle/Http/Message/Header.phpôdUôÊþS¶3lib/guzzle/Guzzle/Http/Message/MessageInterface.php dU Û“`³¶+lib/guzzle/Guzzle/Http/Message/PostFile.php² dU² M.>æ¶4lib/guzzle/Guzzle/Http/Message/PostFileInterface.phpûdUûÓ¶*lib/guzzle/Guzzle/Http/Message/Request.phpKdUK1þW߶1lib/guzzle/Guzzle/Http/Message/RequestFactory.phpÄ2dUÄ2éšh¶:lib/guzzle/Guzzle/Http/Message/RequestFactoryInterface.phpxdUx®&Û¶3lib/guzzle/Guzzle/Http/Message/RequestInterface.php7!dU7!ïÕ•¶+lib/guzzle/Guzzle/Http/Message/Response.phpãfdUãf„ƒç¤¶$lib/guzzle/Guzzle/Http/Mimetypes.php‰¤dU‰¤‰¶:lib/guzzle/Guzzle/Http/QueryAggregator/CommaAggregator.phpdUû^<Ͷ>lib/guzzle/Guzzle/Http/QueryAggregator/DuplicateAggregator.php<dU<9›|\¶8lib/guzzle/Guzzle/Http/QueryAggregator/PhpAggregator.phptdUtó$¢ç¶Clib/guzzle/Guzzle/Http/QueryAggregator/QueryAggregatorInterface.phpždUž)­¶&lib/guzzle/Guzzle/Http/QueryString.php*"dU*"áîíö.lib/guzzle/Guzzle/Http/ReadLimitEntityBody.php¡ dU¡ ÃÒS¶)lib/guzzle/Guzzle/Http/RedirectPlugin.php{'dU{'s;“¶+lib/guzzle/Guzzle/Http/Resources/cacert.pem«ÑdU«ÑNGZ ¶'lib/guzzle/Guzzle/Http/StaticClient.php'dU'¶Zª!¶lib/guzzle/Guzzle/Http/Url.php"9dU"9+a÷_¶*lib/guzzle/Guzzle/Inflection/Inflector.phpSdUSB#c¢¶3lib/guzzle/Guzzle/Inflection/InflectorInterface.php>dU>Ö¸ìk¶3lib/guzzle/Guzzle/Inflection/MemoizingInflector.php­dU­l—_t¶5lib/guzzle/Guzzle/Inflection/PreComputedInflector.phpëdUë\:û¶-lib/guzzle/Guzzle/Iterator/AppendIterator.php¼dU¼»ý±¶.lib/guzzle/Guzzle/Iterator/ChunkedIterator.phpdUGZª¤¶-lib/guzzle/Guzzle/Iterator/FilterIterator.phpÚdUÚÚ¬³¶*lib/guzzle/Guzzle/Iterator/MapIterator.phpTdUTR`1q¶2lib/guzzle/Guzzle/Iterator/MethodProxyIterator.phpbdUb]ì¶,lib/guzzle/Guzzle/Log/AbstractLogAdapter.php dU p÷˜-¶)lib/guzzle/Guzzle/Log/ArrayLogAdapter.phpgdUgxÆc¶+lib/guzzle/Guzzle/Log/ClosureLogAdapter.phpGdUGÔÉ#p¶-lib/guzzle/Guzzle/Log/LogAdapterInterface.phpëdUë£\:¶*lib/guzzle/Guzzle/Log/MessageFormatter.phpÏdUÏëB¶+lib/guzzle/Guzzle/Log/MonologLogAdapter.phpãdUã+$ÈY¶'lib/guzzle/Guzzle/Log/PsrLogAdapter.php^dU^´Á¶'lib/guzzle/Guzzle/Log/Zf1LogAdapter.phpídUíçÄYÚ¶'lib/guzzle/Guzzle/Log/Zf2LogAdapter.php‰dU‰>'ý†¶0lib/guzzle/Guzzle/Parser/Cookie/CookieParser.phpzdUzü•¤©¶9lib/guzzle/Guzzle/Parser/Cookie/CookieParserInterface.phpÌdUÌŽ=¶:lib/guzzle/Guzzle/Parser/Message/AbstractMessageParser.phpŒdUŒŠJ2¶2lib/guzzle/Guzzle/Parser/Message/MessageParser.php dU ú¹,¶;lib/guzzle/Guzzle/Parser/Message/MessageParserInterface.php·dU·(5Ù;¶:lib/guzzle/Guzzle/Parser/Message/PeclHttpMessageParser.php®dU®ó믶+lib/guzzle/Guzzle/Parser/ParserRegistry.phpdUãµÚø¶8lib/guzzle/Guzzle/Parser/UriTemplate/PeclUriTemplate.php´dU´ÿãQѶ4lib/guzzle/Guzzle/Parser/UriTemplate/UriTemplate.php dU Y—ˆ¶=lib/guzzle/Guzzle/Parser/UriTemplate/UriTemplateInterface.phpþdUþ[Íÿ¶*lib/guzzle/Guzzle/Parser/Url/UrlParser.php”dU”loV2¶3lib/guzzle/Guzzle/Parser/Url/UrlParserInterface.phpdUÑ"˜¶.lib/guzzle/Guzzle/Plugin/Async/AsyncPlugin.php™ dU™ ‘ô`¯¶<lib/guzzle/Guzzle/Plugin/Backoff/AbstractBackoffStrategy.phpI dUI ÙÚZ4¶Elib/guzzle/Guzzle/Plugin/Backoff/AbstractErrorCodeBackoffStrategy.phpdUÝ|¶2lib/guzzle/Guzzle/Plugin/Backoff/BackoffLogger.php dU (Õ*˜¶2lib/guzzle/Guzzle/Plugin/Backoff/BackoffPlugin.php=dU=Z“mï¶=lib/guzzle/Guzzle/Plugin/Backoff/BackoffStrategyInterface.phpãdUãXà±|¶<lib/guzzle/Guzzle/Plugin/Backoff/CallbackBackoffStrategy.phpôdUôÑ>ù¶<lib/guzzle/Guzzle/Plugin/Backoff/ConstantBackoffStrategy.php‡dU‡ jžv¶8lib/guzzle/Guzzle/Plugin/Backoff/CurlBackoffStrategy.phpßdUß%+ž¶?lib/guzzle/Guzzle/Plugin/Backoff/ExponentialBackoffStrategy.phpŽdUŽmŒhS¶8lib/guzzle/Guzzle/Plugin/Backoff/HttpBackoffStrategy.php†dU†#Ǧ¶:lib/guzzle/Guzzle/Plugin/Backoff/LinearBackoffStrategy.phpdUT #¶@lib/guzzle/Guzzle/Plugin/Backoff/ReasonPhraseBackoffStrategy.php®dU®Ò sW¶=lib/guzzle/Guzzle/Plugin/Backoff/TruncatedBackoffStrategy.phpÏdUÏåAQp¶<lib/guzzle/Guzzle/Plugin/Cache/CacheKeyProviderInterface.phpõdUõ¤kÈ˶.lib/guzzle/Guzzle/Plugin/Cache/CachePlugin.php:3dU:3P‚¶8lib/guzzle/Guzzle/Plugin/Cache/CacheStorageInterface.phpÕdUÕ]à9¶;lib/guzzle/Guzzle/Plugin/Cache/CallbackCanCacheStrategy.phpƒdUƒ,\„p¶<lib/guzzle/Guzzle/Plugin/Cache/CanCacheStrategyInterface.php‰dU‰¢óÁ[¶:lib/guzzle/Guzzle/Plugin/Cache/DefaultCacheKeyProvider.phpÞdUÞ˜ÞV¡¶6lib/guzzle/Guzzle/Plugin/Cache/DefaultCacheStorage.php2dU2‚è@¶:lib/guzzle/Guzzle/Plugin/Cache/DefaultCanCacheStrategy.phpŒdUŒ´‘ù©¶6lib/guzzle/Guzzle/Plugin/Cache/DefaultRevalidation.phpÑdUѶÚßܶ3lib/guzzle/Guzzle/Plugin/Cache/DenyRevalidation.php–dU–ì¶8lib/guzzle/Guzzle/Plugin/Cache/RevalidationInterface.phpNdUNŠD•¶3lib/guzzle/Guzzle/Plugin/Cache/SkipRevalidation.php–dU–Nt¶*lib/guzzle/Guzzle/Plugin/Cookie/Cookie.php21dU21·Æî’¶<lib/guzzle/Guzzle/Plugin/Cookie/CookieJar/ArrayCookieJar.php@dU@‹6.~¶@lib/guzzle/Guzzle/Plugin/Cookie/CookieJar/CookieJarInterface.phpj dUj 4`Û¶;lib/guzzle/Guzzle/Plugin/Cookie/CookieJar/FileCookieJar.php†dU†t2L¶0lib/guzzle/Guzzle/Plugin/Cookie/CookiePlugin.php‰dU‰L"]½¶Dlib/guzzle/Guzzle/Plugin/Cookie/Exception/InvalidCookieException.phpªdUª!m|€¶4lib/guzzle/Guzzle/Plugin/CurlAuth/CurlAuthPlugin.phpldUlËž³¶Jlib/guzzle/Guzzle/Plugin/ErrorResponse/ErrorResponseExceptionInterface.phpVdUV|¬F¡¶>lib/guzzle/Guzzle/Plugin/ErrorResponse/ErrorResponsePlugin.php dU d…'ö¶Klib/guzzle/Guzzle/Plugin/ErrorResponse/Exception/ErrorResponseException.php¡dU¡«ÔÒ™¶2lib/guzzle/Guzzle/Plugin/History/HistoryPlugin.phpQdUQDSØ+¶*lib/guzzle/Guzzle/Plugin/Log/LogPlugin.phpýdUýÆA"Ú¶8lib/guzzle/Guzzle/Plugin/Md5/CommandContentMd5Plugin.phpdUÖ'f”¶3lib/guzzle/Guzzle/Plugin/Md5/Md5ValidatorPlugin.phpu dUu „Nmÿ¶,lib/guzzle/Guzzle/Plugin/Mock/MockPlugin.phpNdUNpô¾¶.lib/guzzle/Guzzle/Plugin/Oauth/OauthPlugin.php((dU((=,šŽ¶2lib/guzzle/Guzzle/Service/AbstractConfigLoader.phpqdUq©ù7ñ¶4lib/guzzle/Guzzle/Service/Builder/ServiceBuilder.phpdUúò€¶=lib/guzzle/Guzzle/Service/Builder/ServiceBuilderInterface.phpÆdUÆçS”)¶:lib/guzzle/Guzzle/Service/Builder/ServiceBuilderLoader.phpD dUD °ß_æ¶1lib/guzzle/Guzzle/Service/CachingConfigLoader.php”dU”ï¶$lib/guzzle/Guzzle/Service/Client.php%dU%¡ W¶-lib/guzzle/Guzzle/Service/ClientInterface.php“ dU“ ³Ÿ¶5lib/guzzle/Guzzle/Service/Command/AbstractCommand.php40dU40Qbº°¶4lib/guzzle/Guzzle/Service/Command/ClosureCommand.phpdU‘§.¶6lib/guzzle/Guzzle/Service/Command/CommandInterface.phpÅ dUÅ %¼‘¬¶>lib/guzzle/Guzzle/Service/Command/CreateResponseClassEvent.php<dU< 8+¶>lib/guzzle/Guzzle/Service/Command/DefaultRequestSerializer.phpÖdUÖ 9µ[¶;lib/guzzle/Guzzle/Service/Command/DefaultResponseParser.phpÕdUÕñ.'|¶:lib/guzzle/Guzzle/Service/Command/Factory/AliasFactory.php`dU`d‹†¶>lib/guzzle/Guzzle/Service/Command/Factory/CompositeFactory.phpdUj1̶Blib/guzzle/Guzzle/Service/Command/Factory/ConcreteClassFactory.phpEdUEïº=¶>lib/guzzle/Guzzle/Service/Command/Factory/FactoryInterface.phpªdUªÏ Yc¶8lib/guzzle/Guzzle/Service/Command/Factory/MapFactory.phpdUŸ øø¶Glib/guzzle/Guzzle/Service/Command/Factory/ServiceDescriptionFactory.phpmdUm€ù“¶Tlib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/AbstractRequestVisitor.phpþdUþÒ×Zv¶Ilib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/BodyVisitor.php¯ dU¯ Y4¡¶Klib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/HeaderVisitor.phpùdUù ϶q¶Ilib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/JsonVisitor.phpèdUèçÈa ¶Nlib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/PostFieldVisitor.php dU ˱„Ô¶Mlib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/PostFileVisitor.php¾dU¾àÖ$p¶Jlib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/QueryVisitor.phpdU=øˆ§¶Ulib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/RequestVisitorInterface.php7dU7{¸HƶQlib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/ResponseBodyVisitor.phpódUóV´›¨¶Hlib/guzzle/Guzzle/Service/Command/LocationVisitor/Request/XmlVisitor.php£dU£ ñ š¶Vlib/guzzle/Guzzle/Service/Command/LocationVisitor/Response/AbstractResponseVisitor.phpfdUf}…ÏM¶Jlib/guzzle/Guzzle/Service/Command/LocationVisitor/Response/BodyVisitor.php3dU3…‘²¶Llib/guzzle/Guzzle/Service/Command/LocationVisitor/Response/HeaderVisitor.phpdUðÕ¿¶Jlib/guzzle/Guzzle/Service/Command/LocationVisitor/Response/JsonVisitor.phpº dUº ë€è²¶Rlib/guzzle/Guzzle/Service/Command/LocationVisitor/Response/ReasonPhraseVisitor.phpHdUHÿ˜1¶Wlib/guzzle/Guzzle/Service/Command/LocationVisitor/Response/ResponseVisitorInterface.php2dU2‚Ïø[¶Plib/guzzle/Guzzle/Service/Command/LocationVisitor/Response/StatusCodeVisitor.phpBdUB²x—@¶Ilib/guzzle/Guzzle/Service/Command/LocationVisitor/Response/XmlVisitor.phpÐdUÐ Õi÷¶Flib/guzzle/Guzzle/Service/Command/LocationVisitor/VisitorFlyweight.phpÓdUÓõçQ¶6lib/guzzle/Guzzle/Service/Command/OperationCommand.phpÛ dUÛ ×Yø­¶=lib/guzzle/Guzzle/Service/Command/OperationResponseParser.phpÑdUÑR綶@lib/guzzle/Guzzle/Service/Command/RequestSerializerInterface.phpædUæÖEk¶<lib/guzzle/Guzzle/Service/Command/ResponseClassInterface.php»dU»sÝo¶=lib/guzzle/Guzzle/Service/Command/ResponseParserInterface.phpëdUëwŽ²{¶3lib/guzzle/Guzzle/Service/ConfigLoaderInterface.php»dU»VQøh¶3lib/guzzle/Guzzle/Service/Description/Operation.phpv=dUv=_¼Þ‰¶<lib/guzzle/Guzzle/Service/Description/OperationInterface.php‰dU‰eé ç¶3lib/guzzle/Guzzle/Service/Description/Parameter.phpßadUßa[‹¸¶9lib/guzzle/Guzzle/Service/Description/SchemaFormatter.phpédUéÒ/lF¶9lib/guzzle/Guzzle/Service/Description/SchemaValidator.phpj.dUj.Cc¹Þ¶<lib/guzzle/Guzzle/Service/Description/ServiceDescription.phpŒdUŒÂÒ#ŶElib/guzzle/Guzzle/Service/Description/ServiceDescriptionInterface.php±dU±/Sëã¶Blib/guzzle/Guzzle/Service/Description/ServiceDescriptionLoader.phpç dUç %Àõ@¶<lib/guzzle/Guzzle/Service/Description/ValidatorInterface.phpÑdUÑóµb»¶8lib/guzzle/Guzzle/Service/Exception/CommandException.phpŽdUŽ£Õ¯¶@lib/guzzle/Guzzle/Service/Exception/CommandTransferException.phpÅ dUÅ V——϶Clib/guzzle/Guzzle/Service/Exception/DescriptionBuilderException.php™dU™Æ£Ñï¶Klib/guzzle/Guzzle/Service/Exception/InconsistentClientTransferException.php–dU–y £“¶>lib/guzzle/Guzzle/Service/Exception/ResponseClassException.php•dU•#ìíN¶?lib/guzzle/Guzzle/Service/Exception/ServiceBuilderException.php•dU•ïèNζ@lib/guzzle/Guzzle/Service/Exception/ServiceNotFoundException.phpndUn¼S¬h¶;lib/guzzle/Guzzle/Service/Exception/ValidationException.phpdUb‘dè¶Flib/guzzle/Guzzle/Service/Resource/AbstractResourceIteratorFactory.phpdU`éÀ¶Glib/guzzle/Guzzle/Service/Resource/CompositeResourceIteratorFactory.phpïdUïÈì¾’¶Alib/guzzle/Guzzle/Service/Resource/MapResourceIteratorFactory.phpˆdUˆµ¾‰÷¶,lib/guzzle/Guzzle/Service/Resource/Model.phpdUBpQ…¶7lib/guzzle/Guzzle/Service/Resource/ResourceIterator.php\dU\K…˶Clib/guzzle/Guzzle/Service/Resource/ResourceIteratorApplyBatched.phpS dUS Öœû¶Clib/guzzle/Guzzle/Service/Resource/ResourceIteratorClassFactory.phpÈdUÈqüû¶Glib/guzzle/Guzzle/Service/Resource/ResourceIteratorFactoryInterface.phpdU癤Ѷ@lib/guzzle/Guzzle/Service/Resource/ResourceIteratorInterface.phpdUã2ÏP¶4lib/guzzle/Guzzle/Stream/PhpStreamRequestFactory.php$dU$Û9Ķ#lib/guzzle/Guzzle/Stream/Stream.phpdUåôÓ|¶,lib/guzzle/Guzzle/Stream/StreamInterface.php8dU81‚ݶ:lib/guzzle/Guzzle/Stream/StreamRequestFactoryInterface.php[dU[4¶lib/guzzle/LICENSEWdUW–[Ë ¶lib/php-timer/LICENSEdUÔN>¶lib/php-timer/Timer.php6dU6#X6ñ¶lib/phpseclib/Crypt/AES.phpådUåkÜ“C¶lib/phpseclib/Crypt/Base.php,dU,ˆü:¶ lib/phpseclib/Crypt/Blowfish.phpedUe¿^ìI¶lib/phpseclib/Crypt/DES.php)dU)Ómi¶lib/phpseclib/Crypt/Hash.phpÕkdUÕkŒÍ¿8¶lib/phpseclib/Crypt/Random.php¾(dU¾( œìv¶lib/phpseclib/Crypt/RC2.php MdU M­É¢5¶lib/phpseclib/Crypt/RC4.phpDdUDצ½c¶ lib/phpseclib/Crypt/Rijndael.phpóûdUóû˜†ù«¶lib/phpseclib/Crypt/RSA.phpƒdUƒcÜ…ö¶!lib/phpseclib/Crypt/TripleDES.php™1dU™13϶lib/phpseclib/Crypt/Twofish.php¯’dU¯’ÔË!»¶lib/phpseclib/File/ANSI.phpHdUH¦ô,¶#lib/phpseclib/File/ASN1/Element.phpmdUmN{r&¶lib/phpseclib/File/ASN1.phptÉdUtÉãï܉¶lib/phpseclib/File/X509.php«ŒdU«Œj¶lib/phpseclib/LICENSEXdUX{y'Á¶!lib/phpseclib/Math/BigInteger.phpäãdUäãÁµçZ¶lib/phpseclib/Net/SCP.phpd#dUd#æ:¶!lib/phpseclib/Net/SFTP/Stream.phpòSdUòSÖ{|¶lib/phpseclib/Net/SFTP.phpWdUWvx¤Æ¶lib/phpseclib/Net/SSH1.phpÍdUÍ–ÿ¶lib/phpseclib/Net/SSH2.phpüdUüÑGbݶlib/phpseclib/openssl.cnfhdUhݶ+lib/phpseclib/System/SSH/Agent/Identity.phpÊdUÊQ¢6¶"lib/phpseclib/System/SSH/Agent.phpdUlO¾¶%lib/sebastian-environment/Console.php†dU†šXç¶!lib/sebastian-environment/LICENSEdUiV”¶%lib/sebastian-environment/Runtime.phpdU´j°¶lib/sebastian-version/LICENSEdUåûœ ¶!lib/sebastian-version/Version.php dU O>¶lib/softlayer-os/LICENSEùdUù.J°Î¶+lib/softlayer-os/ObjectStorage/Abstract.php¿BdU¿BW¶+lib/softlayer-os/ObjectStorage/AuthData.phpîdUîrþ¢”¶,lib/softlayer-os/ObjectStorage/Container.php^dU^s¼¦¶;lib/softlayer-os/ObjectStorage/Exception/Authentication.phpVdUVóԴŶ6lib/softlayer-os/ObjectStorage/Exception/Container.phpQdUQV¼Ž¶<lib/softlayer-os/ObjectStorage/Exception/Http/BadGateway.php‰dU‰vIpœ¶<lib/softlayer-os/ObjectStorage/Exception/Http/BadRequest.php‰dU‰)»Ó’¶:lib/softlayer-os/ObjectStorage/Exception/Http/Conflict.php‡dU‡˜o÷ζ;lib/softlayer-os/ObjectStorage/Exception/Http/Forbidden.phpˆdUˆ²ö§¶;lib/softlayer-os/ObjectStorage/Exception/Http/Interface.phpbdUb³¬m¶Elib/softlayer-os/ObjectStorage/Exception/Http/InternalServerError.php’dU’é…¶Blib/softlayer-os/ObjectStorage/Exception/Http/MethodNotAllowed.phpdUºñ0‘¶?lib/softlayer-os/ObjectStorage/Exception/Http/NotAcceptable.phpŒdUŒÕDD¶:lib/softlayer-os/ObjectStorage/Exception/Http/NotFound.php‡dU‡Ø-•2¶@lib/softlayer-os/ObjectStorage/Exception/Http/NotImplemented.phpdU–߶Mlib/softlayer-os/ObjectStorage/Exception/Http/ProxyAuthenticationRequired.phpšdUšï€¶@lib/softlayer-os/ObjectStorage/Exception/Http/RequestTimeout.phpdU‹tûP¶>lib/softlayer-os/ObjectStorage/Exception/Http/Unauthorized.php‹dU‹7+cH¶1lib/softlayer-os/ObjectStorage/Exception/Http.phpV dUV ›Cb¶3lib/softlayer-os/ObjectStorage/Exception/Object.phpNdUNñÂY«¶7lib/softlayer-os/ObjectStorage/Exception/TokenStore.phpRdURAw5J¶,lib/softlayer-os/ObjectStorage/Exception.phppdUp,Ç8ð¶0lib/softlayer-os/ObjectStorage/Http/Abstract.phpädUä"ÁŒÞ¶4lib/softlayer-os/ObjectStorage/Http/Adapter/Curl.phpdUo/ô%¶9lib/softlayer-os/ObjectStorage/Http/Adapter/Interface.phpédUé­Õæ¶6lib/softlayer-os/ObjectStorage/Http/Adapter/Socket.php’dU’ä¸fܶ4lib/softlayer-os/ObjectStorage/Http/Adapter/Zend.php~ dU~ ´9Ͷ.lib/softlayer-os/ObjectStorage/Http/Client.phpµdUµ™|h›¶/lib/softlayer-os/ObjectStorage/Http/Request.phpdU2œ™Ø¶0lib/softlayer-os/ObjectStorage/Http/Response.phpLdULÈÅH¬¶)lib/softlayer-os/ObjectStorage/Object.php˜dU˜û–¶2lib/softlayer-os/ObjectStorage/TokenStore/File.phpG dUG ¦iá¶7lib/softlayer-os/ObjectStorage/TokenStore/Interface.php¸dU¸lR«´¶4lib/softlayer-os/ObjectStorage/TokenStore/Memory.phpËdU˹ŒÛض-lib/softlayer-os/ObjectStorage/TokenStore.php_dU_ƒè¾¶'lib/softlayer-os/ObjectStorage/Util.phpdUGltá¶"lib/softlayer-os/ObjectStorage.phpATdUATë7ô¶,lib/swiftmailer/classes/Swift/Attachment.php¶dU¶ìéÈå¶Jlib/swiftmailer/classes/Swift/ByteStream/AbstractFilterableInputStream.phpMdUME»B¶<lib/swiftmailer/classes/Swift/ByteStream/ArrayByteStream.phpÛdUÛÛnD4¶;lib/swiftmailer/classes/Swift/ByteStream/FileByteStream.phpŒdUŒÉ0¶Dlib/swiftmailer/classes/Swift/ByteStream/TemporaryFileByteStream.phpìdUìˆ Y¶Ilib/swiftmailer/classes/Swift/CharacterReader/GenericFixedWidthReader.php@ dU@ Ã;êh¶?lib/swiftmailer/classes/Swift/CharacterReader/UsAsciiReader.phpÕdUÕ;ªÈ¶<lib/swiftmailer/classes/Swift/CharacterReader/Utf8Reader.php£dU£sŠD¶1lib/swiftmailer/classes/Swift/CharacterReader.phpßdUßéÆd¶Ulib/swiftmailer/classes/Swift/CharacterReaderFactory/SimpleCharacterReaderFactory.php dU ‡¨Žh¶8lib/swiftmailer/classes/Swift/CharacterReaderFactory.php"dU"ß âA¶Flib/swiftmailer/classes/Swift/CharacterStream/ArrayCharacterStream.php'!dU'!UvÙã¶Clib/swiftmailer/classes/Swift/CharacterStream/NgCharacterStream.php£dU£KÁî2¶1lib/swiftmailer/classes/Swift/CharacterStream.php¹dU¹ÞÙ¾a¶3lib/swiftmailer/classes/Swift/ConfigurableSpool.phpidUiaa–y¶5lib/swiftmailer/classes/Swift/DependencyContainer.phpi&dUi&æøA$¶5lib/swiftmailer/classes/Swift/DependencyException.phpMdUM|†V¶.lib/swiftmailer/classes/Swift/EmbeddedFile.phpRdURâf‡¯¶7lib/swiftmailer/classes/Swift/Encoder/Base64Encoder.php<dU<Y² œ¶3lib/swiftmailer/classes/Swift/Encoder/QpEncoder.php™)dU™)_'þ¶8lib/swiftmailer/classes/Swift/Encoder/Rfc2231Encoder.phpL dUL Y}_¶)lib/swiftmailer/classes/Swift/Encoder.phpÞdUÞòÛÑǶ*lib/swiftmailer/classes/Swift/Encoding.php”dU”šß‰¶5lib/swiftmailer/classes/Swift/Events/CommandEvent.php°dU°¸ X¶8lib/swiftmailer/classes/Swift/Events/CommandListener.phpCdUCU’­“¶.lib/swiftmailer/classes/Swift/Events/Event.phpdU&MŽÑ¶8lib/swiftmailer/classes/Swift/Events/EventDispatcher.php˜ dU˜ FÉ b¶6lib/swiftmailer/classes/Swift/Events/EventListener.phpcdUcΑú&¶4lib/swiftmailer/classes/Swift/Events/EventObject.php=dU=ƒÕ¶6lib/swiftmailer/classes/Swift/Events/ResponseEvent.php7dU7Zþ º¶9lib/swiftmailer/classes/Swift/Events/ResponseListener.phpGdUGÔ˜¯¶2lib/swiftmailer/classes/Swift/Events/SendEvent.phpj dUj ÏS1*¶5lib/swiftmailer/classes/Swift/Events/SendListener.phpdUjñ ¶>lib/swiftmailer/classes/Swift/Events/SimpleEventDispatcher.phpdUÔÎðí¶=lib/swiftmailer/classes/Swift/Events/TransportChangeEvent.php8dU84³t¶@lib/swiftmailer/classes/Swift/Events/TransportChangeListener.phpØdUØyc¶@lib/swiftmailer/classes/Swift/Events/TransportExceptionEvent.php%dU%˜i1ä¶Clib/swiftmailer/classes/Swift/Events/TransportExceptionListener.php€dU€ögã.¶3lib/swiftmailer/classes/Swift/FailoverTransport.php€dU€õX-q¶+lib/swiftmailer/classes/Swift/FileSpool.phpÞdUÞ œg¶,lib/swiftmailer/classes/Swift/FileStream.phpìdUì|* ¶,lib/swiftmailer/classes/Swift/Filterable.php¨dU¨ÏG¾¶'lib/swiftmailer/classes/Swift/Image.phpùdUùÿ°ËǶ1lib/swiftmailer/classes/Swift/InputByteStream.phpÑdUÑN‘VŠ¶-lib/swiftmailer/classes/Swift/IoException.php dU ]B“û¶8lib/swiftmailer/classes/Swift/KeyCache/ArrayKeyCache.phpédUéÀî¶7lib/swiftmailer/classes/Swift/KeyCache/DiskKeyCache.phpµ#dUµ# Þ½)¶>lib/swiftmailer/classes/Swift/KeyCache/KeyCacheInputStream.phpdUÏužU¶7lib/swiftmailer/classes/Swift/KeyCache/NullKeyCache.phpË dUË 6q°¶Dlib/swiftmailer/classes/Swift/KeyCache/SimpleKeyCacheInputStream.phpä dUä Dliÿ¶*lib/swiftmailer/classes/Swift/KeyCache.phpS dUS ƒZûж7lib/swiftmailer/classes/Swift/LoadBalancedTransport.php‰dU‰“ø¶?lib/swiftmailer/classes/Swift/Mailer/ArrayRecipientIterator.php¿dU¿Dxø¶:lib/swiftmailer/classes/Swift/Mailer/RecipientIterator.phpëdUë ßB¶(lib/swiftmailer/classes/Swift/Mailer.php dU ƒ:ç¶/lib/swiftmailer/classes/Swift/MailTransport.phpYdUY¡Ú½¶-lib/swiftmailer/classes/Swift/MemorySpool.phpSdUSÆŒæ¶)lib/swiftmailer/classes/Swift/Message.phpkdUk û‘í¶1lib/swiftmailer/classes/Swift/Mime/Attachment.php˜dU˜¬¹@¶:lib/swiftmailer/classes/Swift/ReplacementFilterFactory.php&dU&u 3¶8lib/swiftmailer/classes/Swift/RfcComplianceException.php+dU+äo”¡¶3lib/swiftmailer/classes/Swift/SendmailTransport.phpdUƒÏ¶/lib/swiftmailer/classes/Swift/SignedMessage.phpÅdUÅÉ…®R¶(lib/swiftmailer/classes/Swift/Signer.phptdUt™k´¢¶4lib/swiftmailer/classes/Swift/Signers/BodySigner.phpdUb Þÿ¶4lib/swiftmailer/classes/Swift/Signers/DKIMSigner.phpTEdUTE½›Oe¶9lib/swiftmailer/classes/Swift/Signers/DomainKeySigner.php·2dU·2ÞÕ}¶6lib/swiftmailer/classes/Swift/Signers/HeaderSigner.php÷dU÷¹cäq¶8lib/swiftmailer/classes/Swift/Signers/OpenDKIMSigner.phpdU«©¶5lib/swiftmailer/classes/Swift/Signers/SMimeSigner.phpu8dUu8ÞŶ/lib/swiftmailer/classes/Swift/SmtpTransport.php–dU–Ýiè¶'lib/swiftmailer/classes/Swift/Spool.phpÔdUÔ¾F?M¶0lib/swiftmailer/classes/Swift/SpoolTransport.php2dU2Qd¾¶.lib/swiftmailer/classes/Swift/StreamFilter.phpÑdUÑþ|Õh¶Jlib/swiftmailer/classes/Swift/StreamFilters/ByteArrayReplacementFilter.php;dU;ºÒ¶Glib/swiftmailer/classes/Swift/StreamFilters/StringReplacementFilter.phpdUn›ü̶Nlib/swiftmailer/classes/Swift/StreamFilters/StringReplacementFilterFactory.phpÖdUÖ8AÏ-¶0lib/swiftmailer/classes/Swift/SwiftException.phpdUo \ž¶Alib/swiftmailer/classes/Swift/Transport/AbstractSmtpTransport.php<8dU<8‡ëÍͶKlib/swiftmailer/classes/Swift/Transport/Esmtp/Auth/CramMd5Authenticator.php‡dU‡iN±Ò¶Ilib/swiftmailer/classes/Swift/Transport/Esmtp/Auth/LoginAuthenticator.phpadUalf¶Hlib/swiftmailer/classes/Swift/Transport/Esmtp/Auth/NTLMAuthenticator.phpXdUXK¶Ilib/swiftmailer/classes/Swift/Transport/Esmtp/Auth/PlainAuthenticator.phpdUeNKζKlib/swiftmailer/classes/Swift/Transport/Esmtp/Auth/XOAuth2Authenticator.phpldUlÉWhF¶?lib/swiftmailer/classes/Swift/Transport/Esmtp/Authenticator.phpHdUHÛËÄã¶=lib/swiftmailer/classes/Swift/Transport/Esmtp/AuthHandler.php-dU-Á‡±¶8lib/swiftmailer/classes/Swift/Transport/EsmtpHandler.php dU Ä}õ¶:lib/swiftmailer/classes/Swift/Transport/EsmtpTransport.phpÛ(dUÛ(sÚÆ̶=lib/swiftmailer/classes/Swift/Transport/FailoverTransport.phpÂdUÂ0w~¶4lib/swiftmailer/classes/Swift/Transport/IoBuffer.phpdUú²'R¶Alib/swiftmailer/classes/Swift/Transport/LoadBalancedTransport.phpÈdUÈB"ó¤¶7lib/swiftmailer/classes/Swift/Transport/MailInvoker.phpædUæmßà¶9lib/swiftmailer/classes/Swift/Transport/MailTransport.php«dU«$ãgi¶9lib/swiftmailer/classes/Swift/Transport/NullTransport.php´dU´ ¶=lib/swiftmailer/classes/Swift/Transport/SendmailTransport.php}dU}P_Ãʶ=lib/swiftmailer/classes/Swift/Transport/SimpleMailInvoker.phpîdUîŠ%z¶5lib/swiftmailer/classes/Swift/Transport/SmtpAgent.phpÔdUÔ8V£×¶:lib/swiftmailer/classes/Swift/Transport/SpoolTransport.php\ dU\ d¼SͶ8lib/swiftmailer/classes/Swift/Transport/StreamBuffer.php %dU %õà o¶+lib/swiftmailer/classes/Swift/Transport.php÷dU÷bwå¶4lib/swiftmailer/classes/Swift/TransportException.phpNdUN?u N¶*lib/swiftmailer/classes/Swift/Validate.php¿dU¿8‘XC¶!lib/swiftmailer/classes/Swift.php0dU0›¦© ¶.lib/swiftmailer/dependency_maps/cache_deps.phpvdUvžƒ8˶0lib/swiftmailer/dependency_maps/message_deps.phpÇdUÇ@ØÒ¶-lib/swiftmailer/dependency_maps/mime_deps.phpÃdUÃ3ñÂo¶2lib/swiftmailer/dependency_maps/transport_deps.phpé dUé —Vc,¶lib/swiftmailer/LICENSE$dU$?¿ÏÖ¶lib/swiftmailer/mime_types.php dU Y %h¶lib/swiftmailer/preferences.phpwdUw¦®¶lib/swiftmailer/swift_init.phpÕdUÕq}mv¶"lib/swiftmailer/swift_required.php¹dU¹f×]ê¶5lib/swiftmailer/swiftmailer_generate_mimes_config.php­dU­3×C¶>lib/symfony/event-dispatcher/ContainerAwareEventDispatcher.php°dU°}òì¶?lib/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php‹%dU‹%e$3¶Hlib/symfony/event-dispatcher/Debug/TraceableEventDispatcherInterface.php#dU#«Ó–c¶6lib/symfony/event-dispatcher/Debug/WrappedListener.phpÕdUÕðM} ¶Jlib/symfony/event-dispatcher/DependencyInjection/RegisterListenersPass.phpËdU˧£ Ƕ&lib/symfony/event-dispatcher/Event.php‡ dU‡ ¬f m¶0lib/symfony/event-dispatcher/EventDispatcher.phpÍdUÍÝ6¶9lib/symfony/event-dispatcher/EventDispatcherInterface.php· dU· ûc»ù¶9lib/symfony/event-dispatcher/EventSubscriberInterface.php-dU-µ½Á/¶-lib/symfony/event-dispatcher/GenericEvent.php?dU?ªm|¶9lib/symfony/event-dispatcher/ImmutableEventDispatcher.phpÀdUÀOh¶$lib/symfony/event-dispatcher/LICENSE)dU)ë&•¶Blib/symfony/event-dispatcher/Tests/AbstractEventDispatcherTest.php3dU3Á2£¶Hlib/symfony/event-dispatcher/Tests/ContainerAwareEventDispatcherTest.phpdU৶Ilib/symfony/event-dispatcher/Tests/Debug/TraceableEventDispatcherTest.phpdUìø$$¶Tlib/symfony/event-dispatcher/Tests/DependencyInjection/RegisterListenersPassTest.phpdU®¡Da¶:lib/symfony/event-dispatcher/Tests/EventDispatcherTest.phpýdUýÅ/æ{¶0lib/symfony/event-dispatcher/Tests/EventTest.php, dU, Ÿ 8i¶7lib/symfony/event-dispatcher/Tests/GenericEventTest.phpö dUö 0•N0¶Clib/symfony/event-dispatcher/Tests/ImmutableEventDispatcherTest.phpa dUa ²ãî¶ Listener.phpJdUJC£¶ Log/Json.phpádUáè×™À¶Log/Logger.phpdU`ýsʶ Log/Mail.php@:dU@:tˆ¶Log/Printer.php dU Oö manifest.txtÓdUÓÏ&ŶResult/Backup.phpÐdUÐȅ鹶Result/PrinterCli.php¹8dU¹8þ0‡^¶ Result.phpc&dUc&©Oâs¶ Runner.php¸dU¸ná׶ Util/Arr.php%dU%tÃÏv¶ Util/Cli.php|dU|í(¯û¶ Util/Math.php7dU77W¶Util/String.phpñdUñ9²(*¶ Version.phpådU剚ÆÀ¶ * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Exception extends App\Exception { } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class SizeDiffPreviousPercent implements Check { /** * @see \phpbu\App\Backup\Check::pass() * @param \phpbu\App\Backup\Target $target * @param string $value * @param \phpbu\App\Backup\Collector $collector * @param \phpbu\App\Result $result * @return boolean * @throws \phpbu\App\Exception */ public function pass(Target $target, $value, Collector $collector, Result $result) { // throws App\Exception if file doesn't exist $backupSize = $target->getSize(); $history = $collector->getBackupFiles(); $historyCount = count($history); $pass = true; if ($historyCount > 0) { // oldest backups first ksort($history); /* @var $prevFile \SplFileInfo */ $prevFile = array_shift($history); $prevSize = $prevFile->getSize(); $diffPercent = Math::getDiffInPercent($backupSize, $prevSize); $pass = $diffPercent < $value; } return $pass; } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class SizeMin implements Check { /** * @see \phpbu\App\Backup\Check::pass() * @param \phpbu\App\Backup\Target $target * @param string $value * @param \phpbu\App\Backup\Collector $collector * @param \phpbu\App\Result $result * @return boolean * @throws \phpbu\App\Exception */ public function pass(Target $target, $value, Collector $collector, Result $result) { // throws App\Exception if file doesn't exist $actualSize = $target->getSize(); $testSize = String::toBytes($value); return $testSize <= $actualSize; } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ interface Check { /** * Checks the created backup. * * @param \phpbu\App\Backup\Target $target * @param string $value * @param \phpbu\App\Backup\Collector * @param \phpbu\App\Result * @return boolean */ public function pass(Target $target, $value, Collector $collector, Result $result); } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Capacity implements Cleaner { /** * Original XML value * * @var string */ protected $capacityRaw; /** * Capacity in bytes. * * @var mixed */ protected $capacityBytes; /** * Delete current backup as well * * @var boolean */ protected $deleteTarget; /** * Setup the the Cleaner. * * @see \phpbu\App\Backup\Cleanup::setup() * @param array $options * @throws \phpbu\App\Backup\Cleaner\Exception */ public function setup(array $options) { if (!isset($options['size'])) { throw new Exception('option \'size\' is missing'); } try { $bytes = String::toBytes($options['size']); } catch (RuntimeException $e) { throw new Exception($e->getMessage()); } $this->deleteTarget = isset($options['deleteTarget']) ? String::toBoolean($options['deleteTarget'], false) : false; $this->capacityRaw = $options['size']; $this->capacityBytes = $bytes; } /** * Cleanup your backup directory. * * @see \phpbu\App\Backup\Cleanup::cleanup() * @param \phpbu\App\Backup\Target $target * @param \phpbu\App\Backup\Collector $collector * @param \phpbu\App\Result $result * @throws \phpbu\App\Backup\Cleaner\Exception */ public function cleanup(Target $target, Collector $collector, Result $result) { $files = $collector->getBackupFiles(); $size = $target->getSize(); /** @var \phpbu\App\Backup\File $file */ foreach ($files as $file) { $size += $file->getSize(); } // backups exceed capacity? if ($size > $this->capacityBytes) { // oldest backups first ksort($files); while ($size > $this->capacityBytes && count($files) > 0) { $file = array_shift($files); $size -= $file->getSize(); if (!$file->isWritable()) { throw new Exception(sprintf('can\'t delete file: %s', $file->getPathname())); } $result->debug(sprintf('delete %s', $file->getPathname())); $file->unlink(); } // deleted all old backups but still exceeding the space limit // delete the currently created backup as well if ($this->deleteTarget && $size > $this->capacityBytes) { $target->unlink(); } } } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Exception extends App\Exception { } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Outdated implements Cleaner { /** * Original XML value * * @var string */ protected $offsetRaw; /** * Offset in seconds. * * @var integer */ protected $offsetSeconds; /** * Setup the Cleaner. * * @see \phpbu\App\Backup\Cleanup::setup() * @param array $options * @throws \phpbu\App\Backup\Cleaner\Exception */ public function setup(array $options) { if (!isset($options['older'])) { throw new Exception('option \'older\' is missing'); } try { $seconds = String::toTime($options['older']); } catch (RuntimeException $e) { throw new Exception($e->getMessage()); } $this->offsetRaw = $options['older']; $this->offsetSeconds = $seconds; } /** * Cleanup your backup directory. * * @see \phpbu\App\Backup\Cleanup::cleanup() * @param \phpbu\App\Backup\Target $target * @param \phpbu\App\Backup\Collector $collector * @param \phpbu\App\Result $result * @throws \phpbu\App\Backup\Cleaner\Exception */ public function cleanup(Target $target, Collector $collector, Result $result) { $minTime = time() - $this->offsetSeconds; $files = $collector->getBackupFiles(); /** @var \phpbu\App\Backup\File $file */ foreach ($files as $file) { // last mod date < min date? delete! if ($file->getMTime() < $minTime) { if (!$file->isWritable()) { throw new Exception(sprintf('can\'t delete file: %s', $file->getPathname())); } $result->debug(sprintf('delete %s', $file->getPathname())); $file->unlink(); } } } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Quantity implements Cleaner { /** * Amount of backups to keep * * @var integer */ protected $amount; /** * Setup the Cleaner. * * @see \phpbu\App\Backup\Cleanup::setup() * @param array $options * @throws \phpbu\App\Backup\Cleaner\Exception */ public function setup(array $options) { if (!isset($options['amount'])) { throw new Exception('option \'amount\' is missing'); } if (!is_numeric($options['amount'])) { throw new Exception(sprintf('invalid value for \'amount\': %s', $options['amount'])); } if ($options['amount'] < 1) { throw new Exception(sprintf('value for \'amount\' must be greater 0, %s given', $options['amount'])); } $this->amount = intval($options['amount']); } /** * Cleanup your backup directory. * * @see \phpbu\App\Backup\Cleanup::cleanup() * @param \phpbu\App\Backup\Target $target * @param \phpbu\App\Backup\Collector $collector * @param \phpbu\App\Result $result * @throws \phpbu\App\Backup\Cleaner\Exception */ public function cleanup(Target $target, Collector $collector, Result $result) { $files = $collector->getBackupFiles(); // backups exceed capacity? if (count($files) > $this->amount) { // oldest backups first ksort($files); // add one for current backup while (count($files) + 1 > $this->amount) { $file = array_shift($files); $result->debug(sprintf('delete %s', $file->getPathname())); if (!$file->isWritable()) { throw new Exception(sprintf('can\'t delete file: %s', $file->getPathname())); } $result->debug(sprintf('delete %s', $file->getPathname())); $file->unlink(); } } } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ interface Cleaner { /** * Setup the cleaner. * * @param array $options * @return void */ public function setup(array $options); /** * Cleanup you backup location * * @param \phpbu\App\Backup\Target $target * @param \phpbu\App\Backup\Collector $collector * @param \phpbu\App\Result $result * @return void */ public function cleanup(Target $target, Collector $collector, Result $result); } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Cmd { /** * Command name * * @var string */ private $name; /** * Display stderr * * @var boolean */ private $isSilent = false; /** * Command options * * @var array */ private $options = array(); /** * Constructor. * * @param string $name */ public function __construct($name) { $this->name = $name; } /** * Name getter. * * @return string */ public function getName() { return $this->name; } /** * Silent setter * * @param boolean $bool */ public function silence($bool = true) { $this->isSilent = $bool; } /** * Add option to list. * * @param string $option * @param mixed $argument * @param string $glue */ public function addOption($option, $argument = null, $glue = '=') { if (is_array($argument)) { $argument = array_map('escapeshellarg', $argument); $glue = ' '; $escapedArgument = implode(' ', $argument); } else { $escapedArgument = escapeshellarg($argument); } $this->options[] = $option . (null !== $argument ? $glue . $escapedArgument : ''); } /** * Add argument to list. * * @param mixed $argument */ public function addArgument($argument) { if (is_array($argument)) { $argument = array_map('escapeshellarg', $argument); $escapedArgument = implode(' ', $argument); } else { $escapedArgument = escapeshellarg($argument); } $this->options[] = $escapedArgument; } /** * Magic to string method. * * @return string */ public function __toString() { return $this->name . ( count($this->options) ? ' ' . implode(' ', $this->options) : '' ) . ( $this->isSilent ? ' 2> /dev/null' : '' ); } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Exec { /** * List of system commands to execute. * * @var array<\phpbu\Backup\Cli\Cmd> */ private $commands = array(); /** * Executes the commands. * * @param string $redirect * @return \phpbu\App\Backup\Cli\Result * @throws \phpbu\App\Exception */ public function execute($redirect = null) { $cmd = $this->getExec() . ( $redirect ? ' > ' . $redirect : '' ); $output = array(); $code = 0; $old = error_reporting(0); exec($cmd, $output, $code); error_reporting($old); return new Result($cmd, $code, $output); } /** * Generates the system command. * * @return string * @throws \phpbu\App\Exception */ public function getExec() { $amount = count($this->commands); if ($amount < 1) { throw new Exception('no command to execute'); } $cmd = $amount > 1 ? '(' . implode(' && ', $this->commands) . ')' : $this->commands[0]; return $cmd; } /** * Adds a system command to the command list. * * @param \phpbu\App\Backup\Cli\Cmd $cmd */ public function addCommand(Cmd $cmd) { $this->commands[] = $cmd; } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Result { /** * Command that got executed. * * @var string */ private $cmd; /** * Result code * * @var integer */ private $code; /** * Output buffer. * * @var array */ private $buffer = array(); /** * Text output * * @var string */ private $output; /** * Constructor * * @param string $cmd * @param integer $code * @param mixed $output */ public function __construct($cmd, $code, array $output = array()) { $this->cmd = $cmd; $this->code = $code; $this->buffer = $output; } /** * Cmd getter. * * @return string */ public function getCmd() { return $this->cmd; } /** * Code getter. * * @return integer */ public function getCode() { return $this->code; } /** * Command executed successful. */ public function wasSuccessful() { return $this->code == 0; } /** * Output getter. * * @return mixed array */ public function getOutput() { return $this->buffer; } /** * Return the output ins string format. * * @return string */ public function getOutputAsString() { if (null === $this->output) { $this->output = $this->bufferToText(); } return $this->output; } /** * Converts the output buffer array into a string. * * @return string */ private function bufferToText() { return implode(PHP_EOL, $this->buffer); } /** * Magic to string method. * * @return string */ public function __toString() { return $this->getOutputAsString(); } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Collector { /** * Backup target * * @var \phpbu\App\Backup\Target */ protected $target; /** * Collection cache * * @var array<\phpbu\App\Backup\File> */ protected $files; /** * Constructor * * @param Target $target */ public function __construct(Target $target) { $this->target = $target; } /** * Get all created backups. * * @return array<\phpbu\App\Backup\File> */ public function getBackupFiles() { if (null === $this->files) { $this->files = array(); // collect all matching backup files $this->collect($this->target->getPathThatIsNotChanging(), 0); } return $this->files; } /** * Recursive backup collecting. * * @param string $path * @param integer $depth */ protected function collect($path, $depth) { $dItter = new DirectoryIterator($path); // collect all matching subdirs and get all the backup files if ($depth < $this->target->countChangingPathElements()) { foreach ($dItter as $i => $file) { if ($file->isDot()) { continue; } // TODO: match directory against dir-regex Target::getChangingPathElements if ($file->isDir()) { $this->collect($file->getPathname(), $depth + 1); } } } else { // create regex to match only created backup files $fileRegex = String::datePlaceholdersToRegex($this->target->getFilenameRaw()); if ($this->target->shouldBeCompressed()) { $fileRegex .= '.' . $this->target->getCompressor()->getSuffix(); } /** @var \SplFileInfo $file */ foreach ($dItter as $i => $file) { if ($file->isDir()) { continue; } // skip currently created backup if ($file->getPathname() == $this->target->getPathname()) { continue; } if (preg_match('#' . $fileRegex . '#i', $file->getFilename())) { $index = date('YmdHis', $file->getMTime()) . '-' . $i . '-' . $file->getPathname(); $this->files[$index] = new File($file->getFileInfo()); } } } } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Compressor { /** * Path to command binary * * @var string */ protected $path; /** * Command name * * @var string */ protected $cmd; /** * Suffix for compressed files * * @var string */ protected $suffix; /** * MIME type for compressed files * * @var string */ protected $mimeType; /** * List of available compressors * * @var array */ protected static $availableCompressors = array( 'gzip' => array( 'suffix' => 'gz', 'mime' => 'application/x-gzip' ), 'bzip2' => array( 'suffix' => 'bz2', 'mime' => 'application/x-bzip2' ), 'zip' => array( 'suffix' => 'zip', 'mime' => 'application/zip' ) ); /** * Constructor. * * @param string $cmd * @param string $pathToCmd without trailing slash */ protected function __construct($cmd, $pathToCmd = null) { $this->path = $pathToCmd . (!empty($pathToCmd) ? DIRECTORY_SEPARATOR : ''); $this->cmd = $cmd; $this->suffix = self::$availableCompressors[$cmd]['suffix']; $this->mimeType = self::$availableCompressors[$cmd]['mime']; } /** * Return the cli command. * * @param boolean $includingPath * @return string */ public function getCommand($includingPath = true) { return ($includingPath ? $this->path : '') . $this->cmd; } /** * Return Exec to actually execute the compressor command. * * @param string $fileToCompress * @param array $options * @return \phpbu\App\Backup\CLi\Exec */ public function getExec($fileToCompress, array $options = array()) { $cmd = new Cmd($this->getCommand()); foreach ($options as $opt) { $cmd->addOption($opt); } $cmd->addArgument($fileToCompress); $exec = new Exec(); $exec->addCommand($cmd); return $exec; } /** * Returns the compressor suffix e.g. 'bzip2' * * @return string */ public function getSuffix() { return $this->suffix; } /** * Returns the compressor mime type. * * @return string */ public function getMimeType() { return $this->mimeType; } /** * Factory method. * * @param string $name * @return \phpbu\App\Backup\Compressor * @throws \phpbu\App\Exception */ public static function create($name) { $path = null; // check if a path is given for the compressor if (basename($name) !== $name) { $path = dirname($name); $name = basename($name); } if (!isset(self::$availableCompressors[$name])) { throw new Exception('invalid compressor:' . $name); } return new static($name, $path); } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class File { /** * FileInfo * * @var \SplFileInfo */ protected $fileInfo; /** * Constructor * * @param SplFileInfo $fileInfo */ public function __construct(SplFileInfo $fileInfo) { $this->fileInfo = $fileInfo; } /** * FileInfo getter. * * @return SplFileInfo */ public function getFileInfo() { return $this->fileInfo; } /** * Return the filesize. * * @return integer */ public function getSize() { return $this->fileInfo->getSize(); } /** * Return the filename. * * @return string */ public function getFilename() { return $this->fileInfo->getFilename(); } /** * Return the full path and filename. * * @return string */ public function getPathname() { return $this->fileInfo->getPathname(); } /** * Return the path. * * @return string */ public function getPath() { return $this->fileInfo->getPath(); } /** * Return last modified date as unix timestamp. * * @return integer */ public function getMTime() { return $this->fileInfo->getMTime(); } /** * Return whether the file is writable or not. * * @return boolean */ public function isWritable() { return $this->fileInfo->isWritable(); } /** * Deletes the file. * * @throws \phpbu\App\Exception */ public function unlink() { $old = error_reporting(0); if (!unlink($this->fileInfo->getPathname())) { error_reporting($old); throw new Exception(sprintf('can\'t delete file: %s', $this->fileInfo->getPathname())); } error_reporting($old); } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.3 */ abstract class Cli { /** * Path to command * * @var string */ protected $binary; /** * Command to execute * * @var \phpbu\App\Backup\Cli\Exec */ protected $exec; /** * Executes the cli commands and handles compression * * @param \phpbu\App\Backup\Cli\Exec $exec * @param \phpbu\App\Backup\Target $target * @param bool $compressOutput * @return \phpbu\App\Backup\Cli\Result * @throws \phpbu\App\Exception */ protected function execute(Exec $exec, Target $target, $compressOutput = true) { /** @var \phpbu\App\Backup\Cli\Result $res */ $res = $exec->execute($compressOutput ? $target->getPathnamePlain() : null); $code = $res->getCode(); $cmd = $res->getCmd(); $output = $res->getOutput(); if ($code == 0) { // run the compressor command if ($compressOutput && $target->shouldBeCompressed()) { // compress the generated output with configured compressor $res = $this->compressOutput($target); if ($res->getCode() !== 0) { // remove compressed file with errors if ($target->fileExists()) { $target->unlink(); } } $cmd .= PHP_EOL . $res->getCmd(); $code += $res->getCode(); $output = array_merge($output, $res->getOutput()); } } else { // remove file with errors if ($target->fileExists(true)) { $target->unlink(true); } } return new Result($cmd, $code, $output); } /** * Compress the generated output. * * @param \phpbu\App\Backup\Target Target $target * @return \phpbu\App\Backup\Cli\Result */ protected function compressOutput(Target $target) { $exec = $target->getCompressor() ->getExec($target->getPathnamePlain(), array('-f')); $old = error_reporting(0); $res = $exec->execute(); error_reporting($old); return $res; } /** * Binary setter, mostly for test purposes. * * @param string $pathToMysqldump */ public function setBinary($pathToMysqldump) { $this->binary = $pathToMysqldump; } /** * Exec setter, mostly for test purposes. * * @param \phpbu\App\Backup\Cli\Exec $exec */ public function setExec(Exec $exec) { $this->exec = $exec; } /** * Adds an option to a command if it is not empty. * * @param \phpbu\App\Backup\Cli\Cmd $cmd * @param string $option * @param mixed $check * @param boolean $asValue * @param string $glue */ protected function addOptionIfNotEmpty(Cmd $cmd, $option, $check, $asValue = true, $glue = '=') { if (!empty($check)) { if ($asValue) { $cmd->addOption($option, $check, $glue); } else { $cmd->addOption($option); } } } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.1.6 */ class Mongodump extends Cli implements Source { /** * Show stdErr * * @var boolean */ private $showStdErr; /** * Use IPv6 * --ipv6 * * @var boolean */ private $useIPv6; /** * Host to connect to * --host * * @var string */ private $host; /** * User to connect with * --user * * @var string */ private $user; /** * Password to authenticate with * --password * * @var string */ private $password; /** * Database to use for authentication * --authenticationDatabase * * @var string */ private $authenticationDatabase; /** * List of databases to backup * --db * * @var array */ private $databases; /** * List of collections to backup * --collection * * @var array */ private $collections; /** * List of collections to ignore * --excludeCollections array of strings * * @var array */ private $excludeCollections; /** * List of prefixes to exclude collections * --excludeCollectionWithPrefix array of strings * * @var array */ private $excludeCollectionsWithPrefix; /** * Use php to validate the MongoDB connection * * @var boolean */ private $validateConnection; /** * Tar source to compress MongoDB dump directory * * @var \phpbu\App\Backup\Source\Tar */ private $tar; /** * (No PHPDoc) * * @see \phpbu\App\Backup\Source * @param array $conf * @throws \phpbu\App\Exception */ public function setup(array $conf = array()) { $this->setupMongodump($conf); $this->setupSourceData($conf); // credentials $this->host = Util\Arr::getValue($conf, 'host'); $this->user = Util\Arr::getValue($conf, 'user'); $this->password = Util\Arr::getValue($conf, 'password'); $this->authenticationDatabase = Util\Arr::getValue($conf, 'authenticationDatabase'); // config & validation $this->useIPv6 = Util\String::toBoolean(Util\Arr::getValue($conf, 'ipv6', ''), false); $this->showStdErr = Util\String::toBoolean(Util\Arr::getValue($conf, 'showStdErr', ''), false); $this->validateConnection = Util\String::toBoolean(Util\Arr::getValue($conf, 'validateConnection', ''), false); } /** * Search for Mongodump command. * * @param array $conf */ protected function setupMongodump(array $conf) { if (empty($this->binary)) { $this->binary = Util\Cli::detectCmdLocation('mongodump', Util\Arr::getValue($conf, 'pathToMongodump')); } } /** * Fetch databases and collections to backup. * * @param array $conf */ protected function setupSourceData(array $conf) { $this->databases = Util\String::toList(Util\Arr::getValue($conf, 'databases')); $this->collections = Util\String::toList(Util\Arr::getValue($conf, 'collections')); $this->excludeCollections = Util\String::toList(Util\Arr::getValue($conf, 'excludeCollections')); $this->excludeCollectionsWithPrefix = Util\String::toList(Util\Arr::getValue($conf, 'excludeCollectionsWithPrefix')); } /** * (non-PHPDoc) * * @see \phpbu\App\Backup\Source * @param \phpbu\App\Backup\Target $target * @param \phpbu\App\Result $result * @return \phpbu\App\Result * @throws \phpbu\App\Exception */ public function backup(Target $target, Result $result) { if ($this->validateConnection) { $this->checkConnection($this->host, $this->user, $this->password, $this->databases); } $exec = $this->getExec($target); $mongodump = $this->execute($exec, $target, false); $result->debug($mongodump->getCmd()); if (!$mongodump->wasSuccessful()) { throw new Exception('Mongodump failed'); } try { $tar = $this->getTar($target); $tar->backup($target, $result); $result->debug('remove dump directory'); } catch (\Exception $e) { throw new Exception('Failed to \'tar\' Mongodump directory', 1, $e); } return $result; } /** * Create the Exec to run the Mongodump command * * @param \phpbu\App\Backup\Target $target * @return \phpbu\App\Backup\Cli\Exec */ public function getExec(Target $target) { if (null == $this->exec) { $dump = $this->getDumpDir($target); $this->exec = new Exec(); $cmd = new Cmd($this->binary); $this->exec->addCommand($cmd); // no std error unless it is activated if (!$this->showStdErr) { $cmd->silence(); // i kill you } $cmd->addOption('--out', $dump, ' '); $this->addOptionIfNotEmpty($cmd, '--ipv6', $this->useIPv6, false); $this->addOptionIfNotEmpty($cmd, '--host', $this->host, true, ' '); $this->addOptionIfNotEmpty($cmd, '--user', $this->user, true, ' '); $this->addOptionIfNotEmpty($cmd, '--password', $this->password, true, ' '); $this->addOptionIfNotEmpty($cmd, '--authenticationDatabase', $this->authenticationDatabase, true, ' '); if (count($this->databases)) { foreach ($this->databases as $db) { $cmd->addOption('--database', $db, ' '); } } if (count($this->collections)) { foreach ($this->collections as $col) { $cmd->addOption('--collection', $col, ' '); } } $this->addOptionIfNotEmpty($cmd, '--excludeCollection', $this->excludeCollections); $this->addOptionIfNotEmpty($cmd, '--excludeCollectionWithPrefix', $this->excludeCollectionsWithPrefix); } return $this->exec; } /** * Tar setter, mostly for test purposes. * * @param \phpbu\App\Backup\Source\Tar $tar */ public function setTar(Tar $tar) { $this->tar = $tar; } /** * Create a Tar backup source to compress the MongoDB dump directory. * * @param \phpbu\App\Backup\Target $target * @return \phpbu\App\Backup\Source\Tar * @throws \phpbu\App\Exception */ public function getTar(Target $target) { if (null == $this->tar) { $this->tar = new Tar(); $this->tar->setup( array( 'path' => $this->getDumpDir($target), 'removeDir' => 'true', ) ); } return $this->tar; } /** * Get the MongoDB dump directory. * * @param \phpbu\App\Backup\Target $target * @return string */ public function getDumpDir(Target $target) { return $target->getPath() . '/dump'; } /** * Test MongoDB connection. * * @param string $host * @param string $user * @param string $password * @param array $databases * @throws \phpbu\App\Exception */ public function checkConnection($host, $user, $password, array $databases = array()) { // ToDo: implement mongo db connection validation } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Mysqldump extends Cli implements Source { /** * Show stdErr * * @var boolean */ private $showStdErr; /** * Host to connect to * --host * * @var string */ private $host; /** * User to connect with * --user * * @var string */ private $user; /** * Password to authenticate with * --password * * @var string */ private $password; /** * List of tables to backup * --tables array of strings * * @var array */ private $tables; /** * List of databases to backup * --databases array of strings * * @var array */ private $databases; /** * List of tables to ignore * * @var array */ private $ignoreTables; /** * List of tables where only the table structure is stored * * @var array */ private $structureOnly; /** * Use mysqldump quick mode * -q * * @var boolean */ private $quick; /** * Use mysqldump with compression * -C * * @var boolean */ private $compress; /** * Dump only table structures * --no-data * * @var boolean */ private $noData; /** * Use php to validate the mysql connection * * @var boolean */ private $validateConnection; /** * Setup. * * @see \phpbu\App\Backup\Source * @param array $conf * @throws \phpbu\App\Exception */ public function setup(array $conf = array()) { $this->setupMysqldump($conf); $this->setupSourceData($conf); $this->host = Util\Arr::getValue($conf, 'host'); $this->user = Util\Arr::getValue($conf, 'user'); $this->password = Util\Arr::getValue($conf, 'password'); $this->showStdErr = Util\String::toBoolean(Util\Arr::getValue($conf, 'showStdErr', ''), false); $this->quick = Util\String::toBoolean(Util\Arr::getValue($conf, 'quick', ''), false); $this->compress = Util\String::toBoolean(Util\Arr::getValue($conf, 'compress', ''), false); $this->validateConnection = Util\String::toBoolean(Util\Arr::getValue($conf, 'validateConnection', ''), false); $this->noData = Util\String::toBoolean(Util\Arr::getValue($conf, 'noData', ''), false); } /** * Search for mysqldump command. * * @param array $conf */ protected function setupMysqldump(array $conf) { if (empty($this->binary)) { $this->binary = Util\Cli::detectCmdLocation( 'mysqldump', Util\Arr::getValue($conf, 'pathToMysqldump'), array( '/usr/local/mysql/bin/mysqldump', // Mac OS X '/usr/mysql/bin/mysqldump' // Linux ) ); } } /** * Get tables and databases to backup. * * @param array $conf */ protected function setupSourceData(array $conf) { $this->tables = Util\String::toList(Util\Arr::getValue($conf, 'tables')); $this->databases = Util\String::toList(Util\Arr::getValue($conf, 'databases')); $this->ignoreTables = Util\String::toList(Util\Arr::getValue($conf, 'ignoreTables')); $this->structureOnly = Util\String::toList(Util\Arr::getValue($conf, 'structureOnly')); } /** * (non-PHPDoc) * * @see \phpbu\App\Backup\Source * @param \phpbu\App\Backup\Target $target * @param \phpbu\App\Result $result * @return \phpbu\App\Result * @throws \phpbu\App\Exception */ public function backup(Target $target, Result $result) { if ($this->validateConnection) { $this->checkConnection($this->host, $this->user, $this->password, $this->databases); } $exec = $this->getExec(); $mysqldump = $this->execute($exec, $target); $result->debug($mysqldump->getCmd()); if (!$mysqldump->wasSuccessful()) { throw new Exception('mysqldump failed'); } return $result; } /** * Create the Exec to run the mysqldump command. * * @return \phpbu\App\Backup\Cli\Exec * @throws Exception */ public function getExec() { if (null == $this->exec) { $this->exec = new Exec(); $cmd = new Cmd($this->binary); $this->exec->addCommand($cmd); // no std error unless it is activated if (!$this->showStdErr) { $cmd->silence(); // i kill you } $this->addOptionIfNotEmpty($cmd, '--user', $this->user); $this->addOptionIfNotEmpty($cmd, '--password', $this->password); $this->addOptionIfNotEmpty($cmd, '--host', $this->host); $this->addOptionIfNotEmpty($cmd, '-q', $this->quick, false); $this->addOptionIfNotEmpty($cmd, '-C', $this->compress, false); if (count($this->tables)) { $cmd->addOption('--tables', $this->tables); } else { if (count($this->databases)) { $cmd->addOption('--databases', $this->databases); } else { $cmd->addOption('--all-databases'); } } if (count($this->ignoreTables)) { foreach ($this->ignoreTables as $table) { $cmd->addOption('--ignore-table', $table); } } if ($this->noData) { $cmd->addOption('--no-data'); } else { if (count($this->structureOnly)) { $cmd->addOption('--no-data'); $cmd2 = clone($cmd); foreach ($this->structureOnly as $table) { $cmd2->addOption('--ignore-table', $table); } $cmd2->addOption('--skip-add-drop-table'); $cmd2->addOption('--no-create-db'); $cmd2->addOption('--no-create-info'); $this->exec->addCommand($cmd2); } } } return $this->exec; } /** * Test mysql connection. * * @param string $host * @param string $user * @param string $password * @param array $databases * @throws \phpbu\App\Exception */ public function checkConnection($host, $user, $password, array $databases = array()) { // no host configured if (empty($host)) { // localhost by default $host = 'localhost'; } // no user configured if (empty($user)) { if (php_sapi_name() != 'cli') { throw new Exception('user is required for connection validation'); } // in cli mode we use the system user as default $user = $_SERVER['USER']; } // no databases configured if (empty($databases)) { // add the null database to trigger foreach anyway $databases[] = null; } // check all configured databases foreach ($databases as $db) { $mysqli = @new \mysqli($host, $user, $password, $db); if (0 != $mysqli->connect_errno) { $msg = $mysqli->error; unset($mysqli); throw new Exception(sprintf('Can\'t connect to mysql server: %s', $msg)); } $mysqli->close(); unset($mysqli); } } } 'j', 'gzip' => 'z', ); /** * Setup. * * @see \phpbu\App\Backup\Source * @param array $conf * @throws \phpbu\App\Exception */ public function setup(array $conf = array()) { $this->setupTar($conf); $this->showStdErr = Util\String::toBoolean(Util\Arr::getValue($conf, 'showStdErr', ''), false); $this->path = Util\Arr::getValue($conf, 'path'); $this->removeDir = Util\String::toBoolean(Util\Arr::getValue($conf, 'removeDir', ''), false); if (empty($this->path)) { throw new Exception('path option is mandatory'); } } /** * Search for tar command. * * @param array $conf */ protected function setupTar(array $conf) { if (empty($this->binary)) { $this->binary = Util\Cli::detectCmdLocation('tar', Util\Arr::getValue($conf, 'pathToTar')); } } /** * (non-PHPDoc) * * @see \phpbu\App\Backup\Source * @param \phpbu\App\Backup\Target $target * @param \phpbu\App\Result $result * @return \phpbu\App\Result * @throws \phpbu\App\Exception */ public function backup(Target $target, Result $result) { // set uncompressed default MIME type $target->setMimeType('application/x-tar'); $compressA = $target->shouldBeCompressed(); $exec = $this->getExec($target); $compressB = $target->shouldBeCompressed(); $tar = $this->execute($exec, $target, false); // maybe compression got deactivated because of an invalid compressor if ($compressA != $compressB) { $result->debug('deactivated compression'); } $result->debug($tar->getCmd()); if (!$tar->wasSuccessful()) { throw new Exception('tar failed'); } return $result; } /** * Create the Exec to run the 'tar' command. * * @param \phpbu\App\Backup\Target $target * @return \phpbu\App\Backup\Cli\Exec */ public function getExec(Target $target) { if (null == $this->exec) { $this->exec = new Exec(); $tar = new Cmd($this->binary); // no std error unless it is activated if (!$this->showStdErr) { $tar->silence(); // i kill you } // check if 'tar' can handle the requested compression if ($target->shouldBeCompressed()) { $name = $target->getCompressor()->getCommand(false); $compressOption = $this->getCompressorOption($name); // the requested compression is not available for the 'tar' command if (!$compressOption) { $target->disableCompression(); } } else { $compressOption = ''; } $tar->addOption('-' . $compressOption . 'cf'); $tar->addArgument($target->getPathname()); $tar->addOption('-C', $this->path, ' '); $tar->addArgument('.'); $this->exec->addCommand($tar); // delete the source data if requested if ($this->removeDir) { $this->exec->addCommand($this->getRmCommand()); } } return $this->exec; } /** * Return 'tar' compressor option e.g. 'j' for bzip2. * * @param $compressor * @return string */ protected function getCompressorOption($compressor) { return $this->isCompressorValid($compressor) ? $this->compressors[$compressor] : null; } /** * Return 'rm' command. * * @return \phpbu\App\Backup\Cli\Cmd */ protected function getRmCommand() { $rm = new Cmd('rm'); $rm->addOption('-rf', $this->path, ' '); if (!$this->showStdErr) { $rm->silence(); } return $rm; } /** * Return true if a given compressor is valid false otherwise. * * @param string $compressor * @return boolean */ protected function isCompressorValid($compressor) { return isset($this->compressors[$compressor]); } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ interface Source { /** * Setup the source. * * @param array $conf */ public function setup(array $conf = array()); /** * Runner the backup * * @param \phpbu\App\Backup\Target $target * @param \phpbu\App\Result $result */ public function backup(Target $target, Result $result); } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.1.4 */ class AmazonS3 implements Sync { /** * AWS key * * @var string */ protected $key; /** * AWS secret * * @var string */ protected $secret; /** * AWS S3 bucket * * @var string */ protected $bucket; /** * AWS S3 region * * @var string */ protected $region; /** * AWS remote path / object key * * @var string */ protected $path; /** * AWS acl * 'private' by default * * @var string */ protected $acl; /** * (non-PHPDoc) * * @see \phpbu\App\Backup\Sync::setup() * @param array $config * @throws \phpbu\App\Backup\Sync\Exception */ public function setup(array $config) { if (!class_exists('\\Aws\\S3\\S3Client')) { throw new Exception('Amazon SDK not loaded: use composer "aws/aws-sdk-php": "2.7.*" to install'); } if (!Arr::isSetAndNotEmptyString($config, 'key')) { throw new Exception('AWS key is mandatory'); } if (!Arr::isSetAndNotEmptyString($config, 'secret')) { throw new Exception('AWS secret is mandatory'); } if (!Arr::isSetAndNotEmptyString($config, 'bucket')) { throw new Exception('AWS S3 bucket name is mandatory'); } if (!Arr::isSetAndNotEmptyString($config, 'region')) { throw new Exception('AWS S3 region is mandatory'); } if (!Arr::isSetAndNotEmptyString($config, 'path')) { throw new Exception('AWS S3 path / object-key is mandatory'); } $this->key = $config['key']; $this->secret = $config['secret']; $this->bucket = $config['bucket']; $this->region = $config['region']; $this->path = String::withTrailingSlash(String::replaceDatePlaceholders($config['path'])); $this->acl = Arr::getValue($config, 'acl', 'private'); } /** * Execute the sync * * @see \phpbu\App\Backup\Sync::sync() * @param \phpbu\App\Backup\Target $target * @param \phpbu\App\Result $result * @throws \phpbu\App\Backup\Sync\Exception */ public function sync(Target $target, Result $result) { $sourcePath = $target->getPathname(); $targetPath = $this->path . $target->getFilename(); $s3 = S3Client::factory( array( 'signature' => 'v4', 'region' => $this->region, 'credentials' => array( 'key' => $this->key, 'secret' => $this->secret, ) ) ); try { $fh = fopen($sourcePath, 'r'); $s3->upload($this->bucket, $targetPath, $fh, $this->acl); } catch (\Exception $e) { throw new Exception($e->getMessage(), null, $e); } $result->debug('upload: done'); } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.1.0 */ abstract class Cli { /** * Executes a cli command. * * @param \phpbu\App\Backup\Cli\Cmd * @throws \phpbu\App\Backup\Sync\Exception */ protected function execute(Cmd $command) { $exec = new Exec(); $exec->addCommand($command); /* @var $res \phpbu\App\Backup\Cli\Result */ $res = $exec->execute(); if ($res->getCode()) { throw new Exception('sync failed: ' . PHP_EOL . $res->getOutputAsString()); } } /** * Replaces %TARGET_DIR% and %TARGET_FILE% in given string. * * @param string $string * @param Target $target * @return string */ protected function replaceTargetPlaceholder($string, Target $target) { $targetFile = $target->getPathname(); $targetDir = dirname($targetFile); $search = array('%TARGET_DIR%', '%TARGET_FILE%'); $replace = array($targetDir, $targetFile); return str_replace($search, $replace, $string); } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.1.2 */ class Copycom implements Sync { /** * API access key * * @var string */ protected $appKey; /** * API access token * * @var string */ protected $appSecret; /** * API access key * * @var string */ protected $userKey; /** * API access token * * @var string */ protected $userSecret; /** * Remote path * * @var string */ protected $path; /** * (non-PHPDoc) * * @see \phpbu\App\Backup\Sync::setup() * @param array $config * @throws \phpbu\App\Backup\Sync\Exception */ public function setup(array $config) { if (!class_exists('\\Barracuda\\Copy\\API')) { throw new Exception('Copy api not loaded: use composer "barracuda/copy": "1.1.*" to install'); } if (!Arr::isSetAndNotEmptyString($config, 'app.key')) { throw new Exception('API access key is mandatory'); } if (!Arr::isSetAndNotEmptyString($config, 'app.secret')) { throw new Exception('API access secret is mandatory'); } if (!Arr::isSetAndNotEmptyString($config, 'user.key')) { throw new Exception('User access key is mandatory'); } if (!Arr::isSetAndNotEmptyString($config, 'user.secret')) { throw new Exception('User access secret is mandatory'); } if (!Arr::isSetAndNotEmptyString($config, 'path')) { throw new Exception('copy.com path is mandatory'); } $this->appKey = $config['app.key']; $this->appSecret = $config['app.secret']; $this->userKey = $config['user.key']; $this->userSecret = $config['user.secret']; $this->path = String::withTrailingSlash(String::replaceDatePlaceholders($config['path'])); } /** * (non-PHPDoc) * * @see \phpbu\App\Backup\Sync::sync() * @param \phpbu\App\Backup\Target $target * @param \phpbu\App\Result $result * @throws \phpbu\App\Backup\Sync\Exception */ public function sync(Target $target, Result $result) { $sourcePath = $target->getPathname(); $targetPath = $this->path . $target->getFilename(); $copy = new CopycomApi($this->appKey, $this->appSecret, $this->userKey, $this->userSecret); try { // open a file to upload $fh = fopen($sourcePath, 'rb'); // upload the file in 1MB chunks $parts = array(); while ($data = fread($fh, 1024 * 1024)) { $part = $copy->sendData($data); array_push($parts, $part); } fclose($fh); // finalize the file $copy->createFile($targetPath, $parts); } catch (\Exception $e) { throw new Exception($e->getMessage(), null, $e); } $result->debug('upload: done'); } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.1.1 */ class Dropbox implements Sync { /** * API access token * * Goto https://www.dropbox.com/developers/apps * create your app * - Dropbox api app * - files and datastore * - yes * - provide some app name "my-dropbox-app" * - generate access token to authenticate connection to your dropbox * * @var string */ protected $token; /** * Remote path * * @var string */ protected $path; /** * (non-PHPDoc) * * @see \phpbu\App\Backup\Sync::setup() * @param array $config * @throws \phpbu\App\Backup\Sync\Exception */ public function setup(array $config) { if (!class_exists('\\Dropbox\\Client')) { throw new Exception('Dropbox sdk not loaded: use composer "dropbox/dropbox-sdk": "1.1.*" to install'); } if (!Arr::isSetAndNotEmptyString($config, 'token')) { throw new Exception('API access token is mandatory'); } if (!Arr::isSetAndNotEmptyString($config, 'path')) { throw new Exception('dropbox path is mandatory'); } $this->token = $config['token']; $this->path = String::withTrailingSlash(String::replaceDatePlaceholders($config['path'])); } /** * (non-PHPDoc) * * @see \phpbu\App\Backup\Sync::sync() * @param \phpbu\App\Backup\Target $target * @param \phpbu\App\Result $result * @throws \phpbu\App\Backup\Sync\Exception */ public function sync(Target $target, Result $result) { $sourcePath = $target->getPathname(); $dropboxPath = $this->path . $target->getFilename(); $client = new DropboxApi\Client($this->token, "phpbu/1.1.0"); $pathError = DropboxApi\Path::findErrorNonRoot($dropboxPath); if (substr(__FILE__, 0, 7) == 'phar://') { DropboxApi\RootCertificates::useExternalPaths(); } if ($pathError !== null) { throw new Exception(sprintf('Invalid \'dropbox-path\': %s', $pathError)); } $size = null; if (stream_is_local($sourcePath)) { $size = filesize($sourcePath); } try { $fp = fopen($sourcePath, 'rb'); $res = $client->uploadFile($dropboxPath, DropboxApi\WriteMode::add(), $fp, $size); fclose($fp); } catch (\Exception $e) { throw new Exception($e->getMessage(), null, $e); } $result->debug('upload: done (' . $res['size'] . ')'); } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Exception extends App\Exception { } config = $config; } public function sync(Target $target, Result $result) { throw new Exception('NotImplementedException'); } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.1.0 */ class Rsync extends Cli implements Sync { /** * Raw args * * @var string */ protected $args; /** * Remote username * * @var string */ protected $user; /** * Target host * * @var string */ protected $host; /** * Target path * * @var string */ protected $path; /** * Files to ignore, extracted from config string separated by ":" * * @var array */ protected $excludes; /** * Should only the created backup be synced or the complete directory * * @var boolean */ protected $isDirSync; /** * Remove deleted files remotely as well * * @var boolean */ protected $delete; /** * (non-PHPDoc) * * @see \phpbu\App\Backup\Sync::setup() * @param array $config * @throws \phpbu\App\Backup\Sync\Exception */ public function setup(array $config) { if (Arr::isSetAndNotEmptyString($config, 'args')) { $this->args = $config['args']; } else { if (!Arr::isSetAndNotEmptyString($config, 'path')) { throw new Exception('option \'path\' is missing'); } $this->path = String::replaceDatePlaceholders($config['path']); if (Arr::isSetAndNotEmptyString($config, 'user')) { $this->user = $config['user']; } if (Arr::isSetAndNotEmptyString($config, 'host')) { $this->host = $config['host']; } $this->excludes = array_map('trim', explode(':', Arr::getValue($config, 'exclude', ''))); $this->delete = String::toBoolean(Arr::getValue($config, 'delete', ''), false); $this->isDirSync = String::toBoolean(Arr::getValue($config, 'dirsync', ''), false); } } /** * (non-PHPDoc) * * @see \phpbu\App\Backup\Sync::sync() * @param \phpbu\App\Backup\Target $target * @param \phpbu\App\Result $result * @throws \phpbu\App\Backup\Sync\Exception */ public function sync(Target $target, Result $result) { $rsync = new Cmd(CliUtil::detectCmdLocation('rsync')); if ($this->args) { // pro mode define all arguments yourself // WARNING! no escaping is done by phpbu $result->debug('WARNING: phpbu uses your rsync args without escaping'); $rsync->addOption($this->replaceTargetPlaceholder($this->args, $target)); } else { // std err > dev null $rsync->silence(); $targetFile = $target->getPathname(); $targetDir = dirname($targetFile); // use archive mode, verbose and compress if not already done $options = '-av' . ($target->shouldBeCompressed() ? '' : 'z'); $rsync->addOption($options); if (count($this->excludes)) { foreach ($this->excludes as $ex) { $rsync->addOption('--exclude', $ex); } } // source handling if ($this->isDirSync) { // sync the whole folder // delete remote files as well? if ($this->delete) { $rsync->addOption('--delete'); } $rsync->addArgument($targetDir); } else { // sync just the created backup $rsync->addArgument($targetFile); } // target handling // get rsync host string $syncTarget = $this->getRsyncHostString(); // remote path $syncTarget .= $this->path; $rsync->addArgument($syncTarget); } // add some debug output $result->debug((string) $rsync); $this->execute($rsync); } /** * Return rsync host string. * * @return string */ public function getRsyncHostString() { $host = ''; // remote host if (null !== $this->host) { // remote user if (null !== $this->user) { $host .= $this->user . '@'; } $host .= $this->host . ':'; } return $host; } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Sftp implements Sync { /** * Host to connect to * * @var string */ protected $host; /** * User to connect with * * @var string */ protected $user; /** * Password to authenticate user * * @var string */ protected $password; /** * Remote path where to put the backup * * @var string */ protected $remotePath; /** * (non-PHPDoc) * * @see \phpbu\App\Backup\Sync::setup() * @param array $config * @throws \phpbu\App\Backup\Sync\Exception */ public function setup(array $config) { if (!class_exists('\\phpseclib\\Net\\SFTP')) { throw new Exception('phpseclib not installed - use composer to install "phpseclib/phpseclib" version 2.x'); } if (!Arr::isSetAndNotEmptyString($config, 'host')) { throw new Exception('option \'host\' is missing'); } if (!Arr::isSetAndNotEmptyString($config, 'user')) { throw new Exception('option \'user\' is missing'); } if (!Arr::isSetAndNotEmptyString($config, 'password')) { throw new Exception('option \'password\' is missing'); } $path = Arr::getValue($config, 'path', ''); if ('/' === substr($path, 0, 1)) { throw new Exception('absolute path is not allowed'); } $this->host = $config['host']; $this->user = $config['user']; $this->password = $config['password']; $this->remotePath = String::withoutTrailingSlash(String::replaceDatePlaceholders($path)); } /** * (non-PHPDoc) * * @see \phpbu\App\Backup\Sync::sync() * @param \phpbu\App\Backup\Target $target * @param \phpbu\App\Result $result * @throws \phpbu\App\Backup\Sync\Exception */ public function sync(Target $target, Result $result) { // silence phpseclib $old = error_reporting(0); $sftp = new phpseclib\Net\SFTP($this->host); if (!$sftp->login($this->user, $this->password)) { error_reporting($old); throw new Exception( sprintf( 'authentication failed for %s@%s%s', $this->user, $this->host, empty($this->password) ? '' : ' with password ****' ) ); } error_reporting($old); $remoteFilename = $target->getFilename(); $localFile = $target->getPathname(); if ('' !== $this->remotePath) { $remoteDirs = explode('/', $this->remotePath); foreach ($remoteDirs as $dir) { if (!$sftp->is_dir($dir)) { $result->debug(sprintf('creating remote dir \'%s\'', $dir)); $sftp->mkdir($dir); } $result->debug(sprintf('change to remote dir \'%s\'', $dir)); $sftp->chdir($dir); } } $result->debug(sprintf('store file \'%s\' as \'%s\'', $localFile, $remoteFilename)); $result->debug(sprintf('last error \'%s\'', $sftp->getLastSFTPError())); /** @noinspection PhpInternalEntityUsedInspection */ if (!$sftp->put($remoteFilename, $localFile, phpseclib\Net\SFTP::SOURCE_LOCAL_FILE)) { throw new Exception(sprintf('error uploading file: %s - %s', $localFile, $sftp->getLastSFTPError())); } } } * @author Sebastian Feldmann * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.1.6 */ class SoftLayer implements Sync { /** * SoftLayer user * * @var string */ protected $user; /** * SoftLayer secret * * @var string */ protected $secret; /** * SoftLayer container * * @var string */ protected $container; /** * SoftLayer host * * @var string */ protected $host; /** * SoftLayer remote path * * @var string */ protected $path; /** * (non-PHPDoc) * * @see \phpbu\App\Backup\Sync::setup() * @param array $config * @throws \phpbu\App\Backup\Sync\Exception */ public function setup(array $config) { if (!class_exists('\\ObjectStorage')) { throw new Exception('SoftLayer SDK not loaded: use composer "softlayer/objectstorage": "dev-master" to install'); } if (!Arr::isSetAndNotEmptyString($config, 'user')) { throw new Exception('SoftLayer user is mandatory'); } if (!Arr::isSetAndNotEmptyString($config, 'secret')) { throw new Exception('SoftLayer password is mandatory'); } if (!Arr::isSetAndNotEmptyString($config, 'container')) { throw new Exception('SoftLayer container name is mandatory'); } if (!Arr::isSetAndNotEmptyString($config, 'host')) { throw new Exception('SoftLayer host is mandatory'); } if (!Arr::isSetAndNotEmptyString($config, 'path')) { throw new Exception('SoftLayer path is mandatory'); } $this->user = $config['user']; $this->secret = $config['secret']; $this->container = $config['container']; $this->host = $config['host']; $this->path = String::withLeadingSlash( String::withTrailingSlash(String::replaceDatePlaceholders($config['path'])) ); } /** * (non-PHPDoc) * * @see \phpbu\App\Backup\Sync::sync() * @param \phpbu\App\backup\Target $target * @param \phpbu\App\Result $result * @throws \phpbu\App\Backup\Sync\Exception */ public function sync(Target $target, Result $result) { $sourcePath = $target->getPathname(); $targetPath = $this->path . $target->getFilename(); $options = array('adapter' => ObjectStorage_Http_Client::SOCKET, 'timeout' => 20); $objectStorage = new ObjectStorage($this->host, $this->user, $this->secret, $options); $result->debug('softlayer source: ' . $sourcePath); $result->debug('softlayer target: ' . $targetPath); try { /** @var \ObjectStorage_Container $object */ $container = $objectStorage->with($this->container . $targetPath) ->setLocalFile($sourcePath) ->setMeta('description', 'PHPBU Backup: ' . date('r', time())) ->setHeader('Content-Type', $target->getMimeType()); $container->create(); } catch (\Exception $e) { throw new Exception($e->getMessage(), null, $e); } $result->debug('upload: done'); } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ interface Sync { /** * Setup the Sync object with all xml options. * * @param array $options */ public function setup(array $options); /** * Execute the Sync * Copy your backup to another location * * @param \phpbu\App\Backup\Target $target * @param \phpbu\App\Result $result */ public function sync(Target $target, Result $result); } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Target { /** * Absolute path to the directory where to store the backup. * * @var string */ private $path; /** * Path to the backup with potential date placeholders like %d. * * @var string */ private $pathRaw; /** * Indicates if the path changes over time. * * @var boolean */ private $pathIsChanging = false; /** * Part of the path without placeholders * * @var string */ private $pathNotChanging; /** * List of directories containing date placeholders * * @var array */ private $pathElementsChanging = array(); /** * Backup filename. * * @var string */ private $filename; /** * Filename with potential date placeholders like %d. * * @var string */ private $filenameRaw; /** * Indicates if the filename changes over time. * * @var boolean */ private $filenameIsChanging = false; /** * Target MIME type * * @var string */ private $mimeType = 'text/plain'; /** * Size in bytes * * @var integer */ private $size; /** * Permissions for potential directory or file creation. * * @var integer (octal) */ private $permissions; /** * Should the file be compressed. * * @var boolean */ private $compress = false; /** * File compression. * * @var \phpbu\App\Backup\Compressor */ private $compressor; /** * Constructor * * @param string $path * @param string $filename * @param integer $time * @throws \phpbu\App\Exception */ public function __construct($path, $filename, $time = null) { $this->setPath($path, $time); $this->setFile($filename, $time); } /** * Directory setter. * * @param string $path * @param integer $time * @throws \phpbu\App\Exception */ public function setPath($path, $time = null) { $this->pathRaw = $path; if (false !== strpos($path, '%')) { $this->pathIsChanging = true; // path should be absolute so we remove the root slash $dirs = explode('/', substr($this->pathRaw, 1)); $this->pathNotChanging = ''; $foundChangingElement = false; foreach ($dirs as $d) { if ($foundChangingElement || false !== strpos($d, '%')) { $this->pathElementsChanging[] = $d; $foundChangingElement = true; } else { $this->pathNotChanging .= DIRECTORY_SEPARATOR . $d; } } // replace potential date placeholder $path = String::replaceDatePlaceholders($path, $time); } else { $this->pathNotChanging = $path; } $this->path = $path; } /** * Filename setter. * * @param string $file * @param integer $time */ public function setFile($file, $time = null) { $this->filenameRaw = $file; if (false !== strpos($file, '%')) { $this->filenameIsChanging = true; $file = String::replaceDatePlaceholders($file, $time); } $this->filename = $file; } /** * Checks if the backup target directory is writable. * Creates the Directory if it doesn't exist. * * @throws \phpbu\App\Exception */ public function setupPath() { // if directory doesn't exist, create it if (!is_dir($this->path)) { $reporting = error_reporting(); error_reporting(0); $created = mkdir($this->path, 0755, true); error_reporting($reporting); if (!$created) { throw new Exception(sprintf('cant\'t create directory: %s', $this->path)); } } if (!is_writable($this->path)) { throw new Exception(sprintf('no write permission for directory: %s', $this->path)); } } /** * Target file MIME type setter. * * @param string $mime */ public function setMimeType($mime) { $this->mimeType = $mime; } /** * Permission setter. * * @param string $permissions * @throws \phpbu\App\Exception */ public function setPermissions($permissions) { if (empty($permissions)) { $permissions = 0700; } else { $oct = intval($permissions, 8); $dec = octdec($oct); if ($dec < 1 || $dec > octdec(0777)) { throw new Exception(sprintf('invalid permissions: %s', $permissions)); } $permissions = $oct; } $this->permissions = $permissions; } /** * Permission getter. * * @return integer */ public function getPermissions() { return $this->permissions; } /** * Return the path to the backup file. * * @return string */ public function getPath() { return $this->path; } /** * Return the path to the backup file. * * @return string */ public function getPathRaw() { return $this->pathRaw; } /** * Return the name to the backup file. * * @param boolean $plain * @return string */ public function getFilename($plain = false) { return $this->filename . ( !$plain && $this->shouldBeCompressed() ? '.' . $this->compressor->getSuffix() : '' ); } /** * Return the name of the backup file without compressor or encryption suffix. * * @return string */ public function getFilenamePlain() { return $this->getFilename(true); } /** * Return the raw name of the backup file incl. date placeholder. * * @return string */ public function getFilenameRaw() { return $this->filenameRaw; } /** * Return file MIME type. * * @return string */ public function getMimeType() { $mimeType = $this->mimeType; if ($this->shouldBeCompressed()) { $mimeType = $this->compressor->getMimeType(); } return $mimeType; } /** * Return the actual filesize in bytes. * * @throws Exception * @return integer */ public function getSize() { if (null === $this->size) { if (!file_exists($this)) { throw new Exception(sprintf('target file \'%s\' doesn\'t exist', $this->getFilename())); } $this->size = filesize($this); } return $this->size; } /** * Target file exists already. * * @param boolean $plain * @return boolean */ public function fileExists($plain = false) { return file_exists($this->getPathname($plain)); } /** * Deletes the target file. * * @param boolean $plain * @throws \phpbu\App\Exception */ public function unlink($plain = false) { if (!$this->fileExists($plain)) { throw new Exception(sprintf('target file \'%s\' doesn\'t exist', $this->getFilename($plain))); } if (!is_writable($this->getPathname($plain))) { throw new Exception(sprintf('can\t delete file \'%s\'', $this->getFilename($plain))); } $this->size = filesize($this->getPathname($plain)); } /** * Return path and filename of the backup file. * * @param boolean $plain * @return string */ public function getPathname($plain = false) { return $this->path . DIRECTORY_SEPARATOR . $this->getFilename($plain); } /** * Return path and plain filename of the backup file. * * @return string */ public function getPathnamePlain() { return $this->getPathname(true); } /** * Is dirname configured with any date placeholders. * * @return boolean */ public function hasChangingPath() { return $this->pathIsChanging; } /** * Return the part of the path that is not changing. * * @return string */ public function getPathThatIsNotChanging() { return $this->pathNotChanging; } /** * Changing path elements getter. * * @return array */ public function getChangingPathElements() { return $this->pathElementsChanging; } /** * Return amount of changing path elements. * * @return integer */ public function countChangingPathElements() { return count($this->pathElementsChanging); } /** * Filename configured with any date placeholders. * * @return boolean */ public function hasChangingFilename() { return $this->filenameIsChanging; } /** * Disable file compression. */ public function disableCompression() { $this->compress = false; } /** * Enable file compression. * * @throws \phpbu\App\Exception */ public function enableCompression() { if (null == $this->compressor) { throw new Exception('can\'t enable compression without a compressor'); } $this->compress = true; } /** * Compressor setter. * * @param \phpbu\App\Backup\Compressor $compressor */ public function setCompressor(Compressor $compressor) { $this->compressor = $compressor; $this->compress = true; } /** * Compressor getter. * * @return \phpbu\App\Backup\Compressor */ public function getCompressor() { return $this->compressor; } /** * Is a compressor set? * * @return boolean */ public function shouldBeCompressed() { return $this->compress !== false; } /** * Magic to string method. * * @return string */ public function __toString() { return $this->getPathname(); } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Args { /** * List of available - options. * * @var array */ private $shortOptions = array( 'h' => true, 'v' => true, 'V' => true, ); /** * List of available -- options. * * @var array */ private $longOptions = array( 'bootstrap=' => true, 'colors' => true, 'configuration=' => true, 'debug' => true, 'help' => true, 'include-path=' => true, 'verbose' => true, 'version' => true ); /** * Constructor. */ public function __construct() { if (defined('__PHPBU_PHAR__')) { $this->longOptions['selfupdate'] = true; $this->longOptions['self-update'] = true; } } /** * Get all cli options. * * @param array $args * @return array */ public function getOptions(array $args) { // remove script name from args if (isset($args[0][0]) && $args[0][0] != '-') { array_shift($args); } $options = array(); reset($args); array_map('trim', $args); foreach ($args as $i => $arg) { $argLength = strlen($arg); // if empty arg or arg doesn't start with "-" skip it if (empty($arg) || $arg == '--' || $arg[0] != '-') { continue; } if ($argLength > 1 && $arg[1] == '-') { $this->parseLongOption(substr($arg, 2), $options); } else { $this->parseShortOption(substr($arg, 1), $options); } } return $options; } /** * Check short option and put into option list. * * @param string $arg * @param array $options * @throws \phpbu\App\Exception */ public function parseShortOption($arg, array &$options) { if (!isset($this->shortOptions[$arg])) { throw new Exception('unknown option: -' . $arg); } $options['-' . $arg] = true; } /** * Check long option and put into option list. * * @param string $arg * @param array $options * @throws \phpbu\App\Exception */ public function parseLongOption($arg, array &$options) { $list = explode('=', $arg); $option = $list[0]; $argument = true; if (count($list) > 1) { $argument = $list[1]; } if (count($list) > 2) { throw new Exception('invalid value for option: --' . $arg); } if (!isset($this->longOptions[$option]) && !isset($this->longOptions[$option . '='])) { throw new Exception('unknown option: --' . $option); } if ($argument === true && isset($this->longOptions[$option . '='])) { throw new Exception('argument required for option: --' . $option); } if ($argument !== true && isset($this->longOptions[$option])) { throw new Exception('needless argument for option: --' . $option); } $options['--' . $option] = $argument; } } * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package phpbu * @author Sebastian Feldmann * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ namespace phpbu\App; use Phar; use phpbu\App\Cmd\Args; use phpbu\App\Util\Arr; /** * Main application class. * * @package phpbu * @author Sebastian Feldmann * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Cmd { const EXIT_SUCCESS = 0; const EXIT_FAILURE = 1; const EXIT_EXCEPTION = 2; /** * Ascii-Art app logo * * @var string */ private static $logo = ' __ __ ____ / /_ ____ / /_ __ __ / __ \/ __ \/ __ \/ __ \/ / / / / /_/ / / / / /_/ / /_/ / /_/ / / .___/_/ /_/ .___/_.___/\__,_/ /_/ /_/ '; /** * Is version string printed already. * * @var boolean */ private $isVersionStringPrinted = false; /** * List of given arguments * * @var array */ private $arguments; /** * Runs the application. * * @param array $args */ public function run(array $args) { $this->handleOpt($args); $ret = self::EXIT_FAILURE; $runner = new Runner(); try { $result = $runner->run($this->arguments); if ($result->wasSuccessful()) { $ret = self::EXIT_SUCCESS; } elseif ($result->errorCount() > 0) { $ret = self::EXIT_EXCEPTION; } } catch (\Exception $e) { echo $e->getMessage() . PHP_EOL; $ret = self::EXIT_EXCEPTION; } exit($ret); } /** * Check arguments and load configuration file. * * @param array $args */ protected function handleOpt(array $args) { try { $parser = new Args(); $options = $parser->getOptions($args); $this->handleArgs($options); } catch (Exception $e) { $this->printError($e->getMessage(), true); } if (isset($this->arguments['include-path'])) { $this->handleIncludePath($this->arguments['include-path']); } try { $this->handleConfiguration(); } catch (Exception $e) { $this->printError($e->getMessage()); } // no backups to handle if (!isset($this->arguments['backups'])) { $this->printLogo(); $this->printHelp(); exit(self::EXIT_EXCEPTION); } } /** * Handle the parsed command line options * * @param array $options * @return void */ protected function handleArgs(array $options) { foreach ($options as $option => $argument) { switch ($option) { case '--bootstrap': $this->arguments['bootstrap'] = $argument; break; case '--colors': $this->arguments['colors'] = $argument; break; case '--configuration': $this->arguments['configuration'] = $argument; break; case '--debug': $this->arguments['debug'] = $argument; break; case '-h': case '--help': $this->printHelp(); exit(self::EXIT_SUCCESS); case 'include-path': $this->arguments['include-path'] = $argument; break; case '--selfupdate': case '--self-update': $this->handleSelfUpdate(); break; case '-v': case '--verbose': $this->arguments['verbose'] = true; break; case '-V': case '--version': $this->printVersionString(); exit(self::EXIT_SUCCESS); } } } /** * Check all configuration possibilities. * * @return void */ protected function handleConfiguration() { // check configuration argument // if configuration argument is a directory // check for default configuration files 'phpbu.xml' and 'phpbu.xml.dist' if (isset($this->arguments['configuration']) && is_dir($this->arguments['configuration'])) { $this->handleConfigurationDir(); } elseif (!isset($this->arguments['configuration'])) { // no configuration argument search for default configuration files // 'phpbu.xml' and 'phpbu.xml.dist' in current working directory $this->handleConfigurationDefault(); } if (isset($this->arguments['configuration'])) { $configuration = new Configuration($this->arguments['configuration']); $phpbu = $configuration->getAppSettings(); $phpSettings = $configuration->getPhpSettings(); $this->arguments['logging'] = $configuration->getLoggingSettings(); $this->arguments['backups'] = $configuration->getBackupSettings(); // argument bootstrap overrules config bootstrap if (isset($this->arguments['bootstrap'])) { $this->handleBootstrap($this->arguments['bootstrap']); } elseif (isset($phpbu['bootstrap'])) { $this->handleBootstrap($phpbu['bootstrap']); } if (Arr::getValue($phpbu, 'verbose') === true) { $this->arguments['verbose'] = true; } if (Arr::getValue($phpbu, 'colors') === true) { $this->arguments['colors'] = true; } if (Arr::getValue($phpbu, 'debug') === true) { $this->arguments['debug'] = true; } if (!empty($phpSettings['include_path'])) { $this->handleIncludePath($phpSettings['include_path']); } // handle php.ini settings foreach ($phpSettings['ini'] as $name => $value) { if (defined($value)) { $value = constant($value); } ini_set($name, $value); } } } /** * Check directory for default configuration files phpbu.xml, phpbu.xml.dist. * * @return void */ protected function handleConfigurationDir() { $configurationFile = $this->arguments['configuration'] . '/phpbu.xml'; if (file_exists($configurationFile)) { $this->arguments['configuration'] = realpath($configurationFile); } elseif (file_exists($configurationFile . '.dist')) { $this->arguments['configuration'] = realpath($configurationFile . '.dist'); } } /** * Check default configuration files phpbu.xml, phpbu.xml.dist in current working directory. * * @return void */ protected function handleConfigurationDefault() { if (file_exists('phpbu.xml')) { $this->arguments['configuration'] = realpath('phpbu.xml'); } elseif (file_exists('phpbu.xml.dist')) { $this->arguments['configuration'] = realpath('phpbu.xml.dist'); } } /** * Handles the php include_path settings. * * @param mixed $path * @return void */ protected function handleIncludePath($path) { if (is_array($path)) { $path = implode(PATH_SEPARATOR, $path); } ini_set('include_path', $path . PATH_SEPARATOR . ini_get('include_path')); } /** * Handles the bootstrap file inclusion. * * @param string $filename * @throws \phpbu\App\Exception */ protected function handleBootstrap($filename) { $pathToFile = stream_resolve_include_path($filename); if (!$pathToFile || !is_readable($pathToFile)) { throw new Exception(sprintf('Cannot open bootstrap file "%s".' . PHP_EOL, $filename)); } require $pathToFile; } /** * Handle the phar self-update. */ protected function handleSelfUpdate() { $this->printVersionString(); $remoteFilename = sprintf('http://phar.phpbu.de/phpbu%s.phar', Version::getReleaseChannel()); $localFilename = realpath($_SERVER['argv'][0]); $tempFilename = basename($localFilename, '.phar') . '-temp.phar'; echo 'Updating the phpbu PHAR ... '; $old = error_reporting(0); $phar = file_get_contents($remoteFilename); error_reporting($old); if (!$phar) { echo ' failed' . PHP_EOL . 'Could not reach phpbu update site' . PHP_EOL; exit(self::EXIT_EXCEPTION); } file_put_contents($tempFilename, $phar); chmod($tempFilename, 0777 & ~umask()); // check downloaded phar try { $phar = new Phar($tempFilename); unset($phar); // replace current phar with the new one rename($tempFilename, $localFilename); } catch (Exception $e) { // cleanup crappy phar unlink($tempFilename); echo 'failed' . PHP_EOL . $e->getMessage() . PHP_EOL; exit(self::EXIT_EXCEPTION); } echo 'done' . PHP_EOL; exit(self::EXIT_SUCCESS); } /** * Shows the current application version. */ private function printVersionString() { if ($this->isVersionStringPrinted) { return; } echo Version::getVersionString() . PHP_EOL; $this->isVersionStringPrinted = true; } /** * Show the phpbu logo */ protected function printLogo() { echo self::$logo . PHP_EOL; } /** * Show the help message. */ protected function printHelp() { $this->printVersionString(); echo << A "bootstrap" PHP file that is included before the backup. --configuration= A phpbu xml config file. --colors Use colors in output. --debug Display debugging information during backup generation. -h, --help Prints this usage information. -v, --verbose Output more verbose information. -V, --version Output version information and exit. EOT; if (defined('__PHPBU_PHAR__')) { echo ' --self-update Update phpbu to the latest version.' . PHP_EOL; } } /** * Shows some given error message. * * @param string $message * @param bool $hint */ private function printError($message, $hint = false) { $help = $hint ? ', use "phpbu -h" for help' : ''; $this->printVersionString(); echo $message . $help . PHP_EOL; exit(self::EXIT_EXCEPTION); } /** * Main method, is called by phpbu command and the phar file. */ public static function main() { $app = new static(); $app->run($_SERVER['argv']); } } * * * * * . * * * * * * * * * * * * * * * * @package phpbu * @subpackage App * @author Sebastian Feldmann * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Configuration { /** * Path to config file. * * @var string */ private $filename; /** * Config file DOMDocument * * @var \DOMDocument */ private $document; /** * Xpath to navigate the config DOM. * * @var \DOMXPath */ private $xpath; /** * Constructor * * @param string $filename */ public function __construct($filename) { $this->filename = $filename; $this->document = $this->loadXmlFile($filename); $this->xpath = new DOMXPath($this->document); } /** * Get the phpbu application settings. * * @return array */ public function getAppSettings() { $settings = array(); $root = $this->document->documentElement; if ($root->hasAttribute('bootstrap')) { $settings['bootstrap'] = $this->toAbsolutePath((string) $root->getAttribute('bootstrap')); } if ($root->hasAttribute('verbose')) { $settings['verbose'] = String::toBoolean((string) $root->getAttribute('verbose'), false); } if ($root->hasAttribute('colors')) { $settings['colors'] = String::toBoolean((string) $root->getAttribute('colors'), false); } return $settings; } /** * Get the php settings. * Checking for include_path and ini settings. * * @return array */ public function getPhpSettings() { $settings = array( 'include_path' => array(), 'ini' => array(), ); foreach ($this->xpath->query('php/includePath') as $includePath) { $path = (string) $includePath->nodeValue; if ($path) { $settings['include_path'][] = $this->toAbsolutePath($path); } } foreach ($this->xpath->query('php/ini') as $ini) { /** @var DOMElement $ini */ $name = (string) $ini->getAttribute('name'); $value = (string) $ini->getAttribute('value'); $settings['ini'][$name] = $value; } return $settings; } /** * Get the backup configurations. * * @return array */ public function getBackupSettings() { $settings = array(); foreach ($this->xpath->query('backups/backup') as $backupNode) { $settings[] = $this->getBackupConfig($backupNode); } return $settings; } /** * Get the config for a single backup node. * * @param \DOMElement $backupNode * @throws \phpbu\App\Exception * @return array */ private function getBackupConfig(DOMElement $backupNode) { $stopOnError = String::toBoolean((string) $backupNode->getAttribute('stopOnError'), false); $backupName = $backupNode->getAttribute('name'); $source = $this->getSource($backupNode); $target = $this->getTarget($backupNode); $checks = $this->getChecks($backupNode); $syncs = $this->getSyncs($backupNode); $cleanup = $this->getCleanup($backupNode); return array( 'name' => $backupName, 'stopOnError' => $stopOnError, 'source' => $source, 'target' => $target, 'checks' => $checks, 'syncs' => $syncs, 'cleanup' => $cleanup, ); } /** * Get source configuration. * * @param \DOMElement $node * @return array * @throws \phpbu\App\Exception */ protected function getSource(DOMElement $node) { $source = array(); $sources = $node->getElementsByTagName('source'); if ($sources->length !== 1) { throw new Exception('backup requires exactly one source config'); } /** @var DOMElement $sourceNode */ $sourceNode = $sources->item(0); $type = (string) $sourceNode->getAttribute('type'); if (!$type) { throw new Exception('source requires type attribute'); } $source['type'] = $type; $source['options'] = $this->getOptions($sourceNode); return $source; } /** * Get Target configuration. * * @param \DOMElement $node * @return array * @throws \phpbu\App\Exception */ protected function getTarget(DOMElement $node) { $targets = $node->getElementsByTagName('target'); if ($targets->length !== 1) { throw new Exception('backup requires exactly one target config'); } /** @var DOMElement $targetNode */ $targetNode = $targets->item(0); $compress = (string) $targetNode->getAttribute('compress'); $filename = (string) $targetNode->getAttribute('filename'); $dirname = (string) $targetNode->getAttribute('dirname'); if ($dirname) { $dirname = $this->toAbsolutePath($dirname); } return array( 'dirname' => $dirname, 'filename' => $filename, 'compress' => $compress, ); } /** * Get backup checks. * * @param \DOMElement $node * @return array */ protected function getChecks(DOMElement $node) { $checks = array(); /** @var DOMElement $checkNode */ foreach ($node->getElementsByTagName('check') as $checkNode) { $type = (string) $checkNode->getAttribute('type'); $value = (string) $checkNode->getAttribute('value'); // skip invalid sanity checks if (!$type || !$value) { continue; } $checks[] = array('type' => $type, 'value' => $value); } return $checks; } /** * Get backup sync configurations. * * @param \DOMElement $node * @return array */ protected function getSyncs(DOMElement $node) { $syncs = array(); /** @var DOMElement $syncNode */ foreach ($node->getElementsByTagName('sync') as $syncNode) { $sync = array( 'type' => (string) $syncNode->getAttribute('type'), 'skipOnCheckFail' => String::toBoolean((string) $syncNode->getAttribute('skipOnCheckFail'), true), 'options' => array() ); $sync['options'] = $this->getOptions($syncNode); $syncs[] = $sync; } return $syncs; } /** * Get the cleanup configuration. * * @param \DOMElement $node * @return array */ protected function getCleanup(DOMElement $node) { $cleanup = array(); /** @var DOMElement $cleanupNode */ foreach ($node->getElementsByTagName('cleanup') as $cleanupNode) { $cleanup = array( 'type' => (string) $cleanupNode->getAttribute('type'), 'skipOnCheckFail' => String::toBoolean((string) $cleanupNode->getAttribute('skipOnCheckFail'), true), 'skipOnSyncFail' => String::toBoolean((string) $cleanupNode->getAttribute('skipOnSyncFail'), true), 'options' => array() ); $cleanup['options'] = $this->getOptions($cleanupNode); } return $cleanup; } /** * Extracts all option tags. * * @param DOMElement $node * @return array */ protected function getOptions(DOMElement $node) { $options = array(); /** @var DOMElement $optionNode */ foreach ($node->getElementsByTagName('option') as $optionNode) { $name = (string) $optionNode->getAttribute('name'); $value = (string) $optionNode->getAttribute('value'); $options[$name] = $value; } return $options; } /** * Get the log configuration. * * @return array */ public function getLoggingSettings() { $loggers = array(); /** @var DOMElement $logNode */ foreach ($this->xpath->query('logging/log') as $logNode) { $log = array( 'type' => (string) $logNode->getAttribute('type'), 'options' => array(), ); $tarAtr = (string) $logNode->getAttribute('target'); if (!empty($tarAtr)) { $log['options']['target'] = $this->toAbsolutePath($tarAtr); } /** @var DOMElement $optionNode */ foreach ($logNode->getElementsByTagName('option') as $optionNode) { $name = (string) $optionNode->getAttribute('name'); $value = (string) $optionNode->getAttribute('value'); // check for path option if ('target' == $name) { $value = $this->toAbsolutePath($value); } $log['options'][$name] = $value; } $loggers[] = $log; } return $loggers; } /** * Converts a path to an absolute one if necessary. * * @param string $path * @param boolean $useIncludePath * @return string */ protected function toAbsolutePath($path, $useIncludePath = false) { return Cli::toAbsolutePath($path, dirname($this->filename), $useIncludePath); } /** * Load the XML-File. * * @param string $filename * @throws \phpbu\App\Exception * @return \DOMDocument */ private function loadXmlFile($filename) { $reporting = error_reporting(0); $contents = file_get_contents($filename); error_reporting($reporting); if ($contents === false) { throw new Exception(sprintf('Could not read "%s".', $filename)); } $document = new \DOMDocument; $message = ''; $internal = libxml_use_internal_errors(true); $reporting = error_reporting(0); $document->documentURI = $filename; $loaded = $document->loadXML($contents); foreach (libxml_get_errors() as $error) { $message .= "\n" . $error->message; } libxml_use_internal_errors($internal); error_reporting($reporting); if ($loaded === false || $message !== '') { throw new Exception( sprintf( 'Error loading file "%s".%s', $filename, $message != '' ? "\n" . $message : '' ) ); } return $document; } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Exception extends \Exception { } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ abstract class Factory { /** * Map of available sources, checks, syncs and cleanups. * * @var array */ private static $classMap = array( // type => fqcn 'logger' => array( 'json' => '\\phpbu\\App\\Log\\Json', 'mail' => '\\phpbu\\App\\Log\\Mail', ), 'source' => array( 'mongodump' => '\\phpbu\\App\\Backup\\Source\\Mongodump', 'mysqldump' => '\\phpbu\\App\\Backup\\Source\\Mysqldump', 'tar' => '\\phpbu\\App\\Backup\\Source\\Tar', ), 'check' => array( 'sizemin' => '\\phpbu\\App\\Backup\\Check\\SizeMin', 'sizediffpreviouspercent' => '\\phpbu\\App\\Backup\\Check\\SizeDiffPreviousPercent', 'sizediffavgpercent' => '\\phpbu\\App\\Backup\\Check\\SizeDiffAvgPercent', ), 'sync' => array( 'amazons3' => '\\phpbu\\App\\Backup\\Sync\\AmazonS3', 'copycom' => '\\phpbu\\App\\Backup\\Sync\\Copycom', 'dropbox' => '\\phpbu\\App\\Backup\\Sync\\Dropbox', 'ftp' => '\\phpbu\\App\\Backup\\Sync\\Ftp', 'rsync' => '\\phpbu\\App\\Backup\\Sync\\Rsync', 'sftp' => '\\phpbu\\App\\Backup\\Sync\\Sftp', 'softlayer' => '\\phpbu\\App\\Backup\\Sync\\SoftLayer', ), 'cleaner' => array( 'capacity' => '\\phpbu\\App\\Backup\\Cleaner\\Capacity', 'outdated' => '\\phpbu\\App\\Backup\\Cleaner\\Outdated', 'quantity' => '\\phpbu\\App\\Backup\\Cleaner\\Quantity', ), ); /** * Backup Factory. * Creates 'Source', 'Check', 'Sync' and 'Cleaner' Objects. * * @param string $type * @param string $alias * @throws \phpbu\App\Exception * @return mixed */ public static function create($type, $alias) { $type = strtolower($type); $alias = strtolower($alias); self::checkType($type); if (!isset(self::$classMap[$type][$alias])) { throw new Exception(sprintf('unknown %s: %s', $type, $alias)); } $class = self::$classMap[$type][$alias]; return new $class(); } /** * Logger Factory. * * @param string $alias * @param array $conf * @throws \phpbu\App\Exception * @return \phpbu\App\Backup\Source */ public static function createLogger($alias, $conf = array()) { /** @var \phpbu\App\Log\Logger $logger */ $logger = self::create('logger', $alias); if (!($logger instanceof Logger)) { throw new Exception(sprintf('logger \'%s\' has to implement the \'Logger\' interfaces', $alias)); } if (!($logger instanceof Listener)) { throw new Exception(sprintf('logger \'%s\' has to implement the \'Listener\' interface', $alias)); } $logger->setup($conf); return $logger; } /** * Source Factory. * * @param string $alias * @param array $conf * @throws \phpbu\App\Exception * @return \phpbu\App\Backup\Source */ public static function createSource($alias, $conf = array()) { /** @var \phpbu\App\Backup\Source $source */ $source = self::create('source', $alias); if (!($source instanceof Source)) { throw new Exception(sprintf('source \'%s\' has to implement the \'Source\' interface', $alias)); } $source->setup($conf); return $source; } /** * Check Factory. * * @param string $alias * @throws \phpbu\App\Exception * @return \phpbu\App\Backup\Check */ public static function createCheck($alias) { /** @var \phpbu\App\Backup\Check $check */ $check = self::create('check', $alias); if (!($check instanceof Check)) { throw new Exception(sprintf('Check \'%s\' has to implement the \'Check\' interface', $alias)); } return $check; } /** * Sync Factory. * * @param string $alias * @param array $conf * @throws \phpbu\App\Exception * @return \phpbu\App\Backup\Sync */ public static function createSync($alias, $conf = array()) { /** @var \phpbu\App\Backup\Sync $sync */ $sync = self::create('sync', $alias); if (!($sync instanceof Sync)) { throw new Exception(sprintf('sync \'%s\' has to implement the \'Sync\' interface', $alias)); } $sync->setup($conf); return $sync; } /** * Cleaner Factory. * * @param string $alias * @param array $conf * @throws \phpbu\App\Exception * @return \phpbu\App\Backup\Cleaner */ public static function createCleaner($alias, $conf = array()) { /** @var \phpbu\App\Backup\Cleaner $cleaner */ $cleaner = self::create('cleaner', $alias); if (!($cleaner instanceof Cleaner)) { throw new Exception(sprintf('cleaner \'%s\' has to implement the \'Cleaner\' interface', $alias)); } $cleaner->setup($conf); return $cleaner; } /** * Extend the backup factory. * * @param string $type Type to create 'source', 'check', 'sync' or 'cleaner' * @param string $alias Name the class is registered at * @param string $fqcn Full Qualified Class Name * @param boolean $force Overwrite already registered class * @throws \phpbu\App\Exception */ public static function register($type, $alias, $fqcn, $force = false) { $type = strtolower($type); $alias = strtolower($alias); self::checkType($type); if (!$force && isset(self::$classMap[$type][$alias])) { throw new Exception(sprintf('%s is already registered use force parameter to overwrite', $type)); } self::$classMap[$type][$alias] = $fqcn; } /** * Throws an exception if type is invalid. * * @param string $type * @throws \phpbu\App\Exception */ private static function checkType($type) { if (!isset(self::$classMap[$type])) { throw new Exception('invalid type, use \'source\', \'check\', \'sync\', \'cleaner\' or \'logger\''); } } } addAlias('_aws', self::getDefaultServiceDefinition()) ->addAlias('_sdk1', __DIR__ . '/Resources/sdk1-config.php'); return $loader->load($config, $globalParameters); } /** * Get the full path to the default service builder definition file * * @return string */ public static function getDefaultServiceDefinition() { return __DIR__ . '/Resources/aws-config.php'; } /** * Returns the configuration for the service builder * * @return array */ public function getConfig() { return $this->builderConfig; } /** * Enables the facades for the clients defined in the service builder * * @param string|null $namespace The namespace that the facades should be mounted to. Defaults to global namespace * * @return Aws */ public function enableFacades($namespace = null) { Facade::mountFacades($this, $namespace); return $this; } } get(Options::BASE_URL), $config); $this->credentials = $credentials; $this->signature = $signature; $this->aggregator = new DuplicateAggregator(); // Make sure the user agent is prefixed by the SDK version $this->setUserAgent('aws-sdk-php2/' . Aws::VERSION, true); // Add the event listener so that requests are signed before they are sent $dispatcher = $this->getEventDispatcher(); $dispatcher->addSubscriber(new SignatureListener($credentials, $signature)); if ($backoff = $config->get(Options::BACKOFF)) { $dispatcher->addSubscriber($backoff, -255); } } public function __call($method, $args) { if (substr($method, 0, 3) === 'get' && substr($method, -8) === 'Iterator') { // Allow magic method calls for iterators (e.g. $client->getIterator($params)) $commandOptions = isset($args[0]) ? $args[0] : null; $iteratorOptions = isset($args[1]) ? $args[1] : array(); return $this->getIterator(substr($method, 3, -8), $commandOptions, $iteratorOptions); } elseif (substr($method, 0, 9) == 'waitUntil') { // Allow magic method calls for waiters (e.g. $client->waitUntil($params)) return $this->waitUntil(substr($method, 9), isset($args[0]) ? $args[0]: array()); } else { return parent::__call(ucfirst($method), $args); } } /** * Get an endpoint for a specific region from a service description * @deprecated This function will no longer be updated to work with new regions. */ public static function getEndpoint(ServiceDescriptionInterface $description, $region, $scheme) { try { $service = $description->getData('endpointPrefix'); $provider = RulesEndpointProvider::fromDefaults(); $result = $provider(array( 'service' => $service, 'region' => $region, 'scheme' => $scheme )); return $result['endpoint']; } catch (\InvalidArgumentException $e) { throw new InvalidArgumentException($e->getMessage(), 0, $e); } } public function getCredentials() { return $this->credentials; } public function setCredentials(CredentialsInterface $credentials) { $formerCredentials = $this->credentials; $this->credentials = $credentials; // Dispatch an event that the credentials have been changed $this->dispatch('client.credentials_changed', array( 'credentials' => $credentials, 'former_credentials' => $formerCredentials, )); return $this; } public function getSignature() { return $this->signature; } public function getRegions() { return $this->serviceDescription->getData('regions'); } public function getRegion() { return $this->getConfig(Options::REGION); } public function setRegion($region) { $config = $this->getConfig(); $formerRegion = $config->get(Options::REGION); $global = $this->serviceDescription->getData('globalEndpoint'); $provider = $config->get('endpoint_provider'); if (!$provider) { throw new \RuntimeException('No endpoint provider configured'); } // Only change the region if the service does not have a global endpoint if (!$global || $this->serviceDescription->getData('namespace') === 'S3') { $endpoint = call_user_func( $provider, array( 'scheme' => $config->get(Options::SCHEME), 'region' => $region, 'service' => $config->get(Options::SERVICE) ) ); $this->setBaseUrl($endpoint['endpoint']); $config->set(Options::BASE_URL, $endpoint['endpoint']); $config->set(Options::REGION, $region); // Update the signature if necessary $signature = $this->getSignature(); if ($signature instanceof EndpointSignatureInterface) { /** @var $signature EndpointSignatureInterface */ $signature->setRegionName($region); } // Dispatch an event that the region has been changed $this->dispatch('client.region_changed', array( 'region' => $region, 'former_region' => $formerRegion, )); } return $this; } public function waitUntil($waiter, array $input = array()) { $this->getWaiter($waiter, $input)->wait(); return $this; } public function getWaiter($waiter, array $input = array()) { return $this->getWaiterFactory()->build($waiter) ->setClient($this) ->setConfig($input); } public function setWaiterFactory(WaiterFactoryInterface $waiterFactory) { $this->waiterFactory = $waiterFactory; return $this; } public function getWaiterFactory() { if (!$this->waiterFactory) { $clientClass = get_class($this); // Use a composite factory that checks for classes first, then config waiters $this->waiterFactory = new CompositeWaiterFactory(array( new WaiterClassFactory(substr($clientClass, 0, strrpos($clientClass, '\\')) . '\\Waiter') )); if ($this->getDescription()) { $waiterConfig = $this->getDescription()->getData('waiters') ?: array(); $this->waiterFactory->addFactory(new WaiterConfigFactory($waiterConfig)); } } return $this->waiterFactory; } public function getApiVersion() { return $this->serviceDescription->getApiVersion(); } /** * {@inheritdoc} * @throws \Aws\Common\Exception\TransferException */ public function send($requests) { try { return parent::send($requests); } catch (CurlException $e) { $wrapped = new TransferException($e->getMessage(), null, $e); $wrapped->setCurlHandle($e->getCurlHandle()) ->setCurlInfo($e->getCurlInfo()) ->setError($e->getError(), $e->getErrorNo()) ->setRequest($e->getRequest()); throw $wrapped; } } /** * Ensures that the duplicate query string aggregator is used so that * query string values are sent over the wire as foo=bar&foo=baz. * {@inheritdoc} */ public function createRequest( $method = 'GET', $uri = null, $headers = null, $body = null, array $options = array() ) { $request = parent::createRequest($method, $uri, $headers, $body, $options); $request->getQuery()->setAggregator($this->aggregator); return $request; } } 'https'); /** * @var array Default client requirements */ protected static $commonConfigRequirements = array(Options::SERVICE_DESCRIPTION); /** * @var string The namespace of the client */ protected $clientNamespace; /** * @var array The config options */ protected $config = array(); /** * @var array The config defaults */ protected $configDefaults = array(); /** * @var array The config requirements */ protected $configRequirements = array(); /** * @var ExceptionParserInterface The Parser interface for the client */ protected $exceptionParser; /** * @var array Array of configuration data for iterators available for the client */ protected $iteratorsConfig = array(); /** @var string */ private $clientClass; /** @var string */ private $serviceName; /** * Factory method for creating the client builder * * @param string $namespace The namespace of the client * * @return ClientBuilder */ public static function factory($namespace = null) { return new static($namespace); } /** * Constructs a client builder * * @param string $namespace The namespace of the client */ public function __construct($namespace = null) { $this->clientNamespace = $namespace; // Determine service and class name $this->clientClass = 'Aws\Common\Client\DefaultClient'; if ($this->clientNamespace) { $this->serviceName = substr($this->clientNamespace, strrpos($this->clientNamespace, '\\') + 1); $this->clientClass = $this->clientNamespace . '\\' . $this->serviceName . 'Client'; } } /** * Sets the config options * * @param array|Collection $config The config options * * @return ClientBuilder */ public function setConfig($config) { $this->config = $this->processArray($config); return $this; } /** * Sets the config options' defaults * * @param array|Collection $defaults The default values * * @return ClientBuilder */ public function setConfigDefaults($defaults) { $this->configDefaults = $this->processArray($defaults); return $this; } /** * Sets the required config options * * @param array|Collection $required The required config options * * @return ClientBuilder */ public function setConfigRequirements($required) { $this->configRequirements = $this->processArray($required); return $this; } /** * Sets the exception parser. If one is not provided the builder will use * the default XML exception parser. * * @param ExceptionParserInterface $parser The exception parser * * @return ClientBuilder */ public function setExceptionParser(ExceptionParserInterface $parser) { $this->exceptionParser = $parser; return $this; } /** * Set the configuration for the client's iterators * * @param array $config Configuration data for client's iterators * * @return ClientBuilder */ public function setIteratorsConfig(array $config) { $this->iteratorsConfig = $config; return $this; } /** * Performs the building logic using all of the parameters that have been * set and falling back to default values. Returns an instantiate service * client with credentials prepared and plugins attached. * * @return AwsClientInterface * @throws InvalidArgumentException */ public function build() { // Resolve configuration $config = Collection::fromConfig( $this->config, array_merge(self::$commonConfigDefaults, $this->configDefaults), (self::$commonConfigRequirements + $this->configRequirements) ); if ($config[Options::VERSION] === 'latest') { $config[Options::VERSION] = constant("{$this->clientClass}::LATEST_API_VERSION"); } if (!isset($config['endpoint_provider'])) { $config['endpoint_provider'] = RulesEndpointProvider::fromDefaults(); } // Resolve the endpoint, signature, and credentials $description = $this->updateConfigFromDescription($config); $signature = $this->getSignature($description, $config); $credentials = $this->getCredentials($config); $this->extractHttpConfig($config); // Resolve exception parser if (!$this->exceptionParser) { $this->exceptionParser = new DefaultXmlExceptionParser(); } // Resolve backoff strategy $backoff = $config->get(Options::BACKOFF); if ($backoff === null) { $backoff = $this->createDefaultBackoff(); $config->set(Options::BACKOFF, $backoff); } if ($backoff) { $this->addBackoffLogger($backoff, $config); } /** @var $client AwsClientInterface */ $client = new $this->clientClass($credentials, $signature, $config); $client->setDescription($description); // Add exception marshaling so that more descriptive exception are thrown if ($this->clientNamespace) { $exceptionFactory = new NamespaceExceptionFactory( $this->exceptionParser, "{$this->clientNamespace}\\Exception", "{$this->clientNamespace}\\Exception\\{$this->serviceName}Exception" ); $client->addSubscriber(new ExceptionListener($exceptionFactory)); } // Add the UserAgentPlugin to append to the User-Agent header of requests $client->addSubscriber(new UserAgentListener()); // Filters used for the cache plugin $client->getConfig()->set( 'params.cache.key_filter', 'header=date,x-amz-date,x-amz-security-token,x-amzn-authorization' ); // Set the iterator resource factory based on the provided iterators config $client->setResourceIteratorFactory(new AwsResourceIteratorFactory( $this->iteratorsConfig, new ResourceIteratorClassFactory($this->clientNamespace . '\\Iterator') )); // Disable parameter validation if needed if ($config->get(Options::VALIDATION) === false) { $params = $config->get('command.params') ?: array(); $params['command.disable_validation'] = true; $config->set('command.params', $params); } return $client; } /** * Add backoff logging to the backoff plugin if needed * * @param BackoffPlugin $plugin Backoff plugin * @param Collection $config Configuration settings * * @throws InvalidArgumentException */ protected function addBackoffLogger(BackoffPlugin $plugin, Collection $config) { // The log option can be set to `debug` or an instance of a LogAdapterInterface if ($logger = $config->get(Options::BACKOFF_LOGGER)) { $format = $config->get(Options::BACKOFF_LOGGER_TEMPLATE); if ($logger === 'debug') { $logger = new ClosureLogAdapter(function ($message) { trigger_error($message . "\n"); }); } elseif (!($logger instanceof LogAdapterInterface)) { throw new InvalidArgumentException( Options::BACKOFF_LOGGER . ' must be set to `debug` or an instance of ' . 'Guzzle\\Common\\Log\\LogAdapterInterface' ); } // Create the plugin responsible for logging exponential backoff retries $logPlugin = new BackoffLogger($logger); // You can specify a custom format or use the default if ($format) { $logPlugin->setTemplate($format); } $plugin->addSubscriber($logPlugin); } } /** * Ensures that an array (e.g. for config data) is actually in array form * * @param array|Collection $array The array data * * @return array * @throws InvalidArgumentException if the arg is not an array or Collection */ protected function processArray($array) { if ($array instanceof Collection) { $array = $array->getAll(); } if (!is_array($array)) { throw new InvalidArgumentException('The config must be provided as an array or Collection.'); } return $array; } /** * Update a configuration object from a service description * * @param Collection $config Config to update * * @return ServiceDescription * @throws InvalidArgumentException */ protected function updateConfigFromDescription(Collection $config) { $description = $config->get(Options::SERVICE_DESCRIPTION); if (!($description instanceof ServiceDescription)) { // Inject the version into the sprintf template if it is a string if (is_string($description)) { $description = sprintf($description, $config->get(Options::VERSION)); } $description = ServiceDescription::factory($description); $config->set(Options::SERVICE_DESCRIPTION, $description); } if (!$config->get(Options::SERVICE)) { $config->set(Options::SERVICE, $description->getData('endpointPrefix')); } if ($iterators = $description->getData('iterators')) { $this->setIteratorsConfig($iterators); } $this->handleRegion($config); $this->handleEndpoint($config); return $description; } /** * Return an appropriate signature object for a a client based on the * "signature" configuration setting, or the default signature specified in * a service description. The signature can be set to a valid signature * version identifier string or an instance of Aws\Common\Signature\SignatureInterface. * * @param ServiceDescription $description Description that holds a signature option * @param Collection $config Configuration options * * @return SignatureInterface * @throws InvalidArgumentException */ protected function getSignature(ServiceDescription $description, Collection $config) { // If a custom signature has not been provided, then use the default // signature setting specified in the service description. $signature = $config->get(Options::SIGNATURE) ?: $description->getData('signatureVersion'); if (is_string($signature)) { if ($signature == 'v4') { $signature = new SignatureV4(); } elseif ($signature == 'v2') { $signature = new SignatureV2(); } elseif ($signature == 'v3https') { $signature = new SignatureV3Https(); } else { throw new InvalidArgumentException("Invalid signature type: {$signature}"); } } elseif (!($signature instanceof SignatureInterface)) { throw new InvalidArgumentException('The provided signature is not ' . 'a signature version string or an instance of ' . 'Aws\\Common\\Signature\\SignatureInterface'); } // Allow a custom service name or region value to be provided if ($signature instanceof EndpointSignatureInterface) { // Determine the service name to use when signing $signature->setServiceName($config->get(Options::SIGNATURE_SERVICE) ?: $description->getData('signingName') ?: $description->getData('endpointPrefix')); // Determine the region to use when signing requests $signature->setRegionName($config->get(Options::SIGNATURE_REGION) ?: $config->get(Options::REGION)); } return $signature; } protected function getCredentials(Collection $config) { $credentials = $config->get(Options::CREDENTIALS); if (is_array($credentials)) { $credentials = Credentials::factory($credentials); } elseif ($credentials === false) { $credentials = new NullCredentials(); } elseif (!$credentials instanceof CredentialsInterface) { $credentials = Credentials::factory($config); } return $credentials; } private function handleRegion(Collection $config) { // Make sure a valid region is set $region = $config[Options::REGION]; $description = $config[Options::SERVICE_DESCRIPTION]; $global = $description->getData('globalEndpoint'); if (!$global && !$region) { throw new InvalidArgumentException( 'A region is required when using ' . $description->getData('serviceFullName') ); } elseif ($global && !$region) { $config[Options::REGION] = 'us-east-1'; } } private function handleEndpoint(Collection $config) { // Alias "endpoint" with "base_url" for forwards compatibility. if ($config['endpoint']) { $config[Options::BASE_URL] = $config['endpoint']; return; } if ($config[Options::BASE_URL]) { return; } $endpoint = call_user_func( $config['endpoint_provider'], array( 'scheme' => $config[Options::SCHEME], 'region' => $config[Options::REGION], 'service' => $config[Options::SERVICE] ) ); $config[Options::BASE_URL] = $endpoint['endpoint']; // Set a signature if one was not explicitly provided. if (!$config->hasKey(Options::SIGNATURE) && isset($endpoint['signatureVersion']) ) { $config->set(Options::SIGNATURE, $endpoint['signatureVersion']); } // The the signing region if endpoint rule specifies one. if (isset($endpoint['credentialScope'])) { $scope = $endpoint['credentialScope']; if (isset($scope['region'])) { $config->set(Options::SIGNATURE_REGION, $scope['region']); } } } private function createDefaultBackoff() { return new BackoffPlugin( // Retry failed requests up to 3 times if it is determined that the request can be retried new TruncatedBackoffStrategy(3, // Retry failed requests with 400-level responses due to throttling new ThrottlingErrorChecker($this->exceptionParser, // Retry failed requests due to transient network or cURL problems new CurlBackoffStrategy(null, // Retry failed requests with 500-level responses new HttpBackoffStrategy(array(500, 503, 509), // Retry requests that failed due to expired credentials new ExpiredCredentialsChecker($this->exceptionParser, new ExponentialBackoffStrategy() ) ) ) ) ) ); } private function extractHttpConfig(Collection $config) { $http = $config['http']; if (!is_array($http)) { return; } if (isset($http['verify'])) { $config[Options::SSL_CERT] = $http['verify']; } } } setConfig($config) ->setConfigDefaults(array(Options::SCHEME => 'https')) ->build(); } } true, 'ExpiredTokenException' => true, 'ExpiredToken' => true ); /** * @var ExceptionParserInterface Exception parser used to parse exception responses */ protected $exceptionParser; public function __construct(ExceptionParserInterface $exceptionParser, BackoffStrategyInterface $next = null) { $this->exceptionParser = $exceptionParser; $this->next = $next; } public function makesDecision() { return true; } protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null) { if ($response && $response->isClientError()) { $parts = $this->exceptionParser->parse($request, $response); if (!isset($this->retryable[$parts['code']]) || !$request->getClient()) { return null; } /** @var $client AwsClientInterface */ $client = $request->getClient(); // Only retry if the credentials can be refreshed if (!($client->getCredentials() instanceof AbstractRefreshableCredentials)) { return null; } // Resign the request using new credentials $client->getSignature()->signRequest($request, $client->getCredentials()->setExpiration(-1)); // Retry immediately with no delay return 0; } } } true, 'Throttling' => true, 'ThrottlingException' => true, 'ProvisionedThroughputExceededException' => true, 'RequestThrottled' => true, ); /** * @var ExceptionParserInterface Exception parser used to parse exception responses */ protected $exceptionParser; public function __construct(ExceptionParserInterface $exceptionParser, BackoffStrategyInterface $next = null) { $this->exceptionParser = $exceptionParser; if ($next) { $this->setNext($next); } } /** * {@inheritdoc} */ public function makesDecision() { return true; } /** * {@inheritdoc} */ protected function getDelay( $retries, RequestInterface $request, Response $response = null, HttpException $e = null ) { if ($response && $response->isClientError()) { $parts = $this->exceptionParser->parse($request, $response); return isset(self::$throttlingExceptions[$parts['code']]) ? true : null; } } } commands = $commands; $this->bodyParameter = (string) $bodyParameter; $this->sourceParameter = (string) $sourceParameter; } /** * {@inheritdoc} */ public static function getSubscribedEvents() { return array('command.before_prepare' => array('onCommandBeforePrepare')); } /** * Converts filenames and file handles into EntityBody objects before the command is validated * * @param Event $event Event emitted * @throws InvalidArgumentException */ public function onCommandBeforePrepare(Event $event) { /** @var $command Command */ $command = $event['command']; if (in_array($command->getName(), $this->commands)) { // Get the interesting parameters $source = $command->get($this->sourceParameter); $body = $command->get($this->bodyParameter); // If a file path is passed in then get the file handle if (is_string($source) && file_exists($source)) { $body = fopen($source, 'r'); } // Prepare the body parameter and remove the source file parameter if (null !== $body) { $command->remove($this->sourceParameter); $command->set($this->bodyParameter, EntityBody::factory($body)); } else { throw new InvalidArgumentException("You must specify a non-null value for the {$this->bodyParameter} or {$this->sourceParameter} parameters."); } } } } 'onBeforeSend'); } /** * Adds strings to the User-Agent header using the `ua.append` parameter of a command * * @param Event $event Event emitted */ public function onBeforeSend(Event $event) { $command = $event['command']; if ($userAgentAppends = $command->get(self::OPTION)) { $request = $command->getRequest(); $userAgent = (string) $request->getHeader('User-Agent'); foreach ((array) $userAgentAppends as $append) { $append = ' ' . $append; if (strpos($userAgent, $append) === false) { $userAgent .= $append; } } $request->setHeader('User-Agent', $userAgent); } } } fqname = $command->getName(); $query = array(); $this->customResolver($value, $param, $query, $param->getWireName()); $request->addPostFields($query); } /** * Map nested parameters into the location_key based parameters * * @param array $value Value to map * @param Parameter $param Parameter that holds information about the current key * @param array $query Built up query string values * @param string $prefix String to prepend to sub query values */ protected function customResolver($value, Parameter $param, array &$query, $prefix = '') { switch ($param->getType()) { case 'object': $this->resolveObject($param, $value, $prefix, $query); break; case 'array': $this->resolveArray($param, $value, $prefix, $query); break; default: $query[$prefix] = $param->filter($value); } } /** * Custom handling for objects * * @param Parameter $param Parameter for the object * @param array $value Value that is set for this parameter * @param string $prefix Prefix for the resulting key * @param array $query Query string array passed by reference */ protected function resolveObject(Parameter $param, array $value, $prefix, array &$query) { // Maps are implemented using additional properties $hasAdditionalProperties = ($param->getAdditionalProperties() instanceof Parameter); $additionalPropertyCount = 0; foreach ($value as $name => $v) { if ($subParam = $param->getProperty($name)) { // if the parameter was found by name as a regular property $key = $prefix . '.' . $subParam->getWireName(); $this->customResolver($v, $subParam, $query, $key); } elseif ($hasAdditionalProperties) { // Handle map cases like &Attribute.1.Name=&Attribute.1.Value= $additionalPropertyCount++; $data = $param->getData(); $keyName = isset($data['keyName']) ? $data['keyName'] : 'key'; $valueName = isset($data['valueName']) ? $data['valueName'] : 'value'; $query["{$prefix}.{$additionalPropertyCount}.{$keyName}"] = $name; $newPrefix = "{$prefix}.{$additionalPropertyCount}.{$valueName}"; if (is_array($v)) { $this->customResolver($v, $param->getAdditionalProperties(), $query, $newPrefix); } else { $query[$newPrefix] = $param->filter($v); } } } } /** * Custom handling for arrays * * @param Parameter $param Parameter for the object * @param array $value Value that is set for this parameter * @param string $prefix Prefix for the resulting key * @param array $query Query string array passed by reference */ protected function resolveArray(Parameter $param, array $value, $prefix, array &$query) { static $serializeEmpty = array( 'SetLoadBalancerPoliciesForBackendServer' => 1, 'SetLoadBalancerPoliciesOfListener' => 1, 'UpdateStack' => 1 ); // For BC, serialize empty lists for specific operations if (!$value) { if (isset($serializeEmpty[$this->fqname])) { $query[$prefix] = ''; } return; } $offset = $param->getData('offset') ?: 1; foreach ($value as $index => $v) { $index += $offset; if (is_array($v) && $items = $param->getItems()) { $this->customResolver($v, $items, $query, $prefix . '.' . $index); } else { $query[$prefix . '.' . $index] = $param->filter($v); } } } } request->getBody()) { $this->request->setBody('{}'); } // Never send the Expect header when interacting with a JSON query service $this->request->removeHeader('Expect'); // Always send JSON requests as a raw string rather than using streams to avoid issues with // cURL error code 65: "necessary data rewind wasn't possible". // This could be removed after PHP addresses https://bugs.php.net/bug.php?id=47204 $this->request->getCurlOptions()->set(CurlHandle::BODY_AS_STRING, true); } } getRequestSerializer()->addVisitor('aws.query', self::$queryVisitor); $this->getResponseParser()->addVisitor('xml', self::$xmlVisitor); } } getOperation(); if ($operation->getServiceDescription()->getData('resultWrapped')) { $wrappingNode = $operation->getName() . 'Result'; if (isset($result[$wrappingNode])) { $result = $result[$wrappingNode] + $result; unset($result[$wrappingNode]); } } } /** * Accounts for wrapper nodes * {@inheritdoc} */ public function visit( CommandInterface $command, Response $response, Parameter $param, &$value, $context = null ) { parent::visit($command, $response, $param, $value, $context); // Account for wrapper nodes (e.g. RDS, ElastiCache, etc) if ($param->getData('wrapper')) { $wireName = $param->getWireName(); $value += $value[$wireName]; unset($value[$wireName]); } } /** * Filter used when converting XML maps into associative arrays in service descriptions * * @param array $value Value to filter * @param string $entryName Name of each entry * @param string $keyName Name of each key * @param string $valueName Name of each value * * @return array Returns the map of the XML data */ public static function xmlMap($value, $entryName, $keyName, $valueName) { $result = array(); foreach ($value as $entry) { $result[$entry[$keyName]] = $entry[$valueName]; } return $result; } } credentials = $credentials; } /** * {@inheritdoc} */ public function serialize() { return $this->credentials->serialize(); } /** * {@inheritdoc} */ public function unserialize($serialized) { $this->credentials = new Credentials('', ''); $this->credentials->unserialize($serialized); } /** * {@inheritdoc} */ public function getAccessKeyId() { return $this->credentials->getAccessKeyId(); } /** * {@inheritdoc} */ public function getSecretKey() { return $this->credentials->getSecretKey(); } /** * {@inheritdoc} */ public function getSecurityToken() { return $this->credentials->getSecurityToken(); } /** * {@inheritdoc} */ public function getExpiration() { return $this->credentials->getExpiration(); } /** * {@inheritdoc} */ public function isExpired() { return $this->credentials->isExpired(); } /** * {@inheritdoc} */ public function setAccessKeyId($key) { $this->credentials->setAccessKeyId($key); return $this; } /** * {@inheritdoc} */ public function setSecretKey($secret) { $this->credentials->setSecretKey($secret); return $this; } /** * {@inheritdoc} */ public function setSecurityToken($token) { $this->credentials->setSecurityToken($token); return $this; } /** * {@inheritdoc} */ public function setExpiration($timestamp) { $this->credentials->setExpiration($timestamp); return $this; } } credentials->isExpired()) { $this->refresh(); } return $this->credentials->getAccessKeyId(); } /** * {@inheritdoc} */ public function getSecretKey() { if ($this->credentials->isExpired()) { $this->refresh(); } return $this->credentials->getSecretKey(); } /** * {@inheritdoc} */ public function getSecurityToken() { if ($this->credentials->isExpired()) { $this->refresh(); } return $this->credentials->getSecurityToken(); } /** * {@inheritdoc} */ public function serialize() { if ($this->credentials->isExpired()) { $this->refresh(); } return $this->credentials->serialize(); } /** * Attempt to get new credentials */ abstract protected function refresh(); } credentials = $credentials; $this->cache = $cache; $this->cacheKey = $cacheKey; } /** * Attempt to get new credentials from cache or from the adapted object */ protected function refresh() { if (!$cache = $this->cache->fetch($this->cacheKey)) { // The credentials were not found, so try again and cache if new $this->credentials->getAccessKeyId(); if (!$this->credentials->isExpired()) { // The credentials were updated, so cache them $this->cache->save($this->cacheKey, $this->credentials, $this->credentials->getExpiration() - time()); } } else { // The credentials were found in cache, so update the adapter object // if the cached credentials are not expired if (!$cache->isExpired()) { $this->credentials->setAccessKeyId($cache->getAccessKeyId()); $this->credentials->setSecretKey($cache->getSecretKey()); $this->credentials->setSecurityToken($cache->getSecurityToken()); $this->credentials->setExpiration($cache->getExpiration()); } } } } null, Options::SECRET => null, Options::TOKEN => null, Options::TOKEN_TTD => null, Options::PROFILE => null, Options::CREDENTIALS_CACHE => null, Options::CREDENTIALS_CACHE_KEY => null, Options::CREDENTIALS_CLIENT => null ); } /** * Factory method for creating new credentials. This factory method will * create the appropriate credentials object with appropriate decorators * based on the passed configuration options. * * @param array $config Options to use when instantiating the credentials * * @return CredentialsInterface * @throws InvalidArgumentException If the caching options are invalid * @throws RuntimeException If using the default cache and APC is disabled */ public static function factory($config = array()) { // Add default key values foreach (self::getConfigDefaults() as $key => $value) { if (!isset($config[$key])) { $config[$key] = $value; } } // Start tracking the cache key $cacheKey = $config[Options::CREDENTIALS_CACHE_KEY]; // Create the credentials object if (!$config[Options::KEY] || !$config[Options::SECRET]) { $credentials = self::createFromEnvironment($config); // If no cache key was set, use the crc32 hostname of the server $cacheKey = $cacheKey ?: 'credentials_' . crc32(gethostname()); } else { // Instantiate using short or long term credentials $credentials = new static( $config[Options::KEY], $config[Options::SECRET], $config[Options::TOKEN], $config[Options::TOKEN_TTD] ); // If no cache key was set, use the access key ID $cacheKey = $cacheKey ?: 'credentials_' . $config[Options::KEY]; } // Check if the credentials are refreshable, and if so, configure caching $cache = $config[Options::CREDENTIALS_CACHE]; if ($cacheKey && $cache) { $credentials = self::createCache($credentials, $cache, $cacheKey); } return $credentials; } /** * Create credentials from the credentials ini file in the HOME directory. * * @param string|null $profile Pass a specific profile to use. If no * profile is specified we will attempt to use * the value specified in the AWS_PROFILE * environment variable. If AWS_PROFILE is not * set, the "default" profile is used. * @param string|null $filename Pass a string to specify the location of the * credentials files. If null is passed, the * SDK will attempt to find the configuration * file at in your HOME directory at * ~/.aws/credentials. * @return CredentialsInterface * @throws \RuntimeException if the file cannot be found, if the file is * invalid, or if the profile is invalid. */ public static function fromIni($profile = null, $filename = null) { if (!$filename) { $filename = self::getHomeDir() . '/.aws/credentials'; } if (!$profile) { $profile = self::getEnvVar(self::ENV_PROFILE) ?: 'default'; } if (!file_exists($filename) || !($data = parse_ini_file($filename, true))) { throw new \RuntimeException("Invalid AWS credentials file: {$filename}."); } if (empty($data[$profile])) { throw new \RuntimeException("Invalid AWS credentials profile {$profile} in {$filename}."); } return new self( $data[$profile]['aws_access_key_id'], $data[$profile]['aws_secret_access_key'], isset($data[$profile]['aws_security_token']) ? $data[$profile]['aws_security_token'] : null ); } /** * Constructs a new BasicAWSCredentials object, with the specified AWS * access key and AWS secret key * * @param string $accessKeyId AWS access key ID * @param string $secretAccessKey AWS secret access key * @param string $token Security token to use * @param int $expiration UNIX timestamp for when credentials expire */ public function __construct($accessKeyId, $secretAccessKey, $token = null, $expiration = null) { $this->key = trim($accessKeyId); $this->secret = trim($secretAccessKey); $this->token = $token; $this->ttd = $expiration; } public function serialize() { return json_encode(array( Options::KEY => $this->key, Options::SECRET => $this->secret, Options::TOKEN => $this->token, Options::TOKEN_TTD => $this->ttd )); } public function unserialize($serialized) { $data = json_decode($serialized, true); $this->key = $data[Options::KEY]; $this->secret = $data[Options::SECRET]; $this->token = $data[Options::TOKEN]; $this->ttd = $data[Options::TOKEN_TTD]; } public function getAccessKeyId() { return $this->key; } public function getSecretKey() { return $this->secret; } public function getSecurityToken() { return $this->token; } public function getExpiration() { return $this->ttd; } public function isExpired() { return $this->ttd !== null && time() >= $this->ttd; } public function setAccessKeyId($key) { $this->key = $key; return $this; } public function setSecretKey($secret) { $this->secret = $secret; return $this; } public function setSecurityToken($token) { $this->token = $token; return $this; } public function setExpiration($timestamp) { $this->ttd = $timestamp; return $this; } /** * When no keys are provided, attempt to create them based on the * environment or instance profile credentials. * * @param array|Collection $config * * @return CredentialsInterface */ private static function createFromEnvironment($config) { // Get key and secret from ENV variables $envKey = self::getEnvVar(self::ENV_KEY); if (!($envSecret = self::getEnvVar(self::ENV_SECRET))) { // Use AWS_SECRET_ACCESS_KEY if AWS_SECRET_KEY was not set. $envSecret = self::getEnvVar(self::ENV_SECRET_ACCESS_KEY); } // Use credentials from the environment variables if available if ($envKey && $envSecret) { return new static($envKey, $envSecret); } // Use credentials from the ini file in HOME directory if available $home = self::getHomeDir(); if ($home && file_exists("{$home}/.aws/credentials")) { return self::fromIni($config[Options::PROFILE], "{$home}/.aws/credentials"); } // Use instance profile credentials (available on EC2 instances) return new RefreshableInstanceProfileCredentials( new static('', '', '', 1), $config[Options::CREDENTIALS_CLIENT] ); } private static function createCache(CredentialsInterface $credentials, $cache, $cacheKey) { if ($cache === 'true' || $cache === true) { // If no cache adapter was provided, then create one for the user // @codeCoverageIgnoreStart if (!extension_loaded('apc')) { throw new RequiredExtensionNotLoadedException('PHP has not been compiled with APC. Unable to cache ' . 'the credentials.'); } elseif (!class_exists('Doctrine\Common\Cache\ApcCache')) { throw new RuntimeException( 'Cannot set ' . Options::CREDENTIALS_CACHE . ' to true because the Doctrine cache component is ' . 'not installed. Either install doctrine/cache or pass in an instantiated ' . 'Guzzle\Cache\CacheAdapterInterface object' ); } // @codeCoverageIgnoreEnd $cache = new DoctrineCacheAdapter(new \Doctrine\Common\Cache\ApcCache()); } elseif (!($cache instanceof CacheAdapterInterface)) { throw new InvalidArgumentException('Unable to utilize caching with the specified options'); } // Decorate the credentials with a cache return new CacheableCredentials($credentials, $cache, $cacheKey); } private static function getHomeDir() { // On Linux/Unix-like systems, use the HOME environment variable if ($homeDir = self::getEnvVar('HOME')) { return $homeDir; } // Get the HOMEDRIVE and HOMEPATH values for Windows hosts $homeDrive = self::getEnvVar('HOMEDRIVE'); $homePath = self::getEnvVar('HOMEPATH'); return ($homeDrive && $homePath) ? $homeDrive . $homePath : null; } /** * Fetches the value of an environment variable by checking $_SERVER and getenv(). * * @param string $var Name of the environment variable * * @return mixed|null */ private static function getEnvVar($var) { return isset($_SERVER[$var]) ? $_SERVER[$var] : getenv($var); } } credentials = $credentials; $this->client = $client ?: InstanceMetadataClient::factory(); } /** * Attempt to get new credentials from the instance profile * * @throws InstanceProfileCredentialsException On error */ protected function refresh() { $credentials = $this->client->getInstanceProfileCredentials(); // Expire the token 1 minute before it actually expires to pre-fetch before expiring $this->credentials->setAccessKeyId($credentials->getAccessKeyId()) ->setSecretKey($credentials->getSecretKey()) ->setSecurityToken($credentials->getSecurityToken()) ->setExpiration($credentials->getExpiration()); } } getConstants(); } return self::$cache[$class]; } } factory = $factory; } /** * {@inheritdoc} */ public static function getSubscribedEvents() { return array('request.error' => array('onRequestError', -1)); } /** * Throws a more meaningful request exception if available * * @param Event $event Event emitted */ public function onRequestError(Event $event) { $e = $this->factory->fromResponse($event['request'], $event['response']); $event->stopPropagation(); throw $e; } } statusCode = $code; } /** * Get the error response code from the service * * @return string|null */ public function getStatusCode() { return $this->statusCode; } } getMessage(), 0, $exception ); $this->state = $state; } /** * Get the state of the transfer * * @return TransferStateInterface */ public function getState() { return $this->state; } } parser = $parser; $this->baseNamespace = $baseNamespace; $this->defaultException = $defaultException; } /** * {@inheritdoc} */ public function fromResponse(RequestInterface $request, Response $response) { $parts = $this->parser->parse($request, $response); // Removing leading 'AWS.' and embedded periods $className = $this->baseNamespace . '\\' . str_replace(array('AWS.', '.'), '', $parts['code']); if (substr($className, -9) !== 'Exception') { $className .= 'Exception'; } $className = class_exists($className) ? $className : $this->defaultException; return $this->createException($className, $request, $response, $parts); } /** * Create an prepare an exception object * * @param string $className Name of the class to create * @param RequestInterface $request Request * @param Response $response Response received * @param array $parts Parsed exception data * * @return \Exception */ protected function createException($className, RequestInterface $request, Response $response, array $parts) { $class = new $className($parts['message']); if ($class instanceof ServiceResponseException) { $class->setExceptionCode($parts['code']); $class->setExceptionType($parts['type']); $class->setResponse($response); $class->setRequest($request); $class->setRequestId($parts['request_id']); } return $class; } } null, 'message' => null, 'type' => $response->isClientError() ? 'client' : 'server', 'request_id' => (string) $response->getHeader('x-amzn-RequestId'), 'parsed' => null ); // Parse the json and normalize key casings if (null !== $json = json_decode($response->getBody(true), true)) { $data['parsed'] = array_change_key_case($json); } // Do additional, protocol-specific parsing and return the result $data = $this->doParse($data, $response); // Remove "Fault" suffix from exception names if (isset($data['code']) && strpos($data['code'], 'Fault')) { $data['code'] = preg_replace('/^([a-zA-Z]+)Fault$/', '$1', $data['code']); } return $data; } /** * Pull relevant exception data out of the parsed json * * @param array $data The exception data * @param Response $response The response from the service containing the error * * @return array */ abstract protected function doParse(array $data, Response $response); } null, 'message' => null, 'type' => $response->isClientError() ? 'client' : 'server', 'request_id' => null, 'parsed' => null ); if ($body = $response->getBody(true)) { $this->parseBody(new \SimpleXMLElement($body), $data); } else { $this->parseHeaders($request, $response, $data); } return $data; } /** * Parses additional exception information from the response headers * * @param RequestInterface $request Request that was issued * @param Response $response The response from the request * @param array $data The current set of exception data */ protected function parseHeaders(RequestInterface $request, Response $response, array &$data) { $data['message'] = $response->getStatusCode() . ' ' . $response->getReasonPhrase(); if ($requestId = $response->getHeader('x-amz-request-id')) { $data['request_id'] = $requestId; $data['message'] .= " (Request-ID: $requestId)"; } } /** * Parses additional exception information from the response body * * @param \SimpleXMLElement $body The response body as XML * @param array $data The current set of exception data */ protected function parseBody(\SimpleXMLElement $body, array &$data) { $data['parsed'] = $body; $namespaces = $body->getDocNamespaces(); if (isset($namespaces[''])) { // Account for the default namespace being defined and PHP not being able to handle it :( $body->registerXPathNamespace('ns', $namespaces['']); $prefix = 'ns:'; } else { $prefix = ''; } if ($tempXml = $body->xpath("//{$prefix}Code[1]")) { $data['code'] = (string) $tempXml[0]; } if ($tempXml = $body->xpath("//{$prefix}Message[1]")) { $data['message'] = (string) $tempXml[0]; } $tempXml = $body->xpath("//{$prefix}RequestId[1]"); if (empty($tempXml)) { $tempXml = $body->xpath("//{$prefix}RequestID[1]"); } if (isset($tempXml[0])) { $data['request_id'] = (string) $tempXml[0]; } } } getHeader('x-amzn-ErrorType')) { $data['code'] = substr($code, 0, strpos($code, ':')); } return $data; } } exceptionCode = $code; } /** * Get the exception code * * @return string|null */ public function getExceptionCode() { return $this->exceptionCode; } /** * Set the exception type * * @param string $type Exception type */ public function setExceptionType($type) { $this->exceptionType = $type; } /** * Get the exception type (one of client or server) * * @return string|null */ public function getExceptionType() { return $this->exceptionType; } /** * Set the request ID * * @param string $id Request ID */ public function setRequestId($id) { $this->requestId = $id; } /** * Get the Request ID * * @return string|null */ public function getRequestId() { return $this->requestId; } /** * Set the associated response * * @param Response $response Response */ public function setResponse(Response $response) { $this->response = $response; } /** * Get the associated response object * * @return Response|null */ public function getResponse() { return $this->response; } /** * Set the associated request * * @param RequestInterface $request */ public function setRequest(RequestInterface $request) { $this->request = $request; } /** * Get the associated request object * * @return RequestInterface|null */ public function getRequest() { return $this->request; } /** * Get the status code of the response * * @return int|null */ public function getStatusCode() { return $this->response ? $this->response->getStatusCode() : null; } /** * Cast to a string * * @return string */ public function __toString() { $message = get_class($this) . ': ' . 'AWS Error Code: ' . $this->getExceptionCode() . ', ' . 'Status Code: ' . $this->getStatusCode() . ', ' . 'AWS Request ID: ' . $this->getRequestId() . ', ' . 'AWS Error Type: ' . $this->getExceptionType() . ', ' . 'AWS Error Message: ' . $this->getMessage(); // Add the User-Agent if available if ($this->request) { $message .= ', ' . 'User-Agent: ' . $this->request->getHeader('User-Agent'); } return $message; } } getConfig() as $service) { if (isset($service['alias'], $service['class'])) { $facadeClass = __NAMESPACE__ . '\\' . $service['alias']; $facadeAlias = ltrim($targetNamespace . '\\' . $service['alias'], '\\'); if (!class_exists($facadeAlias) && class_exists($facadeClass)) { // @codeCoverageIgnoreStart class_alias($facadeClass, $facadeAlias); // @codeCoverageIgnoreEnd } } } } /** * Returns the instance of the client that the facade operates on * * @return \Aws\Common\Client\AwsClientInterface */ public static function getClient() { return self::$serviceBuilder->get(static::getServiceBuilderKey()); } public static function __callStatic($method, $args) { return call_user_func_array(array(self::getClient(), $method), $args); } } context = hash_init($algorithm); } /** * {@inheritdoc} */ public function addData($data) { if (!$this->context) { throw new LogicException('You may not add more data to a finalized chunk hash.'); } hash_update($this->context, $data); return $this; } /** * {@inheritdoc} */ public function getHash($returnBinaryForm = false) { if (!$this->hash) { $this->hashRaw = hash_final($this->context, true); $this->hash = HashUtils::binToHex($this->hashRaw); $this->context = null; } return $returnBinaryForm ? $this->hashRaw : $this->hash; } /** * {@inheritdoc} */ public function __clone() { if ($this->context) { $this->context = hash_copy($this->context); } } } checksums = $inBinaryForm ? $checksums : array_map('Aws\Common\Hash\HashUtils::hexToBin', $checksums); // Pre-calculate hash $treeHash->getHash(); return $treeHash; } /** * Create a tree hash from a content body * * @param string|resource|EntityBody $content Content to create a tree hash for * @param string $algorithm A valid hash algorithm name as returned by `hash_algos()` * * @return TreeHash */ public static function fromContent($content, $algorithm = self::DEFAULT_ALGORITHM) { $treeHash = new self($algorithm); // Read the data in 1MB chunks and add to tree hash $content = EntityBody::factory($content); while ($data = $content->read(Size::MB)) { $treeHash->addData($data); } // Pre-calculate hash $treeHash->getHash(); return $treeHash; } /** * Validates an entity body with a tree hash checksum * * @param string|resource|EntityBody $content Content to create a tree hash for * @param string $checksum The checksum to use for validation * @param string $algorithm A valid hash algorithm name as returned by `hash_algos()` * * @return bool */ public static function validateChecksum($content, $checksum, $algorithm = self::DEFAULT_ALGORITHM) { $treeHash = self::fromContent($content, $algorithm); return ($checksum === $treeHash->getHash()); } /** * {@inheritdoc} */ public function __construct($algorithm = self::DEFAULT_ALGORITHM) { HashUtils::validateAlgorithm($algorithm); $this->algorithm = $algorithm; } /** * {@inheritdoc} * @throws LogicException if the root tree hash is already calculated * @throws InvalidArgumentException if the data is larger than 1MB */ public function addData($data) { // Error if hash is already calculated if ($this->hash) { throw new LogicException('You may not add more data to a finalized tree hash.'); } // Make sure that only 1MB chunks or smaller get passed in if (strlen($data) > Size::MB) { throw new InvalidArgumentException('The chunk of data added is too large for tree hashing.'); } // Store the raw hash of this data segment $this->checksums[] = hash($this->algorithm, $data, true); return $this; } /** * Add a checksum to the tree hash directly * * @param string $checksum The checksum to add * @param bool $inBinaryForm Whether or not the checksum is already in binary form * * @return self * @throws LogicException if the root tree hash is already calculated */ public function addChecksum($checksum, $inBinaryForm = false) { // Error if hash is already calculated if ($this->hash) { throw new LogicException('You may not add more checksums to a finalized tree hash.'); } // Convert the checksum to binary form if necessary $this->checksums[] = $inBinaryForm ? $checksum : HashUtils::hexToBin($checksum); return $this; } /** * {@inheritdoc} */ public function getHash($returnBinaryForm = false) { if (!$this->hash) { // Perform hashes up the tree to arrive at the root checksum of the tree hash $hashes = $this->checksums; while (count($hashes) > 1) { $sets = array_chunk($hashes, 2); $hashes = array(); foreach ($sets as $set) { $hashes[] = (count($set) === 1) ? $set[0] : hash($this->algorithm, $set[0] . $set[1], true); } } $this->hashRaw = $hashes[0]; $this->hash = HashUtils::binToHex($this->hashRaw); } return $returnBinaryForm ? $this->hashRaw : $this->hash; } /** * @return array Array of raw checksums composing the tree hash */ public function getChecksums() { return $this->checksums; } } getHost(), -14) != '.amazonaws.com') { return self::DEFAULT_REGION; } $serviceAndRegion = substr($url->getHost(), 0, -14); // Special handling for S3 regions $separator = strpos($serviceAndRegion, 's3') === 0 ? '-' : '.'; $separatorPos = strpos($serviceAndRegion, $separator); // If don't detect a separator, then return the default region if ($separatorPos === false) { return self::DEFAULT_REGION; } $region = substr($serviceAndRegion, $separatorPos + 1); // All GOV regions currently use the default GOV region if ($region == 'us-gov') { return self::DEFAULT_GOV_REGION; } return $region; } /** * Parse the AWS service name from a URL * * @param Url $url HTTP URL * * @return string Returns a service name (or empty string) * @link http://docs.aws.amazon.com/general/latest/gr/rande.html */ public static function parseServiceName(Url $url) { // The service name is the first part of the host $parts = explode('.', $url->getHost(), 2); // Special handling for S3 if (stripos($parts[0], 's3') === 0) { return 's3'; } return $parts[0]; } } 'http://169.254.169.254/{version}/', 'version' => 'latest', 'request.options' => array( 'connect_timeout' => 5, 'timeout' => 10 ) ), array('base_url', 'version')); return new self($config); } /** * Constructor override */ public function __construct(Collection $config) { $this->setConfig($config); $this->setBaseUrl($config->get(Options::BASE_URL)); $this->defaultHeaders = new Collection(); $this->setRequestFactory(RequestFactory::getInstance()); } /** * Get instance profile credentials * * @return Credentials * @throws InstanceProfileCredentialsException */ public function getInstanceProfileCredentials() { try { $request = $this->get('meta-data/iam/security-credentials/'); $credentials = trim($request->send()->getBody(true)); $result = $this->get("meta-data/iam/security-credentials/{$credentials}")->send()->json(); } catch (\Exception $e) { $message = sprintf('Error retrieving credentials from the instance profile metadata server. When you are' . ' not running inside of Amazon EC2, you must provide your AWS access key ID and secret access key in' . ' the "key" and "secret" options when creating a client or provide an instantiated' . ' Aws\\Common\\Credentials\\CredentialsInterface object. (%s)', $e->getMessage()); throw new InstanceProfileCredentialsException($message, $e->getCode()); } // Ensure that the status code was successful if ($result['Code'] !== 'Success') { $e = new InstanceProfileCredentialsException('Unexpected response code: ' . $result['Code']); $e->setStatusCode($result['Code']); throw $e; } return new Credentials( $result['AccessKeyId'], $result['SecretAccessKey'], $result['Token'], strtotime($result['Expiration']) ); } } client->get(); try { $request->getCurlOptions()->set(CURLOPT_CONNECTTIMEOUT, 10) ->set(CURLOPT_TIMEOUT, 10); $request->send(); return true; } catch (CurlException $e) { return false; } } } lastResult; } /** * {@inheritdoc} * This AWS specific version of the resource iterator provides a default implementation of the typical AWS iterator * process. It relies on configuration and extension to implement the operation-specific logic of handling results * and nextTokens. This method will loop until resources are acquired or there are no more iterations available. */ protected function sendRequest() { do { // Prepare the request including setting the next token $this->prepareRequest(); if ($this->nextToken) { $this->applyNextToken(); } // Execute the request and handle the results $this->command->add(Ua::OPTION, Ua::ITERATOR); $this->lastResult = $this->command->getResult(); $resources = $this->handleResults($this->lastResult); $this->determineNextToken($this->lastResult); // If no resources collected, prepare to reiterate before yielding if ($reiterate = empty($resources) && $this->nextToken) { $this->command = clone $this->originalCommand; } } while ($reiterate); return $resources; } protected function prepareRequest() { // Get the limit parameter key to set $limitKey = $this->get('limit_key'); if ($limitKey && ($limit = $this->command->get($limitKey))) { $pageSize = $this->calculatePageSize(); // If the limit of the command is different than the pageSize of the iterator, use the smaller value if ($limit && $pageSize) { $realLimit = min($limit, $pageSize); $this->command->set($limitKey, $realLimit); } } } protected function handleResults(Model $result) { $results = array(); // Get the result key that contains the results if ($resultKey = $this->get('result_key')) { $results = $this->getValueFromResult($result, $resultKey) ?: array(); } return $results; } protected function applyNextToken() { // Get the token parameter key to set if ($tokenParam = $this->get('input_token')) { // Set the next token. Works with multi-value tokens if (is_array($tokenParam)) { if (is_array($this->nextToken) && count($tokenParam) === count($this->nextToken)) { foreach (array_combine($tokenParam, $this->nextToken) as $param => $token) { $this->command->set($param, $token); } } else { throw new RuntimeException('The definition of the iterator\'s token parameter and the actual token ' . 'value are not compatible.'); } } else { $this->command->set($tokenParam, $this->nextToken); } } } protected function determineNextToken(Model $result) { $this->nextToken = null; // If the value of "more_results" is true or there is no "more_results" to check, then try to get the next token $moreKey = $this->get('more_results'); if ($moreKey === null || $this->getValueFromResult($result, $moreKey)) { // Get the token key to check if ($tokenKey = $this->get('output_token')) { // Get the next token's value. Works with multi-value tokens if (is_array($tokenKey)) { $this->nextToken = array(); foreach ($tokenKey as $key) { $this->nextToken[] = $this->getValueFromResult($result, $key); } } else { $this->nextToken = $this->getValueFromResult($result, $tokenKey); } } } } /** * Extracts the value from the result using Collection::getPath. Also adds some additional logic for keys that need * to access n-1 indexes (e.g., ImportExport, Kinesis). The n-1 logic only works for the known cases. We will switch * to a jmespath implementation in the future to cover all cases * * @param Model $result * @param string $key * * @return mixed|null */ protected function getValueFromResult(Model $result, $key) { // Special handling for keys that need to access n-1 indexes if (strpos($key, '#') !== false) { $keyParts = explode('#', $key, 2); $items = $result->getPath(trim($keyParts[0], '/')); if ($items && is_array($items)) { $index = count($items) - 1; $key = strtr($key, array('#' => $index)); } } // Get the value return $result->getPath($key); } } null, 'output_token' => null, 'limit_key' => null, 'result_key' => null, 'more_results' => null, ); /** * @var array Legacy configuration options mapped to their new names */ private static $legacyConfigOptions = array( 'token_param' => 'input_token', 'token_key' => 'output_token', 'limit_param' => 'limit_key', 'more_key' => 'more_results', ); /** * @var array Iterator configuration for each iterable operation */ protected $config; /** * @var ResourceIteratorFactoryInterface Another factory that will be used first to instantiate the iterator */ protected $primaryIteratorFactory; /** * @param array $config An array of configuration values for the factory * @param ResourceIteratorFactoryInterface $primaryIteratorFactory Another factory to use for chain of command */ public function __construct(array $config, ResourceIteratorFactoryInterface $primaryIteratorFactory = null) { $this->primaryIteratorFactory = $primaryIteratorFactory; $this->config = array(); foreach ($config as $name => $operation) { $this->config[$name] = $operation + self::$defaultIteratorConfig; } } public function build(CommandInterface $command, array $options = array()) { // Get the configuration data for the command $commandName = $command->getName(); $commandSupported = isset($this->config[$commandName]); $options = $this->translateLegacyConfigOptions($options); $options += $commandSupported ? $this->config[$commandName] : array(); // Instantiate the iterator using the primary factory (if one was provided) if ($this->primaryIteratorFactory && $this->primaryIteratorFactory->canBuild($command)) { $iterator = $this->primaryIteratorFactory->build($command, $options); } elseif (!$commandSupported) { throw new InvalidArgumentException("Iterator was not found for {$commandName}."); } else { // Instantiate a generic AWS resource iterator $iterator = new AwsResourceIterator($command, $options); } return $iterator; } public function canBuild(CommandInterface $command) { if ($this->primaryIteratorFactory) { return $this->primaryIteratorFactory->canBuild($command); } else { return isset($this->config[$command->getName()]); } } /** * @param array $config The config for a single operation * * @return array The modified config with legacy options translated */ private function translateLegacyConfigOptions($config) { foreach (self::$legacyConfigOptions as $legacyOption => $newOption) { if (isset($config[$legacyOption])) { $config[$newOption] = $config[$legacyOption]; unset($config[$legacyOption]); } } return $config; } } client = $client; $this->state = $state; $this->source = $source; $this->options = $options; $this->init(); $this->partSize = $this->calculatePartSize(); } public function __invoke() { return $this->upload(); } /** * {@inheritdoc} */ public static function getAllEvents() { return array( self::BEFORE_PART_UPLOAD, self::AFTER_UPLOAD, self::BEFORE_PART_UPLOAD, self::AFTER_PART_UPLOAD, self::AFTER_ABORT, self::AFTER_COMPLETE ); } /** * {@inheritdoc} */ public function abort() { $command = $this->getAbortCommand(); $result = $command->getResult(); $this->state->setAborted(true); $this->stop(); $this->dispatch(self::AFTER_ABORT, $this->getEventData($command)); return $result; } /** * {@inheritdoc} */ public function stop() { $this->stopped = true; return $this->state; } /** * {@inheritdoc} */ public function getState() { return $this->state; } /** * Get the array of options associated with the transfer * * @return array */ public function getOptions() { return $this->options; } /** * Set an option on the transfer * * @param string $option Name of the option * @param mixed $value Value to set * * @return self */ public function setOption($option, $value) { $this->options[$option] = $value; return $this; } /** * Get the source body of the upload * * @return EntityBodyInterface */ public function getSource() { return $this->source; } /** * {@inheritdoc} * @throws MultipartUploadException when an error is encountered. Use getLastException() to get more information. * @throws RuntimeException when attempting to upload an aborted transfer */ public function upload() { if ($this->state->isAborted()) { throw new RuntimeException('The transfer has been aborted and cannot be uploaded'); } $this->stopped = false; $eventData = $this->getEventData(); $this->dispatch(self::BEFORE_UPLOAD, $eventData); try { $this->transfer(); $this->dispatch(self::AFTER_UPLOAD, $eventData); if ($this->stopped) { return null; } else { $result = $this->complete(); $this->dispatch(self::AFTER_COMPLETE, $eventData); } } catch (\Exception $e) { throw new MultipartUploadException($this->state, $e); } return $result; } /** * Get an array used for event notifications * * @param OperationCommand $command Command to include in event data * * @return array */ protected function getEventData(OperationCommand $command = null) { $data = array( 'transfer' => $this, 'source' => $this->source, 'options' => $this->options, 'client' => $this->client, 'part_size' => $this->partSize, 'state' => $this->state ); if ($command) { $data['command'] = $command; } return $data; } /** * Hook to initialize the transfer */ protected function init() {} /** * Determine the upload part size based on the size of the source data and * taking into account the acceptable minimum and maximum part sizes. * * @return int The part size */ abstract protected function calculatePartSize(); /** * Complete the multipart upload * * @return Model Returns the result of the complete multipart upload command */ abstract protected function complete(); /** * Hook to implement in subclasses to perform the actual transfer */ abstract protected function transfer(); /** * Fetches the abort command fom the concrete implementation * * @return OperationCommand */ abstract protected function getAbortCommand(); } uploadId = $uploadId; } /** * {@inheritdoc} */ public function getUploadId() { return $this->uploadId; } /** * Get a data value from the transfer state's uploadId * * @param string $key Key to retrieve (e.g. Bucket, Key, UploadId, etc) * * @return string|null */ public function getFromId($key) { $params = $this->uploadId->toParams(); return isset($params[$key]) ? $params[$key] : null; } /** * {@inheritdoc} */ public function getPart($partNumber) { return isset($this->parts[$partNumber]) ? $this->parts[$partNumber] : null; } /** * {@inheritdoc} */ public function addPart(UploadPartInterface $part) { $partNumber = $part->getPartNumber(); $this->parts[$partNumber] = $part; return $this; } /** * {@inheritdoc} */ public function hasPart($partNumber) { return isset($this->parts[$partNumber]); } /** * {@inheritdoc} */ public function getPartNumbers() { return array_keys($this->parts); } /** * {@inheritdoc} */ public function setAborted($aborted) { $this->aborted = (bool) $aborted; return $this; } /** * {@inheritdoc} */ public function isAborted() { return $this->aborted; } /** * {@inheritdoc} */ public function count() { return count($this->parts); } /** * {@inheritdoc} */ public function getIterator() { return new \ArrayIterator($this->parts); } /** * {@inheritdoc} */ public function serialize() { return serialize(get_object_vars($this)); } /** * {@inheritdoc} */ public function unserialize($serialized) { $data = unserialize($serialized); foreach (get_object_vars($this) as $property => $oldValue) { if (array_key_exists($property, $data)) { $this->{$property} = $data[$property]; } else { throw new RuntimeException("The {$property} property could be restored during unserialization."); } } } } client = $client; return $this; } /** * Set the state of the upload. This is useful for resuming from a previously started multipart upload. * You must use a local file stream as the data source if you wish to resume from a previous upload. * * @param TransferStateInterface|string $state Pass a TransferStateInterface object or the ID of the initiated * multipart upload. When an ID is passed, the builder will create a * state object using the data from a ListParts API response. * * @return $this */ public function resumeFrom($state) { $this->state = $state; return $this; } /** * Set the data source of the transfer * * @param resource|string|EntityBody $source Source of the transfer. Pass a string to transfer from a file on disk. * You can also stream from a resource returned from fopen or a Guzzle * {@see EntityBody} object. * * @return $this * @throws InvalidArgumentException when the source cannot be found or opened */ public function setSource($source) { // Use the contents of a file as the data source if (is_string($source)) { if (!file_exists($source)) { throw new InvalidArgumentException("File does not exist: {$source}"); } // Clear the cache so that we send accurate file sizes clearstatcache(true, $source); $source = fopen($source, 'r'); } $this->source = EntityBody::factory($source); if ($this->source->isSeekable() && $this->source->getSize() == 0) { throw new InvalidArgumentException('Empty body provided to upload builder'); } return $this; } /** * Specify the headers to set on the upload * * @param array $headers Headers to add to the uploaded object * * @return $this */ public function setHeaders(array $headers) { $this->headers = $headers; return $this; } /** * Build the appropriate uploader based on the builder options * * @return TransferInterface */ abstract public function build(); /** * Initiate the multipart upload * * @return TransferStateInterface */ abstract protected function initiateMultipartUpload(); } loadData($data); return $uploadId; } /** * {@inheritdoc} */ public function toParams() { return $this->data; } /** * {@inheritdoc} */ public function serialize() { return serialize($this->data); } /** * {@inheritdoc} */ public function unserialize($serialized) { $this->loadData(unserialize($serialized)); } /** * Loads an array of data into the UploadId by extracting only the needed keys * * @param array $data Data to load * * @throws InvalidArgumentException if a required key is missing */ protected function loadData($data) { $data = array_replace(static::$expectedValues, array_intersect_key($data, static::$expectedValues)); foreach ($data as $key => $value) { if (isset($data[$key])) { $this->data[$key] = $data[$key]; } else { throw new InvalidArgumentException("A required key [$key] was missing from the UploadId."); } } } } loadData($data); return $part; } /** * {@inheritdoc} */ public function getPartNumber() { return $this->partNumber; } /** * {@inheritdoc} */ public function toArray() { $array = array(); foreach (static::$keyMap as $key => $property) { $array[$key] = $this->{$property}; } return $array; } /** * {@inheritdoc} */ public function serialize() { return serialize($this->toArray()); } /** * {@inheritdoc} */ public function unserialize($serialized) { $this->loadData(unserialize($serialized)); } /** * Loads an array of data into the upload part by extracting only the needed keys * * @param array|\Traversable $data Data to load into the upload part value object * * @throws InvalidArgumentException if a required key is missing */ protected function loadData($data) { foreach (static::$keyMap as $key => $property) { if (isset($data[$key])) { $this->{$property} = $data[$key]; } else { throw new InvalidArgumentException("A required key [$key] was missing from the upload part."); } } } } 'Aws\Common\Aws', 'services' => array( 'default_settings' => array( 'params' => array() ), 'autoscaling' => array( 'alias' => 'AutoScaling', 'extends' => 'default_settings', 'class' => 'Aws\AutoScaling\AutoScalingClient' ), 'cloudformation' => array( 'alias' => 'CloudFormation', 'extends' => 'default_settings', 'class' => 'Aws\CloudFormation\CloudFormationClient' ), 'cloudfront' => array( 'alias' => 'CloudFront', 'extends' => 'default_settings', 'class' => 'Aws\CloudFront\CloudFrontClient' ), 'cloudfront_20120505' => array( 'extends' => 'cloudfront', 'params' => array( 'version' => '2012-05-05' ) ), 'cloudhsm' => array( 'alias' => 'CloudHsm', 'extends' => 'default_settings', 'class' => 'Aws\CloudHsm\CloudHsmClient' ), 'cloudsearch' => array( 'alias' => 'CloudSearch', 'extends' => 'default_settings', 'class' => 'Aws\CloudSearch\CloudSearchClient' ), 'cloudsearch_20110201' => array( 'extends' => 'cloudsearch', 'params' => array( 'version' => '2011-02-01' ) ), 'cloudsearchdomain' => array( 'alias' => 'CloudSearchDomain', 'extends' => 'default_settings', 'class' => 'Aws\CloudSearchDomain\CloudSearchDomainClient' ), 'cloudtrail' => array( 'alias' => 'CloudTrail', 'extends' => 'default_settings', 'class' => 'Aws\CloudTrail\CloudTrailClient' ), 'cloudwatch' => array( 'alias' => 'CloudWatch', 'extends' => 'default_settings', 'class' => 'Aws\CloudWatch\CloudWatchClient' ), 'cloudwatchlogs' => array( 'alias' => 'CloudWatchLogs', 'extends' => 'default_settings', 'class' => 'Aws\CloudWatchLogs\CloudWatchLogsClient' ), 'cognito-identity' => array( 'alias' => 'CognitoIdentity', 'extends' => 'default_settings', 'class' => 'Aws\CognitoIdentity\CognitoIdentityClient' ), 'cognitoidentity' => array('extends' => 'cognito-identity'), 'cognito-sync' => array( 'alias' => 'CognitoSync', 'extends' => 'default_settings', 'class' => 'Aws\CognitoSync\CognitoSyncClient' ), 'cognitosync' => array('extends' => 'cognito-sync'), 'codedeploy' => array( 'alias' => 'CodeDeploy', 'extends' => 'default_settings', 'class' => 'Aws\CodeDeploy\CodeDeployClient' ), 'config' => array( 'alias' => 'ConfigService', 'extends' => 'default_settings', 'class' => 'Aws\ConfigService\ConfigServiceClient' ), 'datapipeline' => array( 'alias' => 'DataPipeline', 'extends' => 'default_settings', 'class' => 'Aws\DataPipeline\DataPipelineClient' ), 'directconnect' => array( 'alias' => 'DirectConnect', 'extends' => 'default_settings', 'class' => 'Aws\DirectConnect\DirectConnectClient' ), 'dynamodb' => array( 'alias' => 'DynamoDb', 'extends' => 'default_settings', 'class' => 'Aws\DynamoDb\DynamoDbClient' ), 'dynamodb_20111205' => array( 'extends' => 'dynamodb', 'params' => array( 'version' => '2011-12-05' ) ), 'ec2' => array( 'alias' => 'Ec2', 'extends' => 'default_settings', 'class' => 'Aws\Ec2\Ec2Client' ), 'ecs' => array( 'alias' => 'Ecs', 'extends' => 'default_settings', 'class' => 'Aws\Ecs\EcsClient' ), 'elasticache' => array( 'alias' => 'ElastiCache', 'extends' => 'default_settings', 'class' => 'Aws\ElastiCache\ElastiCacheClient' ), 'elasticbeanstalk' => array( 'alias' => 'ElasticBeanstalk', 'extends' => 'default_settings', 'class' => 'Aws\ElasticBeanstalk\ElasticBeanstalkClient' ), 'elasticloadbalancing' => array( 'alias' => 'ElasticLoadBalancing', 'extends' => 'default_settings', 'class' => 'Aws\ElasticLoadBalancing\ElasticLoadBalancingClient' ), 'elastictranscoder' => array( 'alias' => 'ElasticTranscoder', 'extends' => 'default_settings', 'class' => 'Aws\ElasticTranscoder\ElasticTranscoderClient' ), 'emr' => array( 'alias' => 'Emr', 'extends' => 'default_settings', 'class' => 'Aws\Emr\EmrClient' ), 'glacier' => array( 'alias' => 'Glacier', 'extends' => 'default_settings', 'class' => 'Aws\Glacier\GlacierClient' ), 'kinesis' => array( 'alias' => 'Kinesis', 'extends' => 'default_settings', 'class' => 'Aws\Kinesis\KinesisClient' ), 'kms' => array( 'alias' => 'Kms', 'extends' => 'default_settings', 'class' => 'Aws\Kms\KmsClient' ), 'lambda' => array( 'alias' => 'Lambda', 'extends' => 'default_settings', 'class' => 'Aws\Lambda\LambdaClient' ), 'iam' => array( 'alias' => 'Iam', 'extends' => 'default_settings', 'class' => 'Aws\Iam\IamClient' ), 'importexport' => array( 'alias' => 'ImportExport', 'extends' => 'default_settings', 'class' => 'Aws\ImportExport\ImportExportClient' ), 'opsworks' => array( 'alias' => 'OpsWorks', 'extends' => 'default_settings', 'class' => 'Aws\OpsWorks\OpsWorksClient' ), 'rds' => array( 'alias' => 'Rds', 'extends' => 'default_settings', 'class' => 'Aws\Rds\RdsClient' ), 'redshift' => array( 'alias' => 'Redshift', 'extends' => 'default_settings', 'class' => 'Aws\Redshift\RedshiftClient' ), 'route53' => array( 'alias' => 'Route53', 'extends' => 'default_settings', 'class' => 'Aws\Route53\Route53Client' ), 'route53domains' => array( 'alias' => 'Route53Domains', 'extends' => 'default_settings', 'class' => 'Aws\Route53Domains\Route53DomainsClient' ), 's3' => array( 'alias' => 'S3', 'extends' => 'default_settings', 'class' => 'Aws\S3\S3Client' ), 'sdb' => array( 'alias' => 'SimpleDb', 'extends' => 'default_settings', 'class' => 'Aws\SimpleDb\SimpleDbClient' ), 'ses' => array( 'alias' => 'Ses', 'extends' => 'default_settings', 'class' => 'Aws\Ses\SesClient' ), 'sns' => array( 'alias' => 'Sns', 'extends' => 'default_settings', 'class' => 'Aws\Sns\SnsClient' ), 'sqs' => array( 'alias' => 'Sqs', 'extends' => 'default_settings', 'class' => 'Aws\Sqs\SqsClient' ), 'ssm' => array( 'alias' => 'Ssm', 'extends' => 'default_settings', 'class' => 'Aws\Ssm\SsmClient' ), 'storagegateway' => array( 'alias' => 'StorageGateway', 'extends' => 'default_settings', 'class' => 'Aws\StorageGateway\StorageGatewayClient' ), 'sts' => array( 'alias' => 'Sts', 'extends' => 'default_settings', 'class' => 'Aws\Sts\StsClient' ), 'support' => array( 'alias' => 'Support', 'extends' => 'default_settings', 'class' => 'Aws\Support\SupportClient' ), 'swf' => array( 'alias' => 'Swf', 'extends' => 'default_settings', 'class' => 'Aws\Swf\SwfClient' ), ) ); 2, 'endpoints' => array( '*/*' => array( 'endpoint' => '{service}.{region}.amazonaws.com' ), 'cn-north-1/*' => array( 'endpoint' => '{service}.{region}.amazonaws.com.cn', 'signatureVersion' => 'v4' ), 'us-gov-west-1/iam' => array( 'endpoint' => 'iam.us-gov.amazonaws.com' ), 'us-gov-west-1/sts' => array( 'endpoint' => 'sts.us-gov-west-1.amazonaws.com' ), 'us-gov-west-1/s3' => array( 'endpoint' => 's3-{region}.amazonaws.com' ), '*/cloudfront' => array( 'endpoint' => 'cloudfront.amazonaws.com', 'credentialScope' => array( 'region' => 'us-east-1' ) ), '*/iam' => array( 'endpoint' => 'iam.amazonaws.com', 'credentialScope' => array( 'region' => 'us-east-1' ) ), '*/importexport' => array( 'endpoint' => 'importexport.amazonaws.com', 'credentialScope' => array( 'region' => 'us-east-1' ) ), '*/route53' => array( 'endpoint' => 'route53.amazonaws.com', 'credentialScope' => array( 'region' => 'us-east-1' ) ), '*/sts' => array( 'endpoint' => 'sts.amazonaws.com', 'credentialScope' => array( 'region' => 'us-east-1' ) ), 'us-east-1/sdb' => array( 'endpoint' => 'sdb.amazonaws.com' ), 'us-east-1/s3' => array( 'endpoint' => 's3.amazonaws.com' ), 'us-west-1/s3' => array( 'endpoint' => 's3-{region}.amazonaws.com' ), 'us-west-2/s3' => array( 'endpoint' => 's3-{region}.amazonaws.com' ), 'eu-west-1/s3' => array( 'endpoint' => 's3-{region}.amazonaws.com' ), 'ap-southeast-1/s3' => array( 'endpoint' => 's3-{region}.amazonaws.com' ), 'ap-southeast-2/s3' => array( 'endpoint' => 's3-{region}.amazonaws.com' ), 'ap-northeast-1/s3' => array( 'endpoint' => 's3-{region}.amazonaws.com' ), 'sa-east-1/s3' => array( 'endpoint' => 's3-{region}.amazonaws.com' ) ) ); array('_aws'), 'services' => array( 'sdk1_settings' => array( 'extends' => 'default_settings', 'params' => array( 'certificate_authority' => false ) ), 'v1.autoscaling' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonAS' ), 'v1.cloudformation' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonCloudFormation' ), 'v1.cloudfront' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonCloudFront' ), 'v1.cloudsearch' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonCloudSearch' ), 'v1.cloudwatch' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonCloudWatch' ), 'v1.dynamodb' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonDynamoDB' ), 'v1.ec2' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonEC2' ), 'v1.elasticache' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonElastiCache' ), 'v1.elasticbeanstalk' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonElasticBeanstalk' ), 'v1.elb' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonELB' ), 'v1.emr' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonEMR' ), 'v1.iam' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonIAM' ), 'v1.importexport' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonImportExport' ), 'v1.rds' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonRDS' ), 'v1.s3' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonS3' ), 'v1.sdb' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonSDB' ), 'v1.ses' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonSES' ), 'v1.sns' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonSNS' ), 'v1.sqs' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonSQS' ), 'v1.storagegateway' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonStorageGateway' ), 'v1.sts' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonSTS' ), 'v1.swf' => array( 'extends' => 'sdk1_settings', 'class' => 'AmazonSWF' ) ) ); patterns = $patterns; } /** * Creates and returns the default RulesEndpointProvider based on the * public rule sets. * * @return self */ public static function fromDefaults() { return new self(require __DIR__ . '/Resources/public-endpoints.php'); } public function __invoke(array $args = array()) { if (!isset($args['service'])) { throw new \InvalidArgumentException('Requires a "service" value'); } if (!isset($args['region'])) { throw new \InvalidArgumentException('Requires a "region" value'); } foreach ($this->getKeys($args['region'], $args['service']) as $key) { if (isset($this->patterns['endpoints'][$key])) { return $this->expand($this->patterns['endpoints'][$key], $args); } } throw new \RuntimeException('Could not resolve endpoint'); } private function expand(array $config, array $args) { $scheme = isset($args['scheme']) ? $args['scheme'] : 'https'; $config['endpoint'] = $scheme . '://' . str_replace( array('{service}', '{region}'), array($args['service'], $args['region']), $config['endpoint'] ); return $config; } private function getKeys($region, $service) { return array("$region/$service", "$region/*", "*/$service", "*/*"); } } credentials = $credentials; $this->signature = $signature; } /** * {@inheritdoc} */ public static function getSubscribedEvents() { return array( 'request.before_send' => array('onRequestBeforeSend', -255), 'client.credentials_changed' => array('onCredentialsChanged') ); } /** * Updates the listener with new credentials if the client is updated * * @param Event $event Event emitted */ public function onCredentialsChanged(Event $event) { $this->credentials = $event['credentials']; } /** * Signs requests before they are sent * * @param Event $event Event emitted */ public function onRequestBeforeSend(Event $event) { if(!$this->credentials instanceof NullCredentials) { $this->signature->signRequest($event['request'], $this->credentials); } } } getTimestamp(true); // set values we need in CanonicalizedParameterString $this->addParameter($request, 'Timestamp', gmdate('c', $timestamp)); $this->addParameter($request, 'SignatureVersion', '2'); $this->addParameter($request, 'SignatureMethod', 'HmacSHA256'); $this->addParameter($request, 'AWSAccessKeyId', $credentials->getAccessKeyId()); if ($token = $credentials->getSecurityToken()) { $this->addParameter($request, 'SecurityToken', $token); } // Get the path and ensure it's absolute $path = '/' . ltrim($request->getUrl(true)->normalizePath()->getPath(), '/'); // build string to sign $sign = $request->getMethod() . "\n" . $request->getHost() . "\n" . $path . "\n" . $this->getCanonicalizedParameterString($request); // Add the string to sign to the request for debugging purposes $request->getParams()->set('aws.string_to_sign', $sign); $signature = base64_encode( hash_hmac( 'sha256', $sign, $credentials->getSecretKey(), true ) ); $this->addParameter($request, 'Signature', $signature); } /** * Add a parameter key and value to the request according to type * * @param RequestInterface $request The request * @param string $key The name of the parameter * @param string $value The value of the parameter */ public function addParameter(RequestInterface $request, $key, $value) { if ($request->getMethod() == 'POST') { $request->setPostField($key, $value); } else { $request->getQuery()->set($key, $value); } } /** * Get the canonicalized query/parameter string for a request * * @param RequestInterface $request Request used to build canonicalized string * * @return string */ private function getCanonicalizedParameterString(RequestInterface $request) { if ($request->getMethod() == 'POST') { $params = $request->getPostFields()->toArray(); } else { $params = $request->getQuery()->toArray(); } // Don't resign a previous signature value unset($params['Signature']); uksort($params, 'strcmp'); $str = ''; foreach ($params as $key => $val) { $str .= rawurlencode($key) . '=' . rawurlencode($val) . '&'; } return substr($str, 0, -1); } } hasHeader('date') && !$request->hasHeader('x-amz-date')) { $request->setHeader('Date', gmdate(DateFormat::RFC1123, $this->getTimestamp())); } // Add the security token if one is present if ($credentials->getSecurityToken()) { $request->setHeader('x-amz-security-token', $credentials->getSecurityToken()); } // Determine the string to sign $stringToSign = (string) ($request->getHeader('Date') ?: $request->getHeader('x-amz-date')); $request->getParams()->set('aws.string_to_sign', $stringToSign); // Calculate the signature $signature = base64_encode(hash_hmac('sha256', $stringToSign, $credentials->getSecretKey(), true)); // Add the authorization header to the request $headerFormat = 'AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=HmacSHA256,Signature=%s'; $request->setHeader('X-Amzn-Authorization', sprintf($headerFormat, $credentials->getAccessKeyId(), $signature)); } } serviceName = $serviceName; $this->regionName = $regionName; } /** * Set the service name instead of inferring it from a request URL * * @param string $service Name of the service used when signing * * @return self */ public function setServiceName($service) { $this->serviceName = $service; return $this; } /** * Set the region name instead of inferring it from a request URL * * @param string $region Name of the region used when signing * * @return self */ public function setRegionName($region) { $this->regionName = $region; return $this; } /** * Set the maximum number of computed hashes to cache * * @param int $maxCacheSize Maximum number of hashes to cache * * @return self */ public function setMaxCacheSize($maxCacheSize) { $this->maxCacheSize = $maxCacheSize; return $this; } public function signRequest(RequestInterface $request, CredentialsInterface $credentials) { $timestamp = $this->getTimestamp(); $longDate = gmdate(DateFormat::ISO8601, $timestamp); $shortDate = substr($longDate, 0, 8); // Remove any previously set Authorization headers so that retries work $request->removeHeader('Authorization'); // Requires a x-amz-date header or Date if ($request->hasHeader('x-amz-date') || !$request->hasHeader('Date')) { $request->setHeader('x-amz-date', $longDate); } else { $request->setHeader('Date', gmdate(DateFormat::RFC1123, $timestamp)); } // Add the security token if one is present if ($credentials->getSecurityToken()) { $request->setHeader('x-amz-security-token', $credentials->getSecurityToken()); } // Parse the service and region or use one that is explicitly set $region = $this->regionName; $service = $this->serviceName; if (!$region || !$service) { $url = Url::factory($request->getUrl()); $region = $region ?: HostNameUtils::parseRegionName($url); $service = $service ?: HostNameUtils::parseServiceName($url); } $credentialScope = $this->createScope($shortDate, $region, $service); $payload = $this->getPayload($request); $signingContext = $this->createSigningContext($request, $payload); $signingContext['string_to_sign'] = $this->createStringToSign( $longDate, $credentialScope, $signingContext['canonical_request'] ); // Calculate the signing key using a series of derived keys $signingKey = $this->getSigningKey($shortDate, $region, $service, $credentials->getSecretKey()); $signature = hash_hmac('sha256', $signingContext['string_to_sign'], $signingKey); $request->setHeader('Authorization', "AWS4-HMAC-SHA256 " . "Credential={$credentials->getAccessKeyId()}/{$credentialScope}, " . "SignedHeaders={$signingContext['signed_headers']}, Signature={$signature}"); // Add debug information to the request $request->getParams()->set('aws.signature', $signingContext); } public function createPresignedUrl( RequestInterface $request, CredentialsInterface $credentials, $expires ) { $request = $this->createPresignedRequest($request, $credentials); $query = $request->getQuery(); $httpDate = gmdate(DateFormat::ISO8601, $this->getTimestamp()); $shortDate = substr($httpDate, 0, 8); $scope = $this->createScope( $shortDate, $this->regionName, $this->serviceName ); $this->addQueryValues($scope, $request, $credentials, $expires); $payload = $this->getPresignedPayload($request); $context = $this->createSigningContext($request, $payload); $stringToSign = $this->createStringToSign( $httpDate, $scope, $context['canonical_request'] ); $key = $this->getSigningKey( $shortDate, $this->regionName, $this->serviceName, $credentials->getSecretKey() ); $query['X-Amz-Signature'] = hash_hmac('sha256', $stringToSign, $key); return $request->getUrl(); } /** * Converts a POST request to a GET request by moving POST fields into the * query string. * * Useful for pre-signing query protocol requests. * * @param EntityEnclosingRequestInterface $request Request to clone * * @return RequestInterface * @throws \InvalidArgumentException if the method is not POST */ public static function convertPostToGet(EntityEnclosingRequestInterface $request) { if ($request->getMethod() !== 'POST') { throw new \InvalidArgumentException('Expected a POST request but ' . 'received a ' . $request->getMethod() . ' request.'); } $cloned = RequestFactory::getInstance() ->cloneRequestWithMethod($request, 'GET'); // Move POST fields to the query if they are present foreach ($request->getPostFields() as $name => $value) { $cloned->getQuery()->set($name, $value); } return $cloned; } /** * Get the payload part of a signature from a request. * * @param RequestInterface $request * * @return string */ protected function getPayload(RequestInterface $request) { // Calculate the request signature payload if ($request->hasHeader('x-amz-content-sha256')) { // Handle streaming operations (e.g. Glacier.UploadArchive) return (string) $request->getHeader('x-amz-content-sha256'); } if ($request instanceof EntityEnclosingRequestInterface) { if ($request->getMethod() == 'POST' && count($request->getPostFields())) { return hash('sha256', (string) $request->getPostFields()); } elseif ($body = $request->getBody()) { return Stream::getHash($request->getBody(), 'sha256'); } } return self::DEFAULT_PAYLOAD; } /** * Get the payload of a request for use with pre-signed URLs. * * @param RequestInterface $request * * @return string */ protected function getPresignedPayload(RequestInterface $request) { return $this->getPayload($request); } protected function createCanonicalizedPath(RequestInterface $request) { $doubleEncoded = rawurlencode(ltrim($request->getPath(), '/')); return '/' . str_replace('%2F', '/', $doubleEncoded); } private function createStringToSign($longDate, $credentialScope, $creq) { return "AWS4-HMAC-SHA256\n{$longDate}\n{$credentialScope}\n" . hash('sha256', $creq); } private function createPresignedRequest( RequestInterface $request, CredentialsInterface $credentials ) { $sr = RequestFactory::getInstance()->cloneRequestWithMethod($request, 'GET'); // Move POST fields to the query if they are present if ($request instanceof EntityEnclosingRequestInterface) { foreach ($request->getPostFields() as $name => $value) { $sr->getQuery()->set($name, $value); } } // Make sure to handle temporary credentials if ($token = $credentials->getSecurityToken()) { $sr->setHeader('X-Amz-Security-Token', $token); $sr->getQuery()->set('X-Amz-Security-Token', $token); } $this->moveHeadersToQuery($sr); return $sr; } /** * Create the canonical representation of a request * * @param RequestInterface $request Request to canonicalize * @param string $payload Request payload (typically the value * of the x-amz-content-sha256 header. * * @return array Returns an array of context information including: * - canonical_request * - signed_headers */ private function createSigningContext(RequestInterface $request, $payload) { $signable = array( 'host' => true, 'date' => true, 'content-md5' => true ); // Normalize the path as required by SigV4 and ensure it's absolute $canon = $request->getMethod() . "\n" . $this->createCanonicalizedPath($request) . "\n" . $this->getCanonicalizedQueryString($request) . "\n"; $canonHeaders = array(); foreach ($request->getHeaders()->getAll() as $key => $values) { $key = strtolower($key); if (isset($signable[$key]) || substr($key, 0, 6) === 'x-amz-') { $values = $values->toArray(); if (count($values) == 1) { $values = $values[0]; } else { sort($values); $values = implode(',', $values); } $canonHeaders[$key] = $key . ':' . preg_replace('/\s+/', ' ', $values); } } ksort($canonHeaders); $signedHeadersString = implode(';', array_keys($canonHeaders)); $canon .= implode("\n", $canonHeaders) . "\n\n" . $signedHeadersString . "\n" . $payload; return array( 'canonical_request' => $canon, 'signed_headers' => $signedHeadersString ); } /** * Get a hash for a specific key and value. If the hash was previously * cached, return it * * @param string $shortDate Short date * @param string $region Region name * @param string $service Service name * @param string $secretKey Secret Access Key * * @return string */ private function getSigningKey($shortDate, $region, $service, $secretKey) { $cacheKey = $shortDate . '_' . $region . '_' . $service . '_' . $secretKey; // Retrieve the hash form the cache or create it and add it to the cache if (!isset($this->hashCache[$cacheKey])) { // When the cache size reaches the max, then just clear the cache if (++$this->cacheSize > $this->maxCacheSize) { $this->hashCache = array(); $this->cacheSize = 0; } $dateKey = hash_hmac('sha256', $shortDate, 'AWS4' . $secretKey, true); $regionKey = hash_hmac('sha256', $region, $dateKey, true); $serviceKey = hash_hmac('sha256', $service, $regionKey, true); $this->hashCache[$cacheKey] = hash_hmac('sha256', 'aws4_request', $serviceKey, true); } return $this->hashCache[$cacheKey]; } /** * Get the canonicalized query string for a request * * @param RequestInterface $request * @return string */ private function getCanonicalizedQueryString(RequestInterface $request) { $queryParams = $request->getQuery()->getAll(); unset($queryParams['X-Amz-Signature']); if (empty($queryParams)) { return ''; } $qs = ''; ksort($queryParams); foreach ($queryParams as $key => $values) { if (is_array($values)) { sort($values); } elseif ($values === 0) { $values = array('0'); } elseif (!$values) { $values = array(''); } foreach ((array) $values as $value) { if ($value === QueryString::BLANK) { $value = ''; } $qs .= rawurlencode($key) . '=' . rawurlencode($value) . '&'; } } return substr($qs, 0, -1); } private function convertExpires($expires) { if ($expires instanceof \DateTime) { $expires = $expires->getTimestamp(); } elseif (!is_numeric($expires)) { $expires = strtotime($expires); } $duration = $expires - time(); // Ensure that the duration of the signature is not longer than a week if ($duration > 604800) { throw new \InvalidArgumentException('The expiration date of a ' . 'signature version 4 presigned URL must be less than one ' . 'week'); } return $duration; } private function createScope($shortDate, $region, $service) { return $shortDate . '/' . $region . '/' . $service . '/aws4_request'; } private function addQueryValues( $scope, RequestInterface $request, CredentialsInterface $credentials, $expires ) { $credential = $credentials->getAccessKeyId() . '/' . $scope; // Set query params required for pre-signed URLs $request->getQuery() ->set('X-Amz-Algorithm', 'AWS4-HMAC-SHA256') ->set('X-Amz-Credential', $credential) ->set('X-Amz-Date', gmdate('Ymd\THis\Z', $this->getTimestamp())) ->set('X-Amz-SignedHeaders', 'Host') ->set('X-Amz-Expires', $this->convertExpires($expires)); } private function moveHeadersToQuery(RequestInterface $request) { $query = $request->getQuery(); foreach ($request->getHeaders() as $name => $header) { if (substr($name, 0, 5) == 'x-amz') { $query[$header->getName()] = (string) $header; } if ($name !== 'host') { $request->removeHeader($name); } } } } client = $client; return $this; } /** * {@inheritdoc} */ public function wait() { if (!$this->client) { throw new RuntimeException('No client has been specified on the waiter'); } parent::wait(); } } config[self::MAX_ATTEMPTS]) ? $this->config[self::MAX_ATTEMPTS] : 10; } /** * Get the amount of time in seconds to delay between attempts * * @return int */ public function getInterval() { return isset($this->config[self::INTERVAL]) ? $this->config[self::INTERVAL] : 0; } /** * {@inheritdoc} */ public function setMaxAttempts($maxAttempts) { $this->config[self::MAX_ATTEMPTS] = $maxAttempts; return $this; } /** * {@inheritdoc} */ public function setInterval($interval) { $this->config[self::INTERVAL] = $interval; return $this; } /** * Set config options associated with the waiter * * @param array $config Options to set * * @return self */ public function setConfig(array $config) { if (isset($config['waiter.before_attempt'])) { $this->getEventDispatcher()->addListener('waiter.before_attempt', $config['waiter.before_attempt']); unset($config['waiter.before_attempt']); } if (isset($config['waiter.before_wait'])) { $this->getEventDispatcher()->addListener('waiter.before_wait', $config['waiter.before_wait']); unset($config['waiter.before_wait']); } $this->config = $config; return $this; } /** * {@inheritdoc} */ public function wait() { $this->attempts = 0; do { $this->dispatch('waiter.before_attempt', array( 'waiter' => $this, 'config' => $this->config, )); if ($this->doWait()) { break; } if (++$this->attempts >= $this->getMaxAttempts()) { throw new RuntimeException('Wait method never resolved to true after ' . $this->attempts . ' attempts'); } $this->dispatch('waiter.before_wait', array( 'waiter' => $this, 'config' => $this->config, )); if ($this->getInterval()) { usleep($this->getInterval() * 1000000); } } while (1); } /** * Method to implement in subclasses * * @return bool Return true when successful, false on failure */ abstract protected function doWait(); } callable = $callable; return $this; } /** * Set additional context for the callable function. This data will be passed into the callable function as the * second argument * * @param array $context Additional context * * @return self */ public function setContext(array $context) { $this->context = $context; return $this; } /** * {@inheritdoc} */ public function doWait() { if (!$this->callable) { throw new RuntimeException('No callable was specified for the wait method'); } return call_user_func($this->callable, $this->attempts, $this->context); } } factories = $factories; } /** * {@inheritdoc} */ public function build($waiter) { if (!($factory = $this->getFactory($waiter))) { throw new InvalidArgumentException("Waiter was not found matching {$waiter}."); } return $factory->build($waiter); } /** * {@inheritdoc} */ public function canBuild($waiter) { return (bool) $this->getFactory($waiter); } /** * Add a factory to the composite factory * * @param WaiterFactoryInterface $factory Factory to add * * @return self */ public function addFactory(WaiterFactoryInterface $factory) { $this->factories[] = $factory; return $this; } /** * Get the factory that matches the waiter name * * @param string $waiter Name of the waiter * * @return WaiterFactoryInterface|bool */ protected function getFactory($waiter) { foreach ($this->factories as $factory) { if ($factory->canBuild($waiter)) { return $factory; } } return false; } } waiterConfig = $waiterConfig; $this->setInterval($waiterConfig->get(WaiterConfig::INTERVAL)); $this->setMaxAttempts($waiterConfig->get(WaiterConfig::MAX_ATTEMPTS)); } /** * {@inheritdoc} */ public function setConfig(array $config) { foreach ($config as $key => $value) { if (substr($key, 0, 7) == 'waiter.') { $this->waiterConfig->set(substr($key, 7), $value); } } if (!isset($config[self::INTERVAL])) { $config[self::INTERVAL] = $this->waiterConfig->get(WaiterConfig::INTERVAL); } if (!isset($config[self::MAX_ATTEMPTS])) { $config[self::MAX_ATTEMPTS] = $this->waiterConfig->get(WaiterConfig::MAX_ATTEMPTS); } return parent::setConfig($config); } /** * Get the waiter's configuration data * * @return WaiterConfig */ public function getWaiterConfig() { return $this->waiterConfig; } /** * {@inheritdoc} */ protected function doWait() { $params = $this->config; // remove waiter settings from the operation's input foreach (array_keys($params) as $key) { if (substr($key, 0, 7) == 'waiter.') { unset($params[$key]); } } $operation = $this->client->getCommand($this->waiterConfig->get(WaiterConfig::OPERATION), $params); try { return $this->checkResult($this->client->execute($operation)); } catch (ValidationException $e) { throw new InvalidArgumentException( $this->waiterConfig->get(WaiterConfig::WAITER_NAME) . ' waiter validation failed: ' . $e->getMessage(), $e->getCode(), $e ); } catch (ServiceResponseException $e) { // Check if this exception satisfies a success or failure acceptor $transition = $this->checkErrorAcceptor($e); if (null !== $transition) { return $transition; } // Check if this exception should be ignored foreach ((array) $this->waiterConfig->get(WaiterConfig::IGNORE_ERRORS) as $ignore) { if ($e->getExceptionCode() == $ignore) { // This exception is ignored, so it counts as a failed attempt rather than a fast-fail return false; } } // Allow non-ignore exceptions to bubble through throw $e; } } /** * Check if an exception satisfies a success or failure acceptor * * @param ServiceResponseException $e * * @return bool|null Returns true for success, false for failure, and null for no transition */ protected function checkErrorAcceptor(ServiceResponseException $e) { if ($this->waiterConfig->get(WaiterConfig::SUCCESS_TYPE) == 'error') { if ($e->getExceptionCode() == $this->waiterConfig->get(WaiterConfig::SUCCESS_VALUE)) { // Mark as a success return true; } } // Mark as an attempt return null; } /** * Check to see if the response model satisfies a success or failure state * * @param Model $result Result model * * @return bool * @throws RuntimeException */ protected function checkResult(Model $result) { // Check if the result evaluates to true based on the path and output model if ($this->waiterConfig->get(WaiterConfig::SUCCESS_TYPE) == 'output' && $this->checkPath( $result, $this->waiterConfig->get(WaiterConfig::SUCCESS_PATH), $this->waiterConfig->get(WaiterConfig::SUCCESS_VALUE) ) ) { return true; } // It did not finish waiting yet. Determine if we need to fail-fast based on the failure acceptor. if ($this->waiterConfig->get(WaiterConfig::FAILURE_TYPE) == 'output') { $failureValue = $this->waiterConfig->get(WaiterConfig::FAILURE_VALUE); if ($failureValue) { $key = $this->waiterConfig->get(WaiterConfig::FAILURE_PATH); if ($this->checkPath($result, $key, $failureValue, false)) { // Determine which of the results triggered the failure $triggered = array_intersect( (array) $this->waiterConfig->get(WaiterConfig::FAILURE_VALUE), array_unique((array) $result->getPath($key)) ); // fast fail because the failure case was satisfied throw new RuntimeException( 'A resource entered into an invalid state of "' . implode(', ', $triggered) . '" while waiting with the "' . $this->waiterConfig->get(WaiterConfig::WAITER_NAME) . '" waiter.' ); } } } return false; } /** * Check to see if the path of the output key is satisfied by the value * * @param Model $model Result model * @param string $key Key to check * @param string $checkValue Compare the key to the value * @param bool $all Set to true to ensure all value match or false to only match one * * @return bool */ protected function checkPath(Model $model, $key = null, $checkValue = array(), $all = true) { // If no key is set, then just assume true because the request succeeded if (!$key) { return true; } if (!($result = $model->getPath($key))) { return false; } $total = $matches = 0; foreach ((array) $result as $value) { $total++; foreach ((array) $checkValue as $check) { if ($value == $check) { $matches++; break; } } } // When matching all values, ensure that the match count matches the total count if ($all && $total != $matches) { return false; } return $matches > 0; } } CamelCase). */ class WaiterClassFactory implements WaiterFactoryInterface { /** * @var array List of namespaces used to look for classes */ protected $namespaces; /** * @var InflectorInterface Inflector used to inflect class names */ protected $inflector; /** * @param array|string $namespaces Namespaces of waiter objects * @param InflectorInterface $inflector Inflector used to resolve class names */ public function __construct($namespaces = array(), InflectorInterface $inflector = null) { $this->namespaces = (array) $namespaces; $this->inflector = $inflector ?: Inflector::getDefault(); } /** * Registers a namespace to check for Waiters * * @param string $namespace Namespace which contains Waiter classes * * @return self */ public function registerNamespace($namespace) { array_unshift($this->namespaces, $namespace); return $this; } /** * {@inheritdoc} */ public function build($waiter) { if (!($className = $this->getClassName($waiter))) { throw new InvalidArgumentException("Waiter was not found matching {$waiter}."); } return new $className(); } /** * {@inheritdoc} */ public function canBuild($waiter) { return $this->getClassName($waiter) !== null; } /** * Get the name of a waiter class * * @param string $waiter Waiter name * * @return string|null */ protected function getClassName($waiter) { $waiterName = $this->inflector->camel($waiter); // Determine the name of the class to load $className = null; foreach ($this->namespaces as $namespace) { $potentialClassName = $namespace . '\\' . $waiterName; if (class_exists($potentialClassName)) { return $potentialClassName; } } return null; } } data = $data; $this->extractConfig(); } /** * Create the command configuration variables */ protected function extractConfig() { // Populate success.* and failure.* if specified in acceptor.* foreach ($this->data as $key => $value) { if (substr($key, 0, 9) == 'acceptor.') { $name = substr($key, 9); if (!isset($this->data["success.{$name}"])) { $this->data["success.{$name}"] = $value; } if (!isset($this->data["failure.{$name}"])) { $this->data["failure.{$name}"] = $value; } unset($this->data[$key]); } } } } config = $config; $this->inflector = $inflector ?: Inflector::getDefault(); } /** * {@inheritdoc} */ public function build($waiter) { return new ConfigResourceWaiter($this->getWaiterConfig($waiter)); } /** * {@inheritdoc} */ public function canBuild($waiter) { return isset($this->config[$waiter]) || isset($this->config[$this->inflector->camel($waiter)]); } /** * Get waiter configuration data, taking __default__ and extensions into account * * @param string $name Waiter name * * @return WaiterConfig * @throws InvalidArgumentException */ protected function getWaiterConfig($name) { if (!$this->canBuild($name)) { throw new InvalidArgumentException('No waiter found matching "' . $name . '"'); } // inflect the name if needed $name = isset($this->config[$name]) ? $name : $this->inflector->camel($name); $waiter = new WaiterConfig($this->config[$name]); $waiter['name'] = $name; // Always use __default__ as the basis if it's set if (isset($this->config['__default__'])) { $parentWaiter = new WaiterConfig($this->config['__default__']); $waiter = $parentWaiter->overwriteWith($waiter); } // Allow for configuration extensions if (isset($this->config[$name]['extends'])) { $waiter = $this->getWaiterConfig($this->config[$name]['extends'])->overwriteWith($waiter); } return $waiter; } } array('onCommandBeforePrepare', -255)); } /** * An event handler for constructing ACP definitions. * * @param Event $event The event to respond to. * * @throws InvalidArgumentException */ public function onCommandBeforePrepare(Event $event) { /** @var $command \Guzzle\Service\Command\AbstractCommand */ $command = $event['command']; $operation = $command->getOperation(); if ($operation->hasParam('ACP') && $command->hasKey('ACP')) { if ($acp = $command->get('ACP')) { // Ensure that the correct object was passed if (!($acp instanceof Acp)) { throw new InvalidArgumentException('ACP must be an instance of Aws\S3\Model\Acp'); } // Check if the user specified both an ACP and Grants if ($command->hasKey('Grants')) { throw new InvalidArgumentException( 'Use either the ACP parameter or the Grants parameter. Do not use both.' ); } // Add the correct headers/body based parameters to the command if ($operation->hasParam('Grants')) { $command->overwriteWith($acp->toArray()); } else { $acp->updateCommand($command); } } // Remove the ACP parameter $command->remove('ACP'); } } } true); public static function getSubscribedEvents() { return array('command.after_prepare' => array('onCommandAfterPrepare', -255)); } /** * Changes how buckets are referenced in the HTTP request * * @param Event $event Event emitted */ public function onCommandAfterPrepare(Event $event) { $command = $event['command']; $bucket = $command['Bucket']; $request = $command->getRequest(); $pathStyle = false; // Skip operations that do not need the bucket moved to the host. if (isset(self::$exclusions[$command->getName()])) { return; } if ($key = $command['Key']) { // Modify the command Key to account for the {/Key*} explosion into an array if (is_array($key)) { $command['Key'] = $key = implode('/', $key); } } // Set the key and bucket on the request $request->getParams()->set('bucket', $bucket)->set('key', $key); // Switch to virtual if PathStyle is disabled, or not a DNS compatible bucket name, or the scheme is // http, or the scheme is https and there are no dots in the host header (avoids SSL issues) if (!$command['PathStyle'] && $command->getClient()->isValidBucketName($bucket) && !($command->getRequest()->getScheme() == 'https' && strpos($bucket, '.')) ) { // Switch to virtual hosted bucket $request->setHost($bucket . '.' . $request->getHost()); $request->setPath(preg_replace("#^/{$bucket}#", '', $request->getPath())); } else { $pathStyle = true; } if (!$bucket) { $request->getParams()->set('s3.resource', '/'); } elseif ($pathStyle) { // Path style does not need a trailing slash $request->getParams()->set( 's3.resource', '/' . rawurlencode($bucket) . ($key ? ('/' . S3Client::encodeKey($key)) : '') ); } else { // Bucket style needs a trailing slash $request->getParams()->set( 's3.resource', '/' . rawurlencode($bucket) . ($key ? ('/' . S3Client::encodeKey($key)) : '/') ); } } } client->createPresignedUrl($this->prepare(), $expires); } /** * {@inheritdoc} */ protected function process() { $request = $this->getRequest(); $response = $this->getResponse(); // Dispatch an error if a 301 redirect occurred if ($response->getStatusCode() == 301) { $this->getClient()->getEventDispatcher()->dispatch('request.error', new Event(array( 'request' => $this->getRequest(), 'response' => $response ))); } parent::process(); // Set the GetObject URL if using the PutObject operation if ($this->result instanceof Model && $this->getName() == 'PutObject') { $this->result->set('ObjectURL', $request->getUrl()); } } } errors = $errors; } /** * Get the errored objects * * @return array Returns an array of associative arrays, each containing * a 'Code', 'Message', and 'Key' key. */ public function getErrors() { return $this->errors; } } getStatusCode() === 301) { $data['type'] = 'client'; if (isset($data['message'], $data['parsed'])) { $data['message'] = rtrim($data['message'], '.') . ': "' . $data['parsed']->Endpoint . '".'; } } return $data; } /** * {@inheritdoc} */ protected function parseHeaders(RequestInterface $request, Response $response, array &$data) { parent::parseHeaders($request, $response, $data); // Get the request $status = $response->getStatusCode(); $method = $request->getMethod(); // Attempt to determine code for 403s and 404s if ($status === 403) { $data['code'] = 'AccessDenied'; } elseif ($method === 'HEAD' && $status === 404) { $path = explode('/', trim($request->getPath(), '/')); $host = explode('.', $request->getHost()); $bucket = (count($host) === 4) ? $host[0] : array_shift($path); $object = array_shift($path); if ($bucket && $object) { $data['code'] = 'NoSuchKey'; } elseif ($bucket) { $data['code'] = 'NoSuchBucket'; } } } } get('Buckets') ?: array(); // If only the names_only set, change arrays to a string if ($this->get('names_only')) { foreach ($buckets as &$bucket) { $bucket = $bucket['Name']; } } return $buckets; } } get('Uploads') ?: array(); // If there are prefixes and we want them, merge them in if ($this->get('return_prefixes') && $result->hasKey('CommonPrefixes')) { $uploads = array_merge($uploads, $result->get('CommonPrefixes')); } return $uploads; } } get('Contents') ?: array(); $numObjects = count($objects); $lastKey = $numObjects ? $objects[$numObjects - 1]['Key'] : false; if ($lastKey && !$result->hasKey($this->get('output_token'))) { $result->set($this->get('output_token'), $lastKey); } // Closure for getting the name of an object or prefix $getName = function ($object) { return isset($object['Key']) ? $object['Key'] : $object['Prefix']; }; // If common prefixes returned (i.e. a delimiter was set) and they need to be returned, there is more to do if ($this->get('return_prefixes') && $result->hasKey('CommonPrefixes')) { // Collect and format the prefixes to include with the objects $objects = array_merge($objects, $result->get('CommonPrefixes')); // Sort the objects and prefixes to maintain alphabetical order, but only if some of each were returned if ($this->get('sort_results') && $lastKey && $objects) { usort($objects, function ($object1, $object2) use ($getName) { return strcmp($getName($object1), $getName($object2)); }); } } // If only the names are desired, iterate through the results and convert the arrays to the object/prefix names if ($this->get('names_only')) { $objects = array_map($getName, $objects); } return $objects; } } get('Versions') ?: array(); $deleteMarkers = $result->get('DeleteMarkers') ?: array(); $versions = array_merge($versions, $deleteMarkers); // If there are prefixes and we want them, merge them in if ($this->get('return_prefixes') && $result->hasKey('CommonPrefixes')) { $versions = array_merge($versions, $result->get('CommonPrefixes')); } return $versions; } } filePrefix = $filePrefix; $this->dirHandle = $dirHandle; $this->next(); } public function __destruct() { if ($this->dirHandle) { closedir($this->dirHandle); } } public function rewind() { $this->key = 0; rewinddir($this->dirHandle); } public function current() { return $this->currentFile; } public function next() { if ($file = readdir($this->dirHandle)) { $this->currentFile = new \SplFileInfo($this->filePrefix . $file); } else { $this->currentFile = false; } $this->key++; } public function key() { return $this->key; } public function valid() { return $this->currentFile !== false; } } setOwner($owner); $this->setGrants($grants); } /** * Create an Acp object from an array. This can be used to create an ACP from a response to a GetObject/Bucket ACL * operation. * * @param array $data Array of ACP data * * @return Acp */ public static function fromArray(array $data) { $builder = new AcpBuilder(); $builder->setOwner((string) $data['Owner']['ID'], $data['Owner']['DisplayName']); // Add each Grantee to the ACP foreach ($data['Grants'] as $grant) { $permission = $grant['Permission']; // Determine the type for response bodies that are missing the Type parameter if (!isset($grant['Grantee']['Type'])) { if (isset($grant['Grantee']['ID'])) { $grant['Grantee']['Type'] = 'CanonicalUser'; } elseif (isset($grant['Grantee']['URI'])) { $grant['Grantee']['Type'] = 'Group'; } else { $grant['Grantee']['Type'] = 'AmazonCustomerByEmail'; } } switch ($grant['Grantee']['Type']) { case 'Group': $builder->addGrantForGroup($permission, $grant['Grantee']['URI']); break; case 'AmazonCustomerByEmail': $builder->addGrantForEmail($permission, $grant['Grantee']['EmailAddress']); break; case 'CanonicalUser': $builder->addGrantForUser( $permission, $grant['Grantee']['ID'], $grant['Grantee']['DisplayName'] ); } } return $builder->build(); } /** * Set the owner of the ACP policy * * @param Grantee $owner ACP policy owner * * @return $this * * @throws InvalidArgumentException if the grantee does not have an ID set */ public function setOwner(Grantee $owner) { if (!$owner->isCanonicalUser()) { throw new InvalidArgumentException('The owner must have an ID set.'); } $this->owner = $owner; return $this; } /** * Get the owner of the ACP policy * * @return Grantee */ public function getOwner() { return $this->owner; } /** * Set the grants for the ACP * * @param array|\Traversable $grants List of grants for the ACP * * @return $this * * @throws InvalidArgumentException */ public function setGrants($grants = array()) { $this->grants = new \SplObjectStorage(); if ($grants) { if (is_array($grants) || $grants instanceof \Traversable) { /** @var $grant Grant */ foreach ($grants as $grant) { $this->addGrant($grant); } } else { throw new InvalidArgumentException('Grants must be passed in as an array or Traversable object.'); } } return $this; } /** * Get all of the grants * * @return \SplObjectStorage */ public function getGrants() { return $this->grants; } /** * Add a Grant * * @param Grant $grant Grant to add * * @return $this */ public function addGrant(Grant $grant) { if (count($this->grants) < 100) { $this->grants->attach($grant); } else { throw new OverflowException('An ACP may contain up to 100 grants.'); } return $this; } /** * Get the total number of attributes * * @return int */ public function count() { return count($this->grants); } /** * Returns the grants for iteration * * @return \SplObjectStorage */ public function getIterator() { return $this->grants; } /** * Applies grant headers to a command's parameters * * @param AbstractCommand $command Command to be updated * * @return $this */ public function updateCommand(AbstractCommand $command) { $parameters = array(); foreach ($this->grants as $grant) { /** @var $grant Grant */ $parameters = array_merge_recursive($parameters, $grant->getParameterArray()); } foreach ($parameters as $name => $values) { $command->set($name, implode(', ', (array) $values)); } return $this; } /** * {@inheritdoc} */ public function toArray() { $grants = array(); foreach ($this->grants as $grant) { $grants[] = $grant->toArray(); } return array( 'Owner' => array( 'ID' => $this->owner->getId(), 'DisplayName' => $this->owner->getDisplayName() ), 'Grants' => $grants ); } } owner = new Grantee($id, $displayName ?: $id, GranteeType::USER); return $this; } /** * Create and store a Grant with a CanonicalUser Grantee for the ACL * * @param string $permission Permission for the Grant * @param string $id Grantee identifier * @param string $displayName Grantee display name * * @return $this */ public function addGrantForUser($permission, $id, $displayName = null) { $grantee = new Grantee($id, $displayName ?: $id, GranteeType::USER); $this->addGrant($permission, $grantee); return $this; } /** * Create and store a Grant with a AmazonCustomerByEmail Grantee for the ACL * * @param string $permission Permission for the Grant * @param string $email Grantee email address * * @return $this */ public function addGrantForEmail($permission, $email) { $grantee = new Grantee($email, null, GranteeType::EMAIL); $this->addGrant($permission, $grantee); return $this; } /** * Create and store a Grant with a Group Grantee for the ACL * * @param string $permission Permission for the Grant * @param string $group Grantee group * * @return $this */ public function addGrantForGroup($permission, $group) { $grantee = new Grantee($group, null, GranteeType::GROUP); $this->addGrant($permission, $grantee); return $this; } /** * Create and store a Grant for the ACL * * @param string $permission Permission for the Grant * @param Grantee $grantee The Grantee for the Grant * * @return $this */ public function addGrant($permission, Grantee $grantee) { $this->grants[] = new Grant($grantee, $permission); return $this; } /** * Builds the ACP and returns it * * @return Acp */ public function build() { return new Acp($this->owner, $this->grants); } } client = $client; $this->bucket = $bucket; } /** * {@inheritdoc} */ public static function getAllEvents() { return array(self::AFTER_DELETE, self::BEFORE_CLEAR, self::AFTER_CLEAR); } /** * Set the bucket that is to be cleared * * @param string $bucket Name of the bucket to clear * * @return $this */ public function setBucket($bucket) { $this->bucket = $bucket; return $this; } /** * Get the iterator used to yield the keys to be deleted. A default iterator * will be created and returned if no iterator has been explicitly set. * * @return \Iterator */ public function getIterator() { if (!$this->iterator) { $this->iterator = $this->client->getIterator('ListObjectVersions', array( 'Bucket' => $this->bucket )); } return $this->iterator; } /** * Sets a different iterator to use than the default iterator. This can be helpful when you wish to delete * only specific keys from a bucket (e.g. keys that match a certain prefix or delimiter, or perhaps keys that * pass through a filtered, decorated iterator). * * @param \Iterator $iterator Iterator used to yield the keys to be deleted * * @return $this */ public function setIterator(\Iterator $iterator) { $this->iterator = $iterator; return $this; } /** * Set the MFA token to send with each request * * @param string $mfa MFA token to send with each request. The value is the concatenation of the authentication * device's serial number, a space, and the value displayed on your authentication device. * * @return $this */ public function setMfa($mfa) { $this->mfa = $mfa; return $this; } /** * Clear the bucket * * @return int Returns the number of deleted keys * @throws ExceptionCollection */ public function clear() { $that = $this; $batch = DeleteObjectsBatch::factory($this->client, $this->bucket, $this->mfa); $batch = new NotifyingBatch($batch, function ($items) use ($that) { $that->dispatch(ClearBucket::AFTER_DELETE, array('keys' => $items)); }); $batch = new FlushingBatch(new ExceptionBufferingBatch($batch), 1000); // Let any listeners know that the bucket is about to be cleared $this->dispatch(self::BEFORE_CLEAR, array( 'iterator' => $this->getIterator(), 'batch' => $batch, 'mfa' => $this->mfa )); $deleted = 0; foreach ($this->getIterator() as $object) { if (isset($object['VersionId'])) { $versionId = $object['VersionId'] == 'null' ? null : $object['VersionId']; } else { $versionId = null; } $batch->addKey($object['Key'], $versionId); $deleted++; } $batch->flush(); // If any errors were encountered, then throw an ExceptionCollection if (count($batch->getExceptions())) { $e = new ExceptionCollection(); foreach ($batch->getExceptions() as $exception) { $e->add($exception->getPrevious()); } throw $e; } // Let any listeners know that the bucket was cleared $this->dispatch(self::AFTER_CLEAR, array('deleted' => $deleted)); return $deleted; } } %s, VersionId => %s] and call flush when the objects * should be deleted. */ class DeleteObjectsBatch extends AbstractBatchDecorator { /** * Factory for creating a DeleteObjectsBatch * * @param AwsClientInterface $client Client used to transfer requests * @param string $bucket Bucket that contains the objects to delete * @param string $mfa MFA token to use with the request * * @return static */ public static function factory(AwsClientInterface $client, $bucket, $mfa = null) { $batch = BatchBuilder::factory() ->createBatchesWith(new BatchSizeDivisor(1000)) ->transferWith(new DeleteObjectsTransfer($client, $bucket, $mfa)) ->build(); return new static($batch); } /** * Add an object to be deleted * * @param string $key Key of the object * @param string $versionId VersionID of the object * * @return $this */ public function addKey($key, $versionId = null) { return $this->add(array( 'Key' => $key, 'VersionId' => $versionId )); } /** * {@inheritdoc} */ public function add($item) { if ($item instanceof AbstractCommand && $item->getName() == 'DeleteObject') { $item = array( 'Key' => $item['Key'], 'VersionId' => $item['VersionId'] ); } if (!is_array($item) || (!isset($item['Key']))) { throw new InvalidArgumentException('Item must be a DeleteObject command or array containing a Key and VersionId key.'); } return parent::add($item); } } client = $client; $this->bucket = $bucket; $this->mfa = $mfa; } /** * Set a new MFA token value * * @param string $token MFA token * * @return $this */ public function setMfa($token) { $this->mfa = $token; return $this; } /** * {@inheritdoc} * @throws OverflowException if a batch has more than 1000 items * @throws InvalidArgumentException when an invalid batch item is encountered */ public function transfer(array $batch) { if (empty($batch)) { return; } if (count($batch) > 1000) { throw new OverflowException('Batches should be divided into chunks of no larger than 1000 keys'); } $del = array(); $command = $this->client->getCommand('DeleteObjects', array( 'Bucket' => $this->bucket, Ua::OPTION => Ua::BATCH )); if ($this->mfa) { $command->getRequestHeaders()->set('x-amz-mfa', $this->mfa); } foreach ($batch as $object) { // Ensure that the batch item is valid if (!is_array($object) || !isset($object['Key'])) { throw new InvalidArgumentException('Invalid batch item encountered: ' . var_export($batch, true)); } $del[] = array( 'Key' => $object['Key'], 'VersionId' => isset($object['VersionId']) ? $object['VersionId'] : null ); } $command['Objects'] = $del; $command->execute(); $this->processResponse($command); } /** * Process the response of the DeleteMultipleObjects request * * @paramCommandInterface $command Command executed */ protected function processResponse(CommandInterface $command) { $result = $command->getResult(); // Ensure that the objects were deleted successfully if (!empty($result['Errors'])) { $errors = $result['Errors']; throw new DeleteMultipleObjectsException($errors); } } } 'GrantRead', Permission::WRITE => 'GrantWrite', Permission::READ_ACP => 'GrantReadACP', Permission::WRITE_ACP => 'GrantWriteACP', Permission::FULL_CONTROL => 'GrantFullControl' ); /** * @var Grantee The grantee affected by the grant */ protected $grantee; /** * @var string The permission set by the grant */ protected $permission; /** * Constructs an ACL * * @param Grantee $grantee Affected grantee * @param string $permission Permission applied */ public function __construct(Grantee $grantee, $permission) { $this->setGrantee($grantee); $this->setPermission($permission); } /** * Set the grantee affected by the grant * * @param Grantee $grantee Affected grantee * * @return $this */ public function setGrantee(Grantee $grantee) { $this->grantee = $grantee; return $this; } /** * Get the grantee affected by the grant * * @return Grantee */ public function getGrantee() { return $this->grantee; } /** * Set the permission set by the grant * * @param string $permission Permission applied * * @return $this * * @throws InvalidArgumentException */ public function setPermission($permission) { $valid = Permission::values(); if (!in_array($permission, $valid)) { throw new InvalidArgumentException('The permission must be one of ' . 'the following: ' . implode(', ', $valid) . '.'); } $this->permission = $permission; return $this; } /** * Get the permission set by the grant * * @return string */ public function getPermission() { return $this->permission; } /** * Returns an array of the operation parameter and value to set on the operation * * @return array */ public function getParameterArray() { return array( self::$parameterMap[$this->permission] => $this->grantee->getHeaderValue() ); } /** * {@inheritdoc} */ public function toArray() { return array( 'Grantee' => $this->grantee->toArray(), 'Permission' => $this->permission ); } } 'id', GranteeType::EMAIL => 'emailAddress', GranteeType::GROUP => 'uri' ); /** * @var string The account ID, email, or URL identifying the grantee */ protected $id; /** * @var string The display name of the grantee */ protected $displayName; /** * @var string The type of the grantee (CanonicalUser or Group) */ protected $type; /** * Constructs a Grantee * * @param string $id Grantee identifier * @param string $displayName Grantee display name * @param string $expectedType The expected type of the grantee */ public function __construct($id, $displayName = null, $expectedType = null) { $this->type = GranteeType::USER; $this->setId($id, $expectedType); $this->setDisplayName($displayName); } /** * Sets the account ID, email, or URL identifying the grantee * * @param string $id Grantee identifier * @param string $expectedType The expected type of the grantee * * @return Grantee * * @throws UnexpectedValueException if $expectedType is set and the grantee * is not of that type after instantiation * @throws InvalidArgumentException when the ID provided is not a string */ public function setId($id, $expectedType = null) { if (in_array($id, Group::values())) { $this->type = GranteeType::GROUP; } elseif (!is_string($id)) { throw new InvalidArgumentException('The grantee ID must be provided as a string value.'); } if (strpos($id, '@') !== false) { $this->type = GranteeType::EMAIL; } if ($expectedType && $expectedType !== $this->type) { throw new UnexpectedValueException('The type of the grantee after ' . 'setting the ID did not match the specified, expected type "' . $expectedType . '" but received "' . $this->type . '".'); } $this->id = $id; return $this; } /** * Gets the grantee identifier * * @return string */ public function getId() { return $this->id; } /** * Gets the grantee email address (if it is set) * * @return null|string */ public function getEmailAddress() { return $this->isAmazonCustomerByEmail() ? $this->id : null; } /** * Gets the grantee URI (if it is set) * * @return null|string */ public function getGroupUri() { return $this->isGroup() ? $this->id : null; } /** * Sets the display name of the grantee * * @param string $displayName Grantee name * * @return Grantee * * @throws LogicException when the grantee type not CanonicalUser */ public function setDisplayName($displayName) { if ($this->type === GranteeType::USER) { if (empty($displayName) || !is_string($displayName)) { $displayName = $this->id; } $this->displayName = $displayName; } else { if ($displayName) { throw new LogicException('The display name can only be set ' . 'for grantees specified by ID.'); } } return $this; } /** * Gets the grantee display name * * @return string */ public function getDisplayName() { return $this->displayName; } /** * Gets the grantee type (determined by ID) * * @return string */ public function getType() { return $this->type; } /** * Returns true if this grantee object represents a canonical user by ID * * @return bool */ public function isCanonicalUser() { return ($this->type === GranteeType::USER); } /** * Returns true if this grantee object represents a customer by email * * @return bool */ public function isAmazonCustomerByEmail() { return ($this->type === GranteeType::EMAIL); } /** * Returns true if this grantee object represents a group by URL * * @return bool */ public function isGroup() { return ($this->type === GranteeType::GROUP); } /** * Returns the value used in headers to specify this grantee * * @return string */ public function getHeaderValue() { $key = static::$headerMap[$this->type]; return "{$key}=\"{$this->id}\""; } /** * {@inheritdoc} */ public function toArray() { $result = array( 'Type' => $this->type ); switch ($this->type) { case GranteeType::USER: $result['ID'] = $this->id; $result['DisplayName'] = $this->displayName; break; case GranteeType::EMAIL: $result['EmailAddress'] = $this->id; break; case GranteeType::GROUP: $result['URI'] = $this->id; } return $result; } } options = array_replace(array( 'min_part_size' => self::MIN_PART_SIZE, 'part_md5' => true ), $this->options); // Make sure the part size can be calculated somehow if (!$this->options['min_part_size'] && !$this->source->getContentLength()) { throw new RuntimeException('The ContentLength of the data source could not be determined, and no ' . 'min_part_size option was provided'); } } /** * {@inheritdoc} */ protected function calculatePartSize() { $partSize = $this->source->getContentLength() ? (int) ceil(($this->source->getContentLength() / self::MAX_PARTS)) : self::MIN_PART_SIZE; $partSize = max($this->options['min_part_size'], $partSize); $partSize = min($partSize, self::MAX_PART_SIZE); $partSize = max($partSize, self::MIN_PART_SIZE); return $partSize; } /** * {@inheritdoc} */ protected function complete() { /** @var $part UploadPart */ $parts = array(); foreach ($this->state as $part) { $parts[] = array( 'PartNumber' => $part->getPartNumber(), 'ETag' => $part->getETag(), ); } $params = $this->state->getUploadId()->toParams(); $params[Ua::OPTION] = Ua::MULTIPART_UPLOAD; $params['Parts'] = $parts; $command = $this->client->getCommand('CompleteMultipartUpload', $params); return $command->getResult(); } /** * {@inheritdoc} */ protected function getAbortCommand() { $params = $this->state->getUploadId()->toParams(); $params[Ua::OPTION] = Ua::MULTIPART_UPLOAD; /** @var $command OperationCommand */ $command = $this->client->getCommand('AbortMultipartUpload', $params); return $command; } } source->isLocal() || $this->source->getWrapper() != 'plainfile') { throw new RuntimeException('The source data must be a local file stream when uploading in parallel.'); } if (empty($this->options['concurrency'])) { throw new RuntimeException('The `concurrency` option must be specified when instantiating.'); } } /** * {@inheritdoc} */ protected function transfer() { $totalParts = (int) ceil($this->source->getContentLength() / $this->partSize); $concurrency = min($totalParts, $this->options['concurrency']); $partsToSend = $this->prepareParts($concurrency); $eventData = $this->getEventData(); while (!$this->stopped && count($this->state) < $totalParts) { $currentTotal = count($this->state); $commands = array(); for ($i = 0; $i < $concurrency && $i + $currentTotal < $totalParts; $i++) { // Move the offset to the correct position $partsToSend[$i]->setOffset(($currentTotal + $i) * $this->partSize); // @codeCoverageIgnoreStart if ($partsToSend[$i]->getContentLength() == 0) { break; } // @codeCoverageIgnoreEnd $params = $this->state->getUploadId()->toParams(); $eventData['command'] = $this->client->getCommand('UploadPart', array_replace($params, array( 'PartNumber' => count($this->state) + 1 + $i, 'Body' => $partsToSend[$i], 'ContentMD5' => (bool) $this->options['part_md5'], Ua::OPTION => Ua::MULTIPART_UPLOAD ))); $commands[] = $eventData['command']; // Notify any listeners of the part upload $this->dispatch(self::BEFORE_PART_UPLOAD, $eventData); } // Allow listeners to stop the transfer if needed if ($this->stopped) { break; } // Execute each command, iterate over the results, and add to the transfer state /** @var $command \Guzzle\Service\Command\OperationCommand */ foreach ($this->client->execute($commands) as $command) { $this->state->addPart(UploadPart::fromArray(array( 'PartNumber' => count($this->state) + 1, 'ETag' => $command->getResponse()->getEtag(), 'Size' => (int) $command->getResponse()->getContentLength(), 'LastModified' => gmdate(DateFormat::RFC2822) ))); $eventData['command'] = $command; // Notify any listeners the the part was uploaded $this->dispatch(self::AFTER_PART_UPLOAD, $eventData); } } } /** * Prepare the entity body handles to use while transferring * * @param int $concurrency Number of parts to prepare * * @return array Parts to send */ protected function prepareParts($concurrency) { $url = $this->source->getUri(); // Use the source EntityBody as the first part $parts = array(new ReadLimitEntityBody($this->source, $this->partSize)); // Open EntityBody handles for each part to upload in parallel for ($i = 1; $i < $concurrency; $i++) { $parts[] = new ReadLimitEntityBody(new EntityBody(fopen($url, 'r')), $this->partSize); } return $parts; } } stopped && !$this->source->isConsumed()) { if ($this->source->getContentLength() && $this->source->isSeekable()) { // If the stream is seekable and the Content-Length known, then stream from the data source $body = new ReadLimitEntityBody($this->source, $this->partSize, $this->source->ftell()); } else { // We need to read the data source into a temporary buffer before streaming $body = EntityBody::factory(); while ($body->getContentLength() < $this->partSize && $body->write( $this->source->read(max(1, min(10 * Size::KB, $this->partSize - $body->getContentLength()))) )); } // @codeCoverageIgnoreStart if ($body->getContentLength() == 0) { break; } // @codeCoverageIgnoreEnd $params = $this->state->getUploadId()->toParams(); $command = $this->client->getCommand('UploadPart', array_replace($params, array( 'PartNumber' => count($this->state) + 1, 'Body' => $body, 'ContentMD5' => (bool) $this->options['part_md5'], Ua::OPTION => Ua::MULTIPART_UPLOAD ))); // Notify observers that the part is about to be uploaded $eventData = $this->getEventData(); $eventData['command'] = $command; $this->dispatch(self::BEFORE_PART_UPLOAD, $eventData); // Allow listeners to stop the transfer if needed if ($this->stopped) { break; } $response = $command->getResponse(); $this->state->addPart(UploadPart::fromArray(array( 'PartNumber' => count($this->state) + 1, 'ETag' => $response->getEtag(), 'Size' => $body->getContentLength(), 'LastModified' => gmdate(DateFormat::RFC2822) ))); // Notify observers that the part was uploaded $this->dispatch(self::AFTER_PART_UPLOAD, $eventData); } } } getIterator('ListParts', $uploadId->toParams()) as $part) { $transferState->addPart(UploadPart::fromArray($part)); } return $transferState; } } setOption('Bucket', $bucket); } /** * Set the key of the object * * @param string $key Key of the object to upload * * @return $this */ public function setKey($key) { return $this->setOption('Key', $key); } /** * Set the minimum acceptable part size * * @param int $minSize Minimum acceptable part size in bytes * * @return $this */ public function setMinPartSize($minSize) { $this->minPartSize = (int) max((int) $minSize, AbstractTransfer::MIN_PART_SIZE); return $this; } /** * Set the concurrency level to use when uploading parts. This affects how * many parts are uploaded in parallel. You must use a local file as your * data source when using a concurrency greater than 1 * * @param int $concurrency Concurrency level * * @return $this */ public function setConcurrency($concurrency) { $this->concurrency = $concurrency; return $this; } /** * Explicitly set the MD5 hash of the entire body * * @param string $md5 MD5 hash of the entire body * * @return $this */ public function setMd5($md5) { $this->md5 = $md5; return $this; } /** * Set to true to have the builder calculate the MD5 hash of the entire data * source before initiating a multipart upload (this could be an expensive * operation). This setting can ony be used with seekable data sources. * * @param bool $calculateMd5 Set to true to calculate the MD5 hash of the body * * @return $this */ public function calculateMd5($calculateMd5) { $this->calculateEntireMd5 = (bool) $calculateMd5; return $this; } /** * Specify whether or not to calculate the MD5 hash of each uploaded part. * This setting defaults to true. * * @param bool $usePartMd5 Set to true to calculate the MD5 has of each part * * @return $this */ public function calculatePartMd5($usePartMd5) { $this->calculatePartMd5 = (bool) $usePartMd5; return $this; } /** * Set the ACP to use on the object * * @param Acp $acp ACP to set on the object * * @return $this */ public function setAcp(Acp $acp) { return $this->setOption('ACP', $acp); } /** * Set an option to pass to the initial CreateMultipartUpload operation * * @param string $name Option name * @param string $value Option value * * @return $this */ public function setOption($name, $value) { $this->commandOptions[$name] = $value; return $this; } /** * Add an array of options to pass to the initial CreateMultipartUpload operation * * @param array $options Array of CreateMultipartUpload operation parameters * * @return $this */ public function addOptions(array $options) { $this->commandOptions = array_replace($this->commandOptions, $options); return $this; } /** * Set an array of transfer options to apply to the upload transfer object * * @param array $options Transfer options * * @return $this */ public function setTransferOptions(array $options) { $this->transferOptions = $options; return $this; } /** * {@inheritdoc} * @throws InvalidArgumentException when attempting to resume a transfer using a non-seekable stream * @throws InvalidArgumentException when missing required properties (bucket, key, client, source) */ public function build() { if ($this->state instanceof TransferState) { $this->commandOptions = array_replace($this->commandOptions, $this->state->getUploadId()->toParams()); } if (!isset($this->commandOptions['Bucket']) || !isset($this->commandOptions['Key']) || !$this->client || !$this->source ) { throw new InvalidArgumentException('You must specify a Bucket, Key, client, and source.'); } if ($this->state && !$this->source->isSeekable()) { throw new InvalidArgumentException('You cannot resume a transfer using a non-seekable source.'); } // If no state was set, then create one by initiating or loading a multipart upload if (is_string($this->state)) { $this->state = TransferState::fromUploadId($this->client, UploadId::fromParams(array( 'Bucket' => $this->commandOptions['Bucket'], 'Key' => $this->commandOptions['Key'], 'UploadId' => $this->state ))); } elseif (!$this->state) { $this->state = $this->initiateMultipartUpload(); } $options = array_replace(array( 'min_part_size' => $this->minPartSize, 'part_md5' => (bool) $this->calculatePartMd5, 'concurrency' => $this->concurrency ), $this->transferOptions); return $this->concurrency > 1 ? new ParallelTransfer($this->client, $this->state, $this->source, $options) : new SerialTransfer($this->client, $this->state, $this->source, $options); } /** * {@inheritdoc} */ protected function initiateMultipartUpload() { // Determine Content-Type if (!isset($this->commandOptions['ContentType'])) { if ($mimeType = $this->source->getContentType()) { $this->commandOptions['ContentType'] = $mimeType; } } $params = array_replace(array( Ua::OPTION => Ua::MULTIPART_UPLOAD, 'command.headers' => $this->headers, 'Metadata' => array() ), $this->commandOptions); // Calculate the MD5 hash if none was set and it is asked of the builder if ($this->calculateEntireMd5) { $this->md5 = $this->source->getContentMd5(); } // If an MD5 is specified, then add it to the custom headers of the request // so that it will be returned when downloading the object from Amazon S3 if ($this->md5) { $params['Metadata']['x-amz-Content-MD5'] = $this->md5; } $result = $this->client->getCommand('CreateMultipartUpload', $params)->execute(); // Create a new state based on the initiated upload $params['UploadId'] = $result['UploadId']; return new TransferState(UploadId::fromParams($params)); } } false, 'Key' => false, 'UploadId' => false ); } 'partNumber', 'ETag' => 'eTag', 'LastModified' => 'lastModified', 'Size' => 'size' ); /** * @var string The ETag for this part */ protected $eTag; /** * @var string The last modified date */ protected $lastModified; /** * @var int The size (or content-length) in bytes of the upload body */ protected $size; /** * @return string */ public function getETag() { return $this->eTag; } /** * @return string */ public function getLastModified() { return $this->lastModified; } /** * @return int */ public function getSize() { return $this->size; } } tag attributes as an array */ protected $formAttributes; /** * @var array The form's elements as an array */ protected $formInputs; /** * @var string The raw json policy */ protected $jsonPolicy; /** * Constructs the PostObject * * The options array accepts the following keys: * * - acl: The access control setting to apply to the uploaded file. Accepts any of the * CannedAcl constants * - Cache-Control: The Cache-Control HTTP header value to apply to the uploaded file * - Content-Disposition: The Content-Disposition HTTP header value to apply to the uploaded file * - Content-Encoding: The Content-Encoding HTTP header value to apply to the uploaded file * - Content-Type: The Content-Type HTTP header value to apply to the uploaded file. The default * value is `application/octet-stream` * - Expires: The Expires HTTP header value to apply to the uploaded file * - key: The location where the file should be uploaded to. The default value is * `^${filename}` which will use the name of the uploaded file * - policy: A raw policy in JSON format. By default, the PostObject creates one for you * - policy_callback: A callback used to modify the policy before encoding and signing it. The * method signature for the callback should accept an array of the policy data as * the 1st argument, (optionally) the PostObject as the 2nd argument, and return * the policy data with the desired modifications. * - success_action_redirect: The URI for Amazon S3 to redirect to upon successful upload * - success_action_status: The status code for Amazon S3 to return upon successful upload * - ttd: The expiration time for the generated upload form data * - x-amz-meta-*: Any custom meta tag that should be set to the object * - x-amz-server-side-encryption: The server-side encryption mechanism to use * - x-amz-storage-class: The storage setting to apply to the object * - x-amz-server-side​-encryption​-customer-algorithm: The SSE-C algorithm * - x-amz-server-side​-encryption​-customer-key: The SSE-C customer secret key * - x-amz-server-side​-encryption​-customer-key-MD5: The MD5 hash of the SSE-C customer secret key * * For the Cache-Control, Content-Disposition, Content-Encoding, * Content-Type, Expires, and key options, to use a "starts-with" comparison * instead of an equals comparison, prefix the value with a ^ (carat) * character * * @param S3Client $client * @param $bucket * @param array $options */ public function __construct(S3Client $client, $bucket, array $options = array()) { $this->setClient($client); $this->setBucket($bucket); parent::__construct($options); } /** * Analyzes the provided data and turns it into useful data that can be * consumed and used to build an upload form * * @return PostObject */ public function prepareData() { // Validate required options $options = Collection::fromConfig($this->data, array( 'ttd' => '+1 hour', 'key' => '^${filename}', )); // Format ttd option $ttd = $options['ttd']; $ttd = is_numeric($ttd) ? (int) $ttd : strtotime($ttd); unset($options['ttd']); // If a policy or policy callback were provided, extract those from the options $rawJsonPolicy = $options['policy']; $policyCallback = $options['policy_callback']; unset($options['policy'], $options['policy_callback']); // Setup policy document $policy = array( 'expiration' => gmdate(DateFormat::ISO8601_S3, $ttd), 'conditions' => array(array('bucket' => $this->bucket)) ); // Configure the endpoint/action $url = Url::factory($this->client->getBaseUrl()); if ($url->getScheme() === 'https' && strpos($this->bucket, '.') !== false) { // Use path-style URLs $url->setPath($this->bucket); } else { // Use virtual-style URLs $url->setHost($this->bucket . '.' . $url->getHost()); } // Setup basic form $this->formAttributes = array( 'action' => (string) $url, 'method' => 'POST', 'enctype' => 'multipart/form-data' ); $this->formInputs = array( 'AWSAccessKeyId' => $this->client->getCredentials()->getAccessKeyId() ); // Add success action status $status = (int) $options->get('success_action_status'); if ($status && in_array($status, array(200, 201, 204))) { $this->formInputs['success_action_status'] = (string) $status; $policy['conditions'][] = array( 'success_action_status' => (string) $status ); unset($options['success_action_status']); } // Add other options foreach ($options as $key => $value) { $value = (string) $value; if ($value[0] === '^') { $value = substr($value, 1); $this->formInputs[$key] = $value; $value = preg_replace('/\$\{(\w*)\}/', '', $value); $policy['conditions'][] = array('starts-with', '$' . $key, $value); } else { $this->formInputs[$key] = $value; $policy['conditions'][] = array($key => $value); } } // Handle the policy $policy = is_callable($policyCallback) ? $policyCallback($policy, $this) : $policy; $this->jsonPolicy = $rawJsonPolicy ?: json_encode($policy); $this->applyPolicy(); return $this; } /** * Sets the S3 client * * @param S3Client $client * * @return PostObject */ public function setClient(S3Client $client) { $this->client = $client; return $this; } /** * Gets the S3 client * * @return S3Client */ public function getClient() { return $this->client; } /** * Sets the bucket and makes sure it is a valid bucket name * * @param string $bucket * * @return PostObject */ public function setBucket($bucket) { $this->bucket = $bucket; return $this; } /** * Gets the bucket name * * @return string */ public function getBucket() { return $this->bucket; } /** * Gets the form attributes as an array * * @return array */ public function getFormAttributes() { return $this->formAttributes; } /** * Gets the form inputs as an array * * @return array */ public function getFormInputs() { return $this->formInputs; } /** * Gets the raw JSON policy * * @return string */ public function getJsonPolicy() { return $this->jsonPolicy; } /** * Handles the encoding, singing, and injecting of the policy */ protected function applyPolicy() { $jsonPolicy64 = base64_encode($this->jsonPolicy); $this->formInputs['policy'] = $jsonPolicy64; $this->formInputs['signature'] = base64_encode(hash_hmac( 'sha1', $jsonPolicy64, $this->client->getCredentials()->getSecretKey(), true )); } } '2006-03-01', 'endpointPrefix' => 's3', 'serviceFullName' => 'Amazon Simple Storage Service', 'serviceAbbreviation' => 'Amazon S3', 'serviceType' => 'rest-xml', 'timestampFormat' => 'rfc822', 'globalEndpoint' => 's3.amazonaws.com', 'signatureVersion' => 's3', 'namespace' => 'S3', 'regions' => array( 'us-east-1' => array( 'http' => true, 'https' => true, 'hostname' => 's3.amazonaws.com', ), 'us-west-1' => array( 'http' => true, 'https' => true, 'hostname' => 's3-us-west-1.amazonaws.com', ), 'us-west-2' => array( 'http' => true, 'https' => true, 'hostname' => 's3-us-west-2.amazonaws.com', ), 'eu-west-1' => array( 'http' => true, 'https' => true, 'hostname' => 's3-eu-west-1.amazonaws.com', ), 'eu-central-1' => array( 'http' => true, 'https' => true, 'hostname' => 's3-eu-central-1.amazonaws.com', ), 'ap-northeast-1' => array( 'http' => true, 'https' => true, 'hostname' => 's3-ap-northeast-1.amazonaws.com', ), 'ap-southeast-1' => array( 'http' => true, 'https' => true, 'hostname' => 's3-ap-southeast-1.amazonaws.com', ), 'ap-southeast-2' => array( 'http' => true, 'https' => true, 'hostname' => 's3-ap-southeast-2.amazonaws.com', ), 'sa-east-1' => array( 'http' => true, 'https' => true, 'hostname' => 's3-sa-east-1.amazonaws.com', ), 'cn-north-1' => array( 'http' => true, 'https' => true, 'hostname' => 's3.cn-north-1.amazonaws.com.cn', ), 'us-gov-west-1' => array( 'http' => true, 'https' => true, 'hostname' => 's3-us-gov-west-1.amazonaws.com', ), ), 'operations' => array( 'AbortMultipartUpload' => array( 'httpMethod' => 'DELETE', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'AbortMultipartUploadOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadAbort.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'UploadId' => array( 'required' => true, 'type' => 'string', 'location' => 'query', 'sentAs' => 'uploadId', ), ), 'errorResponses' => array( array( 'reason' => 'The specified multipart upload does not exist.', 'class' => 'NoSuchUploadException', ), ), ), 'CompleteMultipartUpload' => array( 'httpMethod' => 'POST', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'CompleteMultipartUploadOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadComplete.html', 'data' => array( 'xmlRoot' => array( 'name' => 'CompleteMultipartUpload', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'Parts' => array( 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'CompletedPart', 'type' => 'object', 'sentAs' => 'Part', 'properties' => array( 'ETag' => array( 'type' => 'string', ), 'PartNumber' => array( 'type' => 'numeric', ), ), ), ), 'UploadId' => array( 'required' => true, 'type' => 'string', 'location' => 'query', 'sentAs' => 'uploadId', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'CopyObject' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'CopyObjectOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectCOPY.html', 'data' => array( 'xmlRoot' => array( 'name' => 'CopyObjectRequest', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'ACL' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-acl', ), 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'CacheControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Cache-Control', ), 'ContentDisposition' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Disposition', ), 'ContentEncoding' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Encoding', ), 'ContentLanguage' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Language', ), 'ContentType' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Type', ), 'CopySource' => array( 'required' => true, 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source', ), 'CopySourceIfMatch' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-if-match', ), 'CopySourceIfModifiedSince' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-if-modified-since', ), 'CopySourceIfNoneMatch' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-if-none-match', ), 'CopySourceIfUnmodifiedSince' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-if-unmodified-since', ), 'Expires' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', ), 'GrantFullControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-full-control', ), 'GrantRead' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read', ), 'GrantReadACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read-acp', ), 'GrantWriteACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-write-acp', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'Metadata' => array( 'type' => 'object', 'location' => 'header', 'sentAs' => 'x-amz-meta-', 'additionalProperties' => array( 'type' => 'string', ), ), 'MetadataDirective' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-metadata-directive', ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'StorageClass' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-storage-class', ), 'WebsiteRedirectLocation' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-website-redirect-location', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKey' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'CopySourceSSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-server-side-encryption-customer-algorithm', ), 'CopySourceSSECustomerKey' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-server-side-encryption-customer-key', ), 'CopySourceSSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-server-side-encryption-customer-key-MD5', ), 'ACP' => array( 'type' => 'object', 'additionalProperties' => true, ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), 'errorResponses' => array( array( 'reason' => 'The source object of the COPY operation is not in the active tier and is only stored in Amazon Glacier.', 'class' => 'ObjectNotInActiveTierErrorException', ), ), ), 'CreateBucket' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'CreateBucketOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUT.html', 'data' => array( 'xmlRoot' => array( 'name' => 'CreateBucketConfiguration', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'ACL' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-acl', ), 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'LocationConstraint' => array( 'type' => 'string', 'location' => 'xml', ), 'GrantFullControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-full-control', ), 'GrantRead' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read', ), 'GrantReadACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read-acp', ), 'GrantWrite' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-write', ), 'GrantWriteACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-write-acp', ), 'ACP' => array( 'type' => 'object', 'additionalProperties' => true, ), ), 'errorResponses' => array( array( 'reason' => 'The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.', 'class' => 'BucketAlreadyExistsException', ), ), ), 'CreateMultipartUpload' => array( 'httpMethod' => 'POST', 'uri' => '/{Bucket}{/Key*}?uploads', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'CreateMultipartUploadOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadInitiate.html', 'data' => array( 'xmlRoot' => array( 'name' => 'CreateMultipartUploadRequest', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'ACL' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-acl', ), 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'CacheControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Cache-Control', ), 'ContentDisposition' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Disposition', ), 'ContentEncoding' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Encoding', ), 'ContentLanguage' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Language', ), 'ContentType' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Type', ), 'Expires' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', ), 'GrantFullControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-full-control', ), 'GrantRead' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read', ), 'GrantReadACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read-acp', ), 'GrantWriteACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-write-acp', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'Metadata' => array( 'type' => 'object', 'location' => 'header', 'sentAs' => 'x-amz-meta-', 'additionalProperties' => array( 'type' => 'string', ), ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'StorageClass' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-storage-class', ), 'WebsiteRedirectLocation' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-website-redirect-location', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKey' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'ACP' => array( 'type' => 'object', 'additionalProperties' => true, ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'DeleteBucket' => array( 'httpMethod' => 'DELETE', 'uri' => '/{Bucket}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'DeleteBucketOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETE.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), ), 'DeleteBucketCors' => array( 'httpMethod' => 'DELETE', 'uri' => '/{Bucket}?cors', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'DeleteBucketCorsOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETEcors.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), ), 'DeleteBucketLifecycle' => array( 'httpMethod' => 'DELETE', 'uri' => '/{Bucket}?lifecycle', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'DeleteBucketLifecycleOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETElifecycle.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), ), 'DeleteBucketPolicy' => array( 'httpMethod' => 'DELETE', 'uri' => '/{Bucket}?policy', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'DeleteBucketPolicyOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETEpolicy.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), ), 'DeleteBucketTagging' => array( 'httpMethod' => 'DELETE', 'uri' => '/{Bucket}?tagging', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'DeleteBucketTaggingOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETEtagging.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), ), 'DeleteBucketWebsite' => array( 'httpMethod' => 'DELETE', 'uri' => '/{Bucket}?website', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'DeleteBucketWebsiteOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETEwebsite.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), ), 'DeleteObject' => array( 'httpMethod' => 'DELETE', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'DeleteObjectOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectDELETE.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'MFA' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-mfa', ), 'VersionId' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'versionId', ), ), ), 'DeleteObjects' => array( 'httpMethod' => 'POST', 'uri' => '/{Bucket}?delete', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'DeleteObjectsOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/multiobjectdeleteapi.html', 'data' => array( 'xmlRoot' => array( 'name' => 'Delete', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), 'contentMd5' => true, ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Objects' => array( 'required' => true, 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'ObjectIdentifier', 'type' => 'object', 'sentAs' => 'Object', 'properties' => array( 'Key' => array( 'required' => true, 'type' => 'string', ), 'VersionId' => array( 'type' => 'string', ), ), ), ), 'Quiet' => array( 'type' => 'boolean', 'format' => 'boolean-string', 'location' => 'xml', ), 'MFA' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-mfa', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketAcl' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?acl', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketAclOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETacl.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketCors' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?cors', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketCorsOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETcors.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketLifecycle' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?lifecycle', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketLifecycleOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETlifecycle.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketLocation' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?location', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketLocationOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETlocation.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), ), 'GetBucketLogging' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?logging', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketLoggingOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETlogging.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketNotification' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?notification', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketNotificationOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETnotification.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketPolicy' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?policy', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketPolicyOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETpolicy.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), ), 'GetBucketRequestPayment' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?requestPayment', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketRequestPaymentOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTrequestPaymentGET.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketTagging' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?tagging', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketTaggingOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETtagging.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketVersioning' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?versioning', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketVersioningOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETversioningStatus.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetBucketWebsite' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?website', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetBucketWebsiteOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETwebsite.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'GetObject' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetObjectOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'IfMatch' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'If-Match', ), 'IfModifiedSince' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', 'sentAs' => 'If-Modified-Since', ), 'IfNoneMatch' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'If-None-Match', ), 'IfUnmodifiedSince' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', 'sentAs' => 'If-Unmodified-Since', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'Range' => array( 'type' => 'string', 'location' => 'header', ), 'ResponseCacheControl' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'response-cache-control', ), 'ResponseContentDisposition' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'response-content-disposition', ), 'ResponseContentEncoding' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'response-content-encoding', ), 'ResponseContentLanguage' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'response-content-language', ), 'ResponseContentType' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'response-content-type', ), 'ResponseExpires' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'query', 'sentAs' => 'response-expires', ), 'VersionId' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'versionId', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKey' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SaveAs' => array( 'location' => 'response_body', ), ), 'errorResponses' => array( array( 'reason' => 'The specified key does not exist.', 'class' => 'NoSuchKeyException', ), ), ), 'GetObjectAcl' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}{/Key*}?acl', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetObjectAclOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGETacl.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'VersionId' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'versionId', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), 'errorResponses' => array( array( 'reason' => 'The specified key does not exist.', 'class' => 'NoSuchKeyException', ), ), ), 'GetObjectTorrent' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}{/Key*}?torrent', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'GetObjectTorrentOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGETtorrent.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), ), ), 'HeadBucket' => array( 'httpMethod' => 'HEAD', 'uri' => '/{Bucket}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'HeadBucketOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketHEAD.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), ), 'errorResponses' => array( array( 'reason' => 'The specified bucket does not exist.', 'class' => 'NoSuchBucketException', ), ), ), 'HeadObject' => array( 'httpMethod' => 'HEAD', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'HeadObjectOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectHEAD.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'IfMatch' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'If-Match', ), 'IfModifiedSince' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', 'sentAs' => 'If-Modified-Since', ), 'IfNoneMatch' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'If-None-Match', ), 'IfUnmodifiedSince' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', 'sentAs' => 'If-Unmodified-Since', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'Range' => array( 'type' => 'string', 'location' => 'header', ), 'VersionId' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'versionId', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKey' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), ), 'errorResponses' => array( array( 'reason' => 'The specified key does not exist.', 'class' => 'NoSuchKeyException', ), ), ), 'ListBuckets' => array( 'httpMethod' => 'GET', 'uri' => '/', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'ListBucketsOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTServiceGET.html', 'parameters' => array( 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'ListMultipartUploads' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?uploads', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'ListMultipartUploadsOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadListMPUpload.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Delimiter' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'delimiter', ), 'EncodingType' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'encoding-type', ), 'KeyMarker' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'key-marker', ), 'MaxUploads' => array( 'type' => 'numeric', 'location' => 'query', 'sentAs' => 'max-uploads', ), 'Prefix' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'prefix', ), 'UploadIdMarker' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'upload-id-marker', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'ListObjectVersions' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}?versions', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'ListObjectVersionsOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETVersion.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Delimiter' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'delimiter', ), 'EncodingType' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'encoding-type', ), 'KeyMarker' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'key-marker', ), 'MaxKeys' => array( 'type' => 'numeric', 'location' => 'query', 'sentAs' => 'max-keys', ), 'Prefix' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'prefix', ), 'VersionIdMarker' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'version-id-marker', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'ListObjects' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'ListObjectsOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Delimiter' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'delimiter', ), 'EncodingType' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'encoding-type', ), 'Marker' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'marker', ), 'MaxKeys' => array( 'type' => 'numeric', 'location' => 'query', 'sentAs' => 'max-keys', ), 'Prefix' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'prefix', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), 'errorResponses' => array( array( 'reason' => 'The specified bucket does not exist.', 'class' => 'NoSuchBucketException', ), ), ), 'ListParts' => array( 'httpMethod' => 'GET', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'ListPartsOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadListParts.html', 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'MaxParts' => array( 'type' => 'numeric', 'location' => 'query', 'sentAs' => 'max-parts', ), 'PartNumberMarker' => array( 'type' => 'numeric', 'location' => 'query', 'sentAs' => 'part-number-marker', ), 'UploadId' => array( 'required' => true, 'type' => 'string', 'location' => 'query', 'sentAs' => 'uploadId', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), 'PutBucketAcl' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?acl', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketAclOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTacl.html', 'data' => array( 'xmlRoot' => array( 'name' => 'AccessControlPolicy', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'ACL' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-acl', ), 'Grants' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'AccessControlList', 'items' => array( 'name' => 'Grant', 'type' => 'object', 'properties' => array( 'Grantee' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'EmailAddress' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), 'Type' => array( 'required' => true, 'type' => 'string', 'sentAs' => 'xsi:type', 'data' => array( 'xmlAttribute' => true, 'xmlNamespace' => 'http://www.w3.org/2001/XMLSchema-instance', ), ), 'URI' => array( 'type' => 'string', ), ), ), 'Permission' => array( 'type' => 'string', ), ), ), ), 'Owner' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'GrantFullControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-full-control', ), 'GrantRead' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read', ), 'GrantReadACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read-acp', ), 'GrantWrite' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-write', ), 'GrantWriteACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-write-acp', ), 'ACP' => array( 'type' => 'object', 'additionalProperties' => true, ), ), ), 'PutBucketCors' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?cors', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketCorsOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTcors.html', 'data' => array( 'xmlRoot' => array( 'name' => 'CORSConfiguration', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), 'contentMd5' => true, ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'CORSRules' => array( 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'CORSRule', 'type' => 'object', 'sentAs' => 'CORSRule', 'properties' => array( 'AllowedHeaders' => array( 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'AllowedHeader', 'type' => 'string', 'sentAs' => 'AllowedHeader', ), ), 'AllowedMethods' => array( 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'AllowedMethod', 'type' => 'string', 'sentAs' => 'AllowedMethod', ), ), 'AllowedOrigins' => array( 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'AllowedOrigin', 'type' => 'string', 'sentAs' => 'AllowedOrigin', ), ), 'ExposeHeaders' => array( 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'ExposeHeader', 'type' => 'string', 'sentAs' => 'ExposeHeader', ), ), 'MaxAgeSeconds' => array( 'type' => 'numeric', ), ), ), ), ), ), 'PutBucketLifecycle' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?lifecycle', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketLifecycleOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTlifecycle.html', 'data' => array( 'xmlRoot' => array( 'name' => 'LifecycleConfiguration', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), 'contentMd5' => true, ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Rules' => array( 'required' => true, 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Rule', 'type' => 'object', 'sentAs' => 'Rule', 'properties' => array( 'Expiration' => array( 'type' => 'object', 'properties' => array( 'Date' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time', ), 'Days' => array( 'type' => 'numeric', ), ), ), 'ID' => array( 'type' => 'string', ), 'Prefix' => array( 'required' => true, 'type' => 'string', ), 'Status' => array( 'required' => true, 'type' => 'string', ), 'Transition' => array( 'type' => 'object', 'properties' => array( 'Date' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time', ), 'Days' => array( 'type' => 'numeric', ), 'StorageClass' => array( 'type' => 'string', ), ), ), 'NoncurrentVersionTransition' => array( 'type' => 'object', 'properties' => array( 'NoncurrentDays' => array( 'type' => 'numeric', ), 'StorageClass' => array( 'type' => 'string', ), ), ), 'NoncurrentVersionExpiration' => array( 'type' => 'object', 'properties' => array( 'NoncurrentDays' => array( 'type' => 'numeric', ), ), ), ), ), ), ), ), 'PutBucketLogging' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?logging', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketLoggingOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTlogging.html', 'data' => array( 'xmlRoot' => array( 'name' => 'BucketLoggingStatus', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), 'xmlAllowEmpty' => true, ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'LoggingEnabled' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'TargetBucket' => array( 'type' => 'string', ), 'TargetGrants' => array( 'type' => 'array', 'items' => array( 'name' => 'Grant', 'type' => 'object', 'properties' => array( 'Grantee' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'EmailAddress' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), 'Type' => array( 'required' => true, 'type' => 'string', 'sentAs' => 'xsi:type', 'data' => array( 'xmlAttribute' => true, 'xmlNamespace' => 'http://www.w3.org/2001/XMLSchema-instance', ), ), 'URI' => array( 'type' => 'string', ), ), ), 'Permission' => array( 'type' => 'string', ), ), ), ), 'TargetPrefix' => array( 'type' => 'string', ), ), ), ), ), 'PutBucketNotification' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?notification', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketNotificationOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTnotification.html', 'data' => array( 'xmlRoot' => array( 'name' => 'NotificationConfiguration', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'TopicConfiguration' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Id' => array( 'type' => 'string', ), 'Events' => array( 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Event', 'type' => 'string', ), ), 'Event' => array( 'type' => 'string', ), 'Topic' => array( 'type' => 'string', ), ), ), 'QueueConfiguration' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Id' => array( 'type' => 'string', ), 'Event' => array( 'type' => 'string', ), 'Events' => array( 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Event', 'type' => 'string', ), ), 'Queue' => array( 'type' => 'string', ), ), ), 'CloudFunctionConfiguration' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Id' => array( 'type' => 'string', ), 'Event' => array( 'type' => 'string', ), 'Events' => array( 'type' => 'array', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Event', 'type' => 'string', ), ), 'CloudFunction' => array( 'type' => 'string', ), 'InvocationRole' => array( 'type' => 'string', ), ), ), ), ), 'PutBucketPolicy' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?policy', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketPolicyOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTpolicy.html', 'data' => array( 'xmlRoot' => array( 'name' => 'PutBucketPolicyRequest', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Policy' => array( 'required' => true, 'type' => array( 'string', 'object', ), 'location' => 'body', ), ), ), 'PutBucketRequestPayment' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?requestPayment', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketRequestPaymentOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTrequestPaymentPUT.html', 'data' => array( 'xmlRoot' => array( 'name' => 'RequestPaymentConfiguration', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Payer' => array( 'required' => true, 'type' => 'string', 'location' => 'xml', ), ), ), 'PutBucketTagging' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?tagging', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketTaggingOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTtagging.html', 'data' => array( 'xmlRoot' => array( 'name' => 'Tagging', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), 'contentMd5' => true, ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'TagSet' => array( 'required' => true, 'type' => 'array', 'location' => 'xml', 'items' => array( 'name' => 'Tag', 'type' => 'object', 'properties' => array( 'Key' => array( 'required' => true, 'type' => 'string', ), 'Value' => array( 'required' => true, 'type' => 'string', ), ), ), ), ), ), 'PutBucketVersioning' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?versioning', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketVersioningOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTVersioningStatus.html', 'data' => array( 'xmlRoot' => array( 'name' => 'VersioningConfiguration', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'MFA' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-mfa', ), 'MFADelete' => array( 'type' => 'string', 'location' => 'xml', 'sentAs' => 'MfaDelete', ), 'Status' => array( 'type' => 'string', 'location' => 'xml', ), ), ), 'PutBucketWebsite' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}?website', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutBucketWebsiteOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTwebsite.html', 'data' => array( 'xmlRoot' => array( 'name' => 'WebsiteConfiguration', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), 'xmlAllowEmpty' => true, ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'ErrorDocument' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Key' => array( 'required' => true, 'type' => 'string', ), ), ), 'IndexDocument' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Suffix' => array( 'required' => true, 'type' => 'string', ), ), ), 'RedirectAllRequestsTo' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'HostName' => array( 'required' => true, 'type' => 'string', ), 'Protocol' => array( 'type' => 'string', ), ), ), 'RoutingRules' => array( 'type' => 'array', 'location' => 'xml', 'items' => array( 'name' => 'RoutingRule', 'type' => 'object', 'properties' => array( 'Condition' => array( 'type' => 'object', 'properties' => array( 'HttpErrorCodeReturnedEquals' => array( 'type' => 'string', ), 'KeyPrefixEquals' => array( 'type' => 'string', ), ), ), 'Redirect' => array( 'required' => true, 'type' => 'object', 'properties' => array( 'HostName' => array( 'type' => 'string', ), 'HttpRedirectCode' => array( 'type' => 'string', ), 'Protocol' => array( 'type' => 'string', ), 'ReplaceKeyPrefixWith' => array( 'type' => 'string', ), 'ReplaceKeyWith' => array( 'type' => 'string', ), ), ), ), ), ), ), ), 'PutObject' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutObjectOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html', 'data' => array( 'xmlRoot' => array( 'name' => 'PutObjectRequest', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'ACL' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-acl', ), 'Body' => array( 'type' => array( 'string', 'object', ), 'location' => 'body', ), 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'CacheControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Cache-Control', ), 'ContentDisposition' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Disposition', ), 'ContentEncoding' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Encoding', ), 'ContentLanguage' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Language', ), 'ContentLength' => array( 'type' => 'numeric', 'location' => 'header', 'sentAs' => 'Content-Length', ), 'ContentMD5' => array( 'type' => array( 'string', 'boolean', ), 'location' => 'header', 'sentAs' => 'Content-MD5', ), 'ContentType' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Type', ), 'Expires' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', ), 'GrantFullControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-full-control', ), 'GrantRead' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read', ), 'GrantReadACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read-acp', ), 'GrantWriteACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-write-acp', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'Metadata' => array( 'type' => 'object', 'location' => 'header', 'sentAs' => 'x-amz-meta-', 'additionalProperties' => array( 'type' => 'string', ), ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'StorageClass' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-storage-class', ), 'WebsiteRedirectLocation' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-website-redirect-location', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKey' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'ACP' => array( 'type' => 'object', 'additionalProperties' => true, ), ), ), 'PutObjectAcl' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}{/Key*}?acl', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'PutObjectAclOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUTacl.html', 'data' => array( 'xmlRoot' => array( 'name' => 'AccessControlPolicy', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'ACL' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-acl', ), 'Grants' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'AccessControlList', 'items' => array( 'name' => 'Grant', 'type' => 'object', 'properties' => array( 'Grantee' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'EmailAddress' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), 'Type' => array( 'required' => true, 'type' => 'string', 'sentAs' => 'xsi:type', 'data' => array( 'xmlAttribute' => true, 'xmlNamespace' => 'http://www.w3.org/2001/XMLSchema-instance', ), ), 'URI' => array( 'type' => 'string', ), ), ), 'Permission' => array( 'type' => 'string', ), ), ), ), 'Owner' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'GrantFullControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-full-control', ), 'GrantRead' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read', ), 'GrantReadACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-read-acp', ), 'GrantWrite' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-write', ), 'GrantWriteACP' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-grant-write-acp', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'ACP' => array( 'type' => 'object', 'additionalProperties' => true, ), ), 'errorResponses' => array( array( 'reason' => 'The specified key does not exist.', 'class' => 'NoSuchKeyException', ), ), ), 'RestoreObject' => array( 'httpMethod' => 'POST', 'uri' => '/{Bucket}{/Key*}?restore', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'RestoreObjectOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectRestore.html', 'data' => array( 'xmlRoot' => array( 'name' => 'RestoreRequest', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'VersionId' => array( 'type' => 'string', 'location' => 'query', 'sentAs' => 'versionId', ), 'Days' => array( 'required' => true, 'type' => 'numeric', 'location' => 'xml', ), ), 'errorResponses' => array( array( 'reason' => 'This operation is not allowed against this storage tier', 'class' => 'ObjectAlreadyInActiveTierErrorException', ), ), ), 'UploadPart' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'UploadPartOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadUploadPart.html', 'data' => array( 'xmlRoot' => array( 'name' => 'UploadPartRequest', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'Body' => array( 'type' => array( 'string', 'object', ), 'location' => 'body', ), 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'ContentLength' => array( 'type' => 'numeric', 'location' => 'header', 'sentAs' => 'Content-Length', ), 'ContentMD5' => array( 'type' => array( 'string', 'boolean', ), 'location' => 'header', 'sentAs' => 'Content-MD5', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'PartNumber' => array( 'required' => true, 'type' => 'numeric', 'location' => 'query', 'sentAs' => 'partNumber', ), 'UploadId' => array( 'required' => true, 'type' => 'string', 'location' => 'query', 'sentAs' => 'uploadId', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKey' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), ), ), 'UploadPartCopy' => array( 'httpMethod' => 'PUT', 'uri' => '/{Bucket}{/Key*}', 'class' => 'Aws\\S3\\Command\\S3Command', 'responseClass' => 'UploadPartCopyOutput', 'responseType' => 'model', 'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadUploadPartCopy.html', 'data' => array( 'xmlRoot' => array( 'name' => 'UploadPartCopyRequest', 'namespaces' => array( 'http://s3.amazonaws.com/doc/2006-03-01/', ), ), ), 'parameters' => array( 'Bucket' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', ), 'CopySource' => array( 'required' => true, 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source', ), 'CopySourceIfMatch' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-if-match', ), 'CopySourceIfModifiedSince' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-if-modified-since', ), 'CopySourceIfNoneMatch' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-if-none-match', ), 'CopySourceIfUnmodifiedSince' => array( 'type' => array( 'object', 'string', 'integer', ), 'format' => 'date-time-http', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-if-unmodified-since', ), 'CopySourceRange' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-range', ), 'Key' => array( 'required' => true, 'type' => 'string', 'location' => 'uri', 'filters' => array( 'Aws\\S3\\S3Client::explodeKey', ), ), 'PartNumber' => array( 'required' => true, 'type' => 'numeric', 'location' => 'query', 'sentAs' => 'partNumber', ), 'UploadId' => array( 'required' => true, 'type' => 'string', 'location' => 'query', 'sentAs' => 'uploadId', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKey' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'CopySourceSSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-server-side-encryption-customer-algorithm', ), 'CopySourceSSECustomerKey' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-server-side-encryption-customer-key', ), 'CopySourceSSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-server-side-encryption-customer-key-MD5', ), 'command.expects' => array( 'static' => true, 'default' => 'application/xml', ), ), ), ), 'models' => array( 'AbortMultipartUploadOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'CompleteMultipartUploadOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Location' => array( 'type' => 'string', 'location' => 'xml', ), 'Bucket' => array( 'type' => 'string', 'location' => 'xml', ), 'Key' => array( 'type' => 'string', 'location' => 'xml', ), 'Expiration' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-expiration', ), 'ETag' => array( 'type' => 'string', 'location' => 'xml', ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'VersionId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-version-id', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'CopyObjectOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'ETag' => array( 'type' => 'string', 'location' => 'xml', ), 'LastModified' => array( 'type' => 'string', 'location' => 'xml', ), 'Expiration' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-expiration', ), 'CopySourceVersionId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-version-id', ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'CreateBucketOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Location' => array( 'type' => 'string', 'location' => 'header', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'CreateMultipartUploadOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Bucket' => array( 'type' => 'string', 'location' => 'xml', 'sentAs' => 'Bucket', ), 'Key' => array( 'type' => 'string', 'location' => 'xml', ), 'UploadId' => array( 'type' => 'string', 'location' => 'xml', ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'DeleteBucketOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'DeleteBucketCorsOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'DeleteBucketLifecycleOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'DeleteBucketPolicyOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'DeleteBucketTaggingOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'DeleteBucketWebsiteOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'DeleteObjectOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'DeleteMarker' => array( 'type' => 'boolean', 'location' => 'header', 'sentAs' => 'x-amz-delete-marker', ), 'VersionId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-version-id', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'DeleteObjectsOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Deleted' => array( 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'DeletedObject', 'type' => 'object', 'properties' => array( 'Key' => array( 'type' => 'string', ), 'VersionId' => array( 'type' => 'string', ), 'DeleteMarker' => array( 'type' => 'boolean', ), 'DeleteMarkerVersionId' => array( 'type' => 'string', ), ), ), ), 'Errors' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'Error', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Error', 'type' => 'object', 'sentAs' => 'Error', 'properties' => array( 'Key' => array( 'type' => 'string', ), 'VersionId' => array( 'type' => 'string', ), 'Code' => array( 'type' => 'string', ), 'Message' => array( 'type' => 'string', ), ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketAclOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Owner' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), 'Grants' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'AccessControlList', 'items' => array( 'name' => 'Grant', 'type' => 'object', 'sentAs' => 'Grant', 'properties' => array( 'Grantee' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'EmailAddress' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), 'Type' => array( 'type' => 'string', 'sentAs' => 'xsi:type', 'data' => array( 'xmlAttribute' => true, 'xmlNamespace' => 'http://www.w3.org/2001/XMLSchema-instance', ), ), 'URI' => array( 'type' => 'string', ), ), ), 'Permission' => array( 'type' => 'string', ), ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketCorsOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'CORSRules' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'CORSRule', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'CORSRule', 'type' => 'object', 'sentAs' => 'CORSRule', 'properties' => array( 'AllowedHeaders' => array( 'type' => 'array', 'sentAs' => 'AllowedHeader', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'AllowedHeader', 'type' => 'string', 'sentAs' => 'AllowedHeader', ), ), 'AllowedMethods' => array( 'type' => 'array', 'sentAs' => 'AllowedMethod', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'AllowedMethod', 'type' => 'string', 'sentAs' => 'AllowedMethod', ), ), 'AllowedOrigins' => array( 'type' => 'array', 'sentAs' => 'AllowedOrigin', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'AllowedOrigin', 'type' => 'string', 'sentAs' => 'AllowedOrigin', ), ), 'ExposeHeaders' => array( 'type' => 'array', 'sentAs' => 'ExposeHeader', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'ExposeHeader', 'type' => 'string', 'sentAs' => 'ExposeHeader', ), ), 'MaxAgeSeconds' => array( 'type' => 'numeric', ), ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketLifecycleOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Rules' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'Rule', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Rule', 'type' => 'object', 'sentAs' => 'Rule', 'properties' => array( 'Expiration' => array( 'type' => 'object', 'properties' => array( 'Date' => array( 'type' => 'string', ), 'Days' => array( 'type' => 'numeric', ), ), ), 'ID' => array( 'type' => 'string', ), 'Prefix' => array( 'type' => 'string', ), 'Status' => array( 'type' => 'string', ), 'Transition' => array( 'type' => 'object', 'properties' => array( 'Date' => array( 'type' => 'string', ), 'Days' => array( 'type' => 'numeric', ), 'StorageClass' => array( 'type' => 'string', ), ), ), 'NoncurrentVersionTransition' => array( 'type' => 'object', 'properties' => array( 'NoncurrentDays' => array( 'type' => 'numeric', ), 'StorageClass' => array( 'type' => 'string', ), ), ), 'NoncurrentVersionExpiration' => array( 'type' => 'object', 'properties' => array( 'NoncurrentDays' => array( 'type' => 'numeric', ), ), ), ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketLocationOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Location' => array( 'type' => 'string', 'location' => 'body', 'filters' => array( 'strval', 'strip_tags', 'trim', ), ), ), ), 'GetBucketLoggingOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'LoggingEnabled' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'TargetBucket' => array( 'type' => 'string', ), 'TargetGrants' => array( 'type' => 'array', 'items' => array( 'name' => 'Grant', 'type' => 'object', 'sentAs' => 'Grant', 'properties' => array( 'Grantee' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'EmailAddress' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), 'Type' => array( 'type' => 'string', 'sentAs' => 'xsi:type', 'data' => array( 'xmlAttribute' => true, 'xmlNamespace' => 'http://www.w3.org/2001/XMLSchema-instance', ), ), 'URI' => array( 'type' => 'string', ), ), ), 'Permission' => array( 'type' => 'string', ), ), ), ), 'TargetPrefix' => array( 'type' => 'string', ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketNotificationOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'TopicConfiguration' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Id' => array( 'type' => 'string', ), 'Events' => array( 'type' => 'array', 'sentAs' => 'Event', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Event', 'type' => 'string', 'sentAs' => 'Event', ), ), 'Event' => array( 'type' => 'string', ), 'Topic' => array( 'type' => 'string', ), ), ), 'QueueConfiguration' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Id' => array( 'type' => 'string', ), 'Event' => array( 'type' => 'string', ), 'Events' => array( 'type' => 'array', 'sentAs' => 'Event', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Event', 'type' => 'string', 'sentAs' => 'Event', ), ), 'Queue' => array( 'type' => 'string', ), ), ), 'CloudFunctionConfiguration' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Id' => array( 'type' => 'string', ), 'Event' => array( 'type' => 'string', ), 'Events' => array( 'type' => 'array', 'sentAs' => 'Event', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Event', 'type' => 'string', 'sentAs' => 'Event', ), ), 'CloudFunction' => array( 'type' => 'string', ), 'InvocationRole' => array( 'type' => 'string', ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketPolicyOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Policy' => array( 'type' => 'string', 'instanceOf' => 'Guzzle\\Http\\EntityBody', 'location' => 'body', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketRequestPaymentOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Payer' => array( 'type' => 'string', 'location' => 'xml', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketTaggingOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'TagSet' => array( 'type' => 'array', 'location' => 'xml', 'items' => array( 'name' => 'Tag', 'type' => 'object', 'sentAs' => 'Tag', 'properties' => array( 'Key' => array( 'type' => 'string', ), 'Value' => array( 'type' => 'string', ), ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketVersioningOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Status' => array( 'type' => 'string', 'location' => 'xml', ), 'MFADelete' => array( 'type' => 'string', 'location' => 'xml', 'sentAs' => 'MfaDelete', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetBucketWebsiteOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RedirectAllRequestsTo' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'HostName' => array( 'type' => 'string', ), 'Protocol' => array( 'type' => 'string', ), ), ), 'IndexDocument' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Suffix' => array( 'type' => 'string', ), ), ), 'ErrorDocument' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'Key' => array( 'type' => 'string', ), ), ), 'RoutingRules' => array( 'type' => 'array', 'location' => 'xml', 'items' => array( 'name' => 'RoutingRule', 'type' => 'object', 'sentAs' => 'RoutingRule', 'properties' => array( 'Condition' => array( 'type' => 'object', 'properties' => array( 'HttpErrorCodeReturnedEquals' => array( 'type' => 'string', ), 'KeyPrefixEquals' => array( 'type' => 'string', ), ), ), 'Redirect' => array( 'type' => 'object', 'properties' => array( 'HostName' => array( 'type' => 'string', ), 'HttpRedirectCode' => array( 'type' => 'string', ), 'Protocol' => array( 'type' => 'string', ), 'ReplaceKeyPrefixWith' => array( 'type' => 'string', ), 'ReplaceKeyWith' => array( 'type' => 'string', ), ), ), ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetObjectOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Body' => array( 'type' => 'string', 'instanceOf' => 'Guzzle\\Http\\EntityBody', 'location' => 'body', ), 'DeleteMarker' => array( 'type' => 'boolean', 'location' => 'header', 'sentAs' => 'x-amz-delete-marker', ), 'AcceptRanges' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'accept-ranges', ), 'Expiration' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-expiration', ), 'Restore' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-restore', ), 'LastModified' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Last-Modified', ), 'ContentLength' => array( 'type' => 'numeric', 'location' => 'header', 'sentAs' => 'Content-Length', ), 'ETag' => array( 'type' => 'string', 'location' => 'header', ), 'MissingMeta' => array( 'type' => 'numeric', 'location' => 'header', 'sentAs' => 'x-amz-missing-meta', ), 'VersionId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-version-id', ), 'CacheControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Cache-Control', ), 'ContentDisposition' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Disposition', ), 'ContentEncoding' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Encoding', ), 'ContentLanguage' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Language', ), 'ContentType' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Type', ), 'Expires' => array( 'type' => 'string', 'location' => 'header', ), 'WebsiteRedirectLocation' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-website-redirect-location', ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'Metadata' => array( 'type' => 'object', 'location' => 'header', 'sentAs' => 'x-amz-meta-', 'additionalProperties' => array( 'type' => 'string', ), ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetObjectAclOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Owner' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), 'Grants' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'AccessControlList', 'items' => array( 'name' => 'Grant', 'type' => 'object', 'sentAs' => 'Grant', 'properties' => array( 'Grantee' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'EmailAddress' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), 'Type' => array( 'type' => 'string', 'sentAs' => 'xsi:type', 'data' => array( 'xmlAttribute' => true, 'xmlNamespace' => 'http://www.w3.org/2001/XMLSchema-instance', ), ), 'URI' => array( 'type' => 'string', ), ), ), 'Permission' => array( 'type' => 'string', ), ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'GetObjectTorrentOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Body' => array( 'type' => 'string', 'instanceOf' => 'Guzzle\\Http\\EntityBody', 'location' => 'body', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'HeadBucketOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'HeadObjectOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'DeleteMarker' => array( 'type' => 'boolean', 'location' => 'header', 'sentAs' => 'x-amz-delete-marker', ), 'AcceptRanges' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'accept-ranges', ), 'Expiration' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-expiration', ), 'Restore' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-restore', ), 'LastModified' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Last-Modified', ), 'ContentLength' => array( 'type' => 'numeric', 'location' => 'header', 'sentAs' => 'Content-Length', ), 'ETag' => array( 'type' => 'string', 'location' => 'header', ), 'MissingMeta' => array( 'type' => 'numeric', 'location' => 'header', 'sentAs' => 'x-amz-missing-meta', ), 'VersionId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-version-id', ), 'CacheControl' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Cache-Control', ), 'ContentDisposition' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Disposition', ), 'ContentEncoding' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Encoding', ), 'ContentLanguage' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Language', ), 'ContentType' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'Content-Type', ), 'Expires' => array( 'type' => 'string', 'location' => 'header', ), 'WebsiteRedirectLocation' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-website-redirect-location', ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'Metadata' => array( 'type' => 'object', 'location' => 'header', 'sentAs' => 'x-amz-meta-', 'additionalProperties' => array( 'type' => 'string', ), ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'ListBucketsOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Buckets' => array( 'type' => 'array', 'location' => 'xml', 'items' => array( 'name' => 'Bucket', 'type' => 'object', 'sentAs' => 'Bucket', 'properties' => array( 'Name' => array( 'type' => 'string', ), 'CreationDate' => array( 'type' => 'string', ), ), ), ), 'Owner' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'ListMultipartUploadsOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Bucket' => array( 'type' => 'string', 'location' => 'xml', ), 'KeyMarker' => array( 'type' => 'string', 'location' => 'xml', ), 'UploadIdMarker' => array( 'type' => 'string', 'location' => 'xml', ), 'NextKeyMarker' => array( 'type' => 'string', 'location' => 'xml', ), 'Prefix' => array( 'type' => 'string', 'location' => 'xml', ), 'Delimiter' => array( 'type' => 'string', 'location' => 'xml', ), 'NextUploadIdMarker' => array( 'type' => 'string', 'location' => 'xml', ), 'MaxUploads' => array( 'type' => 'numeric', 'location' => 'xml', ), 'IsTruncated' => array( 'type' => 'boolean', 'location' => 'xml', ), 'Uploads' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'Upload', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'MultipartUpload', 'type' => 'object', 'sentAs' => 'Upload', 'properties' => array( 'UploadId' => array( 'type' => 'string', ), 'Key' => array( 'type' => 'string', ), 'Initiated' => array( 'type' => 'string', ), 'StorageClass' => array( 'type' => 'string', ), 'Owner' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), 'Initiator' => array( 'type' => 'object', 'properties' => array( 'ID' => array( 'type' => 'string', ), 'DisplayName' => array( 'type' => 'string', ), ), ), ), ), ), 'CommonPrefixes' => array( 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'CommonPrefix', 'type' => 'object', 'properties' => array( 'Prefix' => array( 'type' => 'string', ), ), ), ), 'EncodingType' => array( 'type' => 'string', 'location' => 'xml', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'ListObjectVersionsOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'IsTruncated' => array( 'type' => 'boolean', 'location' => 'xml', ), 'KeyMarker' => array( 'type' => 'string', 'location' => 'xml', ), 'VersionIdMarker' => array( 'type' => 'string', 'location' => 'xml', ), 'NextKeyMarker' => array( 'type' => 'string', 'location' => 'xml', ), 'NextVersionIdMarker' => array( 'type' => 'string', 'location' => 'xml', ), 'Versions' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'Version', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'ObjectVersion', 'type' => 'object', 'sentAs' => 'Version', 'properties' => array( 'ETag' => array( 'type' => 'string', ), 'Size' => array( 'type' => 'numeric', ), 'StorageClass' => array( 'type' => 'string', ), 'Key' => array( 'type' => 'string', ), 'VersionId' => array( 'type' => 'string', ), 'IsLatest' => array( 'type' => 'boolean', ), 'LastModified' => array( 'type' => 'string', ), 'Owner' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), ), ), ), 'DeleteMarkers' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'DeleteMarker', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'DeleteMarkerEntry', 'type' => 'object', 'sentAs' => 'DeleteMarker', 'properties' => array( 'Owner' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), 'Key' => array( 'type' => 'string', ), 'VersionId' => array( 'type' => 'string', ), 'IsLatest' => array( 'type' => 'boolean', ), 'LastModified' => array( 'type' => 'string', ), ), ), ), 'Name' => array( 'type' => 'string', 'location' => 'xml', ), 'Prefix' => array( 'type' => 'string', 'location' => 'xml', ), 'Delimiter' => array( 'type' => 'string', 'location' => 'xml', ), 'MaxKeys' => array( 'type' => 'numeric', 'location' => 'xml', ), 'CommonPrefixes' => array( 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'CommonPrefix', 'type' => 'object', 'properties' => array( 'Prefix' => array( 'type' => 'string', ), ), ), ), 'EncodingType' => array( 'type' => 'string', 'location' => 'xml', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'ListObjectsOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'IsTruncated' => array( 'type' => 'boolean', 'location' => 'xml', ), 'Marker' => array( 'type' => 'string', 'location' => 'xml', ), 'NextMarker' => array( 'type' => 'string', 'location' => 'xml', ), 'Contents' => array( 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Object', 'type' => 'object', 'properties' => array( 'Key' => array( 'type' => 'string', ), 'LastModified' => array( 'type' => 'string', ), 'ETag' => array( 'type' => 'string', ), 'Size' => array( 'type' => 'numeric', ), 'StorageClass' => array( 'type' => 'string', ), 'Owner' => array( 'type' => 'object', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), ), ), ), 'Name' => array( 'type' => 'string', 'location' => 'xml', ), 'Prefix' => array( 'type' => 'string', 'location' => 'xml', ), 'Delimiter' => array( 'type' => 'string', 'location' => 'xml', ), 'MaxKeys' => array( 'type' => 'numeric', 'location' => 'xml', ), 'CommonPrefixes' => array( 'type' => 'array', 'location' => 'xml', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'CommonPrefix', 'type' => 'object', 'properties' => array( 'Prefix' => array( 'type' => 'string', ), ), ), ), 'EncodingType' => array( 'type' => 'string', 'location' => 'xml', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'ListPartsOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Bucket' => array( 'type' => 'string', 'location' => 'xml', ), 'Key' => array( 'type' => 'string', 'location' => 'xml', ), 'UploadId' => array( 'type' => 'string', 'location' => 'xml', ), 'PartNumberMarker' => array( 'type' => 'numeric', 'location' => 'xml', ), 'NextPartNumberMarker' => array( 'type' => 'numeric', 'location' => 'xml', ), 'MaxParts' => array( 'type' => 'numeric', 'location' => 'xml', ), 'IsTruncated' => array( 'type' => 'boolean', 'location' => 'xml', ), 'Parts' => array( 'type' => 'array', 'location' => 'xml', 'sentAs' => 'Part', 'data' => array( 'xmlFlattened' => true, ), 'items' => array( 'name' => 'Part', 'type' => 'object', 'sentAs' => 'Part', 'properties' => array( 'PartNumber' => array( 'type' => 'numeric', ), 'LastModified' => array( 'type' => 'string', ), 'ETag' => array( 'type' => 'string', ), 'Size' => array( 'type' => 'numeric', ), ), ), ), 'Initiator' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'ID' => array( 'type' => 'string', ), 'DisplayName' => array( 'type' => 'string', ), ), ), 'Owner' => array( 'type' => 'object', 'location' => 'xml', 'properties' => array( 'DisplayName' => array( 'type' => 'string', ), 'ID' => array( 'type' => 'string', ), ), ), 'StorageClass' => array( 'type' => 'string', 'location' => 'xml', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketAclOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketCorsOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketLifecycleOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketLoggingOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketNotificationOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketPolicyOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketRequestPaymentOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketTaggingOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketVersioningOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutBucketWebsiteOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'PutObjectOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'Expiration' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-expiration', ), 'ETag' => array( 'type' => 'string', 'location' => 'header', ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'VersionId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-version-id', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), 'ObjectURL' => array( ), ), ), 'PutObjectAclOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'RestoreObjectOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'UploadPartOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'ETag' => array( 'type' => 'string', 'location' => 'header', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), 'UploadPartCopyOutput' => array( 'type' => 'object', 'additionalProperties' => true, 'properties' => array( 'CopySourceVersionId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-copy-source-version-id', ), 'ETag' => array( 'type' => 'string', 'location' => 'xml', ), 'LastModified' => array( 'type' => 'string', 'location' => 'xml', ), 'ServerSideEncryption' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption', ), 'SSECustomerAlgorithm' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-algorithm', ), 'SSECustomerKeyMD5' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5', ), 'SSEKMSKeyId' => array( 'type' => 'string', 'location' => 'header', 'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id', ), 'RequestId' => array( 'location' => 'header', 'sentAs' => 'x-amz-request-id', ), ), ), ), 'iterators' => array( 'ListBuckets' => array( 'result_key' => 'Buckets', ), 'ListMultipartUploads' => array( 'limit_key' => 'MaxUploads', 'more_results' => 'IsTruncated', 'output_token' => array( 'NextKeyMarker', 'NextUploadIdMarker', ), 'input_token' => array( 'KeyMarker', 'UploadIdMarker', ), 'result_key' => array( 'Uploads', 'CommonPrefixes', ), ), 'ListObjectVersions' => array( 'more_results' => 'IsTruncated', 'limit_key' => 'MaxKeys', 'output_token' => array( 'NextKeyMarker', 'NextVersionIdMarker', ), 'input_token' => array( 'KeyMarker', 'VersionIdMarker', ), 'result_key' => array( 'Versions', 'DeleteMarkers', 'CommonPrefixes', ), ), 'ListObjects' => array( 'more_results' => 'IsTruncated', 'limit_key' => 'MaxKeys', 'output_token' => 'NextMarker', 'input_token' => 'Marker', 'result_key' => array( 'Contents', 'CommonPrefixes', ), ), 'ListParts' => array( 'more_results' => 'IsTruncated', 'limit_key' => 'MaxParts', 'output_token' => 'NextPartNumberMarker', 'input_token' => 'PartNumberMarker', 'result_key' => 'Parts', ), ), 'waiters' => array( '__default__' => array( 'interval' => 5, 'max_attempts' => 20, ), 'BucketExists' => array( 'operation' => 'HeadBucket', 'success.type' => 'output', 'ignore_errors' => array( 'NoSuchBucket', ), ), 'BucketNotExists' => array( 'operation' => 'HeadBucket', 'success.type' => 'error', 'success.value' => 'NoSuchBucket', ), 'ObjectExists' => array( 'operation' => 'HeadObject', 'success.type' => 'output', 'ignore_errors' => array( 'NoSuchKey', ), ), ), ); params = $params; $this->client = $client; $this->params['Bucket'] = $bucket; $this->params['Key'] = $key; // If a string is passed, then assume that the download should stream to a file on disk if (is_string($target)) { if (!($target = fopen($target, 'a+'))) { throw new RuntimeException("Unable to open {$target} for writing"); } // Always append to the file fseek($target, 0, SEEK_END); } // Get the metadata and Content-MD5 of the object $this->target = EntityBody::factory($target); } /** * Get the bucket of the download * * @return string */ public function getBucket() { return $this->params['Bucket']; } /** * Get the key of the download * * @return string */ public function getKey() { return $this->params['Key']; } /** * Get the file to which the contents are downloaded * * @return string */ public function getFilename() { return $this->target->getUri(); } /** * Download the remainder of the object from Amazon S3 * * Performs a message integrity check if possible * * @return Model */ public function __invoke() { $command = $this->client->getCommand('HeadObject', $this->params); $this->meta = $command->execute(); if ($this->target->ftell() >= $this->meta['ContentLength']) { return false; } $this->meta['ContentMD5'] = (string) $command->getResponse()->getHeader('Content-MD5'); // Use a ReadLimitEntityBody so that rewinding the stream after an error does not cause the file pointer // to enter an inconsistent state with the data being downloaded $this->params['SaveAs'] = new ReadLimitEntityBody( $this->target, $this->meta['ContentLength'], $this->target->ftell() ); $result = $this->getRemaining(); $this->checkIntegrity(); return $result; } /** * Send the command to get the remainder of the object * * @return Model */ protected function getRemaining() { $current = $this->target->ftell(); $targetByte = $this->meta['ContentLength'] - 1; $this->params['Range'] = "bytes={$current}-{$targetByte}"; // Set the starting offset so that the body is never seeked to before this point in the event of a retry $this->params['SaveAs']->setOffset($current); $command = $this->client->getCommand('GetObject', $this->params); return $command->execute(); } /** * Performs an MD5 message integrity check if possible * * @throws UnexpectedValueException if the message does not validate */ protected function checkIntegrity() { if ($this->target->isReadable() && $expected = $this->meta['ContentMD5']) { $actual = $this->target->getContentMd5(); if ($actual != $expected) { throw new UnexpectedValueException( "Message integrity check failed. Expected {$expected} but got {$actual}." ); } } } } 'ListBuckets', 'GetBucket' => 'ListObjects', 'PutBucket' => 'CreateBucket', // SDK 1.x Aliases 'GetBucketHeaders' => 'HeadBucket', 'GetObjectHeaders' => 'HeadObject', 'SetBucketAcl' => 'PutBucketAcl', 'CreateObject' => 'PutObject', 'DeleteObjects' => 'DeleteMultipleObjects', 'PutObjectCopy' => 'CopyObject', 'SetObjectAcl' => 'PutObjectAcl', 'GetLogs' => 'GetBucketLogging', 'GetVersioningStatus' => 'GetBucketVersioning', 'SetBucketPolicy' => 'PutBucketPolicy', 'CreateBucketNotification' => 'PutBucketNotification', 'GetBucketNotifications' => 'GetBucketNotification', 'CopyPart' => 'UploadPartCopy', 'CreateWebsiteConfig' => 'PutBucketWebsite', 'GetWebsiteConfig' => 'GetBucketWebsite', 'DeleteWebsiteConfig' => 'DeleteBucketWebsite', 'CreateObjectExpirationConfig' => 'PutBucketLifecycle', 'GetObjectExpirationConfig' => 'GetBucketLifecycle', 'DeleteObjectExpirationConfig' => 'DeleteBucketLifecycle', ); protected $directory = __DIR__; /** * Factory method to create a new Amazon S3 client using an array of configuration options. * * @param array|Collection $config Client configuration data * * @return S3Client * @link http://docs.aws.amazon.com/aws-sdk-php/guide/latest/configuration.html#client-configuration-options */ public static function factory($config = array()) { $exceptionParser = new S3ExceptionParser(); // Configure the custom exponential backoff plugin for retrying S3 specific errors if (!isset($config[Options::BACKOFF])) { $config[Options::BACKOFF] = static::createBackoffPlugin($exceptionParser); } $config[Options::SIGNATURE] = $signature = static::createSignature($config); $client = ClientBuilder::factory(__NAMESPACE__) ->setConfig($config) ->setConfigDefaults(array( Options::VERSION => self::LATEST_API_VERSION, Options::SERVICE_DESCRIPTION => __DIR__ . '/Resources/s3-%s.php' )) ->setExceptionParser($exceptionParser) ->setIteratorsConfig(array( 'more_key' => 'IsTruncated', 'operations' => array( 'ListBuckets', 'ListMultipartUploads' => array( 'limit_param' => 'MaxUploads', 'token_param' => array('KeyMarker', 'UploadIdMarker'), 'token_key' => array('NextKeyMarker', 'NextUploadIdMarker'), ), 'ListObjects' => array( 'limit_param' => 'MaxKeys', 'token_param' => 'Marker', 'token_key' => 'NextMarker', ), 'ListObjectVersions' => array( 'limit_param' => 'MaxKeys', 'token_param' => array('KeyMarker', 'VersionIdMarker'), 'token_key' => array('nextKeyMarker', 'nextVersionIdMarker'), ), 'ListParts' => array( 'limit_param' => 'MaxParts', 'result_key' => 'Parts', 'token_param' => 'PartNumberMarker', 'token_key' => 'NextPartNumberMarker', ), ) )) ->build(); // Use virtual hosted buckets when possible $client->addSubscriber(new BucketStyleListener()); // Ensure that ACP headers are applied when needed $client->addSubscriber(new AcpListener()); // Validate and add required Content-MD5 hashes (e.g. DeleteObjects) $client->addSubscriber(new S3Md5Listener($signature)); // Allow for specifying bodies with file paths and file handles $client->addSubscriber(new UploadBodyListener(array('PutObject', 'UploadPart'))); // Ensures that if a SSE-CPK key is provided, the key and md5 are formatted correctly $client->addSubscriber(new SseCpkListener); // Add aliases for some S3 operations $default = CompositeFactory::getDefaultChain($client); $default->add( new AliasFactory($client, static::$commandAliases), 'Guzzle\Service\Command\Factory\ServiceDescriptionFactory' ); $client->setCommandFactory($default); return $client; } /** * Create an Amazon S3 specific backoff plugin * * @param S3ExceptionParser $exceptionParser * * @return BackoffPlugin */ private static function createBackoffPlugin(S3ExceptionParser $exceptionParser) { return new BackoffPlugin( new TruncatedBackoffStrategy(3, new CurlBackoffStrategy(null, new HttpBackoffStrategy(null, new SocketTimeoutChecker( new ExpiredCredentialsChecker($exceptionParser, new ExponentialBackoffStrategy() ) ) ) ) ) ); } /** * Create an appropriate signature based on the configuration settings * * @param $config * * @return \Aws\Common\Signature\SignatureInterface * @throws InvalidArgumentException */ private static function createSignature($config) { $currentValue = isset($config[Options::SIGNATURE]) ? $config[Options::SIGNATURE] : null; // Force v4 if no value is provided, a region is in the config, and // the region starts with "cn-" or "eu-central-". $requiresV4 = !$currentValue && isset($config['region']) && (strpos($config['region'], 'eu-central-') === 0 || strpos($config['region'], 'cn-') === 0); // Use the Amazon S3 signature V4 when the value is set to "v4" or when // the value is not set and the region starts with "cn-". if ($currentValue == 'v4' || $requiresV4) { // Force SignatureV4 for specific regions or if specified in the config $currentValue = new S3SignatureV4('s3'); } elseif (!$currentValue || $currentValue == 's3') { // Use the Amazon S3 signature by default $currentValue = new S3Signature(); } // A region is require with v4 if ($currentValue instanceof SignatureV4 && !isset($config['region'])) { throw new InvalidArgumentException('A region must be specified ' . 'when using signature version 4'); } return $currentValue; } /** * Determine if a string is a valid name for a DNS compatible Amazon S3 * bucket, meaning the bucket can be used as a subdomain in a URL (e.g., * ".s3.amazonaws.com"). * * @param string $bucket The name of the bucket to check. * * @return bool TRUE if the bucket name is valid or FALSE if it is invalid. */ public static function isValidBucketName($bucket) { $bucketLen = strlen($bucket); if ($bucketLen < 3 || $bucketLen > 63 || // Cannot look like an IP address preg_match('/(\d+\.){3}\d+$/', $bucket) || // Cannot include special characters, must start and end with lower alnum !preg_match('/^[a-z0-9]([a-z0-9\-\.]*[a-z0-9])?$/', $bucket) ) { return false; } return true; } /** * Create a pre-signed URL for a request * * @param RequestInterface $request Request to generate the URL for. Use the factory methods of the client to * create this request object * @param int|string|\DateTime $expires The time at which the URL should expire. This can be a Unix timestamp, a * PHP DateTime object, or a string that can be evaluated by strtotime * * @return string * @throws InvalidArgumentException if the request is not associated with this client object */ public function createPresignedUrl(RequestInterface $request, $expires) { if ($request->getClient() !== $this) { throw new InvalidArgumentException('The request object must be associated with the client. Use the ' . '$client->get(), $client->head(), $client->post(), $client->put(), etc. methods when passing in a ' . 'request object'); } return $this->signature->createPresignedUrl($request, $this->credentials, $expires); } /** * Returns the URL to an object identified by its bucket and key. If an expiration time is provided, the URL will * be signed and set to expire at the provided time. * * @param string $bucket The name of the bucket where the object is located * @param string $key The key of the object * @param mixed $expires The time at which the URL should expire * @param array $args Arguments to the GetObject command. Additionally you can specify a "Scheme" if you would * like the URL to use a different scheme than what the client is configured to use * * @return string The URL to the object */ public function getObjectUrl($bucket, $key, $expires = null, array $args = array()) { $command = $this->getCommand('GetObject', $args + array('Bucket' => $bucket, 'Key' => $key)); if ($command->hasKey('Scheme')) { $scheme = $command['Scheme']; $request = $command->remove('Scheme')->prepare()->setScheme($scheme)->setPort(null); } else { $request = $command->prepare(); } return $expires ? $this->createPresignedUrl($request, $expires) : $request->getUrl(); } /** * Helper used to clear the contents of a bucket. Use the {@see ClearBucket} object directly * for more advanced options and control. * * @param string $bucket Name of the bucket to clear. * * @return int Returns the number of deleted keys */ public function clearBucket($bucket) { $clear = new ClearBucket($this, $bucket); return $clear->clear(); } /** * Determines whether or not a bucket exists by name * * @param string $bucket The name of the bucket * @param bool $accept403 Set to true if 403s are acceptable * @param array $options Additional options to add to the executed command * * @return bool */ public function doesBucketExist($bucket, $accept403 = true, array $options = array()) { return $this->checkExistenceWithCommand( $this->getCommand('HeadBucket', array_merge($options, array( 'Bucket' => $bucket ))), $accept403 ); } /** * Determines whether or not an object exists by name * * @param string $bucket The name of the bucket * @param string $key The key of the object * @param array $options Additional options to add to the executed command * * @return bool */ public function doesObjectExist($bucket, $key, array $options = array()) { return $this->checkExistenceWithCommand( $this->getCommand('HeadObject', array_merge($options, array( 'Bucket' => $bucket, 'Key' => $key ))) ); } /** * Determines whether or not a bucket policy exists for a bucket * * @param string $bucket The name of the bucket * @param array $options Additional options to add to the executed command * * @return bool */ public function doesBucketPolicyExist($bucket, array $options = array()) { return $this->checkExistenceWithCommand( $this->getCommand('GetBucketPolicy', array_merge($options, array( 'Bucket' => $bucket ))) ); } /** * Raw URL encode a key and allow for '/' characters * * @param string $key Key to encode * * @return string Returns the encoded key */ public static function encodeKey($key) { return str_replace('%2F', '/', rawurlencode($key)); } /** * Explode a prefixed key into an array of values * * @param string $key Key to explode * * @return array Returns the exploded */ public static function explodeKey($key) { // Remove a leading slash if one is found return explode('/', $key && $key[0] == '/' ? substr($key, 1) : $key); } /** * Register the Amazon S3 stream wrapper and associates it with this client object * * @return $this */ public function registerStreamWrapper() { StreamWrapper::register($this); return $this; } /** * Upload a file, stream, or string to a bucket. If the upload size exceeds the specified threshold, the upload * will be performed using parallel multipart uploads. * * @param string $bucket Bucket to upload the object * @param string $key Key of the object * @param mixed $body Object data to upload. Can be a Guzzle\Http\EntityBodyInterface, stream resource, or * string of data to upload. * @param string $acl ACL to apply to the object * @param array $options Custom options used when executing commands: * - params: Custom parameters to use with the upload. The parameters must map to a PutObject * or InitiateMultipartUpload operation parameters. * - min_part_size: Minimum size to allow for each uploaded part when performing a multipart upload. * - concurrency: Maximum number of concurrent multipart uploads. * - before_upload: Callback to invoke before each multipart upload. The callback will receive a * Guzzle\Common\Event object with context. * * @see Aws\S3\Model\MultipartUpload\UploadBuilder for more options and customization * @return \Guzzle\Service\Resource\Model Returns the modeled result of the performed operation */ public function upload($bucket, $key, $body, $acl = 'private', array $options = array()) { $body = EntityBody::factory($body); $options = Collection::fromConfig(array_change_key_case($options), array( 'min_part_size' => AbstractMulti::MIN_PART_SIZE, 'params' => array(), 'concurrency' => $body->getWrapper() == 'plainfile' ? 3 : 1 )); if ($body->getSize() < $options['min_part_size']) { // Perform a simple PutObject operation return $this->putObject(array( 'Bucket' => $bucket, 'Key' => $key, 'Body' => $body, 'ACL' => $acl ) + $options['params']); } // Perform a multipart upload if the file is large enough $transfer = UploadBuilder::newInstance() ->setBucket($bucket) ->setKey($key) ->setMinPartSize($options['min_part_size']) ->setConcurrency($options['concurrency']) ->setClient($this) ->setSource($body) ->setTransferOptions($options->toArray()) ->addOptions($options['params']) ->setOption('ACL', $acl) ->build(); if ($options['before_upload']) { $transfer->getEventDispatcher()->addListener( AbstractTransfer::BEFORE_PART_UPLOAD, $options['before_upload'] ); } return $transfer->upload(); } /** * Recursively uploads all files in a given directory to a given bucket. * * @param string $directory Full path to a directory to upload * @param string $bucket Name of the bucket * @param string $keyPrefix Virtual directory key prefix to add to each upload * @param array $options Associative array of upload options * - params: Array of parameters to use with each PutObject operation performed during the transfer * - base_dir: Base directory to remove from each object key * - force: Set to true to upload every file, even if the file is already in Amazon S3 and has not changed * - concurrency: Maximum number of parallel uploads (defaults to 10) * - debug: Set to true or an fopen resource to enable debug mode to print information about each upload * - multipart_upload_size: When the size of a file exceeds this value, the file will be uploaded using a * multipart upload. * * @see Aws\S3\S3Sync\S3Sync for more options and customization */ public function uploadDirectory($directory, $bucket, $keyPrefix = null, array $options = array()) { $options = Collection::fromConfig( $options, array( 'base_dir' => realpath($directory) ?: $directory ) ); $builder = $options['builder'] ?: UploadSyncBuilder::getInstance(); $builder->uploadFromDirectory($directory) ->setClient($this) ->setBucket($bucket) ->setKeyPrefix($keyPrefix) ->setConcurrency($options['concurrency'] ?: 5) ->setBaseDir($options['base_dir']) ->force($options['force']) ->setOperationParams($options['params'] ?: array()) ->enableDebugOutput($options['debug']); if ($options->hasKey('multipart_upload_size')) { $builder->setMultipartUploadSize($options['multipart_upload_size']); } $builder->build()->transfer(); } /** * Downloads a bucket to the local filesystem * * @param string $directory Directory to download to * @param string $bucket Bucket to download from * @param string $keyPrefix Only download objects that use this key prefix * @param array $options Associative array of download options * - params: Array of parameters to use with each GetObject operation performed during the transfer * - base_dir: Base directory to remove from each object key when storing in the local filesystem * - force: Set to true to download every file, even if the file is already on the local filesystem and has not * changed * - concurrency: Maximum number of parallel downloads (defaults to 10) * - debug: Set to true or a fopen resource to enable debug mode to print information about each download * - allow_resumable: Set to true to allow previously interrupted downloads to be resumed using a Range GET */ public function downloadBucket($directory, $bucket, $keyPrefix = '', array $options = array()) { $options = new Collection($options); $builder = $options['builder'] ?: DownloadSyncBuilder::getInstance(); $builder->setDirectory($directory) ->setClient($this) ->setBucket($bucket) ->setKeyPrefix($keyPrefix) ->setConcurrency($options['concurrency'] ?: 10) ->setBaseDir($options['base_dir']) ->force($options['force']) ->setOperationParams($options['params'] ?: array()) ->enableDebugOutput($options['debug']); if ($options['allow_resumable']) { $builder->allowResumableDownloads(); } $builder->build()->transfer(); } /** * Deletes objects from Amazon S3 that match the result of a ListObjects operation. For example, this allows you * to do things like delete all objects that match a specific key prefix. * * @param string $bucket Bucket that contains the object keys * @param string $prefix Optionally delete only objects under this key prefix * @param string $regex Delete only objects that match this regex * @param array $options Options used when deleting the object: * - before_delete: Callback to invoke before each delete. The callback will receive a * Guzzle\Common\Event object with context. * * @see Aws\S3\S3Client::listObjects * @see Aws\S3\Model\ClearBucket For more options or customization * @return int Returns the number of deleted keys * @throws RuntimeException if no prefix and no regex is given */ public function deleteMatchingObjects($bucket, $prefix = '', $regex = '', array $options = array()) { if (!$prefix && !$regex) { throw new RuntimeException('A prefix or regex is required, or use S3Client::clearBucket().'); } $clear = new ClearBucket($this, $bucket); $iterator = $this->getIterator('ListObjects', array('Bucket' => $bucket, 'Prefix' => $prefix)); if ($regex) { $iterator = new FilterIterator($iterator, function ($current) use ($regex) { return preg_match($regex, $current['Key']); }); } $clear->setIterator($iterator); if (isset($options['before_delete'])) { $clear->getEventDispatcher()->addListener(ClearBucket::BEFORE_CLEAR, $options['before_delete']); } return $clear->clear(); } /** * Determines whether or not a resource exists using a command * * @param CommandInterface $command Command used to poll for the resource * @param bool $accept403 Set to true if 403s are acceptable * * @return bool * @throws S3Exception|\Exception if there is an unhandled exception */ protected function checkExistenceWithCommand(CommandInterface $command, $accept403 = false) { try { $command->execute(); $exists = true; } catch (AccessDeniedException $e) { $exists = (bool) $accept403; } catch (S3Exception $e) { $exists = false; if ($e->getResponse()->getStatusCode() >= 500) { // @codeCoverageIgnoreStart throw $e; // @codeCoverageIgnoreEnd } } return $exists; } } 'onCommandAfterPrepare'); } public function __construct(SignatureInterface $signature) { $this->signature = $signature; } public function onCommandAfterPrepare(Event $event) { $command = $event['command']; $operation = $command->getOperation(); if ($operation->getData('contentMd5')) { // Add the MD5 if it is required for all signers $this->addMd5($command); } elseif ($operation->hasParam('ContentMD5')) { $value = $command['ContentMD5']; // Add a computed MD5 if the parameter is set to true or if // not using Signature V4 and the value is not set (null). if ($value === true || ($value === null && !($this->signature instanceof SignatureV4)) ) { $this->addMd5($command); } } } private function addMd5(CommandInterface $command) { $request = $command->getRequest(); $body = $request->getBody(); if ($body && $body->getSize() > 0) { if (false !== ($md5 = $body->getContentMd5(true, true))) { $request->setHeader('Content-MD5', $md5); } } } } signableQueryString); // Add the security token header if one is being used by the credentials if ($token = $credentials->getSecurityToken()) { $request->setHeader('x-amz-security-token', $token); } $request->removeHeader('x-amz-date'); $request->setHeader('Date', gmdate(\DateTime::RFC2822)); $stringToSign = $this->createCanonicalizedString($request); $request->getParams()->set('aws.string_to_sign', $stringToSign); $request->setHeader( 'Authorization', 'AWS ' . $credentials->getAccessKeyId() . ':' . $this->signString($stringToSign, $credentials) ); } public function createPresignedUrl( RequestInterface $request, CredentialsInterface $credentials, $expires ) { if ($expires instanceof \DateTime) { $expires = $expires->getTimestamp(); } elseif (!is_numeric($expires)) { $expires = strtotime($expires); } // Operate on a clone of the request, so the original is not altered $request = clone $request; // URL encoding already occurs in the URI template expansion. Undo that and encode using the same encoding as // GET object, PUT object, etc. $path = S3Client::encodeKey(rawurldecode($request->getPath())); $request->setPath($path); // Make sure to handle temporary credentials if ($token = $credentials->getSecurityToken()) { $request->setHeader('x-amz-security-token', $token); $request->getQuery()->set('x-amz-security-token', $token); } // Set query params required for pre-signed URLs $request->getQuery() ->set('AWSAccessKeyId', $credentials->getAccessKeyId()) ->set('Expires', $expires) ->set('Signature', $this->signString( $this->createCanonicalizedString($request, $expires), $credentials )); // Move X-Amz-* headers to the query string foreach ($request->getHeaders() as $name => $header) { $name = strtolower($name); if (strpos($name, 'x-amz-') === 0) { $request->getQuery()->set($name, (string) $header); $request->removeHeader($name); } } return $request->getUrl(); } public function signString($string, CredentialsInterface $credentials) { return base64_encode(hash_hmac('sha1', $string, $credentials->getSecretKey(), true)); } public function createCanonicalizedString(RequestInterface $request, $expires = null) { $buffer = $request->getMethod() . "\n"; // Add the interesting headers foreach ($this->signableHeaders as $header) { $buffer .= (string) $request->getHeader($header) . "\n"; } // Choose dates from left to right based on what's set $date = $expires ?: (string) $request->getHeader('date'); $buffer .= "{$date}\n" . $this->createCanonicalizedAmzHeaders($request) . $this->createCanonicalizedResource($request); return $buffer; } /** * Create a canonicalized AmzHeaders string for a signature. * * @param RequestInterface $request Request from which to gather headers * * @return string Returns canonicalized AMZ headers. */ private function createCanonicalizedAmzHeaders(RequestInterface $request) { $headers = array(); foreach ($request->getHeaders() as $name => $header) { $name = strtolower($name); if (strpos($name, 'x-amz-') === 0) { $value = trim((string) $header); if ($value || $value === '0') { $headers[$name] = $name . ':' . $value; } } } if (!$headers) { return ''; } ksort($headers); return implode("\n", $headers) . "\n"; } /** * Create a canonicalized resource for a request * * @param RequestInterface $request Request for the resource * * @return string */ private function createCanonicalizedResource(RequestInterface $request) { $buffer = $request->getParams()->get('s3.resource'); // When sending a raw HTTP request (e.g. $client->get()) if (null === $buffer) { $bucket = $request->getParams()->get('bucket') ?: $this->parseBucketName($request); // Use any specified bucket name, the parsed bucket name, or no bucket name when interacting with GetService $buffer = $bucket ? "/{$bucket}" : ''; // Remove encoding from the path and use the S3 specific encoding $path = S3Client::encodeKey(rawurldecode($request->getPath())); // if the bucket was path style, then ensure that the bucket wasn't duplicated in the resource $buffer .= preg_replace("#^/{$bucket}/{$bucket}#", "/{$bucket}", $path); } // Remove double slashes $buffer = str_replace('//', '/', $buffer); // Add sub resource parameters $query = $request->getQuery(); $first = true; foreach ($this->signableQueryString as $key) { if ($query->hasKey($key)) { $value = $query[$key]; $buffer .= $first ? '?' : '&'; $first = false; $buffer .= $key; // Don't add values for empty sub-resources if ($value !== '' && $value !== false && $value !== null && $value !== QueryString::BLANK ) { $buffer .= "={$value}"; } } } return $buffer; } /** * Parse the bucket name from a request object * * @param RequestInterface $request Request to parse * * @return string */ private function parseBucketName(RequestInterface $request) { $baseUrl = Url::factory($request->getClient()->getBaseUrl()); $baseHost = $baseUrl->getHost(); $host = $request->getHost(); if (strpos($host, $baseHost) === false) { // Does not contain the base URL, so it's either a redirect, CNAME, or using a different region $baseHost = ''; // For every known S3 host, check if that host is present on the request $regions = $request->getClient()->getDescription()->getData('regions'); foreach ($regions as $region) { if (strpos($host, $region['hostname']) !== false) { // This host matches the request host. Tells use the region and endpoint-- we can derive the bucket $baseHost = $region['hostname']; break; } } // If no matching base URL was found, then assume that this is a CNAME, and the CNAME is the bucket if (!$baseHost) { return $host; } } // Remove the baseURL from the host of the request to attempt to determine the bucket name return trim(str_replace($baseHost, '', $request->getHost()), ' .'); } } hasHeader('x-amz-content-sha256')) { $request->setHeader( 'x-amz-content-sha256', $this->getPayload($request) ); } parent::signRequest($request, $credentials); } /** * Override used to allow pre-signed URLs to be created for an * in-determinate request payload. */ protected function getPresignedPayload(RequestInterface $request) { return 'UNSIGNED-PAYLOAD'; } /** * Amazon S3 does not double-encode the path component in the canonical req */ protected function createCanonicalizedPath(RequestInterface $request) { return '/' . ltrim($request->getPath(), '/'); } } setNext($next); } } /** * {@inheridoc} */ public function makesDecision() { return true; } /** * {@inheritdoc} */ protected function getDelay( $retries, RequestInterface $request, Response $response = null, HttpException $e = null ) { if ($response && $response->getStatusCode() == 400 && strpos($response->getBody(), self::ERR) ) { return true; } } } 'onCommandBeforePrepare'); } public function onCommandBeforePrepare(Event $event) { /** @var CommandInterface $command */ $command = $event['command']; // Allows only HTTPS connections when using SSE-C if ($command['SSECustomerKey'] || $command['CopySourceSSECustomerKey'] ) { $this->validateScheme($command); } // Prepare the normal SSE-CPK headers if ($command['SSECustomerKey']) { $this->prepareSseParams($command); } // If it's a copy operation, prepare the SSE-CPK headers for the source. if ($command['CopySourceSSECustomerKey']) { $this->prepareSseParams($command, true); } } private function validateScheme(CommandInterface $command) { if ($command->getClient()->getConfig('scheme') !== 'https') { throw new RuntimeException('You must configure your S3 client to ' . 'use HTTPS in order to use the SSE-C features.'); } } private function prepareSseParams( CommandInterface $command, $isCopy = false ) { $prefix = $isCopy ? 'CopySource' : ''; // Base64 encode the provided key $key = $command[$prefix . 'SSECustomerKey']; $command[$prefix . 'SSECustomerKey'] = base64_encode($key); // Base64 the provided MD5 or, generate an MD5 if not provided if ($md5 = $command[$prefix . 'SSECustomerKeyMD5']) { $command[$prefix . 'SSECustomerKeyMD5'] = base64_encode($md5); } else { $command[$prefix . 'SSECustomerKeyMD5'] = base64_encode(md5($key, true)); } } } /" files with PHP streams, supporting "r", "w", "a", "x". * * # Supported stream related PHP functions: * - fopen, fclose, fread, fwrite, fseek, ftell, feof, fflush * - opendir, closedir, readdir, rewinddir * - copy, rename, unlink * - mkdir, rmdir, rmdir (recursive) * - file_get_contents, file_put_contents * - file_exists, filesize, is_file, is_dir * * # Opening "r" (read only) streams: * * Read only streams are truly streaming by default and will not allow you to seek. This is because data * read from the stream is not kept in memory or on the local filesystem. You can force a "r" stream to be seekable * by setting the "seekable" stream context option true. This will allow true streaming of data from Amazon S3, but * will maintain a buffer of previously read bytes in a 'php://temp' stream to allow seeking to previously read bytes * from the stream. * * You may pass any GetObject parameters as 's3' stream context options. These options will affect how the data is * downloaded from Amazon S3. * * # Opening "w" and "x" (write only) streams: * * Because Amazon S3 requires a Content-Length header, write only streams will maintain a 'php://temp' stream to buffer * data written to the stream until the stream is flushed (usually by closing the stream with fclose). * * You may pass any PutObject parameters as 's3' stream context options. These options will affect how the data is * uploaded to Amazon S3. * * When opening an "x" stream, the file must exist on Amazon S3 for the stream to open successfully. * * # Opening "a" (write only append) streams: * * Similar to "w" streams, opening append streams requires that the data be buffered in a "php://temp" stream. Append * streams will attempt to download the contents of an object in Amazon S3, seek to the end of the object, then allow * you to append to the contents of the object. The data will then be uploaded using a PutObject operation when the * stream is flushed (usually with fclose). * * You may pass any GetObject and/or PutObject parameters as 's3' stream context options. These options will affect how * the data is downloaded and uploaded from Amazon S3. * * Stream context options: * * - "seekable": Set to true to create a seekable "r" (read only) stream by using a php://temp stream buffer * - For "unlink" only: Any option that can be passed to the DeleteObject operation */ class StreamWrapper { /** * @var resource|null Stream context (this is set by PHP when a context is used) */ public $context; /** * @var S3Client Client used to send requests */ protected static $client; /** * @var string Mode the stream was opened with */ protected $mode; /** * @var EntityBody Underlying stream resource */ protected $body; /** * @var array Current parameters to use with the flush operation */ protected $params; /** * @var ListObjectsIterator Iterator used with opendir() and subsequent readdir() calls */ protected $objectIterator; /** * @var string The bucket that was opened when opendir() was called */ protected $openedBucket; /** * @var string The prefix of the bucket that was opened with opendir() */ protected $openedBucketPrefix; /** * @var array The next key to retrieve when using a directory iterator. Helps for fast directory traversal. */ protected static $nextStat = array(); /** * Register the 's3://' stream wrapper * * @param S3Client $client Client to use with the stream wrapper */ public static function register(S3Client $client) { if (in_array('s3', stream_get_wrappers())) { stream_wrapper_unregister('s3'); } stream_wrapper_register('s3', get_called_class(), STREAM_IS_URL); static::$client = $client; } /** * Close the stream */ public function stream_close() { $this->body = null; } /** * @param string $path * @param string $mode * @param int $options * @param string $opened_path * * @return bool */ public function stream_open($path, $mode, $options, &$opened_path) { // We don't care about the binary flag $this->mode = $mode = rtrim($mode, 'bt'); $this->params = $params = $this->getParams($path); $errors = array(); if (!$params['Key']) { $errors[] = 'Cannot open a bucket. You must specify a path in the form of s3://bucket/key'; } if (strpos($mode, '+')) { $errors[] = 'The Amazon S3 stream wrapper does not allow simultaneous reading and writing.'; } if (!in_array($mode, array('r', 'w', 'a', 'x'))) { $errors[] = "Mode not supported: {$mode}. Use one 'r', 'w', 'a', or 'x'."; } // When using mode "x" validate if the file exists before attempting to read if ($mode == 'x' && static::$client->doesObjectExist($params['Bucket'], $params['Key'], $this->getOptions())) { $errors[] = "{$path} already exists on Amazon S3"; } if (!$errors) { if ($mode == 'r') { $this->openReadStream($params, $errors); } elseif ($mode == 'a') { $this->openAppendStream($params, $errors); } else { $this->openWriteStream($params, $errors); } } return $errors ? $this->triggerError($errors) : true; } /** * @return bool */ public function stream_eof() { return $this->body->feof(); } /** * @return bool */ public function stream_flush() { if ($this->mode == 'r') { return false; } $this->body->rewind(); $params = $this->params; $params['Body'] = $this->body; // Attempt to guess the ContentType of the upload based on the // file extension of the key if (!isset($params['ContentType']) && ($type = Mimetypes::getInstance()->fromFilename($params['Key'])) ) { $params['ContentType'] = $type; } try { static::$client->putObject($params); return true; } catch (\Exception $e) { return $this->triggerError($e->getMessage()); } } /** * Read data from the underlying stream * * @param int $count Amount of bytes to read * * @return string */ public function stream_read($count) { return $this->body->read($count); } /** * Seek to a specific byte in the stream * * @param int $offset Seek offset * @param int $whence Whence (SEEK_SET, SEEK_CUR, SEEK_END) * * @return bool */ public function stream_seek($offset, $whence = SEEK_SET) { return $this->body->seek($offset, $whence); } /** * Get the current position of the stream * * @return int Returns the current position in the stream */ public function stream_tell() { return $this->body->ftell(); } /** * Write data the to the stream * * @param string $data * * @return int Returns the number of bytes written to the stream */ public function stream_write($data) { return $this->body->write($data); } /** * Delete a specific object * * @param string $path * @return bool */ public function unlink($path) { try { $this->clearStatInfo($path); static::$client->deleteObject($this->getParams($path)); return true; } catch (\Exception $e) { return $this->triggerError($e->getMessage()); } } /** * @return array */ public function stream_stat() { $stat = fstat($this->body->getStream()); // Add the size of the underlying stream if it is known if ($this->mode == 'r' && $this->body->getSize()) { $stat[7] = $stat['size'] = $this->body->getSize(); } return $stat; } /** * Provides information for is_dir, is_file, filesize, etc. Works on buckets, keys, and prefixes * * @param string $path * @param int $flags * * @return array Returns an array of stat data * @link http://www.php.net/manual/en/streamwrapper.url-stat.php */ public function url_stat($path, $flags) { // Check if this path is in the url_stat cache if (isset(static::$nextStat[$path])) { return static::$nextStat[$path]; } $parts = $this->getParams($path); if (!$parts['Key']) { // Stat "directories": buckets, or "s3://" if (!$parts['Bucket'] || static::$client->doesBucketExist($parts['Bucket'])) { return $this->formatUrlStat($path); } else { return $this->triggerError("File or directory not found: {$path}", $flags); } } try { try { $result = static::$client->headObject($parts)->toArray(); if (substr($parts['Key'], -1, 1) == '/' && $result['ContentLength'] == 0) { // Return as if it is a bucket to account for console bucket objects (e.g., zero-byte object "foo/") return $this->formatUrlStat($path); } else { // Attempt to stat and cache regular object return $this->formatUrlStat($result); } } catch (NoSuchKeyException $e) { // Maybe this isn't an actual key, but a prefix. Do a prefix listing of objects to determine. $result = static::$client->listObjects(array( 'Bucket' => $parts['Bucket'], 'Prefix' => rtrim($parts['Key'], '/') . '/', 'MaxKeys' => 1 )); if (!$result['Contents'] && !$result['CommonPrefixes']) { return $this->triggerError("File or directory not found: {$path}", $flags); } // This is a directory prefix return $this->formatUrlStat($path); } } catch (\Exception $e) { return $this->triggerError($e->getMessage(), $flags); } } /** * Support for mkdir(). * * @param string $path Directory which should be created. * @param int $mode Permissions. 700-range permissions map to ACL_PUBLIC. 600-range permissions map to * ACL_AUTH_READ. All other permissions map to ACL_PRIVATE. Expects octal form. * @param int $options A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE. * * @return bool * @link http://www.php.net/manual/en/streamwrapper.mkdir.php */ public function mkdir($path, $mode, $options) { $params = $this->getParams($path); if (!$params['Bucket']) { return false; } if (!isset($params['ACL'])) { $params['ACL'] = $this->determineAcl($mode); } return !isset($params['Key']) || $params['Key'] === '/' ? $this->createBucket($path, $params) : $this->createPseudoDirectory($path, $params); } /** * Remove a bucket from Amazon S3 * * @param string $path the directory path * @param int $options A bitwise mask of values * * @return bool true if directory was successfully removed * @link http://www.php.net/manual/en/streamwrapper.rmdir.php */ public function rmdir($path, $options) { $params = $this->getParams($path); if (!$params['Bucket']) { return $this->triggerError('You cannot delete s3://. Please specify a bucket.'); } try { if (!$params['Key']) { static::$client->deleteBucket(array('Bucket' => $params['Bucket'])); $this->clearStatInfo($path); return true; } // Use a key that adds a trailing slash if needed. $prefix = rtrim($params['Key'], '/') . '/'; $result = static::$client->listObjects(array( 'Bucket' => $params['Bucket'], 'Prefix' => $prefix, 'MaxKeys' => 1 )); // Check if the bucket contains keys other than the placeholder if ($result['Contents']) { foreach ($result['Contents'] as $key) { if ($key['Key'] == $prefix) { continue; } return $this->triggerError('Psuedo folder is not empty'); } return $this->unlink(rtrim($path, '/') . '/'); } return $result['CommonPrefixes'] ? $this->triggerError('Pseudo folder contains nested folders') : true; } catch (\Exception $e) { return $this->triggerError($e->getMessage()); } } /** * Support for opendir(). * * The opendir() method of the Amazon S3 stream wrapper supports a stream * context option of "listFilter". listFilter must be a callable that * accepts an associative array of object data and returns true if the * object should be yielded when iterating the keys in a bucket. * * @param string $path The path to the directory (e.g. "s3://dir[]") * @param string $options Whether or not to enforce safe_mode (0x04). Unused. * * @return bool true on success * @see http://www.php.net/manual/en/function.opendir.php */ public function dir_opendir($path, $options) { // Reset the cache $this->clearStatInfo(); $params = $this->getParams($path); $delimiter = $this->getOption('delimiter'); $filterFn = $this->getOption('listFilter'); if ($delimiter === null) { $delimiter = '/'; } if ($params['Key']) { $params['Key'] = rtrim($params['Key'], $delimiter) . $delimiter; } $this->openedBucket = $params['Bucket']; $this->openedBucketPrefix = $params['Key']; $operationParams = array('Bucket' => $params['Bucket'], 'Prefix' => $params['Key']); if ($delimiter) { $operationParams['Delimiter'] = $delimiter; } $objectIterator = static::$client->getIterator('ListObjects', $operationParams, array( 'return_prefixes' => true, 'sort_results' => true )); // Filter our "/" keys added by the console as directories, and ensure // that if a filter function is provided that it passes the filter. $this->objectIterator = new FilterIterator( $objectIterator, function ($key) use ($filterFn) { // Each yielded results can contain a "Key" or "Prefix" return (!$filterFn || call_user_func($filterFn, $key)) && (!isset($key['Key']) || substr($key['Key'], -1, 1) !== '/'); } ); $this->objectIterator->next(); return true; } /** * Close the directory listing handles * * @return bool true on success */ public function dir_closedir() { $this->objectIterator = null; return true; } /** * This method is called in response to rewinddir() * * @return boolean true on success */ public function dir_rewinddir() { $this->clearStatInfo(); $this->objectIterator->rewind(); return true; } /** * This method is called in response to readdir() * * @return string Should return a string representing the next filename, or false if there is no next file. * * @link http://www.php.net/manual/en/function.readdir.php */ public function dir_readdir() { // Skip empty result keys if (!$this->objectIterator->valid()) { return false; } $current = $this->objectIterator->current(); if (isset($current['Prefix'])) { // Include "directories". Be sure to strip a trailing "/" // on prefixes. $prefix = rtrim($current['Prefix'], '/'); $result = str_replace($this->openedBucketPrefix, '', $prefix); $key = "s3://{$this->openedBucket}/{$prefix}"; $stat = $this->formatUrlStat($prefix); } else { // Remove the prefix from the result to emulate other // stream wrappers. $result = str_replace($this->openedBucketPrefix, '', $current['Key']); $key = "s3://{$this->openedBucket}/{$current['Key']}"; $stat = $this->formatUrlStat($current); } // Cache the object data for quick url_stat lookups used with // RecursiveDirectoryIterator. static::$nextStat = array($key => $stat); $this->objectIterator->next(); return $result; } /** * Called in response to rename() to rename a file or directory. Currently only supports renaming objects. * * @param string $path_from the path to the file to rename * @param string $path_to the new path to the file * * @return bool true if file was successfully renamed * @link http://www.php.net/manual/en/function.rename.php */ public function rename($path_from, $path_to) { $partsFrom = $this->getParams($path_from); $partsTo = $this->getParams($path_to); $this->clearStatInfo($path_from); $this->clearStatInfo($path_to); if (!$partsFrom['Key'] || !$partsTo['Key']) { return $this->triggerError('The Amazon S3 stream wrapper only supports copying objects'); } try { // Copy the object and allow overriding default parameters if desired, but by default copy metadata static::$client->copyObject($this->getOptions() + array( 'Bucket' => $partsTo['Bucket'], 'Key' => $partsTo['Key'], 'CopySource' => '/' . $partsFrom['Bucket'] . '/' . rawurlencode($partsFrom['Key']), 'MetadataDirective' => 'COPY' )); // Delete the original object static::$client->deleteObject(array( 'Bucket' => $partsFrom['Bucket'], 'Key' => $partsFrom['Key'] ) + $this->getOptions()); } catch (\Exception $e) { return $this->triggerError($e->getMessage()); } return true; } /** * Cast the stream to return the underlying file resource * * @param int $cast_as STREAM_CAST_FOR_SELECT or STREAM_CAST_AS_STREAM * * @return resource */ public function stream_cast($cast_as) { return $this->body->getStream(); } /** * Get the stream context options available to the current stream * * @return array */ protected function getOptions() { $context = $this->context ?: stream_context_get_default(); $options = stream_context_get_options($context); return isset($options['s3']) ? $options['s3'] : array(); } /** * Get a specific stream context option * * @param string $name Name of the option to retrieve * * @return mixed|null */ protected function getOption($name) { $options = $this->getOptions(); return isset($options[$name]) ? $options[$name] : null; } /** * Get the bucket and key from the passed path (e.g. s3://bucket/key) * * @param string $path Path passed to the stream wrapper * * @return array Hash of 'Bucket', 'Key', and custom params */ protected function getParams($path) { $parts = explode('/', substr($path, 5), 2); $params = $this->getOptions(); unset($params['seekable']); return array( 'Bucket' => $parts[0], 'Key' => isset($parts[1]) ? $parts[1] : null ) + $params; } /** * Serialize and sign a command, returning a request object * * @param CommandInterface $command Command to sign * * @return RequestInterface */ protected function getSignedRequest($command) { $request = $command->prepare(); $request->dispatch('request.before_send', array('request' => $request)); return $request; } /** * Initialize the stream wrapper for a read only stream * * @param array $params Operation parameters * @param array $errors Any encountered errors to append to * * @return bool */ protected function openReadStream(array $params, array &$errors) { // Create the command and serialize the request $request = $this->getSignedRequest(static::$client->getCommand('GetObject', $params)); // Create a stream that uses the EntityBody object $factory = $this->getOption('stream_factory') ?: new PhpStreamRequestFactory(); $this->body = $factory->fromRequest($request, array(), array('stream_class' => 'Guzzle\Http\EntityBody')); // Wrap the body in a caching entity body if seeking is allowed if ($this->getOption('seekable')) { $this->body = new CachingEntityBody($this->body); } return true; } /** * Initialize the stream wrapper for a write only stream * * @param array $params Operation parameters * @param array $errors Any encountered errors to append to * * @return bool */ protected function openWriteStream(array $params, array &$errors) { $this->body = new EntityBody(fopen('php://temp', 'r+')); } /** * Initialize the stream wrapper for an append stream * * @param array $params Operation parameters * @param array $errors Any encountered errors to append to * * @return bool */ protected function openAppendStream(array $params, array &$errors) { try { // Get the body of the object $this->body = static::$client->getObject($params)->get('Body'); $this->body->seek(0, SEEK_END); } catch (S3Exception $e) { // The object does not exist, so use a simple write stream $this->openWriteStream($params, $errors); } return true; } /** * Trigger one or more errors * * @param string|array $errors Errors to trigger * @param mixed $flags If set to STREAM_URL_STAT_QUIET, then no error or exception occurs * * @return bool Returns false * @throws RuntimeException if throw_errors is true */ protected function triggerError($errors, $flags = null) { if ($flags & STREAM_URL_STAT_QUIET) { // This is triggered with things like file_exists() if ($flags & STREAM_URL_STAT_LINK) { // This is triggered for things like is_link() return $this->formatUrlStat(false); } return false; } // This is triggered when doing things like lstat() or stat() trigger_error(implode("\n", (array) $errors), E_USER_WARNING); return false; } /** * Prepare a url_stat result array * * @param string|array $result Data to add * * @return array Returns the modified url_stat result */ protected function formatUrlStat($result = null) { static $statTemplate = array( 0 => 0, 'dev' => 0, 1 => 0, 'ino' => 0, 2 => 0, 'mode' => 0, 3 => 0, 'nlink' => 0, 4 => 0, 'uid' => 0, 5 => 0, 'gid' => 0, 6 => -1, 'rdev' => -1, 7 => 0, 'size' => 0, 8 => 0, 'atime' => 0, 9 => 0, 'mtime' => 0, 10 => 0, 'ctime' => 0, 11 => -1, 'blksize' => -1, 12 => -1, 'blocks' => -1, ); $stat = $statTemplate; $type = gettype($result); // Determine what type of data is being cached if ($type == 'NULL' || $type == 'string') { // Directory with 0777 access - see "man 2 stat". $stat['mode'] = $stat[2] = 0040777; } elseif ($type == 'array' && isset($result['LastModified'])) { // ListObjects or HeadObject result $stat['mtime'] = $stat[9] = $stat['ctime'] = $stat[10] = strtotime($result['LastModified']); $stat['size'] = $stat[7] = (isset($result['ContentLength']) ? $result['ContentLength'] : $result['Size']); // Regular file with 0777 access - see "man 2 stat". $stat['mode'] = $stat[2] = 0100777; } return $stat; } /** * Clear the next stat result from the cache * * @param string $path If a path is specific, clearstatcache() will be called */ protected function clearStatInfo($path = null) { static::$nextStat = array(); if ($path) { clearstatcache(true, $path); } } /** * Creates a bucket for the given parameters. * * @param string $path Stream wrapper path * @param array $params A result of StreamWrapper::getParams() * * @return bool Returns true on success or false on failure */ private function createBucket($path, array $params) { if (static::$client->doesBucketExist($params['Bucket'])) { return $this->triggerError("Directory already exists: {$path}"); } try { static::$client->createBucket($params); $this->clearStatInfo($path); return true; } catch (\Exception $e) { return $this->triggerError($e->getMessage()); } } /** * Creates a pseudo-folder by creating an empty "/" suffixed key * * @param string $path Stream wrapper path * @param array $params A result of StreamWrapper::getParams() * * @return bool */ private function createPseudoDirectory($path, array $params) { // Ensure the path ends in "/" and the body is empty. $params['Key'] = rtrim($params['Key'], '/') . '/'; $params['Body'] = ''; // Fail if this pseudo directory key already exists if (static::$client->doesObjectExist($params['Bucket'], $params['Key'])) { return $this->triggerError("Directory already exists: {$path}"); } try { static::$client->putObject($params); $this->clearStatInfo($path); return true; } catch (\Exception $e) { return $this->triggerError($e->getMessage()); } } /** * Determine the most appropriate ACL based on a file mode. * * @param int $mode File mode * * @return string */ private function determineAcl($mode) { $mode = decoct($mode); if ($mode >= 700 && $mode <= 799) { return 'public-read'; } if ($mode >= 600 && $mode <= 699) { return 'authenticated-read'; } return 'private'; } } options = Collection::fromConfig( $options, array('concurrency' => 10), array('client', 'bucket', 'iterator', 'source_converter') ); $this->init(); } public static function getAllEvents() { return array(self::BEFORE_TRANSFER, self::AFTER_TRANSFER); } /** * Begin transferring files */ public function transfer() { // Pull out chunks of uploads to upload in parallel $iterator = new ChunkedIterator($this->options['iterator'], $this->options['concurrency']); foreach ($iterator as $files) { $this->transferFiles($files); } } /** * Create a command or special transfer action for the * * @param \SplFileInfo $file File used to build the transfer * * @return CommandInterface|callable */ abstract protected function createTransferAction(\SplFileInfo $file); /** * Hook to initialize subclasses * @codeCoverageIgnore */ protected function init() {} /** * Process and transfer a group of files * * @param array $files Files to transfer */ protected function transferFiles(array $files) { // Create the base event data object $event = array('sync' => $this, 'client' => $this->options['client']); $commands = array(); foreach ($files as $file) { if ($action = $this->createTransferAction($file)) { $event = array('command' => $action, 'file' => $file) + $event; $this->dispatch(self::BEFORE_TRANSFER, $event); if ($action instanceof CommandInterface) { $commands[] = $action; } elseif (is_callable($action)) { $action(); $this->dispatch(self::AFTER_TRANSFER, $event); } } } $this->transferCommands($commands); } /** * Transfer an array of commands in parallel * * @param array $commands Commands to transfer */ protected function transferCommands(array $commands) { if ($commands) { $this->options['client']->execute($commands); // Notify listeners that each command finished $event = array('sync' => $this, 'client' => $this->options['client']); foreach ($commands as $command) { $event['command'] = $command; $this->dispatch(self::AFTER_TRANSFER, $event); } } } } bucket = $bucket; return $this; } /** * Set the Amazon S3 client object that will send requests * * @param S3Client $client Amazon S3 client * * @return $this */ public function setClient(S3Client $client) { $this->client = $client; return $this; } /** * Set a custom iterator that returns \SplFileInfo objects for the source data * * @param \Iterator $iterator * * @return $this */ public function setSourceIterator(\Iterator $iterator) { $this->sourceIterator = $iterator; return $this; } /** * Set a custom object key provider instead of building one internally * * @param FileNameConverterInterface $converter Filename to object key provider * * @return $this */ public function setSourceFilenameConverter(FilenameConverterInterface $converter) { $this->sourceConverter = $converter; return $this; } /** * Set a custom object key provider instead of building one internally * * @param FileNameConverterInterface $converter Filename to object key provider * * @return $this */ public function setTargetFilenameConverter(FilenameConverterInterface $converter) { $this->targetConverter = $converter; return $this; } /** * Set the base directory of the files being transferred. The base directory is removed from each file path before * converting the file path to an object key or vice versa. * * @param string $baseDir Base directory, which will be deleted from each uploaded object key * * @return $this */ public function setBaseDir($baseDir) { $this->baseDir = $baseDir; return $this; } /** * Specify a prefix to prepend to each Amazon S3 object key or the prefix where object are stored in a bucket * * Can be used to upload files to a pseudo sub-folder key or only download files from a pseudo sub-folder * * @param string $keyPrefix Prefix for each uploaded key * * @return $this */ public function setKeyPrefix($keyPrefix) { // Removing leading slash $this->keyPrefix = ltrim($keyPrefix, '/'); return $this; } /** * Specify the delimiter used for the targeted filesystem (default delimiter is "/") * * @param string $delimiter Delimiter to use to separate paths * * @return $this */ public function setDelimiter($delimiter) { $this->delimiter = $delimiter; return $this; } /** * Specify an array of operation parameters to apply to each operation executed by the sync object * * @param array $params Associative array of PutObject (upload) GetObject (download) parameters * * @return $this */ public function setOperationParams(array $params) { $this->params = $params; return $this; } /** * Set the number of files that can be transferred concurrently * * @param int $concurrency Number of concurrent transfers * * @return $this */ public function setConcurrency($concurrency) { $this->concurrency = $concurrency; return $this; } /** * Set to true to force transfers even if a file already exists and has not changed * * @param bool $force Set to true to force transfers without checking if it has changed * * @return $this */ public function force($force = false) { $this->forcing = (bool) $force; return $this; } /** * Enable debug mode * * @param bool|resource $enabledOrResource Set to true or false to enable or disable debug output. Pass an opened * fopen resource to write to instead of writing to standard out. * @return $this */ public function enableDebugOutput($enabledOrResource = true) { $this->debug = $enabledOrResource; return $this; } /** * Add a filename filter that uses a regular expression to filter out files that you do not wish to transfer. * * @param string $search Regular expression search (in preg_match format). Any filename that matches this regex * will not be transferred. * @return $this */ public function addRegexFilter($search) { $this->assertFileIteratorSet(); $this->sourceIterator = new FilterIterator($this->sourceIterator, function ($i) use ($search) { return !preg_match($search, (string) $i); }); $this->sourceIterator->rewind(); return $this; } /** * Builds a UploadSync or DownloadSync object * * @return AbstractSync */ public function build() { $this->validateRequirements(); $this->sourceConverter = $this->sourceConverter ?: $this->getDefaultSourceConverter(); $this->targetConverter = $this->targetConverter ?: $this->getDefaultTargetConverter(); // Only wrap the source iterator in a changed files iterator if we are not forcing the transfers if (!$this->forcing) { $this->sourceIterator->rewind(); $this->sourceIterator = new ChangedFilesIterator( new \NoRewindIterator($this->sourceIterator), $this->getTargetIterator(), $this->sourceConverter, $this->targetConverter ); $this->sourceIterator->rewind(); } $sync = $this->specificBuild(); if ($this->params) { $this->addCustomParamListener($sync); } if ($this->debug) { $this->addDebugListener($sync, is_bool($this->debug) ? STDOUT : $this->debug); } return $sync; } /** * Hook to implement in subclasses * * @return AbstractSync */ abstract protected function specificBuild(); /** * @return \Iterator */ abstract protected function getTargetIterator(); /** * @return FilenameConverterInterface */ abstract protected function getDefaultSourceConverter(); /** * @return FilenameConverterInterface */ abstract protected function getDefaultTargetConverter(); /** * Add a listener to the sync object to output debug information while transferring * * @param AbstractSync $sync Sync object to listen to * @param resource $resource Where to write debug messages */ abstract protected function addDebugListener(AbstractSync $sync, $resource); /** * Validate that the builder has the minimal requirements * * @throws RuntimeException if the builder is not configured completely */ protected function validateRequirements() { if (!$this->client) { throw new RuntimeException('No client was provided'); } if (!$this->bucket) { throw new RuntimeException('No bucket was provided'); } $this->assertFileIteratorSet(); } /** * Ensure that the base file iterator has been provided * * @throws RuntimeException */ protected function assertFileIteratorSet() { // Interesting... Need to use isset because: Object of class GlobIterator could not be converted to boolean if (!isset($this->sourceIterator)) { throw new RuntimeException('A source file iterator must be specified'); } } /** * Wraps a generated iterator in a filter iterator that removes directories * * @param \Iterator $iterator Iterator to wrap * * @return \Iterator * @throws UnexpectedValueException */ protected function filterIterator(\Iterator $iterator) { $f = new FilterIterator($iterator, function ($i) { if (!$i instanceof \SplFileInfo) { throw new UnexpectedValueException('All iterators for UploadSync must return SplFileInfo objects'); } return $i->isFile(); }); $f->rewind(); return $f; } /** * Add the custom param listener to a transfer object * * @param HasDispatcherInterface $sync */ protected function addCustomParamListener(HasDispatcherInterface $sync) { $params = $this->params; $sync->getEventDispatcher()->addListener( UploadSync::BEFORE_TRANSFER, function (Event $e) use ($params) { if ($e['command'] instanceof CommandInterface) { $e['command']->overwriteWith($params); } } ); } /** * Create an Amazon S3 file iterator based on the given builder settings * * @return OpendirIterator */ protected function createS3Iterator() { // Ensure that the stream wrapper is registered $this->client->registerStreamWrapper(); // Calculate the opendir() bucket and optional key prefix location $dir = "s3://{$this->bucket}"; if ($this->keyPrefix) { $dir .= '/' . ltrim($this->keyPrefix, '/ '); } // Use opendir so that we can pass stream context to the iterator $dh = opendir($dir, stream_context_create(array( 's3' => array( 'delimiter' => '', 'listFilter' => function ($obj) { // Ensure that we do not try to download a glacier object. return !isset($obj['StorageClass']) || $obj['StorageClass'] != 'GLACIER'; } ) ))); // Add the trailing slash for the OpendirIterator concatenation if (!$this->keyPrefix) { $dir .= '/'; } return $this->filterIterator(new \NoRewindIterator(new OpendirIterator($dh, $dir))); } } targetIterator = $targetIterator; $this->sourceConverter = $sourceConverter; $this->targetConverter = $targetConverter; parent::__construct($sourceIterator); } public function accept() { $current = $this->current(); $key = $this->sourceConverter->convert($this->normalize($current)); if (!($data = $this->getTargetData($key))) { return true; } // Ensure the Content-Length matches and it hasn't been modified since the mtime return $current->getSize() != $data[0] || $current->getMTime() > $data[1]; } /** * Returns an array of the files from the target iterator that were not found in the source iterator * * @return array */ public function getUnmatched() { return array_keys($this->cache); } /** * Get key information from the target iterator for a particular filename * * @param string $key Target iterator filename * * @return array|bool Returns an array of data, or false if the key is not in the iterator */ protected function getTargetData($key) { $key = $this->cleanKey($key); if (isset($this->cache[$key])) { $result = $this->cache[$key]; unset($this->cache[$key]); return $result; } $it = $this->targetIterator; while ($it->valid()) { $value = $it->current(); $data = array($value->getSize(), $value->getMTime()); $filename = $this->targetConverter->convert($this->normalize($value)); $filename = $this->cleanKey($filename); if ($filename == $key) { return $data; } $this->cache[$filename] = $data; $it->next(); } return false; } private function normalize($current) { $asString = (string) $current; return strpos($asString, 's3://') === 0 ? $asString : $current->getRealPath(); } private function cleanKey($key) { return ltrim($key, '/'); } } getPathname(); list($bucket, $key) = explode('/', substr($sourceFilename, 5), 2); $filename = $this->options['source_converter']->convert($sourceFilename); $this->createDirectory($filename); // Some S3 buckets contains nested files under the same name as a directory if (is_dir($filename)) { return false; } // Allow a previously interrupted download to resume if (file_exists($filename) && $this->options['resumable']) { return new ResumableDownload($this->options['client'], $bucket, $key, $filename); } return $this->options['client']->getCommand('GetObject', array( 'Bucket' => $bucket, 'Key' => $key, 'SaveAs' => $filename )); } /** * @codeCoverageIgnore */ protected function createDirectory($filename) { $directory = dirname($filename); // Some S3 clients create empty files to denote directories. Remove these so that we can create the directory. if (is_file($directory) && filesize($directory) == 0) { unlink($directory); } // Create the directory if it does not exist if (!is_dir($directory) && !mkdir($directory, 0777, true)) { $errors = error_get_last(); throw new RuntimeException('Could not create directory: ' . $directory . ' - ' . $errors['message']); } } protected function filterCommands(array $commands) { // Build a list of all of the directories in each command so that we don't attempt to create an empty dir in // the same parallel transfer as attempting to create a file in that dir $dirs = array(); foreach ($commands as $command) { $parts = array_values(array_filter(explode('/', $command['SaveAs']))); for ($i = 0, $total = count($parts); $i < $total; $i++) { $dir = ''; for ($j = 0; $j < $i; $j++) { $dir .= '/' . $parts[$j]; } if ($dir && !in_array($dir, $dirs)) { $dirs[] = $dir; } } } return array_filter($commands, function ($command) use ($dirs) { return !in_array($command['SaveAs'], $dirs); }); } protected function transferCommands(array $commands) { parent::transferCommands($this->filterCommands($commands)); } } directory = $directory; return $this; } /** * Call this function to allow partial downloads to be resumed if the download was previously interrupted * * @return self */ public function allowResumableDownloads() { $this->resumable = true; return $this; } protected function specificBuild() { $sync = new DownloadSync(array( 'client' => $this->client, 'bucket' => $this->bucket, 'iterator' => $this->sourceIterator, 'source_converter' => $this->sourceConverter, 'target_converter' => $this->targetConverter, 'concurrency' => $this->concurrency, 'resumable' => $this->resumable, 'directory' => $this->directory )); return $sync; } protected function getTargetIterator() { if (!$this->directory) { throw new RuntimeException('A directory is required'); } if (!is_dir($this->directory) && !mkdir($this->directory, 0777, true)) { // @codeCoverageIgnoreStart throw new RuntimeException('Unable to create root download directory: ' . $this->directory); // @codeCoverageIgnoreEnd } return $this->filterIterator( new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->directory)) ); } protected function getDefaultSourceConverter() { return new KeyConverter( "s3://{$this->bucket}/{$this->baseDir}", $this->directory . DIRECTORY_SEPARATOR, $this->delimiter ); } protected function getDefaultTargetConverter() { return new KeyConverter("s3://{$this->bucket}/{$this->baseDir}", '', $this->delimiter); } protected function assertFileIteratorSet() { $this->sourceIterator = $this->sourceIterator ?: $this->createS3Iterator(); } protected function addDebugListener(AbstractSync $sync, $resource) { $sync->getEventDispatcher()->addListener(UploadSync::BEFORE_TRANSFER, function (Event $e) use ($resource) { if ($e['command'] instanceof CommandInterface) { $from = $e['command']['Bucket'] . '/' . $e['command']['Key']; $to = $e['command']['SaveAs'] instanceof EntityBodyInterface ? $e['command']['SaveAs']->getUri() : $e['command']['SaveAs']; fwrite($resource, "Downloading {$from} -> {$to}\n"); } elseif ($e['command'] instanceof ResumableDownload) { $from = $e['command']->getBucket() . '/' . $e['command']->getKey(); $to = $e['command']->getFilename(); fwrite($resource, "Resuming {$from} -> {$to}\n"); } }); } } baseDir = (string) $baseDir; $this->prefix = $prefix; $this->delimiter = $delimiter; } public function convert($filename) { $key = $filename; // Remove base directory from the key (only the first occurrence) if ($this->baseDir && (false !== $pos = strpos($filename, $this->baseDir))) { $key = substr_replace($key, '', $pos, strlen($this->baseDir)); } // Replace Windows directory separators to become Unix style, and convert that to the custom dir separator $key = str_replace('/', $this->delimiter, str_replace('\\', '/', $key)); // Add the key prefix and remove double slashes that are not in the protocol (e.g. prefixed with ":") $delim = preg_quote($this->delimiter); $key = preg_replace( "#(?delimiter, $this->prefix . $key ); return $key; } } options['multipart_upload_size']) { $this->options['multipart_upload_size'] = AbstractTransfer::MIN_PART_SIZE; } } protected function createTransferAction(\SplFileInfo $file) { // Open the file for reading $filename = $file->getRealPath() ?: $file->getPathName(); if (!($resource = fopen($filename, 'r'))) { // @codeCoverageIgnoreStart throw new RuntimeException('Could not open ' . $file->getPathname() . ' for reading'); // @codeCoverageIgnoreEnd } $key = $this->options['source_converter']->convert($filename); $body = EntityBody::factory($resource); // Determine how the ACL should be applied if ($acl = $this->options['acl']) { $aclType = is_string($this->options['acl']) ? 'ACL' : 'ACP'; } else { $acl = 'private'; $aclType = 'ACL'; } // Use a multi-part upload if the file is larger than the cutoff size and is a regular file if ($body->getWrapper() == 'plainfile' && $file->getSize() >= $this->options['multipart_upload_size']) { $builder = UploadBuilder::newInstance() ->setBucket($this->options['bucket']) ->setKey($key) ->setMinPartSize($this->options['multipart_upload_size']) ->setOption($aclType, $acl) ->setClient($this->options['client']) ->setSource($body) ->setConcurrency($this->options['concurrency']); $this->dispatch( self::BEFORE_MULTIPART_BUILD, array('builder' => $builder, 'file' => $file) ); return $builder->build(); } return $this->options['client']->getCommand('PutObject', array( 'Bucket' => $this->options['bucket'], 'Key' => $key, 'Body' => $body, $aclType => $acl )); } } baseDir = realpath($path); $this->sourceIterator = $this->filterIterator(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator( $path, FI::SKIP_DOTS | FI::UNIX_PATHS | FI::FOLLOW_SYMLINKS ))); return $this; } /** * Set a glob expression that will match files to upload to Amazon S3 * * @param string $glob Glob expression * * @return $this * @link http://www.php.net/manual/en/function.glob.php */ public function uploadFromGlob($glob) { $this->sourceIterator = $this->filterIterator( new \GlobIterator($glob, FI::SKIP_DOTS | FI::UNIX_PATHS | FI::FOLLOW_SYMLINKS) ); return $this; } /** * Set a canned ACL to apply to each uploaded object * * @param string $acl Canned ACL for each upload * * @return $this */ public function setAcl($acl) { $this->acp = $acl; return $this; } /** * Set an Access Control Policy to apply to each uploaded object * * @param Acp $acp Access control policy * * @return $this */ public function setAcp(Acp $acp) { $this->acp = $acp; return $this; } /** * Set the multipart upload size threshold. When the size of a file exceeds this value, the file will be uploaded * using a multipart upload. * * @param int $size Size threshold * * @return $this */ public function setMultipartUploadSize($size) { $this->multipartUploadSize = $size; return $this; } protected function specificBuild() { $sync = new UploadSync(array( 'client' => $this->client, 'bucket' => $this->bucket, 'iterator' => $this->sourceIterator, 'source_converter' => $this->sourceConverter, 'target_converter' => $this->targetConverter, 'concurrency' => $this->concurrency, 'multipart_upload_size' => $this->multipartUploadSize, 'acl' => $this->acp )); return $sync; } protected function addCustomParamListener(HasDispatcherInterface $sync) { // Handle the special multi-part upload event parent::addCustomParamListener($sync); $params = $this->params; $sync->getEventDispatcher()->addListener( UploadSync::BEFORE_MULTIPART_BUILD, function (Event $e) use ($params) { foreach ($params as $k => $v) { $e['builder']->setOption($k, $v); } } ); } protected function getTargetIterator() { return $this->createS3Iterator(); } protected function getDefaultSourceConverter() { return new KeyConverter($this->baseDir, $this->keyPrefix . $this->delimiter, $this->delimiter); } protected function getDefaultTargetConverter() { return new KeyConverter('s3://' . $this->bucket . '/', '', DIRECTORY_SEPARATOR); } protected function addDebugListener(AbstractSync $sync, $resource) { $sync->getEventDispatcher()->addListener(UploadSync::BEFORE_TRANSFER, function (Event $e) use ($resource) { $c = $e['command']; if ($c instanceof CommandInterface) { $uri = $c['Body']->getUri(); $size = $c['Body']->getSize(); fwrite($resource, "Uploading {$uri} -> {$c['Key']} ({$size} bytes)\n"); return; } // Multipart upload $body = $c->getSource(); $totalSize = $body->getSize(); $progress = 0; fwrite($resource, "Beginning multipart upload: " . $body->getUri() . ' -> '); fwrite($resource, $c->getState()->getFromId('Key') . " ({$totalSize} bytes)\n"); $c->getEventDispatcher()->addListener( AbstractTransfer::BEFORE_PART_UPLOAD, function ($e) use (&$progress, $totalSize, $resource) { $command = $e['command']; $size = $command['Body']->getContentLength(); $percentage = number_format(($progress / $totalSize) * 100, 2); fwrite($resource, "- Part {$command['PartNumber']} ({$size} bytes, {$percentage}%)\n"); $progress += $size; } ); }); } } # Apache License Version 2.0, January 2004 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION ## 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. ## 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. ## 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. ## 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 1. You must give any other recipients of the Work or Derivative Works a copy of this License; and 2. You must cause any modified files to carry prominent notices stating that You changed the files; and 3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. ## 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. ## 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. ## 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. ## 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. ## 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS signature = array( 'consumer_key' => $consumerKey, 'shared_secret' => $consumerSecret, 'oauth_token' => $accessToken, 'oauth_secret' => $tokenSecret ); $this->__wakeup(); } /** * Wakeup function on unserialize * */ public function __wakeup() { // curl setup $this->curl = curl_init(); if (!$this->curl) { throw new \Exception("Failed to initialize curl"); } // ca bundle $cacrt = __DIR__ . '/ca.crt'; if (!is_file($cacrt)) { throw new \Exception("Failed to load ca certificate"); } // check for phar execution // in case we have to move the .crt file to a temp folder so curl is able to load it if (substr(__FILE__, 0, 7) == 'phar://') { $cacrt = self::extractPharCacert($cacrt); } curl_setopt($this->curl, CURLOPT_CAINFO, $cacrt); } /** * Upload a file from a string * * @param string $path full path containing leading slash and file name * @param string $data binary data * * @return object described in createFile() */ public function uploadFromString($path, $data) { // create the temporary stream $stream = fopen('php://temp', 'w+'); // write the data fwrite($stream, $data); // rewind the pointer rewind($stream); // upload as a stream return $this->uploadFromStream($path, $stream); } /** * Upload a file from a stream resource * * @param string $path full path containing leading slash and file name * @param resource $stream resource to read data from * * @return object described in createFile() */ public function uploadFromStream($path, $stream) { // send data 1MB at a time $parts = array(); $limit = 1048576; $buffer = ''; while ($buffer .= fread($stream, $limit)) { // check $buffer size for remote stream // ref. http://php.net/manual/function.fread.php // see Example #3 Remote fread() examples if (!feof($stream) && strlen($buffer) < $limit) { continue; } $next = ''; if (strlen($buffer) > $limit) { $next = substr($buffer, $limit); $buffer = substr($buffer, 0, $limit); } $parts[] = $this->sendData($buffer); $buffer = $next; } // close the stream fclose($stream); // update the file in the cloud return $this->createFile('/' . $path, $parts); } /** * Read a file to a string * * @param string $path full path containing leading slash and file name * * @return array contains key of contents which contains binary data of the file */ public function readToString($path) { $object = $this->readToStream($path); $object['contents'] = stream_get_contents($object['stream']); fclose($object['stream']); unset($object['stream']); return $object; } /** * Read a file to a stream * * @param string $path full path containing leading slash and file name * * @return array contains key of stream which contains a stream resource */ public function readToStream($path) { // create the temporary stream $stream = fopen('php://temp', 'w+'); // obtain the list of parts for the file (should be an array of one) $files = $this->listPath('/' . $path, array('include_parts' => true)); if (is_array($files) === false || sizeof($files) !== 1) { throw new \Exception("Could not find file at path: '" . $path . "'"); } // found it, verify its a file $file = array_pop($files); if ($file->{"type"} != "file") { throw new \Exception("Could not find file at path: '" . $path . "'"); } // obtain each part and add it to the stream foreach ($file->{"revisions"}[0]->{"parts"} as $part) { $data = $this->getPart($part->{"fingerprint"}, $part->{"size"}); fwrite($stream, $data); } // rewind the pointer rewind($stream); return compact('stream'); } /** * Send a request to remove a given file. * * @param string $path full path containing leading slash and file name * * @return bool true if the file was removed successfully */ public function removeFile($path) { return $this->removeItem($path, 'file'); } /** * Send a request to remove a given dir. * * @param string $path full path containing leading slash and dir name * * @return bool true if the dir was removed successfully */ public function removeDir($path) { return $this->removeItem($path, 'dir'); } /** * Send a request to remove a given item. * * @param string $path full path containing leading slash and file name * @param string $type file or dir * * @return bool true if the item was removed successfully */ private function removeItem($path, $type) { $request = array(); $request["object_type"] = $type; $this->updateObject('remove', $path, $request); return true; } /** * Rename a file * * Object structure: * { * object_id: "4008" * path: "/example" * type: "dir" || "file" * share_id: "0" * share_owner: "21956799" * company_id: NULL * size: filesize in bytes, 0 for folders * created_time: unix timestamp, e.g. "1389731126" * modified_time: unix timestamp, e.g. "1389731126" * date_last_synced: unix timestamp, e.g. "1389731126" * removed_time: unix timestamp, e.g. "1389731126" or empty string for non-deleted files/folders * mime_type: string * revisions: array of revision objects * } * * @param string $source_path full path containing leading slash and file name * @param string $destination_path full path containing leading slash and file name * * @return stdClass using structure as noted above */ public function rename($source_path, $destination_path) { return $this->updateObject('rename', $source_path, array('new_path' => $destination_path)); } /** * Copy an item * * Object structure: * { * object_id: "4008" * path: "/example" * type: "dir" || "file" * share_id: "0" * share_owner: "21956799" * company_id: NULL * size: filesize in bytes, 0 for folders * created_time: unix timestamp, e.g. "1389731126" * modified_time: unix timestamp, e.g. "1389731126" * date_last_synced: unix timestamp, e.g. "1389731126" * removed_time: unix timestamp, e.g. "1389731126" or empty string for non-deleted files/folders * mime_type: string * revisions: array of revision objects * } * * @param string $source_path full path containing leading slash and file name * @param string $destination_path full path containing leading slash and file name * * @return stdClass using structure as noted above */ public function copy($source_path, $destination_path) { return $this->updateObject('copy', $source_path, array('new_path' => $destination_path)); } /** * List objects within a path * * Object structure: * { * object_id: "4008" * path: "/example" * type: "dir" || "file" * share_id: "0" * share_owner: "21956799" * company_id: NULL * size: filesize in bytes, 0 for folders * created_time: unix timestamp, e.g. "1389731126" * modified_time: unix timestamp, e.g. "1389731126" * date_last_synced: unix timestamp, e.g. "1389731126" * removed_time: unix timestamp, e.g. "1389731126" or empty string for non-deleted files/folders * mime_type: string * revisions: array of revision objects * } * * @param string $path full path with leading slash and optionally a filename * @param array $additionalOptions used for passing options such as include_parts * * @return array List of file/folder objects described above. */ public function listPath($path, $additionalOptions = null) { $list_watermark = false; $return = array(); do { $request = array(); $request["path"] = $path; $request["max_items"] = 100; $request["list_watermark"] = $list_watermark; if ($additionalOptions) { $request = array_merge($request, $additionalOptions); } $result = $this->post("list_objects", $this->encodeRequest("list_objects", $request), true); // add the children if we got some, otherwise add the root object itself to the return if (isset($result->result->children) && empty($result->result->children) === false) { $return = array_merge($return, $result->result->children); $list_watermark = $result->result->list_watermark; } else { $return[] = $result->result->object; } } while (isset($result->result->more_items) && $result->result->more_items == 1); return $return; } /** * Get directory or file meta data * * Object structure: * { * id: "/copy/example" * path: "/example" * name: "example", * type: "dir" || "file" * share_id: "0" * share_owner: "21956799" * company_id: NULL * size: filesize in bytes, 0 for folders * created_time: unix timestamp, e.g. "1389731126" * modified_time: unix timestamp, e.g. "1389731126" * date_last_synced: unix timestamp, e.g. "1389731126" * removed_time: unix timestamp, e.g. "1389731126" or empty string for non-deleted files/folders * mime_type: string * revisions: array of revision objects * children: array of children objects * } * * @param string $path full path with leading slash and optionally a filename * @param string $root Optional, "copy" is the first level of the real filesystem * * @return array List of file/folder objects described above. */ public function getMeta($path, $root = "copy") { $result = $this->get("meta/" . $root . $path); // Decode the json reply $result = json_decode($result); // Check for errors if (isset($result->error)) { if ($result->error == 1301) { // item not found return array(); } throw new \Exception("Error listing path " . $path . ": (" . $result->error . ") '" . $result->message . "'"); } return $result; } /** * Create a dir * * Object structure: * { * object_id: "4008" * path: "/example" * type: "dir" * share_id: "0" * share_owner: "21956799" * company_id: NULL * size: filesize in bytes, 0 for folders * created_time: unix timestamp, e.g. "1389731126" * modified_time: unix timestamp, e.g. "1389731126" * date_last_synced: unix timestamp, e.g. "1389731126" * removed_time: unix timestamp, e.g. "1389731126" or empty string for non-deleted files/folders * } * * @param string $path full path containing leading slash and dir name * @param bool $recursive true to create parent directories * * @return object described above. */ public function createDir($path, $recursive = true) { $request = array( 'object_type' => 'dir', 'recurse' => $recursive, ); return $this->updateObject('create', $path, $request); } /** * Create a file with a set of data parts * * Object structure: * { * object_id: "4008" * path: "/example" * type: "file" * share_id: "0" * share_owner: "21956799" * company_id: NULL * size: filesize in bytes, 0 for folders * created_time: unix timestamp, e.g. "1389731126" * modified_time: unix timestamp, e.g. "1389731126" * date_last_synced: unix timestamp, e.g. "1389731126" * removed_time: unix timestamp, e.g. "1389731126" or empty string for non-deleted files/folders * mime_type: string * revisions: array of revision objects * } * * @param string $path full path containing leading slash and file name * @param array $parts contains arrays of parts returned by \Barracuda\Copy\API\sendData * * @return object described above. */ public function createFile($path, $parts) { $request = array(); $request["object_type"] = "file"; $request["parts"] = array(); $offset = 0; foreach ($parts as $part) { $partRequest = array( 'fingerprint' => $part["fingerprint"], 'offset' => $offset, 'size' => $part["size"], ); array_push($request["parts"], $partRequest); $offset += $part["size"]; } $request["size"] = $offset; return $this->updateObject('create', $path, $request); } /** * Generate the fingerprint for a string of data. * * @param string $data Data part to generate the fingerprint for. * * @return string Fingerprint for $data. **/ public function fingerprint($data) { return md5($data) . sha1($data); } /** * Send a piece of data * * @param string $data binary data * @param int $shareId setting this to zero is best, unless share id is known * * @return array contains fingerprint and size, to be used when creating a file */ public function sendData($data, $shareId = 0) { // first generate a part hash $fingerprint = $this->fingerprint($data); $part_size = strlen($data); // see if the cloud has this part, and send if needed if(!$this->hasPart($fingerprint, $part_size, $shareId)) { $this->sendPart($fingerprint, $part_size, $data, $shareId); } // return information about this part return array("fingerprint" => $fingerprint, "size" => $part_size); } /** * Send a data part * * @param string $fingerprint md5 and sha1 concatenated * @param int $size number of bytes * @param string $data binary data * @param int $shareId setting this to zero is best, unless share id is known * */ public function sendPart($fingerprint, $size, $data, $shareId = 0) { // They must match if (md5($data) . sha1($data) != $fingerprint) { throw new \Exception("Failed to validate part hash"); } $request = array( 'parts' => array( array( 'share_id' => $shareId, 'fingerprint' => $fingerprint, 'size' => $size, 'data' => 'BinaryData-0-' . $size ) ) ); $result = $this->post("send_object_parts_v2", $this->encodeRequest("send_object_parts_v2", $request) . chr(0) . $data, true); if ($result->result->has_failed_parts) { throw new \Exception("Error sending part: " . $result->result->failed_parts[0]->message); } } /** * Check to see if a part already exists * * @param string $fingerprint md5 and sha1 concatenated * @param int $size number of bytes * @param int $shareId setting this to zero is best, unless share id is known * @return bool true if part already exists */ public function hasPart($fingerprint, $size, $shareId = 0) { $request = array( 'parts' => array( array( 'share_id' => $shareId, 'fingerprint' => $fingerprint, 'size' => $size ) ) ); $result = $this->post("has_object_parts_v2", $this->encodeRequest("has_object_parts_v2", $request), true); if (empty($result->result->needed_parts)) { return true; } else { $part = $result->result->needed_parts[0]; if (!empty($part->message)) { throw new \Exception("Error checking for part: " . $part->message); } else { return false; } } } /** * Get a part * * @param string $fingerprint md5 and sha1 concatinated * @param int $size number of bytes * @param int $shareId setting this to zero is best, unless share id is known * * @return string binary data */ public function getPart($fingerprint, $size, $shareId = 0) { $request = array( 'parts' => array( array( 'share_id' => $shareId, 'fingerprint' => $fingerprint, 'size' => $size ) ) ); $result = $this->post("get_object_parts_v2", $this->encodeRequest("get_object_parts_v2", $request)); // Find the null byte $null_offset = strpos($result, chr(0)); // Grab the binary payload $binary = substr($result, $null_offset + 1, strlen($result) - $null_offset); if ($binary === false) { throw new \Exception("Error getting part data"); } // Grab the json payload $json = isset($binary) ? substr($result, 0, $null_offset) : $result; if ($json === false) { throw new \Exception("Error getting part data"); } // Decode the json reply $result = json_decode($json); // Check for errors if (isset($result->error)) { throw new \Exception("Error getting part data"); } if (isset($result->result->parts[0]->message)) { throw new \Exception("Error getting part data: " . $result->result->parts[0]->message); } // Get the part data (since there is only one part the binary payload should just be the data) if (strlen($binary) != $size) { throw new \Exception("Error getting part data"); } return $binary; } /** * Create a New Link * * Object structure: * { * id: "MBrss3roGDk4", * name: "My Cool Shared Files", * public: true, * url: "https://copy.com/MBrss3roGDk4", * url_short: "https://copy.com/MBrss3roGDk4", * creator_id: "1381231", * company_id: null, * confirmation_required: false, * status: "viewed", * permissions: "read" * } * * @param array|string $paths target item(s) path * @param array $options option attributes, (bool) "public", (string) "name" * @param string $root * * @throws \Exception * * @return object described above. */ public function createLink($paths, $options = array(), $root = 'copy') { if (is_string($paths)) { $paths = array($paths); } $paths = array_map(function($p) use ($root){return '/' . $root . $p;}, $paths); $data = array("paths" => $paths); $data = array_merge($data, $options); $result = $this->post("links", $data); // Decode the json reply $result = json_decode($result); // Check for errors if (isset($result->error)) { throw new \Exception("Error listing path " . $path . ": (" . $result->error . ") '" . $result->message . "'"); } return $result; } /** * Update meta object * * Object structure: * { * object_id: "4008" * path: "/example" * type: "dir" || "file" * share_id: "0" * share_owner: "21956799" * company_id: NULL * size: filesize in bytes, 0 for folders * created_time: unix timestamp, e.g. "1389731126" * modified_time: unix timestamp, e.g. "1389731126" * date_last_synced: unix timestamp, e.g. "1389731126" * removed_time: unix timestamp, e.g. "1389731126" or empty string for non-deleted files/folders * mime_type: string * revisions: array of revision objects * } * * @param string $action * @param string $path * @param array $meta contains action, path, and other attributes of the object to update * * @return stdClass using structure as noted above */ private function updateObject($action, $path, $meta) { // Add action and path to meta $meta["action"] = $action; $meta["path"] = $path; $result = $this->post("update_objects", $this->encodeRequest("update_objects", array("meta" => array($meta))), true); // Return the object return $result->{"result"}[0]->{"object"}; } /** * Create and execute cURL request to send data. * * @param string $method API method * @param string $data raw request * @param boolean $decodeResponse true to decode response * * @return mixed result from curl_exec */ private function post($method, $data, $decodeResponse = false) { if (is_array($data)) { $data = str_replace('\\/', '/', json_encode($data)); } curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($this->curl, CURLOPT_POSTFIELDS, $data); curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->getHeaders($method)); curl_setopt($this->curl, CURLOPT_URL, $this->api_url . "/" . $this->getEndpoint($method)); curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($this->curl, CURLOPT_POST, 1); $result = curl_exec($this->curl); // If curl grossly failed, throw if ($result === false) { throw new \Exception("Curl failed to exec " . curl_error($this->curl)); } // Decode the response if requested to do so if ($decodeResponse) { return $this->decodeResponse($result); } else { return $result; } } /** * Create and execute cURL request by GET method. * * @param string $method API method * * @return mixed result from curl_exec */ protected function get($method) { $method = str_replace("%2F", "/", rawurlencode($method)); curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($this->curl, CURLOPT_POSTFIELDS, null); curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->getHeaders($method, "GET")); curl_setopt($this->curl, CURLOPT_URL, $this->api_url . "/" . $this->GetEndpoint($method)); curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($this->curl, CURLOPT_HTTPGET, 1); $result = curl_exec($this->curl); // If curl grossly failed, throw if ($result == FALSE) { throw new \Exception("Curl failed to exec " . curl_error($this->curl)); } return $result; } /** * Return which cloud API end point to use for a given method. * * @param string $method API method * * @return string uri of endpoint without leading slash */ private function getEndpoint($method) { if ($method == "has_object_parts_v2" || $method == "send_object_parts_v2" || $method == "get_object_parts_v2") { return "jsonrpc_binary"; } else if ($method == "update_objects" || $method == "list_objects") { return "jsonrpc"; } else { return "rest/" . $method; } } /** * Generate the HTTP headers need for a given Cloud API method. * * @param string $method API method * @param string $http_method Optional, HTTP request method * * @return array contains headers to use for HTTP requests */ public function getHeaders($method, $http_method = "POST") { $headers = array(); $consumer = new \Eher\OAuth\Consumer($this->signature['consumer_key'], $this->signature['shared_secret']); $signatureMethod = new \Eher\OAuth\HmacSha1(); $token = new \Eher\OAuth\Token($this->signature['oauth_token'], $this->signature['oauth_secret']); $request = \Eher\OAuth\Request::from_consumer_and_token( $consumer, $token, $http_method, $this->api_url . "/" . $this->GetEndpoint($method), array() ); $request->sign_request($signatureMethod, $consumer, $token); if ($method == "has_object_parts_v2" || $method == "send_object_parts_v2" || $method == "get_object_parts_v2") { array_push($headers, "Content-Type: application/octet-stream"); } array_push($headers, "X-Api-Version: 1.0"); array_push($headers, "X-Client-Type: api"); array_push($headers, "X-Client-Time: " . time()); array_push($headers, $request->to_header()); return $headers; } /** * JSON encode request data. * * @param string $method Cloud API method * @param array $json contains data to be encoded * * @return string JSON formatted request body */ private function encodeRequest($method, $json) { $request = array( 'jsonrpc' => '2.0', 'id' => '0', 'method' => $method, 'params' => $json, ); return str_replace('\\/', '/', json_encode($request)); } /** * Decode a JSON response. * * @param string $response JSON response * * @return array JSON decoded string */ private function decodeResponse($response) { // Decode the json reply $result = json_decode($response); // Check for errors if (isset($result->error)) { throw new \Exception("Error: '" . $result->error->message . "'"); } return $result; } /** * Copies the phar cacert from a phar into the temp directory. * * @param string $pharCacertPath Path to the phar cacert. * * @return string Returns the path to the extracted cacert file. */ public static function extractPharCacert($pharCacertPath) { $certFile = sys_get_temp_dir() . '/barracuda-copycom-cacert.crt'; if (!file_exists($pharCacertPath)) { throw new \Exception("Could not find " . $pharCacertPath); } // Copy the cacert file from the phar if it is not in the temp folder. if (!file_exists($certFile) || filesize($certFile) != filesize($pharCacertPath)) { if (!copy($pharCacertPath, $certFile)) { throw new \Exception( "Could not copy " . $pharCacertPath . " to " . $certFile . ": " . var_export(error_get_last(), true) ); } } return $certFile; } } DigiCertHighAssuranceEVRootCA ============================= -----BEGIN CERTIFICATE----- MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j ZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3 LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug RVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm +9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW PNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM xChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB Ik5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3 hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg EsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF MAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2 Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep +OkuE6N36B9K -----END CERTIFICATE----- DigiCertSHA2HighAssuranceServerCA ================================= -----BEGIN CERTIFICATE----- MIIEsTCCA5mgAwIBAgIQBOHnpNxc8vNtwCtCuF0VnzANBgkqhkiG9w0BAQsFADBs MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j ZSBFViBSb290IENBMB4XDTEzMTAyMjEyMDAwMFoXDTI4MTAyMjEyMDAwMFowcDEL MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3 LmRpZ2ljZXJ0LmNvbTEvMC0GA1UEAxMmRGlnaUNlcnQgU0hBMiBIaWdoIEFzc3Vy YW5jZSBTZXJ2ZXIgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC2 4C/CJAbIbQRf1+8KZAayfSImZRauQkCbztyfn3YHPsMwVYcZuU+UDlqUH1VWtMIC Kq/QmO4LQNfE0DtyyBSe75CxEamu0si4QzrZCwvV1ZX1QK/IHe1NnF9Xt4ZQaJn1 itrSxwUfqJfJ3KSxgoQtxq2lnMcZgqaFD15EWCo3j/018QsIJzJa9buLnqS9UdAn 4t07QjOjBSjEuyjMmqwrIw14xnvmXnG3Sj4I+4G3FhahnSMSTeXXkgisdaScus0X sh5ENWV/UyU50RwKmmMbGZJ0aAo3wsJSSMs5WqK24V3B3aAguCGikyZvFEohQcft bZvySC/zA/WiaJJTL17jAgMBAAGjggFJMIIBRTASBgNVHRMBAf8ECDAGAQH/AgEA MA4GA1UdDwEB/wQEAwIBhjAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIw NAYIKwYBBQUHAQEEKDAmMCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC5kaWdpY2Vy dC5jb20wSwYDVR0fBEQwQjBAoD6gPIY6aHR0cDovL2NybDQuZGlnaWNlcnQuY29t L0RpZ2lDZXJ0SGlnaEFzc3VyYW5jZUVWUm9vdENBLmNybDA9BgNVHSAENjA0MDIG BFUdIAAwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly93d3cuZGlnaWNlcnQuY29tL0NQ UzAdBgNVHQ4EFgQUUWj/kK8CB3U8zNllZGKiErhZcjswHwYDVR0jBBgwFoAUsT7D aQP4v0cB1JgmGggC72NkK8MwDQYJKoZIhvcNAQELBQADggEBABiKlYkD5m3fXPwd aOpKj4PWUS+Na0QWnqxj9dJubISZi6qBcYRb7TROsLd5kinMLYBq8I4g4Xmk/gNH E+r1hspZcX30BJZr01lYPf7TMSVcGDiEo+afgv2MW5gxTs14nhr9hctJqvIni5ly /D6q1UEL2tU2ob8cbkdJf17ZSHwD2f2LSaCYJkJA69aSEaRkCldUxPUd1gJea6zu xICaEnL6VpPX/78whQYwvwt/Tv9XBZ0k7YXDK/umdaisLRbvfXknsuvCnQsH6qqF 0wGjIChBWUMo0oHjqvbsezt3tkBigAVBRQHvFwY+3sAzm2fTYS5yh+Rp/BIAV0Ae cPUeybQ= -----END CERTIFICATE----- The MIT License (MIT) Copyright (c) 2013 Barracuda Networks, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. app key (OAuth calls this the consumer key). You can * create an app key and secret on the Dropbox developer website. * * @return string */ function getKey() { return $this->key; } /** @var string */ private $key; /** * Your Dropbox app secret (OAuth calls this the consumer secret). You can * create an app key and secret on the Dropbox developer website. * * Make sure that this is kept a secret. Someone with your app secret can impesonate your * application. People sometimes ask for help on the Dropbox API forums and * copy/paste code that includes their app secret. Do not do that. * * @return string */ function getSecret() { return $this->secret; } /** @var string */ private $secret; /** * The set of servers your app will use. This defaults to the standard Dropbox servers * {@link Host::getDefault}. * * @return Host * * @internal */ function getHost() { return $this->host; } /** @var Host */ private $host; /** * Constructor. * * @param string $key * See {@link getKey()} * @param string $secret * See {@link getSecret()} */ function __construct($key, $secret) { self::checkKeyArg($key); self::checkSecretArg($secret); $this->key = $key; $this->secret = $secret; // The $host parameter is sort of internal. We don't include it in the param list because // we don't want it to be included in the documentation. Use PHP arg list hacks to get at // it. $host = null; if (\func_num_args() == 3) { $host = \func_get_arg(2); Host::checkArgOrNull("host", $host); } if ($host === null) { $host = Host::getDefault(); } $this->host = $host; } /** * Loads a JSON file containing information about your app. At a minimum, the file must include * the "key" and "secret" fields. Run 'php authorize.php' in the examples directory * for details about what this file should look like. * * @param string $path * Path to a JSON file * * @return AppInfo * * @throws AppInfoLoadException */ static function loadFromJsonFile($path) { list($rawJson, $appInfo) = self::loadFromJsonFileWithRaw($path); return $appInfo; } /** * Loads a JSON file containing information about your app. At a minimum, the file must include * the "key" and "secret" fields. Run 'php authorize.php' in the examples directory * for details about what this file should look like. * * @param string $path * Path to a JSON file * * @return array * A list of two items. The first is a PHP array representation of the raw JSON, the second * is an AppInfo object that is the parsed version of the JSON. * * @throws AppInfoLoadException * * @internal */ static function loadFromJsonFileWithRaw($path) { if (!file_exists($path)) { throw new AppInfoLoadException("File doesn't exist: \"$path\""); } $str = Util::stripUtf8Bom(file_get_contents($path)); $jsonArr = json_decode($str, true, 10); if (is_null($jsonArr)) { throw new AppInfoLoadException("JSON parse error: \"$path\""); } $appInfo = self::loadFromJson($jsonArr); return array($jsonArr, $appInfo); } /** * Parses a JSON object to build an AppInfo object. If you would like to load this from a file, * use the loadFromJsonFile() method. * * @param array $jsonArr Output from json_decode($str, true) * * @return AppInfo * * @throws AppInfoLoadException */ static function loadFromJson($jsonArr) { if (!is_array($jsonArr)) { throw new AppInfoLoadException("Expecting JSON object, got something else"); } $requiredKeys = array("key", "secret"); foreach ($requiredKeys as $key) { if (!array_key_exists($key, $jsonArr)) { throw new AppInfoLoadException("Missing field \"$key\""); } if (!is_string($jsonArr[$key])) { throw new AppInfoLoadException("Expecting field \"$key\" to be a string"); } } // Check app_key and app_secret $appKey = $jsonArr["key"]; $appSecret = $jsonArr["secret"]; $tokenErr = self::getTokenPartError($appKey); if (!is_null($tokenErr)) { throw new AppInfoLoadException("Field \"key\" doesn't look like a valid app key: $tokenErr"); } $tokenErr = self::getTokenPartError($appSecret); if (!is_null($tokenErr)) { throw new AppInfoLoadException("Field \"secret\" doesn't look like a valid app secret: $tokenErr"); } // Check for the optional 'host' field if (!array_key_exists('host', $jsonArr)) { $host = null; } else { $baseHost = $jsonArr["host"]; if (!is_string($baseHost)) { throw new AppInfoLoadException("Optional field \"host\" must be a string"); } $api = "api-$baseHost"; $content = "api-content-$baseHost"; $web = "meta-$baseHost"; $host = new Host($api, $content, $web); } return new AppInfo($appKey, $appSecret, $host); } /** * Use this to check that a function argument is of type AppInfo * * @internal */ static function checkArg($argName, $argValue) { if (!($argValue instanceof self)) Checker::throwError($argName, $argValue, __CLASS__); } /** * Use this to check that a function argument is either null or of type * AppInfo. * * @internal */ static function checkArgOrNull($argName, $argValue) { if ($argValue === null) return; if (!($argValue instanceof self)) Checker::throwError($argName, $argValue, __CLASS__); } /** @internal */ static function getTokenPartError($s) { if ($s === null) return "can't be null"; if (strlen($s) === 0) return "can't be empty"; if (strstr($s, ' ')) return "can't contain a space"; return null; // 'null' means "no error" } /** @internal */ static function checkKeyArg($key) { $error = self::getTokenPartError($key); if ($error === null) return; throw new \InvalidArgumentException("Bad 'key': \"$key\": $error."); } /** @internal */ static function checkSecretArg($secret) { $error = self::getTokenPartError($secret); if ($error === null) return; throw new \InvalidArgumentException("Bad 'secret': \"$secret\": $error."); } } AppInfo::loadXXX methods if something goes wrong. */ final class AppInfoLoadException extends \Exception { /** * @param string $message * * @internal */ function __construct($message) { parent::__construct($message); } } array = &$array; $this->key = $key; } /** * Returns the entry's current value or null if nothing is set. * * @return object */ function get() { if (isset($this->array[$this->key])) { return $this->array[$this->key]; } else { return null; } } /** * Set the array entry to the given value. * * @param object $value */ function set($value) { $this->array[$this->key] = $value; } /** * Clear the entry. */ function clear() { unset($this->array[$this->key]); } } appInfo; } /** @var AppInfo */ protected $appInfo; /** * An identifier for the API client, typically of the form "Name/Version". * This is used to set the HTTP User-Agent header when making API requests. * Example: "PhotoEditServer/1.3" * * If you're the author a higher-level library on top of the basic SDK, and the * "Photo Edit" app's server code is using your library to access Dropbox, you should append * your library's name and version to form the full identifier. For example, * if your library is called "File Picker", you might set this field to: * "PhotoEditServer/1.3 FilePicker/0.1-beta" * * The exact format of the User-Agent header is described in * section 3.8 of the HTTP specification. * * Note that underlying HTTP client may append other things to the User-Agent, such as * the name of the library being used to actually make the HTTP request (such as cURL). * * @return string */ function getClientIdentifier() { return $this->clientIdentifier; } /** @var string */ protected $clientIdentifier; /** * The locale of the user of your application. Some API calls return localized * data and error messages; this "user locale" setting determines which locale * the server should use to localize those strings. * * @return null|string */ function getUserLocale() { return $this->userLocale; } /** @var string */ protected $userLocale; /** * Constructor. * * @param AppInfo $appInfo * See {@link getAppInfo()} * @param string $clientIdentifier * See {@link getClientIdentifier()} * @param null|string $userLocale * See {@link getUserLocale()} */ function __construct($appInfo, $clientIdentifier, $userLocale = null) { AppInfo::checkArg("appInfo", $appInfo); Client::checkClientIdentifierArg("clientIdentifier", $clientIdentifier); Checker::argStringNonEmptyOrNull("userLocale", $userLocale); $this->appInfo = $appInfo; $this->clientIdentifier = $clientIdentifier; $this->userLocale = $userLocale; } } list(string $accessToken, Host $host). * * @throws AuthInfoLoadException */ static function loadFromJsonFile($path) { if (!file_exists($path)) { throw new AuthInfoLoadException("File doesn't exist: \"$path\""); } $str = Util::stripUtf8Bom(file_get_contents($path)); $jsonArr = json_decode($str, true, 10); if (is_null($jsonArr)) { throw new AuthInfoLoadException("JSON parse error: \"$path\""); } return self::loadFromJson($jsonArr); } /** * Parses a JSON object to build an AuthInfo object. If you would like to load this from a file, * please use the @see loadFromJsonFile method. * * @param array $jsonArr * A parsed JSON object, typcally the result of json_decode(..., true). * @return array * A list(string $accessToken, Host $host). * * @throws AuthInfoLoadException */ private static function loadFromJson($jsonArr) { if (!is_array($jsonArr)) { throw new AuthInfoLoadException("Expecting JSON object, found something else"); } // Check access_token if (!array_key_exists('access_token', $jsonArr)) { throw new AuthInfoLoadException("Missing field \"access_token\""); } $accessToken = $jsonArr['access_token']; if (!is_string($accessToken)) { throw new AuthInfoLoadException("Expecting field \"access_token\" to be a string"); } // Check for the optional 'host' field if (!array_key_exists('host', $jsonArr)) { $host = null; } else { $baseHost = $jsonArr["host"]; if (!is_string($baseHost)) { throw new AuthInfoLoadException("Optional field \"host\" must be a string"); } $api = "api-$baseHost"; $content = "api-content-$baseHost"; $web = "meta-$baseHost"; $host = new Host($api, $content, $web); } return array($accessToken, $host); } } AuthInfo::loadXXX methods if something goes wrong. */ final class AuthInfoLoadException extends \Exception { /** * @param string $message * * @internal */ function __construct($message) { parent::__construct($message); } } # DigiCert Assured ID Root CA.pem # Certificate: # Data: # Version: 3 (0x2) # Serial Number: # 0c:e7:e0:e5:17:d8:46:fe:8f:e5:60:fc:1b:f0:30:39 # Signature Algorithm: sha1WithRSAEncryption # Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Assured ID Root CA # Validity # Not Before: Nov 10 00:00:00 2006 GMT # Not After : Nov 10 00:00:00 2031 GMT # Subject: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Assured ID Root CA # Subject Public Key Info: # Public Key Algorithm: rsaEncryption # Public-Key: (2048 bit) # Modulus: # 00:ad:0e:15:ce:e4:43:80:5c:b1:87:f3:b7:60:f9: # 71:12:a5:ae:dc:26:94:88:aa:f4:ce:f5:20:39:28: # 58:60:0c:f8:80:da:a9:15:95:32:61:3c:b5:b1:28: # 84:8a:8a:dc:9f:0a:0c:83:17:7a:8f:90:ac:8a:e7: # 79:53:5c:31:84:2a:f6:0f:98:32:36:76:cc:de:dd: # 3c:a8:a2:ef:6a:fb:21:f2:52:61:df:9f:20:d7:1f: # e2:b1:d9:fe:18:64:d2:12:5b:5f:f9:58:18:35:bc: # 47:cd:a1:36:f9:6b:7f:d4:b0:38:3e:c1:1b:c3:8c: # 33:d9:d8:2f:18:fe:28:0f:b3:a7:83:d6:c3:6e:44: # c0:61:35:96:16:fe:59:9c:8b:76:6d:d7:f1:a2:4b: # 0d:2b:ff:0b:72:da:9e:60:d0:8e:90:35:c6:78:55: # 87:20:a1:cf:e5:6d:0a:c8:49:7c:31:98:33:6c:22: # e9:87:d0:32:5a:a2:ba:13:82:11:ed:39:17:9d:99: # 3a:72:a1:e6:fa:a4:d9:d5:17:31:75:ae:85:7d:22: # ae:3f:01:46:86:f6:28:79:c8:b1:da:e4:57:17:c4: # 7e:1c:0e:b0:b4:92:a6:56:b3:bd:b2:97:ed:aa:a7: # f0:b7:c5:a8:3f:95:16:d0:ff:a1:96:eb:08:5f:18: # 77:4f # Exponent: 65537 (0x10001) # X509v3 extensions: # X509v3 Key Usage: critical # Digital Signature, Certificate Sign, CRL Sign # X509v3 Basic Constraints: critical # CA:TRUE # X509v3 Subject Key Identifier: # 45:EB:A2:AF:F4:92:CB:82:31:2D:51:8B:A7:A7:21:9D:F3:6D:C8:0F # X509v3 Authority Key Identifier: # keyid:45:EB:A2:AF:F4:92:CB:82:31:2D:51:8B:A7:A7:21:9D:F3:6D:C8:0F # # Signature Algorithm: sha1WithRSAEncryption # a2:0e:bc:df:e2:ed:f0:e3:72:73:7a:64:94:bf:f7:72:66:d8: # 32:e4:42:75:62:ae:87:eb:f2:d5:d9:de:56:b3:9f:cc:ce:14: # 28:b9:0d:97:60:5c:12:4c:58:e4:d3:3d:83:49:45:58:97:35: # 69:1a:a8:47:ea:56:c6:79:ab:12:d8:67:81:84:df:7f:09:3c: # 94:e6:b8:26:2c:20:bd:3d:b3:28:89:f7:5f:ff:22:e2:97:84: # 1f:e9:65:ef:87:e0:df:c1:67:49:b3:5d:eb:b2:09:2a:eb:26: # ed:78:be:7d:3f:2b:f3:b7:26:35:6d:5f:89:01:b6:49:5b:9f: # 01:05:9b:ab:3d:25:c1:cc:b6:7f:c2:f1:6f:86:c6:fa:64:68: # eb:81:2d:94:eb:42:b7:fa:8c:1e:dd:62:f1:be:50:67:b7:6c: # bd:f3:f1:1f:6b:0c:36:07:16:7f:37:7c:a9:5b:6d:7a:f1:12: # 46:60:83:d7:27:04:be:4b:ce:97:be:c3:67:2a:68:11:df:80: # e7:0c:33:66:bf:13:0d:14:6e:f3:7f:1f:63:10:1e:fa:8d:1b: # 25:6d:6c:8f:a5:b7:61:01:b1:d2:a3:26:a1:10:71:9d:ad:e2: # c3:f9:c3:99:51:b7:2b:07:08:ce:2e:e6:50:b2:a7:fa:0a:45: # 2f:a2:f0:f2 -----BEGIN CERTIFICATE----- MIIDtzCCAp+gAwIBAgIQDOfg5RfYRv6P5WD8G/AwOTANBgkqhkiG9w0BAQUFADBl MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv b3QgQ0EwHhcNMDYxMTEwMDAwMDAwWhcNMzExMTEwMDAwMDAwWjBlMQswCQYDVQQG EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl cnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwggEi MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtDhXO5EOAXLGH87dg+XESpa7c JpSIqvTO9SA5KFhgDPiA2qkVlTJhPLWxKISKityfCgyDF3qPkKyK53lTXDGEKvYP mDI2dsze3Tyoou9q+yHyUmHfnyDXH+Kx2f4YZNISW1/5WBg1vEfNoTb5a3/UsDg+ wRvDjDPZ2C8Y/igPs6eD1sNuRMBhNZYW/lmci3Zt1/GiSw0r/wty2p5g0I6QNcZ4 VYcgoc/lbQrISXwxmDNsIumH0DJaoroTghHtORedmTpyoeb6pNnVFzF1roV9Iq4/ AUaG9ih5yLHa5FcXxH4cDrC0kqZWs72yl+2qp/C3xag/lRbQ/6GW6whfGHdPAgMB AAGjYzBhMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW BBRF66Kv9JLLgjEtUYunpyGd823IDzAfBgNVHSMEGDAWgBRF66Kv9JLLgjEtUYun pyGd823IDzANBgkqhkiG9w0BAQUFAAOCAQEAog683+Lt8ONyc3pklL/3cmbYMuRC dWKuh+vy1dneVrOfzM4UKLkNl2BcEkxY5NM9g0lFWJc1aRqoR+pWxnmrEthngYTf fwk8lOa4JiwgvT2zKIn3X/8i4peEH+ll74fg38FnSbNd67IJKusm7Xi+fT8r87cm NW1fiQG2SVufAQWbqz0lwcy2f8Lxb4bG+mRo64EtlOtCt/qMHt1i8b5QZ7dsvfPx H2sMNgcWfzd8qVttevESRmCD1ycEvkvOl77DZypoEd+A5wwzZr8TDRRu838fYxAe +o0bJW1sj6W3YQGx0qMmoRBxna3iw/nDmVG3KwcIzi7mULKn+gpFL6Lw8g== -----END CERTIFICATE----- # DigiCert Global Root CA.pem # Certificate: # Data: # Version: 3 (0x2) # Serial Number: # 08:3b:e0:56:90:42:46:b1:a1:75:6a:c9:59:91:c7:4a # Signature Algorithm: sha1WithRSAEncryption # Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Global Root CA # Validity # Not Before: Nov 10 00:00:00 2006 GMT # Not After : Nov 10 00:00:00 2031 GMT # Subject: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Global Root CA # Subject Public Key Info: # Public Key Algorithm: rsaEncryption # Public-Key: (2048 bit) # Modulus: # 00:e2:3b:e1:11:72:de:a8:a4:d3:a3:57:aa:50:a2: # 8f:0b:77:90:c9:a2:a5:ee:12:ce:96:5b:01:09:20: # cc:01:93:a7:4e:30:b7:53:f7:43:c4:69:00:57:9d: # e2:8d:22:dd:87:06:40:00:81:09:ce:ce:1b:83:bf: # df:cd:3b:71:46:e2:d6:66:c7:05:b3:76:27:16:8f: # 7b:9e:1e:95:7d:ee:b7:48:a3:08:da:d6:af:7a:0c: # 39:06:65:7f:4a:5d:1f:bc:17:f8:ab:be:ee:28:d7: # 74:7f:7a:78:99:59:85:68:6e:5c:23:32:4b:bf:4e: # c0:e8:5a:6d:e3:70:bf:77:10:bf:fc:01:f6:85:d9: # a8:44:10:58:32:a9:75:18:d5:d1:a2:be:47:e2:27: # 6a:f4:9a:33:f8:49:08:60:8b:d4:5f:b4:3a:84:bf: # a1:aa:4a:4c:7d:3e:cf:4f:5f:6c:76:5e:a0:4b:37: # 91:9e:dc:22:e6:6d:ce:14:1a:8e:6a:cb:fe:cd:b3: # 14:64:17:c7:5b:29:9e:32:bf:f2:ee:fa:d3:0b:42: # d4:ab:b7:41:32:da:0c:d4:ef:f8:81:d5:bb:8d:58: # 3f:b5:1b:e8:49:28:a2:70:da:31:04:dd:f7:b2:16: # f2:4c:0a:4e:07:a8:ed:4a:3d:5e:b5:7f:a3:90:c3: # af:27 # Exponent: 65537 (0x10001) # X509v3 extensions: # X509v3 Key Usage: critical # Digital Signature, Certificate Sign, CRL Sign # X509v3 Basic Constraints: critical # CA:TRUE # X509v3 Subject Key Identifier: # 03:DE:50:35:56:D1:4C:BB:66:F0:A3:E2:1B:1B:C3:97:B2:3D:D1:55 # X509v3 Authority Key Identifier: # keyid:03:DE:50:35:56:D1:4C:BB:66:F0:A3:E2:1B:1B:C3:97:B2:3D:D1:55 # # Signature Algorithm: sha1WithRSAEncryption # cb:9c:37:aa:48:13:12:0a:fa:dd:44:9c:4f:52:b0:f4:df:ae: # 04:f5:79:79:08:a3:24:18:fc:4b:2b:84:c0:2d:b9:d5:c7:fe: # f4:c1:1f:58:cb:b8:6d:9c:7a:74:e7:98:29:ab:11:b5:e3:70: # a0:a1:cd:4c:88:99:93:8c:91:70:e2:ab:0f:1c:be:93:a9:ff: # 63:d5:e4:07:60:d3:a3:bf:9d:5b:09:f1:d5:8e:e3:53:f4:8e: # 63:fa:3f:a7:db:b4:66:df:62:66:d6:d1:6e:41:8d:f2:2d:b5: # ea:77:4a:9f:9d:58:e2:2b:59:c0:40:23:ed:2d:28:82:45:3e: # 79:54:92:26:98:e0:80:48:a8:37:ef:f0:d6:79:60:16:de:ac: # e8:0e:cd:6e:ac:44:17:38:2f:49:da:e1:45:3e:2a:b9:36:53: # cf:3a:50:06:f7:2e:e8:c4:57:49:6c:61:21:18:d5:04:ad:78: # 3c:2c:3a:80:6b:a7:eb:af:15:14:e9:d8:89:c1:b9:38:6c:e2: # 91:6c:8a:ff:64:b9:77:25:57:30:c0:1b:24:a3:e1:dc:e9:df: # 47:7c:b5:b4:24:08:05:30:ec:2d:bd:0b:bf:45:bf:50:b9:a9: # f3:eb:98:01:12:ad:c8:88:c6:98:34:5f:8d:0a:3c:c6:e9:d5: # 95:95:6d:de -----BEGIN CERTIFICATE----- MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG 9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97 nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt 43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4 gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg 06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4= -----END CERTIFICATE----- # DigiCert High Assurance EV Root CA.pem # Certificate: # Data: # Version: 3 (0x2) # Serial Number: # 02:ac:5c:26:6a:0b:40:9b:8f:0b:79:f2:ae:46:25:77 # Signature Algorithm: sha1WithRSAEncryption # Issuer: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert High Assurance EV Root CA # Validity # Not Before: Nov 10 00:00:00 2006 GMT # Not After : Nov 10 00:00:00 2031 GMT # Subject: C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert High Assurance EV Root CA # Subject Public Key Info: # Public Key Algorithm: rsaEncryption # Public-Key: (2048 bit) # Modulus: # 00:c6:cc:e5:73:e6:fb:d4:bb:e5:2d:2d:32:a6:df: # e5:81:3f:c9:cd:25:49:b6:71:2a:c3:d5:94:34:67: # a2:0a:1c:b0:5f:69:a6:40:b1:c4:b7:b2:8f:d0:98: # a4:a9:41:59:3a:d3:dc:94:d6:3c:db:74:38:a4:4a: # cc:4d:25:82:f7:4a:a5:53:12:38:ee:f3:49:6d:71: # 91:7e:63:b6:ab:a6:5f:c3:a4:84:f8:4f:62:51:be: # f8:c5:ec:db:38:92:e3:06:e5:08:91:0c:c4:28:41: # 55:fb:cb:5a:89:15:7e:71:e8:35:bf:4d:72:09:3d: # be:3a:38:50:5b:77:31:1b:8d:b3:c7:24:45:9a:a7: # ac:6d:00:14:5a:04:b7:ba:13:eb:51:0a:98:41:41: # 22:4e:65:61:87:81:41:50:a6:79:5c:89:de:19:4a: # 57:d5:2e:e6:5d:1c:53:2c:7e:98:cd:1a:06:16:a4: # 68:73:d0:34:04:13:5c:a1:71:d3:5a:7c:55:db:5e: # 64:e1:37:87:30:56:04:e5:11:b4:29:80:12:f1:79: # 39:88:a2:02:11:7c:27:66:b7:88:b7:78:f2:ca:0a: # a8:38:ab:0a:64:c2:bf:66:5d:95:84:c1:a1:25:1e: # 87:5d:1a:50:0b:20:12:cc:41:bb:6e:0b:51:38:b8: # 4b:cb # Exponent: 65537 (0x10001) # X509v3 extensions: # X509v3 Key Usage: critical # Digital Signature, Certificate Sign, CRL Sign # X509v3 Basic Constraints: critical # CA:TRUE # X509v3 Subject Key Identifier: # B1:3E:C3:69:03:F8:BF:47:01:D4:98:26:1A:08:02:EF:63:64:2B:C3 # X509v3 Authority Key Identifier: # keyid:B1:3E:C3:69:03:F8:BF:47:01:D4:98:26:1A:08:02:EF:63:64:2B:C3 # # Signature Algorithm: sha1WithRSAEncryption # 1c:1a:06:97:dc:d7:9c:9f:3c:88:66:06:08:57:21:db:21:47: # f8:2a:67:aa:bf:18:32:76:40:10:57:c1:8a:f3:7a:d9:11:65: # 8e:35:fa:9e:fc:45:b5:9e:d9:4c:31:4b:b8:91:e8:43:2c:8e: # b3:78:ce:db:e3:53:79:71:d6:e5:21:94:01:da:55:87:9a:24: # 64:f6:8a:66:cc:de:9c:37:cd:a8:34:b1:69:9b:23:c8:9e:78: # 22:2b:70:43:e3:55:47:31:61:19:ef:58:c5:85:2f:4e:30:f6: # a0:31:16:23:c8:e7:e2:65:16:33:cb:bf:1a:1b:a0:3d:f8:ca: # 5e:8b:31:8b:60:08:89:2d:0c:06:5c:52:b7:c4:f9:0a:98:d1: # 15:5f:9f:12:be:7c:36:63:38:bd:44:a4:7f:e4:26:2b:0a:c4: # 97:69:0d:e9:8c:e2:c0:10:57:b8:c8:76:12:91:55:f2:48:69: # d8:bc:2a:02:5b:0f:44:d4:20:31:db:f4:ba:70:26:5d:90:60: # 9e:bc:4b:17:09:2f:b4:cb:1e:43:68:c9:07:27:c1:d2:5c:f7: # ea:21:b9:68:12:9c:3c:9c:bf:9e:fc:80:5c:9b:63:cd:ec:47: # aa:25:27:67:a0:37:f3:00:82:7d:54:d7:a9:f8:e9:2e:13:a3: # 77:e8:1f:4a -----BEGIN CERTIFICATE----- MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j ZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3 LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug RVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm +9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW PNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM xChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB Ik5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3 hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg EsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF MAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2 Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep +OkuE6N36B9K -----END CERTIFICATE----- # Entrust Root Certification Authority - EC1.pem # Certificate: # Data: # Version: 3 (0x2) # Serial Number: # a6:8b:79:29:00:00:00:00:50:d0:91:f9 # Signature Algorithm: ecdsa-with-SHA384 # Issuer: C=US, O=Entrust, Inc., OU=See www.entrust.net/legal-terms, OU=(c) 2012 Entrust, Inc. - for authorized use only, CN=Entrust Root Certification Authority - EC1 # Validity # Not Before: Dec 18 15:25:36 2012 GMT # Not After : Dec 18 15:55:36 2037 GMT # Subject: C=US, O=Entrust, Inc., OU=See www.entrust.net/legal-terms, OU=(c) 2012 Entrust, Inc. - for authorized use only, CN=Entrust Root Certification Authority - EC1 # Subject Public Key Info: # Public Key Algorithm: id-ecPublicKey # Public-Key: (384 bit) # pub: # 04:84:13:c9:d0:ba:6d:41:7b:e2:6c:d0:eb:55:5f: # 66:02:1a:24:f4:5b:89:69:47:e3:b8:c2:7d:f1:f2: # 02:c5:9f:a0:f6:5b:d5:8b:06:19:86:4f:53:10:6d: # 07:24:27:a1:a0:f8:d5:47:19:61:4c:7d:ca:93:27: # ea:74:0c:ef:6f:96:09:fe:63:ec:70:5d:36:ad:67: # 77:ae:c9:9d:7c:55:44:3a:a2:63:51:1f:f5:e3:62: # d4:a9:47:07:3e:cc:20 # ASN1 OID: secp384r1 # X509v3 extensions: # X509v3 Key Usage: critical # Certificate Sign, CRL Sign # X509v3 Basic Constraints: critical # CA:TRUE # X509v3 Subject Key Identifier: # B7:63:E7:1A:DD:8D:E9:08:A6:55:83:A4:E0:6A:50:41:65:11:42:49 # Signature Algorithm: ecdsa-with-SHA384 # 30:64:02:30:61:79:d8:e5:42:47:df:1c:ae:53:99:17:b6:6f: # 1c:7d:e1:bf:11:94:d1:03:88:75:e4:8d:89:a4:8a:77:46:de: # 6d:61:ef:02:f5:fb:b5:df:cc:fe:4e:ff:fe:a9:e6:a7:02:30: # 5b:99:d7:85:37:06:b5:7b:08:fd:eb:27:8b:4a:94:f9:e1:fa: # a7:8e:26:08:e8:7c:92:68:6d:73:d8:6f:26:ac:21:02:b8:99: # b7:26:41:5b:25:60:ae:d0:48:1a:ee:06 -----BEGIN CERTIFICATE----- MIIC+TCCAoCgAwIBAgINAKaLeSkAAAAAUNCR+TAKBggqhkjOPQQDAzCBvzELMAkG A1UEBhMCVVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3 d3cuZW50cnVzdC5uZXQvbGVnYWwtdGVybXMxOTA3BgNVBAsTMChjKSAyMDEyIEVu dHJ1c3QsIEluYy4gLSBmb3IgYXV0aG9yaXplZCB1c2Ugb25seTEzMDEGA1UEAxMq RW50cnVzdCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRUMxMB4XDTEy MTIxODE1MjUzNloXDTM3MTIxODE1NTUzNlowgb8xCzAJBgNVBAYTAlVTMRYwFAYD VQQKEw1FbnRydXN0LCBJbmMuMSgwJgYDVQQLEx9TZWUgd3d3LmVudHJ1c3QubmV0 L2xlZ2FsLXRlcm1zMTkwNwYDVQQLEzAoYykgMjAxMiBFbnRydXN0LCBJbmMuIC0g Zm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxMzAxBgNVBAMTKkVudHJ1c3QgUm9vdCBD ZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEVDMTB2MBAGByqGSM49AgEGBSuBBAAi A2IABIQTydC6bUF74mzQ61VfZgIaJPRbiWlH47jCffHyAsWfoPZb1YsGGYZPUxBt ByQnoaD41UcZYUx9ypMn6nQM72+WCf5j7HBdNq1nd67JnXxVRDqiY1Ef9eNi1KlH Bz7MIKNCMEAwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0O BBYEFLdj5xrdjekIplWDpOBqUEFlEUJJMAoGCCqGSM49BAMDA2cAMGQCMGF52OVC R98crlOZF7ZvHH3hvxGU0QOIdeSNiaSKd0bebWHvAvX7td/M/k7//qnmpwIwW5nX hTcGtXsI/esni0qU+eH6p44mCOh8kmhtc9hvJqwhAriZtyZBWyVgrtBIGu4G -----END CERTIFICATE----- # Entrust Root Certification Authority - G2.pem # Certificate: # Data: # Version: 3 (0x2) # Serial Number: 1246989352 (0x4a538c28) # Signature Algorithm: sha256WithRSAEncryption # Issuer: C=US, O=Entrust, Inc., OU=See www.entrust.net/legal-terms, OU=(c) 2009 Entrust, Inc. - for authorized use only, CN=Entrust Root Certification Authority - G2 # Validity # Not Before: Jul 7 17:25:54 2009 GMT # Not After : Dec 7 17:55:54 2030 GMT # Subject: C=US, O=Entrust, Inc., OU=See www.entrust.net/legal-terms, OU=(c) 2009 Entrust, Inc. - for authorized use only, CN=Entrust Root Certification Authority - G2 # Subject Public Key Info: # Public Key Algorithm: rsaEncryption # Public-Key: (2048 bit) # Modulus: # 00:ba:84:b6:72:db:9e:0c:6b:e2:99:e9:30:01:a7: # 76:ea:32:b8:95:41:1a:c9:da:61:4e:58:72:cf:fe: # f6:82:79:bf:73:61:06:0a:a5:27:d8:b3:5f:d3:45: # 4e:1c:72:d6:4e:32:f2:72:8a:0f:f7:83:19:d0:6a: # 80:80:00:45:1e:b0:c7:e7:9a:bf:12:57:27:1c:a3: # 68:2f:0a:87:bd:6a:6b:0e:5e:65:f3:1c:77:d5:d4: # 85:8d:70:21:b4:b3:32:e7:8b:a2:d5:86:39:02:b1: # b8:d2:47:ce:e4:c9:49:c4:3b:a7:de:fb:54:7d:57: # be:f0:e8:6e:c2:79:b2:3a:0b:55:e2:50:98:16:32: # 13:5c:2f:78:56:c1:c2:94:b3:f2:5a:e4:27:9a:9f: # 24:d7:c6:ec:d0:9b:25:82:e3:cc:c2:c4:45:c5:8c: # 97:7a:06:6b:2a:11:9f:a9:0a:6e:48:3b:6f:db:d4: # 11:19:42:f7:8f:07:bf:f5:53:5f:9c:3e:f4:17:2c: # e6:69:ac:4e:32:4c:62:77:ea:b7:e8:e5:bb:34:bc: # 19:8b:ae:9c:51:e7:b7:7e:b5:53:b1:33:22:e5:6d: # cf:70:3c:1a:fa:e2:9b:67:b6:83:f4:8d:a5:af:62: # 4c:4d:e0:58:ac:64:34:12:03:f8:b6:8d:94:63:24: # a4:71 # Exponent: 65537 (0x10001) # X509v3 extensions: # X509v3 Key Usage: critical # Certificate Sign, CRL Sign # X509v3 Basic Constraints: critical # CA:TRUE # X509v3 Subject Key Identifier: # 6A:72:26:7A:D0:1E:EF:7D:E7:3B:69:51:D4:6C:8D:9F:90:12:66:AB # Signature Algorithm: sha256WithRSAEncryption # 79:9f:1d:96:c6:b6:79:3f:22:8d:87:d3:87:03:04:60:6a:6b: # 9a:2e:59:89:73:11:ac:43:d1:f5:13:ff:8d:39:2b:c0:f2:bd: # 4f:70:8c:a9:2f:ea:17:c4:0b:54:9e:d4:1b:96:98:33:3c:a8: # ad:62:a2:00:76:ab:59:69:6e:06:1d:7e:c4:b9:44:8d:98:af: # 12:d4:61:db:0a:19:46:47:f3:eb:f7:63:c1:40:05:40:a5:d2: # b7:f4:b5:9a:36:bf:a9:88:76:88:04:55:04:2b:9c:87:7f:1a: # 37:3c:7e:2d:a5:1a:d8:d4:89:5e:ca:bd:ac:3d:6c:d8:6d:af: # d5:f3:76:0f:cd:3b:88:38:22:9d:6c:93:9a:c4:3d:bf:82:1b: # 65:3f:a6:0f:5d:aa:fc:e5:b2:15:ca:b5:ad:c6:bc:3d:d0:84: # e8:ea:06:72:b0:4d:39:32:78:bf:3e:11:9c:0b:a4:9d:9a:21: # f3:f0:9b:0b:30:78:db:c1:dc:87:43:fe:bc:63:9a:ca:c5:c2: # 1c:c9:c7:8d:ff:3b:12:58:08:e6:b6:3d:ec:7a:2c:4e:fb:83: # 96:ce:0c:3c:69:87:54:73:a4:73:c2:93:ff:51:10:ac:15:54: # 01:d8:fc:05:b1:89:a1:7f:74:83:9a:49:d7:dc:4e:7b:8a:48: # 6f:8b:45:f6 -----BEGIN CERTIFICATE----- MIIEPjCCAyagAwIBAgIESlOMKDANBgkqhkiG9w0BAQsFADCBvjELMAkGA1UEBhMC VVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3d3cuZW50 cnVzdC5uZXQvbGVnYWwtdGVybXMxOTA3BgNVBAsTMChjKSAyMDA5IEVudHJ1c3Qs IEluYy4gLSBmb3IgYXV0aG9yaXplZCB1c2Ugb25seTEyMDAGA1UEAxMpRW50cnVz dCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzIwHhcNMDkwNzA3MTcy NTU0WhcNMzAxMjA3MTc1NTU0WjCBvjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUVu dHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3d3cuZW50cnVzdC5uZXQvbGVnYWwt dGVybXMxOTA3BgNVBAsTMChjKSAyMDA5IEVudHJ1c3QsIEluYy4gLSBmb3IgYXV0 aG9yaXplZCB1c2Ugb25seTEyMDAGA1UEAxMpRW50cnVzdCBSb290IENlcnRpZmlj YXRpb24gQXV0aG9yaXR5IC0gRzIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK AoIBAQC6hLZy254Ma+KZ6TABp3bqMriVQRrJ2mFOWHLP/vaCeb9zYQYKpSfYs1/T RU4cctZOMvJyig/3gxnQaoCAAEUesMfnmr8SVycco2gvCoe9amsOXmXzHHfV1IWN cCG0szLni6LVhjkCsbjSR87kyUnEO6fe+1R9V77w6G7CebI6C1XiUJgWMhNcL3hW wcKUs/Ja5CeanyTXxuzQmyWC48zCxEXFjJd6BmsqEZ+pCm5IO2/b1BEZQvePB7/1 U1+cPvQXLOZprE4yTGJ36rfo5bs0vBmLrpxR57d+tVOxMyLlbc9wPBr64ptntoP0 jaWvYkxN4FisZDQSA/i2jZRjJKRxAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAP BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqciZ60B7vfec7aVHUbI2fkBJmqzAN BgkqhkiG9w0BAQsFAAOCAQEAeZ8dlsa2eT8ijYfThwMEYGprmi5ZiXMRrEPR9RP/ jTkrwPK9T3CMqS/qF8QLVJ7UG5aYMzyorWKiAHarWWluBh1+xLlEjZivEtRh2woZ Rkfz6/djwUAFQKXSt/S1mja/qYh2iARVBCuch38aNzx+LaUa2NSJXsq9rD1s2G2v 1fN2D807iDginWyTmsQ9v4IbZT+mD12q/OWyFcq1rca8PdCE6OoGcrBNOTJ4vz4R nAuknZoh8/CbCzB428Hch0P+vGOaysXCHMnHjf87ElgI5rY97HosTvuDls4MPGmH VHOkc8KT/1EQrBVUAdj8BbGJoX90g5pJ19xOe4pIb4tF9g== -----END CERTIFICATE----- # Entrust Root Certification Authority.pem # Certificate: # Data: # Version: 3 (0x2) # Serial Number: 1164660820 (0x456b5054) # Signature Algorithm: sha1WithRSAEncryption # Issuer: C=US, O=Entrust, Inc., OU=www.entrust.net/CPS is incorporated by reference, OU=(c) 2006 Entrust, Inc., CN=Entrust Root Certification Authority # Validity # Not Before: Nov 27 20:23:42 2006 GMT # Not After : Nov 27 20:53:42 2026 GMT # Subject: C=US, O=Entrust, Inc., OU=www.entrust.net/CPS is incorporated by reference, OU=(c) 2006 Entrust, Inc., CN=Entrust Root Certification Authority # Subject Public Key Info: # Public Key Algorithm: rsaEncryption # Public-Key: (2048 bit) # Modulus: # 00:b6:95:b6:43:42:fa:c6:6d:2a:6f:48:df:94:4c: # 39:57:05:ee:c3:79:11:41:68:36:ed:ec:fe:9a:01: # 8f:a1:38:28:fc:f7:10:46:66:2e:4d:1e:1a:b1:1a: # 4e:c6:d1:c0:95:88:b0:c9:ff:31:8b:33:03:db:b7: # 83:7b:3e:20:84:5e:ed:b2:56:28:a7:f8:e0:b9:40: # 71:37:c5:cb:47:0e:97:2a:68:c0:22:95:62:15:db: # 47:d9:f5:d0:2b:ff:82:4b:c9:ad:3e:de:4c:db:90: # 80:50:3f:09:8a:84:00:ec:30:0a:3d:18:cd:fb:fd: # 2a:59:9a:23:95:17:2c:45:9e:1f:6e:43:79:6d:0c: # 5c:98:fe:48:a7:c5:23:47:5c:5e:fd:6e:e7:1e:b4: # f6:68:45:d1:86:83:5b:a2:8a:8d:b1:e3:29:80:fe: # 25:71:88:ad:be:bc:8f:ac:52:96:4b:aa:51:8d:e4: # 13:31:19:e8:4e:4d:9f:db:ac:b3:6a:d5:bc:39:54: # 71:ca:7a:7a:7f:90:dd:7d:1d:80:d9:81:bb:59:26: # c2:11:fe:e6:93:e2:f7:80:e4:65:fb:34:37:0e:29: # 80:70:4d:af:38:86:2e:9e:7f:57:af:9e:17:ae:eb: # 1c:cb:28:21:5f:b6:1c:d8:e7:a2:04:22:f9:d3:da: # d8:cb # Exponent: 65537 (0x10001) # X509v3 extensions: # X509v3 Key Usage: critical # Certificate Sign, CRL Sign # X509v3 Basic Constraints: critical # CA:TRUE # X509v3 Private Key Usage Period: # Not Before: Nov 27 20:23:42 2006 GMT, Not After: Nov 27 20:53:42 2026 GMT # X509v3 Authority Key Identifier: # keyid:68:90:E4:67:A4:A6:53:80:C7:86:66:A4:F1:F7:4B:43:FB:84:BD:6D # # X509v3 Subject Key Identifier: # 68:90:E4:67:A4:A6:53:80:C7:86:66:A4:F1:F7:4B:43:FB:84:BD:6D # 1.2.840.113533.7.65.0: # 0...V7.1:4.0.... # Signature Algorithm: sha1WithRSAEncryption # 93:d4:30:b0:d7:03:20:2a:d0:f9:63:e8:91:0c:05:20:a9:5f: # 19:ca:7b:72:4e:d4:b1:db:d0:96:fb:54:5a:19:2c:0c:08:f7: # b2:bc:85:a8:9d:7f:6d:3b:52:b3:2a:db:e7:d4:84:8c:63:f6: # 0f:cb:26:01:91:50:6c:f4:5f:14:e2:93:74:c0:13:9e:30:3a: # 50:e3:b4:60:c5:1c:f0:22:44:8d:71:47:ac:c8:1a:c9:e9:9b: # 9a:00:60:13:ff:70:7e:5f:11:4d:49:1b:b3:15:52:7b:c9:54: # da:bf:9d:95:af:6b:9a:d8:9e:e9:f1:e4:43:8d:e2:11:44:3a: # bf:af:bd:83:42:73:52:8b:aa:bb:a7:29:cf:f5:64:1c:0a:4d: # d1:bc:aa:ac:9f:2a:d0:ff:7f:7f:da:7d:ea:b1:ed:30:25:c1: # 84:da:34:d2:5b:78:83:56:ec:9c:36:c3:26:e2:11:f6:67:49: # 1d:92:ab:8c:fb:eb:ff:7a:ee:85:4a:a7:50:80:f0:a7:5c:4a: # 94:2e:5f:05:99:3c:52:41:e0:cd:b4:63:cf:01:43:ba:9c:83: # dc:8f:60:3b:f3:5a:b4:b4:7b:ae:da:0b:90:38:75:ef:81:1d: # 66:d2:f7:57:70:36:b3:bf:fc:28:af:71:25:85:5b:13:fe:1e: # 7f:5a:b4:3c -----BEGIN CERTIFICATE----- MIIEkTCCA3mgAwIBAgIERWtQVDANBgkqhkiG9w0BAQUFADCBsDELMAkGA1UEBhMC VVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xOTA3BgNVBAsTMHd3dy5lbnRydXN0 Lm5ldC9DUFMgaXMgaW5jb3Jwb3JhdGVkIGJ5IHJlZmVyZW5jZTEfMB0GA1UECxMW KGMpIDIwMDYgRW50cnVzdCwgSW5jLjEtMCsGA1UEAxMkRW50cnVzdCBSb290IENl cnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA2MTEyNzIwMjM0MloXDTI2MTEyNzIw NTM0MlowgbAxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMTkw NwYDVQQLEzB3d3cuZW50cnVzdC5uZXQvQ1BTIGlzIGluY29ycG9yYXRlZCBieSBy ZWZlcmVuY2UxHzAdBgNVBAsTFihjKSAyMDA2IEVudHJ1c3QsIEluYy4xLTArBgNV BAMTJEVudHJ1c3QgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASIwDQYJ KoZIhvcNAQEBBQADggEPADCCAQoCggEBALaVtkNC+sZtKm9I35RMOVcF7sN5EUFo Nu3s/poBj6E4KPz3EEZmLk0eGrEaTsbRwJWIsMn/MYszA9u3g3s+IIRe7bJWKKf4 4LlAcTfFy0cOlypowCKVYhXbR9n10Cv/gkvJrT7eTNuQgFA/CYqEAOwwCj0Yzfv9 KlmaI5UXLEWeH25DeW0MXJj+SKfFI0dcXv1u5x609mhF0YaDW6KKjbHjKYD+JXGI rb68j6xSlkuqUY3kEzEZ6E5Nn9uss2rVvDlUccp6en+Q3X0dgNmBu1kmwhH+5pPi 94DkZfs0Nw4pgHBNrziGLp5/V6+eF67rHMsoIV+2HNjnogQi+dPa2MsCAwEAAaOB sDCBrTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zArBgNVHRAEJDAi gA8yMDA2MTEyNzIwMjM0MlqBDzIwMjYxMTI3MjA1MzQyWjAfBgNVHSMEGDAWgBRo kORnpKZTgMeGZqTx90tD+4S9bTAdBgNVHQ4EFgQUaJDkZ6SmU4DHhmak8fdLQ/uE vW0wHQYJKoZIhvZ9B0EABBAwDhsIVjcuMTo0LjADAgSQMA0GCSqGSIb3DQEBBQUA A4IBAQCT1DCw1wMgKtD5Y+iRDAUgqV8ZyntyTtSx29CW+1RaGSwMCPeyvIWonX9t O1KzKtvn1ISMY/YPyyYBkVBs9F8U4pN0wBOeMDpQ47RgxRzwIkSNcUesyBrJ6Zua AGAT/3B+XxFNSRuzFVJ7yVTav52Vr2ua2J7p8eRDjeIRRDq/r72DQnNSi6q7pynP 9WQcCk3RvKqsnyrQ/39/2n3qse0wJcGE2jTSW3iDVuycNsMm4hH2Z0kdkquM++v/ eu6FSqdQgPCnXEqULl8FmTxSQeDNtGPPAUO6nIPcj2A781q0tHuu2guQOHXvgR1m 0vdXcDazv/wor3ElhVsT/h5/WrQ8 -----END CERTIFICATE----- # Entrust.net Certification Authority (2048).pem # Certificate: # Data: # Version: 3 (0x2) # Serial Number: 946069240 (0x3863def8) # Signature Algorithm: sha1WithRSAEncryption # Issuer: O=Entrust.net, OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.), OU=(c) 1999 Entrust.net Limited, CN=Entrust.net Certification Authority (2048) # Validity # Not Before: Dec 24 17:50:51 1999 GMT # Not After : Jul 24 14:15:12 2029 GMT # Subject: O=Entrust.net, OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.), OU=(c) 1999 Entrust.net Limited, CN=Entrust.net Certification Authority (2048) # Subject Public Key Info: # Public Key Algorithm: rsaEncryption # Public-Key: (2048 bit) # Modulus: # 00:ad:4d:4b:a9:12:86:b2:ea:a3:20:07:15:16:64: # 2a:2b:4b:d1:bf:0b:4a:4d:8e:ed:80:76:a5:67:b7: # 78:40:c0:73:42:c8:68:c0:db:53:2b:dd:5e:b8:76: # 98:35:93:8b:1a:9d:7c:13:3a:0e:1f:5b:b7:1e:cf: # e5:24:14:1e:b1:81:a9:8d:7d:b8:cc:6b:4b:03:f1: # 02:0c:dc:ab:a5:40:24:00:7f:74:94:a1:9d:08:29: # b3:88:0b:f5:87:77:9d:55:cd:e4:c3:7e:d7:6a:64: # ab:85:14:86:95:5b:97:32:50:6f:3d:c8:ba:66:0c: # e3:fc:bd:b8:49:c1:76:89:49:19:fd:c0:a8:bd:89: # a3:67:2f:c6:9f:bc:71:19:60:b8:2d:e9:2c:c9:90: # 76:66:7b:94:e2:af:78:d6:65:53:5d:3c:d6:9c:b2: # cf:29:03:f9:2f:a4:50:b2:d4:48:ce:05:32:55:8a: # fd:b2:64:4c:0e:e4:98:07:75:db:7f:df:b9:08:55: # 60:85:30:29:f9:7b:48:a4:69:86:e3:35:3f:1e:86: # 5d:7a:7a:15:bd:ef:00:8e:15:22:54:17:00:90:26: # 93:bc:0e:49:68:91:bf:f8:47:d3:9d:95:42:c1:0e: # 4d:df:6f:26:cf:c3:18:21:62:66:43:70:d6:d5:c0: # 07:e1 # Exponent: 65537 (0x10001) # X509v3 extensions: # X509v3 Key Usage: critical # Certificate Sign, CRL Sign # X509v3 Basic Constraints: critical # CA:TRUE # X509v3 Subject Key Identifier: # 55:E4:81:D1:11:80:BE:D8:89:B9:08:A3:31:F9:A1:24:09:16:B9:70 # Signature Algorithm: sha1WithRSAEncryption # 3b:9b:8f:56:9b:30:e7:53:99:7c:7a:79:a7:4d:97:d7:19:95: # 90:fb:06:1f:ca:33:7c:46:63:8f:96:66:24:fa:40:1b:21:27: # ca:e6:72:73:f2:4f:fe:31:99:fd:c8:0c:4c:68:53:c6:80:82: # 13:98:fa:b6:ad:da:5d:3d:f1:ce:6e:f6:15:11:94:82:0c:ee: # 3f:95:af:11:ab:0f:d7:2f:de:1f:03:8f:57:2c:1e:c9:bb:9a: # 1a:44:95:eb:18:4f:a6:1f:cd:7d:57:10:2f:9b:04:09:5a:84: # b5:6e:d8:1d:3a:e1:d6:9e:d1:6c:79:5e:79:1c:14:c5:e3:d0: # 4c:93:3b:65:3c:ed:df:3d:be:a6:e5:95:1a:c3:b5:19:c3:bd: # 5e:5b:bb:ff:23:ef:68:19:cb:12:93:27:5c:03:2d:6f:30:d0: # 1e:b6:1a:ac:de:5a:f7:d1:aa:a8:27:a6:fe:79:81:c4:79:99: # 33:57:ba:12:b0:a9:e0:42:6c:93:ca:56:de:fe:6d:84:0b:08: # 8b:7e:8d:ea:d7:98:21:c6:f3:e7:3c:79:2f:5e:9c:d1:4c:15: # 8d:e1:ec:22:37:cc:9a:43:0b:97:dc:80:90:8d:b3:67:9b:6f: # 48:08:15:56:cf:bf:f1:2b:7c:5e:9a:76:e9:59:90:c5:7c:83: # 35:11:65:51 -----BEGIN CERTIFICATE----- MIIEKjCCAxKgAwIBAgIEOGPe+DANBgkqhkiG9w0BAQUFADCBtDEUMBIGA1UEChML RW50cnVzdC5uZXQxQDA+BgNVBAsUN3d3dy5lbnRydXN0Lm5ldC9DUFNfMjA0OCBp bmNvcnAuIGJ5IHJlZi4gKGxpbWl0cyBsaWFiLikxJTAjBgNVBAsTHChjKSAxOTk5 IEVudHJ1c3QubmV0IExpbWl0ZWQxMzAxBgNVBAMTKkVudHJ1c3QubmV0IENlcnRp ZmljYXRpb24gQXV0aG9yaXR5ICgyMDQ4KTAeFw05OTEyMjQxNzUwNTFaFw0yOTA3 MjQxNDE1MTJaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3d3d3 LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxp YWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEG A1UEAxMqRW50cnVzdC5uZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgp MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArU1LqRKGsuqjIAcVFmQq K0vRvwtKTY7tgHalZ7d4QMBzQshowNtTK91euHaYNZOLGp18EzoOH1u3Hs/lJBQe sYGpjX24zGtLA/ECDNyrpUAkAH90lKGdCCmziAv1h3edVc3kw37XamSrhRSGlVuX MlBvPci6Zgzj/L24ScF2iUkZ/cCovYmjZy/Gn7xxGWC4LeksyZB2ZnuU4q941mVT XTzWnLLPKQP5L6RQstRIzgUyVYr9smRMDuSYB3Xbf9+5CFVghTAp+XtIpGmG4zU/ HoZdenoVve8AjhUiVBcAkCaTvA5JaJG/+EfTnZVCwQ5N328mz8MYIWJmQ3DW1cAH 4QIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNV HQ4EFgQUVeSB0RGAvtiJuQijMfmhJAkWuXAwDQYJKoZIhvcNAQEFBQADggEBADub j1abMOdTmXx6eadNl9cZlZD7Bh/KM3xGY4+WZiT6QBshJ8rmcnPyT/4xmf3IDExo U8aAghOY+rat2l098c5u9hURlIIM7j+VrxGrD9cv3h8Dj1csHsm7mhpElesYT6Yf zX1XEC+bBAlahLVu2B064dae0Wx5XnkcFMXj0EyTO2U87d89vqbllRrDtRnDvV5b u/8j72gZyxKTJ1wDLW8w0B62GqzeWvfRqqgnpv55gcR5mTNXuhKwqeBCbJPKVt7+ bYQLCIt+jerXmCHG8+c8eS9enNFMFY3h7CI3zJpDC5fcgJCNs2ebb0gIFVbPv/Er fF6adulZkMV8gzURZVE= -----END CERTIFICATE----- # GeoTrust Global CA.pem # Certificate: # Data: # Version: 3 (0x2) # Serial Number: 144470 (0x23456) # Signature Algorithm: sha1WithRSAEncryption # Issuer: C=US, O=GeoTrust Inc., CN=GeoTrust Global CA # Validity # Not Before: May 21 04:00:00 2002 GMT # Not After : May 21 04:00:00 2022 GMT # Subject: C=US, O=GeoTrust Inc., CN=GeoTrust Global CA # Subject Public Key Info: # Public Key Algorithm: rsaEncryption # Public-Key: (2048 bit) # Modulus: # 00:da:cc:18:63:30:fd:f4:17:23:1a:56:7e:5b:df: # 3c:6c:38:e4:71:b7:78:91:d4:bc:a1:d8:4c:f8:a8: # 43:b6:03:e9:4d:21:07:08:88:da:58:2f:66:39:29: # bd:05:78:8b:9d:38:e8:05:b7:6a:7e:71:a4:e6:c4: # 60:a6:b0:ef:80:e4:89:28:0f:9e:25:d6:ed:83:f3: # ad:a6:91:c7:98:c9:42:18:35:14:9d:ad:98:46:92: # 2e:4f:ca:f1:87:43:c1:16:95:57:2d:50:ef:89:2d: # 80:7a:57:ad:f2:ee:5f:6b:d2:00:8d:b9:14:f8:14: # 15:35:d9:c0:46:a3:7b:72:c8:91:bf:c9:55:2b:cd: # d0:97:3e:9c:26:64:cc:df:ce:83:19:71:ca:4e:e6: # d4:d5:7b:a9:19:cd:55:de:c8:ec:d2:5e:38:53:e5: # 5c:4f:8c:2d:fe:50:23:36:fc:66:e6:cb:8e:a4:39: # 19:00:b7:95:02:39:91:0b:0e:fe:38:2e:d1:1d:05: # 9a:f6:4d:3e:6f:0f:07:1d:af:2c:1e:8f:60:39:e2: # fa:36:53:13:39:d4:5e:26:2b:db:3d:a8:14:bd:32: # eb:18:03:28:52:04:71:e5:ab:33:3d:e1:38:bb:07: # 36:84:62:9c:79:ea:16:30:f4:5f:c0:2b:e8:71:6b: # e4:f9 # Exponent: 65537 (0x10001) # X509v3 extensions: # X509v3 Basic Constraints: critical # CA:TRUE # X509v3 Subject Key Identifier: # C0:7A:98:68:8D:89:FB:AB:05:64:0C:11:7D:AA:7D:65:B8:CA:CC:4E # X509v3 Authority Key Identifier: # keyid:C0:7A:98:68:8D:89:FB:AB:05:64:0C:11:7D:AA:7D:65:B8:CA:CC:4E # # Signature Algorithm: sha1WithRSAEncryption # 35:e3:29:6a:e5:2f:5d:54:8e:29:50:94:9f:99:1a:14:e4:8f: # 78:2a:62:94:a2:27:67:9e:d0:cf:1a:5e:47:e9:c1:b2:a4:cf: # dd:41:1a:05:4e:9b:4b:ee:4a:6f:55:52:b3:24:a1:37:0a:eb: # 64:76:2a:2e:2c:f3:fd:3b:75:90:bf:fa:71:d8:c7:3d:37:d2: # b5:05:95:62:b9:a6:de:89:3d:36:7b:38:77:48:97:ac:a6:20: # 8f:2e:a6:c9:0c:c2:b2:99:45:00:c7:ce:11:51:22:22:e0:a5: # ea:b6:15:48:09:64:ea:5e:4f:74:f7:05:3e:c7:8a:52:0c:db: # 15:b4:bd:6d:9b:e5:c6:b1:54:68:a9:e3:69:90:b6:9a:a5:0f: # b8:b9:3f:20:7d:ae:4a:b5:b8:9c:e4:1d:b6:ab:e6:94:a5:c1: # c7:83:ad:db:f5:27:87:0e:04:6c:d5:ff:dd:a0:5d:ed:87:52: # b7:2b:15:02:ae:39:a6:6a:74:e9:da:c4:e7:bc:4d:34:1e:a9: # 5c:4d:33:5f:92:09:2f:88:66:5d:77:97:c7:1d:76:13:a9:d5: # e5:f1:16:09:11:35:d5:ac:db:24:71:70:2c:98:56:0b:d9:17: # b4:d1:e3:51:2b:5e:75:e8:d5:d0:dc:4f:34:ed:c2:05:66:80: # a1:cb:e6:33 -----BEGIN CERTIFICATE----- MIIDVDCCAjygAwIBAgIDAjRWMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i YWwgQ0EwHhcNMDIwNTIxMDQwMDAwWhcNMjIwNTIxMDQwMDAwWjBCMQswCQYDVQQG EwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEbMBkGA1UEAxMSR2VvVHJ1c3Qg R2xvYmFsIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2swYYzD9 9BcjGlZ+W988bDjkcbd4kdS8odhM+KhDtgPpTSEHCIjaWC9mOSm9BXiLnTjoBbdq fnGk5sRgprDvgOSJKA+eJdbtg/OtppHHmMlCGDUUna2YRpIuT8rxh0PBFpVXLVDv iS2Aelet8u5fa9IAjbkU+BQVNdnARqN7csiRv8lVK83Qlz6cJmTM386DGXHKTubU 1XupGc1V3sjs0l44U+VcT4wt/lAjNvxm5suOpDkZALeVAjmRCw7+OC7RHQWa9k0+ bw8HHa8sHo9gOeL6NlMTOdReJivbPagUvTLrGAMoUgRx5aszPeE4uwc2hGKceeoW MPRfwCvocWvk+QIDAQABo1MwUTAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTA ephojYn7qwVkDBF9qn1luMrMTjAfBgNVHSMEGDAWgBTAephojYn7qwVkDBF9qn1l uMrMTjANBgkqhkiG9w0BAQUFAAOCAQEANeMpauUvXVSOKVCUn5kaFOSPeCpilKIn Z57QzxpeR+nBsqTP3UEaBU6bS+5Kb1VSsyShNwrrZHYqLizz/Tt1kL/6cdjHPTfS tQWVYrmm3ok9Nns4d0iXrKYgjy6myQzCsplFAMfOEVEiIuCl6rYVSAlk6l5PdPcF PseKUgzbFbS9bZvlxrFUaKnjaZC2mqUPuLk/IH2uSrW4nOQdtqvmlKXBx4Ot2/Un hw4EbNX/3aBd7YdStysVAq45pmp06drE57xNNB6pXE0zX5IJL4hmXXeXxx12E6nV 5fEWCRE11azbJHFwLJhWC9kXtNHjUStedejV0NxPNO3CBWaAocvmMw== -----END CERTIFICATE----- # GeoTrust Primary Certification Authority - G2.pem # Certificate: # Data: # Version: 3 (0x2) # Serial Number: # 3c:b2:f4:48:0a:00:e2:fe:eb:24:3b:5e:60:3e:c3:6b # Signature Algorithm: ecdsa-with-SHA384 # Issuer: C=US, O=GeoTrust Inc., OU=(c) 2007 GeoTrust Inc. - For authorized use only, CN=GeoTrust Primary Certification Authority - G2 # Validity # Not Before: Nov 5 00:00:00 2007 GMT # Not After : Jan 18 23:59:59 2038 GMT # Subject: C=US, O=GeoTrust Inc., OU=(c) 2007 GeoTrust Inc. - For authorized use only, CN=GeoTrust Primary Certification Authority - G2 # Subject Public Key Info: # Public Key Algorithm: id-ecPublicKey # Public-Key: (384 bit) # pub: # 04:15:b1:e8:fd:03:15:43:e5:ac:eb:87:37:11:62: # ef:d2:83:36:52:7d:45:57:0b:4a:8d:7b:54:3b:3a: # 6e:5f:15:02:c0:50:a6:cf:25:2f:7d:ca:48:b8:c7: # 50:63:1c:2a:21:08:7c:9a:36:d8:0b:fe:d1:26:c5: # 58:31:30:28:25:f3:5d:5d:a3:b8:b6:a5:b4:92:ed: # 6c:2c:9f:eb:dd:43:89:a2:3c:4b:48:91:1d:50:ec: # 26:df:d6:60:2e:bd:21 # ASN1 OID: secp384r1 # X509v3 extensions: # X509v3 Basic Constraints: critical # CA:TRUE # X509v3 Key Usage: critical # Certificate Sign, CRL Sign # X509v3 Subject Key Identifier: # 15:5F:35:57:51:55:FB:25:B2:AD:03:69:FC:01:A3:FA:BE:11:55:D5 # Signature Algorithm: ecdsa-with-SHA384 # 30:64:02:30:64:96:59:a6:e8:09:de:8b:ba:fa:5a:88:88:f0: # 1f:91:d3:46:a8:f2:4a:4c:02:63:fb:6c:5f:38:db:2e:41:93: # a9:0e:e6:9d:dc:31:1c:b2:a0:a7:18:1c:79:e1:c7:36:02:30: # 3a:56:af:9a:74:6c:f6:fb:83:e0:33:d3:08:5f:a1:9c:c2:5b: # 9f:46:d6:b6:cb:91:06:63:a2:06:e7:33:ac:3e:a8:81:12:d0: # cb:ba:d0:92:0b:b6:9e:96:aa:04:0f:8a -----BEGIN CERTIFICATE----- MIICrjCCAjWgAwIBAgIQPLL0SAoA4v7rJDteYD7DazAKBggqhkjOPQQDAzCBmDEL MAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsTMChj KSAyMDA3IEdlb1RydXN0IEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTE2 MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0 eSAtIEcyMB4XDTA3MTEwNTAwMDAwMFoXDTM4MDExODIzNTk1OVowgZgxCzAJBgNV BAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAoYykgMjAw NyBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0BgNV BAMTLUdlb1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBH MjB2MBAGByqGSM49AgEGBSuBBAAiA2IABBWx6P0DFUPlrOuHNxFi79KDNlJ9RVcL So17VDs6bl8VAsBQps8lL33KSLjHUGMcKiEIfJo22Av+0SbFWDEwKCXzXV2juLal tJLtbCyf691DiaI8S0iRHVDsJt/WYC69IaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO BgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFBVfNVdRVfslsq0DafwBo/q+EVXVMAoG CCqGSM49BAMDA2cAMGQCMGSWWaboCd6LuvpaiIjwH5HTRqjySkwCY/tsXzjbLkGT qQ7mndwxHLKgpxgceeHHNgIwOlavmnRs9vuD4DPTCF+hnMJbn0bWtsuRBmOiBucz rD6ogRLQy7rQkgu2npaqBA+K -----END CERTIFICATE----- # GeoTrust Primary Certification Authority - G3.pem # Certificate: # Data: # Version: 3 (0x2) # Serial Number: # 15:ac:6e:94:19:b2:79:4b:41:f6:27:a9:c3:18:0f:1f # Signature Algorithm: sha256WithRSAEncryption # Issuer: C=US, O=GeoTrust Inc., OU=(c) 2008 GeoTrust Inc. - For authorized use only, CN=GeoTrust Primary Certification Authority - G3 # Validity # Not Before: Apr 2 00:00:00 2008 GMT # Not After : Dec 1 23:59:59 2037 GMT # Subject: C=US, O=GeoTrust Inc., OU=(c) 2008 GeoTrust Inc. - For authorized use only, CN=GeoTrust Primary Certification Authority - G3 # Subject Public Key Info: # Public Key Algorithm: rsaEncryption # Public-Key: (2048 bit) # Modulus: # 00:dc:e2:5e:62:58:1d:33:57:39:32:33:fa:eb:cb: # 87:8c:a7:d4:4a:dd:06:88:ea:64:8e:31:98:a5:38: # 90:1e:98:cf:2e:63:2b:f0:46:bc:44:b2:89:a1:c0: # 28:0c:49:70:21:95:9f:64:c0:a6:93:12:02:65:26: # 86:c6:a5:89:f0:fa:d7:84:a0:70:af:4f:1a:97:3f: # 06:44:d5:c9:eb:72:10:7d:e4:31:28:fb:1c:61:e6: # 28:07:44:73:92:22:69:a7:03:88:6c:9d:63:c8:52: # da:98:27:e7:08:4c:70:3e:b4:c9:12:c1:c5:67:83: # 5d:33:f3:03:11:ec:6a:d0:53:e2:d1:ba:36:60:94: # 80:bb:61:63:6c:5b:17:7e:df:40:94:1e:ab:0d:c2: # 21:28:70:88:ff:d6:26:6c:6c:60:04:25:4e:55:7e: # 7d:ef:bf:94:48:de:b7:1d:dd:70:8d:05:5f:88:a5: # 9b:f2:c2:ee:ea:d1:40:41:6d:62:38:1d:56:06:c5: # 03:47:51:20:19:fc:7b:10:0b:0e:62:ae:76:55:bf: # 5f:77:be:3e:49:01:53:3d:98:25:03:76:24:5a:1d: # b4:db:89:ea:79:e5:b6:b3:3b:3f:ba:4c:28:41:7f: # 06:ac:6a:8e:c1:d0:f6:05:1d:7d:e6:42:86:e3:a5: # d5:47 # Exponent: 65537 (0x10001) # X509v3 extensions: # X509v3 Basic Constraints: critical # CA:TRUE # X509v3 Key Usage: critical # Certificate Sign, CRL Sign # X509v3 Subject Key Identifier: # C4:79:CA:8E:A1:4E:03:1D:1C:DC:6B:DB:31:5B:94:3E:3F:30:7F:2D # Signature Algorithm: sha256WithRSAEncryption # 2d:c5:13:cf:56:80:7b:7a:78:bd:9f:ae:2c:99:e7:ef:da:df: # 94:5e:09:69:a7:e7:6e:68:8c:bd:72:be:47:a9:0e:97:12:b8: # 4a:f1:64:d3:39:df:25:34:d4:c1:cd:4e:81:f0:0f:04:c4:24: # b3:34:96:c6:a6:aa:30:df:68:61:73:d7:f9:8e:85:89:ef:0e: # 5e:95:28:4a:2a:27:8f:10:8e:2e:7c:86:c4:02:9e:da:0c:77: # 65:0e:44:0d:92:fd:fd:b3:16:36:fa:11:0d:1d:8c:0e:07:89: # 6a:29:56:f7:72:f4:dd:15:9c:77:35:66:57:ab:13:53:d8:8e: # c1:40:c5:d7:13:16:5a:72:c7:b7:69:01:c4:7a:b1:83:01:68: # 7d:8d:41:a1:94:18:c1:25:5c:fc:f0:fe:83:02:87:7c:0d:0d: # cf:2e:08:5c:4a:40:0d:3e:ec:81:61:e6:24:db:ca:e0:0e:2d: # 07:b2:3e:56:dc:8d:f5:41:85:07:48:9b:0c:0b:cb:49:3f:7d: # ec:b7:fd:cb:8d:67:89:1a:ab:ed:bb:1e:a3:00:08:08:17:2a: # 82:5c:31:5d:46:8a:2d:0f:86:9b:74:d9:45:fb:d4:40:b1:7a: # aa:68:2d:86:b2:99:22:e1:c1:2b:c7:9c:f8:f3:5f:a8:82:12: # eb:19:11:2d -----BEGIN CERTIFICATE----- MIID/jCCAuagAwIBAgIQFaxulBmyeUtB9iepwxgPHzANBgkqhkiG9w0BAQsFADCB mDELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsT MChjKSAyMDA4IEdlb1RydXN0IEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25s eTE2MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhv cml0eSAtIEczMB4XDTA4MDQwMjAwMDAwMFoXDTM3MTIwMTIzNTk1OVowgZgxCzAJ BgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAoYykg MjAwOCBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0 BgNVBAMTLUdlb1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkg LSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANziXmJYHTNXOTIz +uvLh4yn1ErdBojqZI4xmKU4kB6Yzy5jK/BGvESyiaHAKAxJcCGVn2TAppMSAmUm hsalifD614SgcK9PGpc/BkTVyetyEH3kMSj7HGHmKAdEc5IiaacDiGydY8hS2pgn 5whMcD60yRLBxWeDXTPzAxHsatBT4tG6NmCUgLthY2xbF37fQJQeqw3CIShwiP/W JmxsYAQlTlV+fe+/lEjetx3dcI0FX4ilm/LC7urRQEFtYjgdVgbFA0dRIBn8exAL DmKudlW/X3e+PkkBUz2YJQN2JFodtNuJ6nnltrM7P7pMKEF/BqxqjsHQ9gUdfeZC huOl1UcCAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYw HQYDVR0OBBYEFMR5yo6hTgMdHNxr2zFblD4/MH8tMA0GCSqGSIb3DQEBCwUAA4IB AQAtxRPPVoB7eni9n64smefv2t+UXglpp+duaIy9cr5HqQ6XErhK8WTTOd8lNNTB zU6B8A8ExCSzNJbGpqow32hhc9f5joWJ7w5elShKKiePEI4ufIbEAp7aDHdlDkQN kv39sxY2+hENHYwOB4lqKVb3cvTdFZx3NWZXqxNT2I7BQMXXExZacse3aQHEerGD AWh9jUGhlBjBJVz88P6DAod8DQ3PLghcSkANPuyBYeYk28rgDi0Hsj5W3I31QYUH SJsMC8tJP33st/3LjWeJGqvtux6jAAgIFyqCXDFdRootD4abdNlF+9RAsXqqaC2G spki4cErx5z481+oghLrGREt -----END CERTIFICATE----- # GeoTrust Primary Certification Authority.pem # Certificate: # Data: # Version: 3 (0x2) # Serial Number: # 18:ac:b5:6a:fd:69:b6:15:3a:63:6c:af:da:fa:c4:a1 # Signature Algorithm: sha1WithRSAEncryption # Issuer: C=US, O=GeoTrust Inc., CN=GeoTrust Primary Certification Authority # Validity # Not Before: Nov 27 00:00:00 2006 GMT # Not After : Jul 16 23:59:59 2036 GMT # Subject: C=US, O=GeoTrust Inc., CN=GeoTrust Primary Certification Authority # Subject Public Key Info: # Public Key Algorithm: rsaEncryption # Public-Key: (2048 bit) # Modulus: # 00:be:b8:15:7b:ff:d4:7c:7d:67:ad:83:64:7b:c8: # 42:53:2d:df:f6:84:08:20:61:d6:01:59:6a:9c:44: # 11:af:ef:76:fd:95:7e:ce:61:30:bb:7a:83:5f:02: # bd:01:66:ca:ee:15:8d:6f:a1:30:9c:bd:a1:85:9e: # 94:3a:f3:56:88:00:31:cf:d8:ee:6a:96:02:d9:ed: # 03:8c:fb:75:6d:e7:ea:b8:55:16:05:16:9a:f4:e0: # 5e:b1:88:c0:64:85:5c:15:4d:88:c7:b7:ba:e0:75: # e9:ad:05:3d:9d:c7:89:48:e0:bb:28:c8:03:e1:30: # 93:64:5e:52:c0:59:70:22:35:57:88:8a:f1:95:0a: # 83:d7:bc:31:73:01:34:ed:ef:46:71:e0:6b:02:a8: # 35:72:6b:97:9b:66:e0:cb:1c:79:5f:d8:1a:04:68: # 1e:47:02:e6:9d:60:e2:36:97:01:df:ce:35:92:df: # be:67:c7:6d:77:59:3b:8f:9d:d6:90:15:94:bc:42: # 34:10:c1:39:f9:b1:27:3e:7e:d6:8a:75:c5:b2:af: # 96:d3:a2:de:9b:e4:98:be:7d:e1:e9:81:ad:b6:6f: # fc:d7:0e:da:e0:34:b0:0d:1a:77:e7:e3:08:98:ef: # 58:fa:9c:84:b7:36:af:c2:df:ac:d2:f4:10:06:70: # 71:35 # Exponent: 65537 (0x10001) # X509v3 extensions: # X509v3 Basic Constraints: critical # CA:TRUE # X509v3 Key Usage: critical # Certificate Sign, CRL Sign # X509v3 Subject Key Identifier: # 2C:D5:50:41:97:15:8B:F0:8F:36:61:5B:4A:FB:6B:D9:99:C9:33:92 # Signature Algorithm: sha1WithRSAEncryption # 5a:70:7f:2c:dd:b7:34:4f:f5:86:51:a9:26:be:4b:b8:aa:f1: # 71:0d:dc:61:c7:a0:ea:34:1e:7a:77:0f:04:35:e8:27:8f:6c: # 90:bf:91:16:24:46:3e:4a:4e:ce:2b:16:d5:0b:52:1d:fc:1f: # 67:a2:02:45:31:4f:ce:f3:fa:03:a7:79:9d:53:6a:d9:da:63: # 3a:f8:80:d7:d3:99:e1:a5:e1:be:d4:55:71:98:35:3a:be:93: # ea:ae:ad:42:b2:90:6f:e0:fc:21:4d:35:63:33:89:49:d6:9b: # 4e:ca:c7:e7:4e:09:00:f7:da:c7:ef:99:62:99:77:b6:95:22: # 5e:8a:a0:ab:f4:b8:78:98:ca:38:19:99:c9:72:9e:78:cd:4b: # ac:af:19:a0:73:12:2d:fc:c2:41:ba:81:91:da:16:5a:31:b7: # f9:b4:71:80:12:48:99:72:73:5a:59:53:c1:63:52:33:ed:a7: # c9:d2:39:02:70:fa:e0:b1:42:66:29:aa:9b:51:ed:30:54:22: # 14:5f:d9:ab:1d:c1:e4:94:f0:f8:f5:2b:f7:ea:ca:78:46:d6: # b8:91:fd:a6:0d:2b:1a:14:01:3e:80:f0:42:a0:95:07:5e:6d: # cd:cc:4b:a4:45:8d:ab:12:e8:b3:de:5a:e5:a0:7c:e8:0f:22: # 1d:5a:e9:59 -----BEGIN CERTIFICATE----- MIIDfDCCAmSgAwIBAgIQGKy1av1pthU6Y2yv2vrEoTANBgkqhkiG9w0BAQUFADBY MQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjExMC8GA1UEAxMo R2VvVHJ1c3QgUHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjEx MjcwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMFgxCzAJBgNVBAYTAlVTMRYwFAYDVQQK Ew1HZW9UcnVzdCBJbmMuMTEwLwYDVQQDEyhHZW9UcnVzdCBQcmltYXJ5IENlcnRp ZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC AQEAvrgVe//UfH1nrYNke8hCUy3f9oQIIGHWAVlqnEQRr+92/ZV+zmEwu3qDXwK9 AWbK7hWNb6EwnL2hhZ6UOvNWiAAxz9juapYC2e0DjPt1befquFUWBRaa9OBesYjA ZIVcFU2Ix7e64HXprQU9nceJSOC7KMgD4TCTZF5SwFlwIjVXiIrxlQqD17wxcwE0 7e9GceBrAqg1cmuXm2bgyxx5X9gaBGgeRwLmnWDiNpcB3841kt++Z8dtd1k7j53W kBWUvEI0EME5+bEnPn7WinXFsq+W06Lem+SYvn3h6YGttm/81w7a4DSwDRp35+MI mO9Y+pyEtzavwt+s0vQQBnBxNQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4G A1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQULNVQQZcVi/CPNmFbSvtr2ZnJM5IwDQYJ KoZIhvcNAQEFBQADggEBAFpwfyzdtzRP9YZRqSa+S7iq8XEN3GHHoOo0Hnp3DwQ1 6CePbJC/kRYkRj5KTs4rFtULUh38H2eiAkUxT87z+gOneZ1TatnaYzr4gNfTmeGl 4b7UVXGYNTq+k+qurUKykG/g/CFNNWMziUnWm07Kx+dOCQD32sfvmWKZd7aVIl6K oKv0uHiYyjgZmclynnjNS6yvGaBzEi38wkG6gZHaFloxt/m0cYASSJlyc1pZU8Fj UjPtp8nSOQJw+uCxQmYpqptR7TBUIhRf2asdweSU8Pj1K/fqynhG1riR/aYNKxoU AT6A8EKglQdebc3MS6RFjasS6LPeWuWgfOgPIh1a6Vk= -----END CERTIFICATE----- # Go Daddy Class 2 Certification Authority.pem # Certificate: # Data: # Version: 3 (0x2) # Serial Number: 0 (0x0) # Signature Algorithm: sha1WithRSAEncryption # Issuer: C=US, O=The Go Daddy Group, Inc., OU=Go Daddy Class 2 Certification Authority # Validity # Not Before: Jun 29 17:06:20 2004 GMT # Not After : Jun 29 17:06:20 2034 GMT # Subject: C=US, O=The Go Daddy Group, Inc., OU=Go Daddy Class 2 Certification Authority # Subject Public Key Info: # Public Key Algorithm: rsaEncryption # Public-Key: (2048 bit) # Modulus: # 00:de:9d:d7:ea:57:18:49:a1:5b:eb:d7:5f:48:86: # ea:be:dd:ff:e4:ef:67:1c:f4:65:68:b3:57:71:a0: # 5e:77:bb:ed:9b:49:e9:70:80:3d:56:18:63:08:6f: # da:f2:cc:d0:3f:7f:02:54:22:54:10:d8:b2:81:d4: # c0:75:3d:4b:7f:c7:77:c3:3e:78:ab:1a:03:b5:20: # 6b:2f:6a:2b:b1:c5:88:7e:c4:bb:1e:b0:c1:d8:45: # 27:6f:aa:37:58:f7:87:26:d7:d8:2d:f6:a9:17:b7: # 1f:72:36:4e:a6:17:3f:65:98:92:db:2a:6e:5d:a2: # fe:88:e0:0b:de:7f:e5:8d:15:e1:eb:cb:3a:d5:e2: # 12:a2:13:2d:d8:8e:af:5f:12:3d:a0:08:05:08:b6: # 5c:a5:65:38:04:45:99:1e:a3:60:60:74:c5:41:a5: # 72:62:1b:62:c5:1f:6f:5f:1a:42:be:02:51:65:a8: # ae:23:18:6a:fc:78:03:a9:4d:7f:80:c3:fa:ab:5a: # fc:a1:40:a4:ca:19:16:fe:b2:c8:ef:5e:73:0d:ee: # 77:bd:9a:f6:79:98:bc:b1:07:67:a2:15:0d:dd:a0: # 58:c6:44:7b:0a:3e:62:28:5f:ba:41:07:53:58:cf: # 11:7e:38:74:c5:f8:ff:b5:69:90:8f:84:74:ea:97: # 1b:af # Exponent: 3 (0x3) # X509v3 extensions: # X509v3 Subject Key Identifier: # D2:C4:B0:D2:91:D4:4C:11:71:B3:61:CB:3D:A1:FE:DD:A8:6A:D4:E3 # X509v3 Authority Key Identifier: # keyid:D2:C4:B0:D2:91:D4:4C:11:71:B3:61:CB:3D:A1:FE:DD:A8:6A:D4:E3 # DirName:/C=US/O=The Go Daddy Group, Inc./OU=Go Daddy Class 2 Certification Authority # serial:00 # # X509v3 Basic Constraints: # CA:TRUE # Signature Algorithm: sha1WithRSAEncryption # 32:4b:f3:b2:ca:3e:91:fc:12:c6:a1:07:8c:8e:77:a0:33:06: # 14:5c:90:1e:18:f7:08:a6:3d:0a:19:f9:87:80:11:6e:69:e4: # 96:17:30:ff:34:91:63:72:38:ee:cc:1c:01:a3:1d:94:28:a4: # 31:f6:7a:c4:54:d7:f6:e5:31:58:03:a2:cc:ce:62:db:94:45: # 73:b5:bf:45:c9:24:b5:d5:82:02:ad:23:79:69:8d:b8:b6:4d: # ce:cf:4c:ca:33:23:e8:1c:88:aa:9d:8b:41:6e:16:c9:20:e5: # 89:9e:cd:3b:da:70:f7:7e:99:26:20:14:54:25:ab:6e:73:85: # e6:9b:21:9d:0a:6c:82:0e:a8:f8:c2:0c:fa:10:1e:6c:96:ef: # 87:0d:c4:0f:61:8b:ad:ee:83:2b:95:f8:8e:92:84:72:39:eb: # 20:ea:83:ed:83:cd:97:6e:08:bc:eb:4e:26:b6:73:2b:e4:d3: # f6:4c:fe:26:71:e2:61:11:74:4a:ff:57:1a:87:0f:75:48:2e: # cf:51:69:17:a0:02:12:61:95:d5:d1:40:b2:10:4c:ee:c4:ac: # 10:43:a6:a5:9e:0a:d5:95:62:9a:0d:cf:88:82:c5:32:0c:e4: # 2b:9f:45:e6:0d:9f:28:9c:b1:b9:2a:5a:57:ad:37:0f:af:1d: # 7f:db:bd:9f -----BEGIN CERTIFICATE----- MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEh MB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBE YWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3 MDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkGA1UEBhMCVVMxITAfBgNVBAoTGFRo ZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28gRGFkZHkgQ2xhc3Mg MiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQADggEN ADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCA PVYYYwhv2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6w wdhFJ2+qN1j3hybX2C32qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXi EqITLdiOr18SPaAIBQi2XKVlOARFmR6jYGB0xUGlcmIbYsUfb18aQr4CUWWoriMY avx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmYvLEHZ6IVDd2gWMZEewo+ YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0OBBYEFNLE sNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h /t2oatTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5 IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmlj YXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQAD ggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wimPQoZ+YeAEW5p5JYXMP80kWNy OO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKtI3lpjbi2Tc7P TMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ HmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mER dEr/VxqHD3VILs9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5Cuf ReYNnyicsbkqWletNw+vHX/bvZ8= -----END CERTIFICATE----- # Go Daddy Root Certificate Authority - G2.pem # Certificate: # Data: # Version: 3 (0x2) # Serial Number: 0 (0x0) # Signature Algorithm: sha256WithRSAEncryption # Issuer: C=US, ST=Arizona, L=Scottsdale, O=GoDaddy.com, Inc., CN=Go Daddy Root Certificate Authority - G2 # Validity # Not Before: Sep 1 00:00:00 2009 GMT # Not After : Dec 31 23:59:59 2037 GMT # Subject: C=US, ST=Arizona, L=Scottsdale, O=GoDaddy.com, Inc., CN=Go Daddy Root Certificate Authority - G2 # Subject Public Key Info: # Public Key Algorithm: rsaEncryption # Public-Key: (2048 bit) # Modulus: # 00:bf:71:62:08:f1:fa:59:34:f7:1b:c9:18:a3:f7: # 80:49:58:e9:22:83:13:a6:c5:20:43:01:3b:84:f1: # e6:85:49:9f:27:ea:f6:84:1b:4e:a0:b4:db:70:98: # c7:32:01:b1:05:3e:07:4e:ee:f4:fa:4f:2f:59:30: # 22:e7:ab:19:56:6b:e2:80:07:fc:f3:16:75:80:39: # 51:7b:e5:f9:35:b6:74:4e:a9:8d:82:13:e4:b6:3f: # a9:03:83:fa:a2:be:8a:15:6a:7f:de:0b:c3:b6:19: # 14:05:ca:ea:c3:a8:04:94:3b:46:7c:32:0d:f3:00: # 66:22:c8:8d:69:6d:36:8c:11:18:b7:d3:b2:1c:60: # b4:38:fa:02:8c:ce:d3:dd:46:07:de:0a:3e:eb:5d: # 7c:c8:7c:fb:b0:2b:53:a4:92:62:69:51:25:05:61: # 1a:44:81:8c:2c:a9:43:96:23:df:ac:3a:81:9a:0e: # 29:c5:1c:a9:e9:5d:1e:b6:9e:9e:30:0a:39:ce:f1: # 88:80:fb:4b:5d:cc:32:ec:85:62:43:25:34:02:56: # 27:01:91:b4:3b:70:2a:3f:6e:b1:e8:9c:88:01:7d: # 9f:d4:f9:db:53:6d:60:9d:bf:2c:e7:58:ab:b8:5f: # 46:fc:ce:c4:1b:03:3c:09:eb:49:31:5c:69:46:b3: # e0:47 # Exponent: 65537 (0x10001) # X509v3 extensions: # X509v3 Basic Constraints: critical # CA:TRUE # X509v3 Key Usage: critical # Certificate Sign, CRL Sign # X509v3 Subject Key Identifier: # 3A:9A:85:07:10:67:28:B6:EF:F6:BD:05:41:6E:20:C1:94:DA:0F:DE # Signature Algorithm: sha256WithRSAEncryption # 99:db:5d:79:d5:f9:97:59:67:03:61:f1:7e:3b:06:31:75:2d: # a1:20:8e:4f:65:87:b4:f7:a6:9c:bc:d8:e9:2f:d0:db:5a:ee: # cf:74:8c:73:b4:38:42:da:05:7b:f8:02:75:b8:fd:a5:b1:d7: # ae:f6:d7:de:13:cb:53:10:7e:8a:46:d1:97:fa:b7:2e:2b:11: # ab:90:b0:27:80:f9:e8:9f:5a:e9:37:9f:ab:e4:df:6c:b3:85: # 17:9d:3d:d9:24:4f:79:91:35:d6:5f:04:eb:80:83:ab:9a:02: # 2d:b5:10:f4:d8:90:c7:04:73:40:ed:72:25:a0:a9:9f:ec:9e: # ab:68:12:99:57:c6:8f:12:3a:09:a4:bd:44:fd:06:15:37:c1: # 9b:e4:32:a3:ed:38:e8:d8:64:f3:2c:7e:14:fc:02:ea:9f:cd: # ff:07:68:17:db:22:90:38:2d:7a:8d:d1:54:f1:69:e3:5f:33: # ca:7a:3d:7b:0a:e3:ca:7f:5f:39:e5:e2:75:ba:c5:76:18:33: # ce:2c:f0:2f:4c:ad:f7:b1:e7:ce:4f:a8:c4:9b:4a:54:06:c5: # 7f:7d:d5:08:0f:e2:1c:fe:7e:17:b8:ac:5e:f6:d4:16:b2:43: # 09:0c:4d:f6:a7:6b:b4:99:84:65:ca:7a:88:e2:e2:44:be:5c: # f7:ea:1c:f5 -----BEGIN CERTIFICATE----- MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz NTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE AxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD E6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH /PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy DfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh GkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR tDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA AaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE FDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX WWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu 9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr gIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo 2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI 4uJEvlz36hz1 -----END CERTIFICATE----- # Go Daddy Secure Certification Authority serialNumber=07969287.pem # Certificate: # Data: # Version: 3 (0x2) # Serial Number: 769 (0x301) # Signature Algorithm: sha1WithRSAEncryption # Issuer: C=US, O=The Go Daddy Group, Inc., OU=Go Daddy Class 2 Certification Authority # Validity # Not Before: Nov 16 01:54:37 2006 GMT # Not After : Nov 16 01:54:37 2026 GMT # Subject: C=US, ST=Arizona, L=Scottsdale, O=GoDaddy.com, Inc., OU=http://certificates.godaddy.com/repository, CN=Go Daddy Secure Certification Authority/serialNumber=07969287 # Subject Public Key Info: # Public Key Algorithm: rsaEncryption # Public-Key: (2048 bit) # Modulus: # 00:c4:2d:d5:15:8c:9c:26:4c:ec:32:35:eb:5f:b8: # 59:01:5a:a6:61:81:59:3b:70:63:ab:e3:dc:3d:c7: # 2a:b8:c9:33:d3:79:e4:3a:ed:3c:30:23:84:8e:b3: # 30:14:b6:b2:87:c3:3d:95:54:04:9e:df:99:dd:0b: # 25:1e:21:de:65:29:7e:35:a8:a9:54:eb:f6:f7:32: # 39:d4:26:55:95:ad:ef:fb:fe:58:86:d7:9e:f4:00: # 8d:8c:2a:0c:bd:42:04:ce:a7:3f:04:f6:ee:80:f2: # aa:ef:52:a1:69:66:da:be:1a:ad:5d:da:2c:66:ea: # 1a:6b:bb:e5:1a:51:4a:00:2f:48:c7:98:75:d8:b9: # 29:c8:ee:f8:66:6d:0a:9c:b3:f3:fc:78:7c:a2:f8: # a3:f2:b5:c3:f3:b9:7a:91:c1:a7:e6:25:2e:9c:a8: # ed:12:65:6e:6a:f6:12:44:53:70:30:95:c3:9c:2b: # 58:2b:3d:08:74:4a:f2:be:51:b0:bf:87:d0:4c:27: # 58:6b:b5:35:c5:9d:af:17:31:f8:0b:8f:ee:ad:81: # 36:05:89:08:98:cf:3a:af:25:87:c0:49:ea:a7:fd: # 67:f7:45:8e:97:cc:14:39:e2:36:85:b5:7e:1a:37: # fd:16:f6:71:11:9a:74:30:16:fe:13:94:a3:3f:84: # 0d:4f # Exponent: 65537 (0x10001) # X509v3 extensions: # X509v3 Subject Key Identifier: # FD:AC:61:32:93:6C:45:D6:E2:EE:85:5F:9A:BA:E7:76:99:68:CC:E7 # X509v3 Authority Key Identifier: # keyid:D2:C4:B0:D2:91:D4:4C:11:71:B3:61:CB:3D:A1:FE:DD:A8:6A:D4:E3 # # X509v3 Basic Constraints: critical # CA:TRUE, pathlen:0 # Authority Information Access: # OCSP - URI:http://ocsp.godaddy.com # # X509v3 CRL Distribution Points: # # Full Name: # URI:http://certificates.godaddy.com/repository/gdroot.crl # # X509v3 Certificate Policies: # Policy: X509v3 Any Policy # CPS: http://certificates.godaddy.com/repository # # X509v3 Key Usage: critical # Certificate Sign, CRL Sign # Signature Algorithm: sha1WithRSAEncryption # d2:86:c0:ec:bd:f9:a1:b6:67:ee:66:0b:a2:06:3a:04:50:8e: # 15:72:ac:4a:74:95:53:cb:37:cb:44:49:ef:07:90:6b:33:d9: # 96:f0:94:56:a5:13:30:05:3c:85:32:21:7b:c9:c7:0a:a8:24: # a4:90:de:46:d3:25:23:14:03:67:c2:10:d6:6f:0f:5d:7b:7a: # cc:9f:c5:58:2a:c1:c4:9e:21:a8:5a:f3:ac:a4:46:f3:9e:e4: # 63:cb:2f:90:a4:29:29:01:d9:72:2c:29:df:37:01:27:bc:4f: # ee:68:d3:21:8f:c0:b3:e4:f5:09:ed:d2:10:aa:53:b4:be:f0: # cc:59:0b:d6:3b:96:1c:95:24:49:df:ce:ec:fd:a7:48:91:14: # 45:0e:3a:36:6f:da:45:b3:45:a2:41:c9:d4:d7:44:4e:3e:b9: # 74:76:d5:a2:13:55:2c:c6:87:a3:b5:99:ac:06:84:87:7f:75: # 06:fc:bf:14:4c:0e:cc:6e:c4:df:3d:b7:12:71:f4:e8:f1:51: # 40:22:28:49:e0:1d:4b:87:a8:34:cc:06:a2:dd:12:5a:d1:86: # 36:64:03:35:6f:6f:77:6e:eb:f2:85:50:98:5e:ab:03:53:ad: # 91:23:63:1f:16:9c:cd:b9:b2:05:63:3a:e1:f4:68:1b:17:05: # 35:95:53:ee -----BEGIN CERTIFICATE----- MIIE3jCCA8agAwIBAgICAwEwDQYJKoZIhvcNAQEFBQAwYzELMAkGA1UEBhMCVVMx ITAfBgNVBAoTGFRoZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28g RGFkZHkgQ2xhc3MgMiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjExMTYw MTU0MzdaFw0yNjExMTYwMTU0MzdaMIHKMQswCQYDVQQGEwJVUzEQMA4GA1UECBMH QXJpem9uYTETMBEGA1UEBxMKU2NvdHRzZGFsZTEaMBgGA1UEChMRR29EYWRkeS5j b20sIEluYy4xMzAxBgNVBAsTKmh0dHA6Ly9jZXJ0aWZpY2F0ZXMuZ29kYWRkeS5j b20vcmVwb3NpdG9yeTEwMC4GA1UEAxMnR28gRGFkZHkgU2VjdXJlIENlcnRpZmlj YXRpb24gQXV0aG9yaXR5MREwDwYDVQQFEwgwNzk2OTI4NzCCASIwDQYJKoZIhvcN AQEBBQADggEPADCCAQoCggEBAMQt1RWMnCZM7DI161+4WQFapmGBWTtwY6vj3D3H KrjJM9N55DrtPDAjhI6zMBS2sofDPZVUBJ7fmd0LJR4h3mUpfjWoqVTr9vcyOdQm VZWt7/v+WIbXnvQAjYwqDL1CBM6nPwT27oDyqu9SoWlm2r4arV3aLGbqGmu75RpR SgAvSMeYddi5Kcju+GZtCpyz8/x4fKL4o/K1w/O5epHBp+YlLpyo7RJlbmr2EkRT cDCVw5wrWCs9CHRK8r5RsL+H0EwnWGu1NcWdrxcx+AuP7q2BNgWJCJjPOq8lh8BJ 6qf9Z/dFjpfMFDniNoW1fho3/Rb2cRGadDAW/hOUoz+EDU8CAwEAAaOCATIwggEu MB0GA1UdDgQWBBT9rGEyk2xF1uLuhV+auud2mWjM5zAfBgNVHSMEGDAWgBTSxLDS kdRMEXGzYcs9of7dqGrU4zASBgNVHRMBAf8ECDAGAQH/AgEAMDMGCCsGAQUFBwEB BCcwJTAjBggrBgEFBQcwAYYXaHR0cDovL29jc3AuZ29kYWRkeS5jb20wRgYDVR0f BD8wPTA7oDmgN4Y1aHR0cDovL2NlcnRpZmljYXRlcy5nb2RhZGR5LmNvbS9yZXBv c2l0b3J5L2dkcm9vdC5jcmwwSwYDVR0gBEQwQjBABgRVHSAAMDgwNgYIKwYBBQUH AgEWKmh0dHA6Ly9jZXJ0aWZpY2F0ZXMuZ29kYWRkeS5jb20vcmVwb3NpdG9yeTAO BgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQEFBQADggEBANKGwOy9+aG2Z+5mC6IG OgRQjhVyrEp0lVPLN8tESe8HkGsz2ZbwlFalEzAFPIUyIXvJxwqoJKSQ3kbTJSMU A2fCENZvD117esyfxVgqwcSeIaha86ykRvOe5GPLL5CkKSkB2XIsKd83ASe8T+5o 0yGPwLPk9Qnt0hCqU7S+8MxZC9Y7lhyVJEnfzuz9p0iRFEUOOjZv2kWzRaJBydTX RE4+uXR21aITVSzGh6O1mawGhId/dQb8vxRMDsxuxN89txJx9OjxUUAiKEngHUuH qDTMBqLdElrRhjZkAzVvb3du6/KFUJheqwNTrZEjYx8WnM25sgVjOuH0aBsXBTWV U+4= -----END CERTIFICATE----- # Thawte Premium Server CA.pem # Certificate: # Data: # Version: 3 (0x2) # Serial Number: 1 (0x1) # Signature Algorithm: md5WithRSAEncryption # Issuer: C=ZA, ST=Western Cape, L=Cape Town, O=Thawte Consulting cc, OU=Certification Services Division, CN=Thawte Premium Server CA/emailAddress=premium-server@thawte.com # Validity # Not Before: Aug 1 00:00:00 1996 GMT # Not After : Dec 31 23:59:59 2020 GMT # Subject: C=ZA, ST=Western Cape, L=Cape Town, O=Thawte Consulting cc, OU=Certification Services Division, CN=Thawte Premium Server CA/emailAddress=premium-server@thawte.com # Subject Public Key Info: # Public Key Algorithm: rsaEncryption # Public-Key: (1024 bit) # Modulus: # 00:d2:36:36:6a:8b:d7:c2:5b:9e:da:81:41:62:8f: # 38:ee:49:04:55:d6:d0:ef:1c:1b:95:16:47:ef:18: # 48:35:3a:52:f4:2b:6a:06:8f:3b:2f:ea:56:e3:af: # 86:8d:9e:17:f7:9e:b4:65:75:02:4d:ef:cb:09:a2: # 21:51:d8:9b:d0:67:d0:ba:0d:92:06:14:73:d4:93: # cb:97:2a:00:9c:5c:4e:0c:bc:fa:15:52:fc:f2:44: # 6e:da:11:4a:6e:08:9f:2f:2d:e3:f9:aa:3a:86:73: # b6:46:53:58:c8:89:05:bd:83:11:b8:73:3f:aa:07: # 8d:f4:42:4d:e7:40:9d:1c:37 # Exponent: 65537 (0x10001) # X509v3 extensions: # X509v3 Basic Constraints: critical # CA:TRUE # Signature Algorithm: md5WithRSAEncryption # 26:48:2c:16:c2:58:fa:e8:16:74:0c:aa:aa:5f:54:3f:f2:d7: # c9:78:60:5e:5e:6e:37:63:22:77:36:7e:b2:17:c4:34:b9:f5: # 08:85:fc:c9:01:38:ff:4d:be:f2:16:42:43:e7:bb:5a:46:fb: # c1:c6:11:1f:f1:4a:b0:28:46:c9:c3:c4:42:7d:bc:fa:ab:59: # 6e:d5:b7:51:88:11:e3:a4:85:19:6b:82:4c:a4:0c:12:ad:e9: # a4:ae:3f:f1:c3:49:65:9a:8c:c5:c8:3e:25:b7:94:99:bb:92: # 32:71:07:f0:86:5e:ed:50:27:a6:0d:a6:23:f9:bb:cb:a6:07: # 14:42 -----BEGIN CERTIFICATE----- MIIDJzCCApCgAwIBAgIBATANBgkqhkiG9w0BAQQFADCBzjELMAkGA1UEBhMCWkEx FTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYD VQQKExRUaGF3dGUgQ29uc3VsdGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlv biBTZXJ2aWNlcyBEaXZpc2lvbjEhMB8GA1UEAxMYVGhhd3RlIFByZW1pdW0gU2Vy dmVyIENBMSgwJgYJKoZIhvcNAQkBFhlwcmVtaXVtLXNlcnZlckB0aGF3dGUuY29t MB4XDTk2MDgwMTAwMDAwMFoXDTIwMTIzMTIzNTk1OVowgc4xCzAJBgNVBAYTAlpB MRUwEwYDVQQIEwxXZXN0ZXJuIENhcGUxEjAQBgNVBAcTCUNhcGUgVG93bjEdMBsG A1UEChMUVGhhd3RlIENvbnN1bHRpbmcgY2MxKDAmBgNVBAsTH0NlcnRpZmljYXRp b24gU2VydmljZXMgRGl2aXNpb24xITAfBgNVBAMTGFRoYXd0ZSBQcmVtaXVtIFNl cnZlciBDQTEoMCYGCSqGSIb3DQEJARYZcHJlbWl1bS1zZXJ2ZXJAdGhhd3RlLmNv bTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0jY2aovXwlue2oFBYo847kkE VdbQ7xwblRZH7xhINTpS9CtqBo87L+pW46+GjZ4X9560ZXUCTe/LCaIhUdib0GfQ ug2SBhRz1JPLlyoAnFxODLz6FVL88kRu2hFKbgifLy3j+ao6hnO2RlNYyIkFvYMR uHM/qgeN9EJN50CdHDcCAwEAAaMTMBEwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG 9w0BAQQFAAOBgQAmSCwWwlj66BZ0DKqqX1Q/8tfJeGBeXm43YyJ3Nn6yF8Q0ufUI hfzJATj/Tb7yFkJD57taRvvBxhEf8UqwKEbJw8RCfbz6q1lu1bdRiBHjpIUZa4JM pAwSremkrj/xw0llmozFyD4lt5SZu5IycQfwhl7tUCemDaYj+bvLpgcUQg== -----END CERTIFICATE----- # Thawte Primary Root CA - G2.pem # Certificate: # Data: # Version: 3 (0x2) # Serial Number: # 35:fc:26:5c:d9:84:4f:c9:3d:26:3d:57:9b:ae:d7:56 # Signature Algorithm: ecdsa-with-SHA384 # Issuer: C=US, O=thawte, Inc., OU=(c) 2007 thawte, Inc. - For authorized use only, CN=thawte Primary Root CA - G2 # Validity # Not Before: Nov 5 00:00:00 2007 GMT # Not After : Jan 18 23:59:59 2038 GMT # Subject: C=US, O=thawte, Inc., OU=(c) 2007 thawte, Inc. - For authorized use only, CN=thawte Primary Root CA - G2 # Subject Public Key Info: # Public Key Algorithm: id-ecPublicKey # Public-Key: (384 bit) # pub: # 04:a2:d5:9c:82:7b:95:9d:f1:52:78:87:fe:8a:16: # bf:05:e6:df:a3:02:4f:0d:07:c6:00:51:ba:0c:02: # 52:2d:22:a4:42:39:c4:fe:8f:ea:c9:c1:be:d4:4d: # ff:9f:7a:9e:e2:b1:7c:9a:ad:a7:86:09:73:87:d1: # e7:9a:e3:7a:a5:aa:6e:fb:ba:b3:70:c0:67:88:a2: # 35:d4:a3:9a:b1:fd:ad:c2:ef:31:fa:a8:b9:f3:fb: # 08:c6:91:d1:fb:29:95 # ASN1 OID: secp384r1 # X509v3 extensions: # X509v3 Basic Constraints: critical # CA:TRUE # X509v3 Key Usage: critical # Certificate Sign, CRL Sign # X509v3 Subject Key Identifier: # 9A:D8:00:30:00:E7:6B:7F:85:18:EE:8B:B6:CE:8A:0C:F8:11:E1:BB # Signature Algorithm: ecdsa-with-SHA384 # 30:66:02:31:00:dd:f8:e0:57:47:5b:a7:e6:0a:c3:bd:f5:80: # 8a:97:35:0d:1b:89:3c:54:86:77:28:ca:a1:f4:79:de:b5:e6: # 38:b0:f0:65:70:8c:7f:02:54:c2:bf:ff:d8:a1:3e:d9:cf:02: # 31:00:c4:8d:94:fc:dc:53:d2:dc:9d:78:16:1f:15:33:23:53: # 52:e3:5a:31:5d:9d:ca:ae:bd:13:29:44:0d:27:5b:a8:e7:68: # 9c:12:f7:58:3f:2e:72:02:57:a3:8f:a1:14:2e -----BEGIN CERTIFICATE----- MIICiDCCAg2gAwIBAgIQNfwmXNmET8k9Jj1Xm67XVjAKBggqhkjOPQQDAzCBhDEL MAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjE4MDYGA1UECxMvKGMp IDIwMDcgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxJDAi BgNVBAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EgLSBHMjAeFw0wNzExMDUwMDAw MDBaFw0zODAxMTgyMzU5NTlaMIGEMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhh d3RlLCBJbmMuMTgwNgYDVQQLEy8oYykgMjAwNyB0aGF3dGUsIEluYy4gLSBGb3Ig YXV0aG9yaXplZCB1c2Ugb25seTEkMCIGA1UEAxMbdGhhd3RlIFByaW1hcnkgUm9v dCBDQSAtIEcyMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEotWcgnuVnfFSeIf+iha/ BebfowJPDQfGAFG6DAJSLSKkQjnE/o/qycG+1E3/n3qe4rF8mq2nhglzh9HnmuN6 papu+7qzcMBniKI11KOasf2twu8x+qi58/sIxpHR+ymVo0IwQDAPBgNVHRMBAf8E BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUmtgAMADna3+FGO6Lts6K DPgR4bswCgYIKoZIzj0EAwMDaQAwZgIxAN344FdHW6fmCsO99YCKlzUNG4k8VIZ3 KMqh9HneteY4sPBlcIx/AlTCv//YoT7ZzwIxAMSNlPzcU9LcnXgWHxUzI1NS41ox XZ3Krr0TKUQNJ1uo52icEvdYPy5yAlejj6EULg== -----END CERTIFICATE----- # Thawte Primary Root CA - G3.pem # Certificate: # Data: # Version: 3 (0x2) # Serial Number: # 60:01:97:b7:46:a7:ea:b4:b4:9a:d6:4b:2f:f7:90:fb # Signature Algorithm: sha256WithRSAEncryption # Issuer: C=US, O=thawte, Inc., OU=Certification Services Division, OU=(c) 2008 thawte, Inc. - For authorized use only, CN=thawte Primary Root CA - G3 # Validity # Not Before: Apr 2 00:00:00 2008 GMT # Not After : Dec 1 23:59:59 2037 GMT # Subject: C=US, O=thawte, Inc., OU=Certification Services Division, OU=(c) 2008 thawte, Inc. - For authorized use only, CN=thawte Primary Root CA - G3 # Subject Public Key Info: # Public Key Algorithm: rsaEncryption # Public-Key: (2048 bit) # Modulus: # 00:b2:bf:27:2c:fb:db:d8:5b:dd:78:7b:1b:9e:77: # 66:81:cb:3e:bc:7c:ae:f3:a6:27:9a:34:a3:68:31: # 71:38:33:62:e4:f3:71:66:79:b1:a9:65:a3:a5:8b: # d5:8f:60:2d:3f:42:cc:aa:6b:32:c0:23:cb:2c:41: # dd:e4:df:fc:61:9c:e2:73:b2:22:95:11:43:18:5f: # c4:b6:1f:57:6c:0a:05:58:22:c8:36:4c:3a:7c:a5: # d1:cf:86:af:88:a7:44:02:13:74:71:73:0a:42:59: # 02:f8:1b:14:6b:42:df:6f:5f:ba:6b:82:a2:9d:5b: # e7:4a:bd:1e:01:72:db:4b:74:e8:3b:7f:7f:7d:1f: # 04:b4:26:9b:e0:b4:5a:ac:47:3d:55:b8:d7:b0:26: # 52:28:01:31:40:66:d8:d9:24:bd:f6:2a:d8:ec:21: # 49:5c:9b:f6:7a:e9:7f:55:35:7e:96:6b:8d:93:93: # 27:cb:92:bb:ea:ac:40:c0:9f:c2:f8:80:cf:5d:f4: # 5a:dc:ce:74:86:a6:3e:6c:0b:53:ca:bd:92:ce:19: # 06:72:e6:0c:5c:38:69:c7:04:d6:bc:6c:ce:5b:f6: # f7:68:9c:dc:25:15:48:88:a1:e9:a9:f8:98:9c:e0: # f3:d5:31:28:61:11:6c:67:96:8d:39:99:cb:c2:45: # 24:39 # Exponent: 65537 (0x10001) # X509v3 extensions: # X509v3 Basic Constraints: critical # CA:TRUE # X509v3 Key Usage: critical # Certificate Sign, CRL Sign # X509v3 Subject Key Identifier: # AD:6C:AA:94:60:9C:ED:E4:FF:FA:3E:0A:74:2B:63:03:F7:B6:59:BF # Signature Algorithm: sha256WithRSAEncryption # 1a:40:d8:95:65:ac:09:92:89:c6:39:f4:10:e5:a9:0e:66:53: # 5d:78:de:fa:24:91:bb:e7:44:51:df:c6:16:34:0a:ef:6a:44: # 51:ea:2b:07:8a:03:7a:c3:eb:3f:0a:2c:52:16:a0:2b:43:b9: # 25:90:3f:70:a9:33:25:6d:45:1a:28:3b:27:cf:aa:c3:29:42: # 1b:df:3b:4c:c0:33:34:5b:41:88:bf:6b:2b:65:af:28:ef:b2: # f5:c3:aa:66:ce:7b:56:ee:b7:c8:cb:67:c1:c9:9c:1a:18:b8: # c4:c3:49:03:f1:60:0e:50:cd:46:c5:f3:77:79:f7:b6:15:e0: # 38:db:c7:2f:28:a0:0c:3f:77:26:74:d9:25:12:da:31:da:1a: # 1e:dc:29:41:91:22:3c:69:a7:bb:02:f2:b6:5c:27:03:89:f4: # 06:ea:9b:e4:72:82:e3:a1:09:c1:e9:00:19:d3:3e:d4:70:6b: # ba:71:a6:aa:58:ae:f4:bb:e9:6c:b6:ef:87:cc:9b:bb:ff:39: # e6:56:61:d3:0a:a7:c4:5c:4c:60:7b:05:77:26:7a:bf:d8:07: # 52:2c:62:f7:70:63:d9:39:bc:6f:1c:c2:79:dc:76:29:af:ce: # c5:2c:64:04:5e:88:36:6e:31:d4:40:1a:62:34:36:3f:35:01: # ae:ac:63:a0 -----BEGIN CERTIFICATE----- MIIEKjCCAxKgAwIBAgIQYAGXt0an6rS0mtZLL/eQ+zANBgkqhkiG9w0BAQsFADCB rjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMf Q2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIw MDggdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxJDAiBgNV BAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EgLSBHMzAeFw0wODA0MDIwMDAwMDBa Fw0zNzEyMDEyMzU5NTlaMIGuMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhhd3Rl LCBJbmMuMSgwJgYDVQQLEx9DZXJ0aWZpY2F0aW9uIFNlcnZpY2VzIERpdmlzaW9u MTgwNgYDVQQLEy8oYykgMjAwOCB0aGF3dGUsIEluYy4gLSBGb3IgYXV0aG9yaXpl ZCB1c2Ugb25seTEkMCIGA1UEAxMbdGhhd3RlIFByaW1hcnkgUm9vdCBDQSAtIEcz MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsr8nLPvb2FvdeHsbnndm gcs+vHyu86YnmjSjaDFxODNi5PNxZnmxqWWjpYvVj2AtP0LMqmsywCPLLEHd5N/8 YZzic7IilRFDGF/Eth9XbAoFWCLINkw6fKXRz4aviKdEAhN0cXMKQlkC+BsUa0Lf b1+6a4KinVvnSr0eAXLbS3ToO39/fR8EtCab4LRarEc9VbjXsCZSKAExQGbY2SS9 9irY7CFJXJv2eul/VTV+lmuNk5Mny5K76qxAwJ/C+IDPXfRa3M50hqY+bAtTyr2S zhkGcuYMXDhpxwTWvGzOW/b3aJzcJRVIiKHpqfiYnODz1TEoYRFsZ5aNOZnLwkUk OQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNV HQ4EFgQUrWyqlGCc7eT/+j4KdCtjA/e2Wb8wDQYJKoZIhvcNAQELBQADggEBABpA 2JVlrAmSicY59BDlqQ5mU1143vokkbvnRFHfxhY0Cu9qRFHqKweKA3rD6z8KLFIW oCtDuSWQP3CpMyVtRRooOyfPqsMpQhvfO0zAMzRbQYi/aytlryjvsvXDqmbOe1bu t8jLZ8HJnBoYuMTDSQPxYA5QzUbF83d597YV4Djbxy8ooAw/dyZ02SUS2jHaGh7c KUGRIjxpp7sC8rZcJwOJ9Abqm+RyguOhCcHpABnTPtRwa7pxpqpYrvS76Wy274fM m7v/OeZWYdMKp8RcTGB7BXcmer/YB1IsYvdwY9k5vG8cwnncdimvzsUsZAReiDZu MdRAGmI0Nj81Aa6sY6A= -----END CERTIFICATE----- # Thawte Primary Root CA.pem # Certificate: # Data: # Version: 3 (0x2) # Serial Number: # 34:4e:d5:57:20:d5:ed:ec:49:f4:2f:ce:37:db:2b:6d # Signature Algorithm: sha1WithRSAEncryption # Issuer: C=US, O=thawte, Inc., OU=Certification Services Division, OU=(c) 2006 thawte, Inc. - For authorized use only, CN=thawte Primary Root CA # Validity # Not Before: Nov 17 00:00:00 2006 GMT # Not After : Jul 16 23:59:59 2036 GMT # Subject: C=US, O=thawte, Inc., OU=Certification Services Division, OU=(c) 2006 thawte, Inc. - For authorized use only, CN=thawte Primary Root CA # Subject Public Key Info: # Public Key Algorithm: rsaEncryption # Public-Key: (2048 bit) # Modulus: # 00:ac:a0:f0:fb:80:59:d4:9c:c7:a4:cf:9d:a1:59: # 73:09:10:45:0c:0d:2c:6e:68:f1:6c:5b:48:68:49: # 59:37:fc:0b:33:19:c2:77:7f:cc:10:2d:95:34:1c: # e6:eb:4d:09:a7:1c:d2:b8:c9:97:36:02:b7:89:d4: # 24:5f:06:c0:cc:44:94:94:8d:02:62:6f:eb:5a:dd: # 11:8d:28:9a:5c:84:90:10:7a:0d:bd:74:66:2f:6a: # 38:a0:e2:d5:54:44:eb:1d:07:9f:07:ba:6f:ee:e9: # fd:4e:0b:29:f5:3e:84:a0:01:f1:9c:ab:f8:1c:7e: # 89:a4:e8:a1:d8:71:65:0d:a3:51:7b:ee:bc:d2:22: # 60:0d:b9:5b:9d:df:ba:fc:51:5b:0b:af:98:b2:e9: # 2e:e9:04:e8:62:87:de:2b:c8:d7:4e:c1:4c:64:1e: # dd:cf:87:58:ba:4a:4f:ca:68:07:1d:1c:9d:4a:c6: # d5:2f:91:cc:7c:71:72:1c:c5:c0:67:eb:32:fd:c9: # 92:5c:94:da:85:c0:9b:bf:53:7d:2b:09:f4:8c:9d: # 91:1f:97:6a:52:cb:de:09:36:a4:77:d8:7b:87:50: # 44:d5:3e:6e:29:69:fb:39:49:26:1e:09:a5:80:7b: # 40:2d:eb:e8:27:85:c9:fe:61:fd:7e:e6:7c:97:1d: # d5:9d # Exponent: 65537 (0x10001) # X509v3 extensions: # X509v3 Basic Constraints: critical # CA:TRUE # X509v3 Key Usage: critical # Certificate Sign, CRL Sign # X509v3 Subject Key Identifier: # 7B:5B:45:CF:AF:CE:CB:7A:FD:31:92:1A:6A:B6:F3:46:EB:57:48:50 # Signature Algorithm: sha1WithRSAEncryption # 79:11:c0:4b:b3:91:b6:fc:f0:e9:67:d4:0d:6e:45:be:55:e8: # 93:d2:ce:03:3f:ed:da:25:b0:1d:57:cb:1e:3a:76:a0:4c:ec: # 50:76:e8:64:72:0c:a4:a9:f1:b8:8b:d6:d6:87:84:bb:32:e5: # 41:11:c0:77:d9:b3:60:9d:eb:1b:d5:d1:6e:44:44:a9:a6:01: # ec:55:62:1d:77:b8:5c:8e:48:49:7c:9c:3b:57:11:ac:ad:73: # 37:8e:2f:78:5c:90:68:47:d9:60:60:e6:fc:07:3d:22:20:17: # c4:f7:16:e9:c4:d8:72:f9:c8:73:7c:df:16:2f:15:a9:3e:fd: # 6a:27:b6:a1:eb:5a:ba:98:1f:d5:e3:4d:64:0a:9d:13:c8:61: # ba:f5:39:1c:87:ba:b8:bd:7b:22:7f:f6:fe:ac:40:79:e5:ac: # 10:6f:3d:8f:1b:79:76:8b:c4:37:b3:21:18:84:e5:36:00:eb: # 63:20:99:b9:e9:fe:33:04:bb:41:c8:c1:02:f9:44:63:20:9e: # 81:ce:42:d3:d6:3f:2c:76:d3:63:9c:59:dd:8f:a6:e1:0e:a0: # 2e:41:f7:2e:95:47:cf:bc:fd:33:f3:f6:0b:61:7e:7e:91:2b: # 81:47:c2:27:30:ee:a7:10:5d:37:8f:5c:39:2b:e4:04:f0:7b: # 8d:56:8c:68 -----BEGIN CERTIFICATE----- MIIEIDCCAwigAwIBAgIQNE7VVyDV7exJ9C/ON9srbTANBgkqhkiG9w0BAQUFADCB qTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMf Q2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIw MDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxHzAdBgNV BAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwHhcNMDYxMTE3MDAwMDAwWhcNMzYw NzE2MjM1OTU5WjCBqTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5j LjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYG A1UECxMvKGMpIDIwMDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl IG9ubHkxHzAdBgNVBAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwggEiMA0GCSqG SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCsoPD7gFnUnMekz52hWXMJEEUMDSxuaPFs W0hoSVk3/AszGcJ3f8wQLZU0HObrTQmnHNK4yZc2AreJ1CRfBsDMRJSUjQJib+ta 3RGNKJpchJAQeg29dGYvajig4tVUROsdB58Hum/u6f1OCyn1PoSgAfGcq/gcfomk 6KHYcWUNo1F77rzSImANuVud37r8UVsLr5iy6S7pBOhih94ryNdOwUxkHt3Ph1i6 Sk/KaAcdHJ1KxtUvkcx8cXIcxcBn6zL9yZJclNqFwJu/U30rCfSMnZEfl2pSy94J NqR32HuHUETVPm4pafs5SSYeCaWAe0At6+gnhcn+Yf1+5nyXHdWdAgMBAAGjQjBA MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBR7W0XP r87Lev0xkhpqtvNG61dIUDANBgkqhkiG9w0BAQUFAAOCAQEAeRHAS7ORtvzw6WfU DW5FvlXok9LOAz/t2iWwHVfLHjp2oEzsUHboZHIMpKnxuIvW1oeEuzLlQRHAd9mz YJ3rG9XRbkREqaYB7FViHXe4XI5ISXycO1cRrK1zN44veFyQaEfZYGDm/Ac9IiAX xPcW6cTYcvnIc3zfFi8VqT79aie2oetaupgf1eNNZAqdE8hhuvU5HIe6uL17In/2 /qxAeeWsEG89jxt5dovEN7MhGITlNgDrYyCZuen+MwS7QcjBAvlEYyCegc5C09Y/ LHbTY5xZ3Y+m4Q6gLkH3LpVHz7z9M/P2C2F+fpErgUfCJzDupxBdN49cOSvkBPB7 jVaMaA== -----END CERTIFICATE-----accessToken; } /** @var AccessToken */ private $accessToken; /** * An identifier for the API client, typically of the form "Name/Version". * This is used to set the HTTP User-Agent header when making API requests. * Example: "PhotoEditServer/1.3" * * If you're the author a higher-level library on top of the basic SDK, and the * "Photo Edit" app's server code is using your library to access Dropbox, you should append * your library's name and version to form the full identifier. For example, * if your library is called "File Picker", you might set this field to: * "PhotoEditServer/1.3 FilePicker/0.1-beta" * * The exact format of the User-Agent header is described in * section 3.8 of the HTTP specification. * * Note that underlying HTTP client may append other things to the User-Agent, such as * the name of the library being used to actually make the HTTP request (such as cURL). * * @return string */ function getClientIdentifier() { return $this->clientIdentifier; } /** @var string */ private $clientIdentifier; /** * The locale of the user of your application. Some API calls return localized * data and error messages; this "user locale" setting determines which locale * the server should use to localize those strings. * * @return null|string */ function getUserLocale() { return $this->userLocale; } /** @var null|string */ private $userLocale; /** * The {@link Host} object that determines the hostnames we make requests to. * * @return Host */ function getHost() { return $this->host; } /** * Constructor. * * @param string $accessToken * See {@link getAccessToken()} * @param string $clientIdentifier * See {@link getClientIdentifier()} * @param null|string $userLocale * See {@link getUserLocale()} */ function __construct($accessToken, $clientIdentifier, $userLocale = null) { self::checkAccessTokenArg("accessToken", $accessToken); self::checkClientIdentifierArg("clientIdentifier", $clientIdentifier); Checker::argStringNonEmptyOrNull("userLocale", $userLocale); $this->accessToken = $accessToken; $this->clientIdentifier = $clientIdentifier; $this->userLocale = $userLocale; // The $host parameter is sort of internal. We don't include it in the param list because // we don't want it to be included in the documentation. Use PHP arg list hacks to get at // it. $host = null; if (\func_num_args() == 4) { $host = \func_get_arg(3); Host::checkArgOrNull("host", $host); } if ($host === null) { $host = Host::getDefault(); } $this->host = $host; // These fields are redundant, but it makes these values a little more convenient // to access. $this->apiHost = $host->getApi(); $this->contentHost = $host->getContent(); } /** @var string */ private $apiHost; /** @var string */ private $contentHost; /** * Given a $base path for an API endpoint (for example, "/files"), append * a Dropbox API file path to the end of that URL. Special characters in the file will * be encoded properly. * * This is for endpoints like "/files" takes the path on the URL and not as a separate * query or POST parameter. * * @param string $base * @param string $path * @return string */ function appendFilePath($base, $path) { return $base . "/auto/" . rawurlencode(substr($path, 1)); } /** * Make an API call to disable the access token that you constructed this Client * with. After calling this, API calls made with this Client will fail. * * See /disable_access_token. * * @throws Exception */ function disableAccessToken() { $response = $this->doPost($this->apiHost, "1/disable_access_token"); if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); } /** * Make an API call to get basic account and quota information. * * * $client = ... * $accountInfo = $client->getAccountInfo(); * print_r($accountInfo); * * * @return array * See /account/info. * * @throws Exception */ function getAccountInfo() { $response = $this->doGet($this->apiHost, "1/account/info"); if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); return RequestUtil::parseResponseJson($response->body); } /** * Downloads a file from Dropbox. The file's contents are written to the * given $outStream and the file's metadata is returned. * * * $client = ...; * $fd = fopen("./Frog.jpeg", "wb"); * $metadata = $client->getFile("/Photos/Frog.jpeg", $fd); * fclose($fd); * print_r($metadata); * * * @param string $path * The path to the file on Dropbox (UTF-8). * * @param resource $outStream * If the file exists, the file contents will be written to this stream. * * @param string|null $rev * If you want the latest revision of the file at the given path, pass in null. * If you want a specific version of a file, pass in value of the file metadata's "rev" field. * * @return null|array * The metadata * object for the file at the given $path and $rev, or null if the file * doesn't exist, * * @throws Exception */ function getFile($path, $outStream, $rev = null) { Path::checkArgNonRoot("path", $path); Checker::argResource("outStream", $outStream); Checker::argStringNonEmptyOrNull("rev", $rev); $url = $this->buildUrlForGetOrPut( $this->contentHost, $this->appendFilePath("1/files", $path), array("rev" => $rev)); $curl = $this->mkCurl($url); $metadataCatcher = new DropboxMetadataHeaderCatcher($curl->handle); $streamRelay = new CurlStreamRelay($curl->handle, $outStream); $response = $curl->exec(); if ($response->statusCode === 404) return null; if ($response->statusCode !== 200) { $response->body = $streamRelay->getErrorBody(); throw RequestUtil::unexpectedStatus($response); } return $metadataCatcher->getMetadata(); } /** * Calling 'uploadFile' with $numBytes less than this value, will cause this SDK * to use the standard /files_put endpoint. When $numBytes is greater than this * value, we'll use the /chunked_upload endpoint. * * @var int */ private static $AUTO_CHUNKED_UPLOAD_THRESHOLD = 9863168; // 8 MB /** * @var int */ private static $DEFAULT_CHUNK_SIZE = 4194304; // 4 MB /** * Creates a file on Dropbox, using the data from $inStream for the file contents. * * * use \Dropbox as dbx; * $client = ...; * $fd = fopen("./frog.jpeg", "rb"); * $md1 = $client->uploadFile("/Photos/Frog.jpeg", * dbx\WriteMode::add(), $fd); * fclose($fd); * print_r($md1); * $rev = $md1["rev"]; * * // Re-upload with WriteMode::update(...), which will overwrite the * // file if it hasn't been modified from our original upload. * $fd = fopen("./frog-new.jpeg", "rb"); * $md2 = $client->uploadFile("/Photos/Frog.jpeg", * dbx\WriteMode::update($rev), $fd); * fclose($fd); * print_r($md2); * * * @param string $path * The Dropbox path to save the file to (UTF-8). * * @param WriteMode $writeMode * What to do if there's already a file at the given path. * * @param resource $inStream * The data to use for the file contents. * * @param int|null $numBytes * You can pass in null if you don't know. If you do provide the size, we can * perform a slightly more efficient upload (fewer network round-trips) for files smaller * than 8 MB. * * @return mixed * The self::$AUTO_CHUNKED_UPLOAD_THRESHOLD) { $metadata = $this->_uploadFileChunked($path, $writeMode, $inStream, $numBytes, self::$DEFAULT_CHUNK_SIZE); } else { $metadata = $this->_uploadFile($path, $writeMode, function(Curl $curl) use ($inStream, $numBytes) { $curl->set(CURLOPT_PUT, true); $curl->set(CURLOPT_INFILE, $inStream); $curl->set(CURLOPT_INFILESIZE, $numBytes); }); } return $metadata; } /** * Creates a file on Dropbox, using the given $data string as the file contents. * * * use \Dropbox as dbx; * $client = ...; * $md = $client->uploadFileFromString("/Grocery List.txt", * dbx\WriteMode::add(), * "1. Coke\n2. Popcorn\n3. Toothpaste\n"); * print_r($md); * * * @param string $path * The Dropbox path to save the file to (UTF-8). * * @param WriteMode $writeMode * What to do if there's already a file at the given path. * * @param string $data * The data to use for the contents of the file. * * @return mixed * The _uploadFile($path, $writeMode, function(Curl $curl) use ($data) { $curl->set(CURLOPT_CUSTOMREQUEST, "PUT"); $curl->set(CURLOPT_POSTFIELDS, $data); $curl->addHeader("Content-Type: application/octet-stream"); }); } /** * Creates a file on Dropbox, using the data from $inStream as the file contents. * * This version of uploadFile splits uploads the file ~4MB chunks at a time and * will retry a few times if one chunk fails to upload. Uses {@link chunkedUploadStart()}, * {@link chunkedUploadContinue()}, and {@link chunkedUploadFinish()}. * * @param string $path * The Dropbox path to save the file to (UTF-8). * * @param WriteMode $writeMode * What to do if there's already a file at the given path. * * @param resource $inStream * The data to use for the file contents. * * @param int|null $numBytes * The number of bytes available from $inStream. * You can pass in null if you don't know. * * @param int|null $chunkSize * The number of bytes to upload in each chunk. You can omit this (or pass in * null and the library will use a reasonable default. * * @return mixed * The _uploadFileChunked($path, $writeMode, $inStream, $numBytes, $chunkSize); } /** * @param string $path * * @param WriteMode $writeMode * What to do if there's already a file at the given path (UTF-8). * * @param resource $inStream * The source of data to upload. * * @param int|null $numBytes * You can pass in null. But if you know how many bytes you expect, pass in * that value and this function will do a sanity check at the end to make sure the number of * bytes read from $inStream matches up. * * @param int $chunkSize * * @return array * The 0); $data = self::readFully($inStream, $chunkSize); $len = strlen($data); $client = $this; $uploadId = RequestUtil::runWithRetry(3, function() use ($data, $client) { return $client->chunkedUploadStart($data); }); $byteOffset = $len; while (!feof($inStream)) { $data = self::readFully($inStream, $chunkSize); $len = strlen($data); while (true) { $r = RequestUtil::runWithRetry(3, function() use ($client, $uploadId, $byteOffset, $data) { return $client->chunkedUploadContinue($uploadId, $byteOffset, $data); }); if ($r === true) { // Chunk got uploaded! $byteOffset += $len; break; } if ($r === false) { // Server didn't recognize our upload ID // This is very unlikely since we're uploading all the chunks in sequence. throw new Exception_BadResponse("Server forgot our uploadId"); } // Otherwise, the server is at a different byte offset from us. $serverByteOffset = $r; assert($serverByteOffset !== $byteOffset); // chunkedUploadContinue ensures this. // An earlier byte offset means the server has lost data we sent earlier. if ($serverByteOffset < $byteOffset) throw new Exception_BadResponse( "Server is at an ealier byte offset: us=$byteOffset, server=$serverByteOffset"); $diff = $serverByteOffset - $byteOffset; // If the server is past where we think it could possibly be, something went wrong. if ($diff > $len) throw new Exception_BadResponse( "Server is more than a chunk ahead: us=$byteOffset, server=$serverByteOffset"); // The normal case is that the server is a bit further along than us because of a // partially-uploaded chunk. Finish it off. $byteOffset += $diff; if ($diff === $len) break; // If the server is at the end, we're done. $data = substr($data, $diff); } } if ($numBytes !== null && $byteOffset !== $numBytes) throw new \InvalidArgumentException( "You passed numBytes=$numBytes but the stream had $byteOffset bytes."); $metadata = RequestUtil::runWithRetry(3, function() use ($client, $uploadId, $path, $writeMode) { return $client->chunkedUploadFinish($uploadId, $path, $writeMode); }); return $metadata; } /** * Sometimes fread() returns less than the request number of bytes (for example, when reading * from network streams). This function repeatedly calls fread until the requested number of * bytes have been read or we've reached EOF. * * @param resource $inStream * @param int $numBytes * @throws StreamReadException * @return string */ private static function readFully($inStream, $numBytes) { Checker::argNat("numBytes", $numBytes); $full = ''; $bytesRemaining = $numBytes; while (!feof($inStream) && $bytesRemaining > 0) { $part = fread($inStream, $bytesRemaining); if ($part === false) throw new StreamReadException("Error reading from \$inStream."); $full .= $part; $bytesRemaining -= strlen($part); } return $full; } /** * @param string $path * @param WriteMode $writeMode * @param callable $curlConfigClosure * @return array */ private function _uploadFile($path, $writeMode, $curlConfigClosure) { Path::checkArg("path", $path); WriteMode::checkArg("writeMode", $writeMode); Checker::argCallable("curlConfigClosure", $curlConfigClosure); $url = $this->buildUrlForGetOrPut( $this->contentHost, $this->appendFilePath("1/files_put", $path), $writeMode->getExtraParams()); $curl = $this->mkCurl($url); $curlConfigClosure($curl); $curl->set(CURLOPT_RETURNTRANSFER, true); $response = $curl->exec(); if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); return RequestUtil::parseResponseJson($response->body); } /** * Start a new chunked upload session and upload the first chunk of data. * * @param string $data * The data to start off the chunked upload session. * * @return array * A pair of (string $uploadId, int $byteOffset). $uploadId * is a unique identifier for this chunked upload session. You pass this in to * {@link chunkedUploadContinue} and {@link chuunkedUploadFinish}. $byteOffset * is the number of bytes that were successfully uploaded. * * @throws Exception */ function chunkedUploadStart($data) { Checker::argString("data", $data); $response = $this->_chunkedUpload(array(), $data); if ($response->statusCode === 404) { throw new Exception_BadResponse("Got a 404, but we didn't send up an 'upload_id'"); } $correction = self::_chunkedUploadCheckForOffsetCorrection($response); if ($correction !== null) throw new Exception_BadResponse( "Got an offset-correcting 400 response, but we didn't send an offset"); if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); list($uploadId, $byteOffset) = self::_chunkedUploadParse200Response($response->body); $len = strlen($data); if ($byteOffset !== $len) throw new Exception_BadResponse( "We sent $len bytes, but server returned an offset of $byteOffset"); return $uploadId; } /** * Append another chunk data to a previously-started chunked upload session. * * @param string $uploadId * The unique identifier for the chunked upload session. This is obtained via * {@link chunkedUploadStart}. * * @param int $byteOffset * The number of bytes you think you've already uploaded to the given chunked upload * session. The server will append the new chunk of data after that point. * * @param string $data * The data to append to the existing chunked upload session. * * @return int|bool * If false, it means the server didn't know about the given * $uploadId. This may be because the chunked upload session has expired * (they last around 24 hours). * If true, the chunk was successfully uploaded. If an integer, it means * you and the server don't agree on the current $byteOffset. The returned * integer is the server's internal byte offset for the chunked upload session. You need * to adjust your input to match. * * @throws Exception */ function chunkedUploadContinue($uploadId, $byteOffset, $data) { Checker::argStringNonEmpty("uploadId", $uploadId); Checker::argNat("byteOffset", $byteOffset); Checker::argString("data", $data); $response = $this->_chunkedUpload( array("upload_id" => $uploadId, "offset" => $byteOffset), $data); if ($response->statusCode === 404) { // The server doesn't know our upload ID. Maybe it expired? return false; } $correction = self::_chunkedUploadCheckForOffsetCorrection($response); if ($correction !== null) { list($correctedUploadId, $correctedByteOffset) = $correction; if ($correctedUploadId !== $uploadId) throw new Exception_BadResponse( "Corrective 400 upload_id mismatch: us=". Util::q($uploadId)." server=".Util::q($correctedUploadId)); if ($correctedByteOffset === $byteOffset) throw new Exception_BadResponse( "Corrective 400 offset is the same as ours: $byteOffset"); return $correctedByteOffset; } if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); list($retUploadId, $retByteOffset) = self::_chunkedUploadParse200Response($response->body); $nextByteOffset = $byteOffset + strlen($data); if ($uploadId !== $retUploadId) throw new Exception_BadResponse( "upload_id mismatch: us=".Util::q($uploadId) .", server=".Util::q($uploadId)); if ($nextByteOffset !== $retByteOffset) throw new Exception_BadResponse( "next-offset mismatch: us=$nextByteOffset, server=$retByteOffset"); return true; } /** * @param string $body * @return array */ private static function _chunkedUploadParse200Response($body) { $j = RequestUtil::parseResponseJson($body); $uploadId = self::getField($j, "upload_id"); $byteOffset = self::getField($j, "offset"); return array($uploadId, $byteOffset); } /** * @param HttpResponse $response * @return array|null */ private static function _chunkedUploadCheckForOffsetCorrection($response) { if ($response->statusCode !== 400) return null; $j = json_decode($response->body, true, 10); if ($j === null) return null; if (!array_key_exists("upload_id", $j) || !array_key_exists("offset", $j)) return null; $uploadId = $j["upload_id"]; $byteOffset = $j["offset"]; return array($uploadId, $byteOffset); } /** * Creates a file on Dropbox using the accumulated contents of the given chunked upload session. * * See /commit_chunked_upload. * * @param string $uploadId * The unique identifier for the chunked upload session. This is obtained via * {@link chunkedUploadStart}. * * @param string $path * The Dropbox path to save the file to ($path). * * @param WriteMode $writeMode * What to do if there's already a file at the given path. * * @return array|null * If null, it means the Dropbox server wasn't aware of the * $uploadId you gave it. * Otherwise, you get back the * metadata object * for the newly-created file. * * @throws Exception */ function chunkedUploadFinish($uploadId, $path, $writeMode) { Checker::argStringNonEmpty("uploadId", $uploadId); Path::checkArgNonRoot("path", $path); WriteMode::checkArg("writeMode", $writeMode); $params = array_merge(array("upload_id" => $uploadId), $writeMode->getExtraParams()); $response = $this->doPost( $this->contentHost, $this->appendFilePath("1/commit_chunked_upload", $path), $params); if ($response->statusCode === 404) return null; if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); return RequestUtil::parseResponseJson($response->body); } /** * @param array $params * @param string $data * @return HttpResponse */ protected function _chunkedUpload($params, $data) // Marked 'protected' so I can override it in testing. { $url = $this->buildUrlForGetOrPut( $this->contentHost, "1/chunked_upload", $params); $curl = $this->mkCurl($url); // We can't use CURLOPT_PUT because it wants a stream, but we already have $data in memory. $curl->set(CURLOPT_CUSTOMREQUEST, "PUT"); $curl->set(CURLOPT_POSTFIELDS, $data); $curl->addHeader("Content-Type: application/octet-stream"); $curl->set(CURLOPT_RETURNTRANSFER, true); return $curl->exec(); } /** * Returns the metadata for whatever file or folder is at the given path. * * * $client = ...; * $md = $client->getMetadata("/Photos/Frog.jpeg"); * print_r($md); * * * @param string $path * The Dropbox path to a file or folder (UTF-8). * * @return array|null * If there is a file or folder at the given path, you'll get back the * metadata object * for that file or folder. If not, you'll get back null. * * @throws Exception */ function getMetadata($path) { Path::checkArg("path", $path); return $this->_getMetadata($path, array("list" => "false")); } /** * Returns the metadata for whatever file or folder is at the given path and, if it's a folder, * also include the metadata for all the immediate children of that folder. * * * $client = ...; * $md = $client->getMetadataWithChildren("/Photos"); * print_r($md); * * * @param string $path * The Dropbox path to a file or folder (UTF-8). * * @return array|null * If there is a file or folder at the given path, you'll get back the * metadata object * for that file or folder, along with all immediate children if it's a folder. If not, * you'll get back null. * * @throws Exception */ function getMetadataWithChildren($path) { Path::checkArg("path", $path); return $this->_getMetadata($path, array("list" => "true", "file_limit" => "25000")); } /** * @param string $path * @param array $params * @return array */ private function _getMetadata($path, $params) { $response = $this->doGet( $this->apiHost, $this->appendFilePath("1/metadata", $path), $params); if ($response->statusCode === 404) return null; if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); $metadata = RequestUtil::parseResponseJson($response->body); if (array_key_exists("is_deleted", $metadata) && $metadata["is_deleted"]) return null; return $metadata; } /** * If you've previously retrieved the metadata for a folder and its children, this method will * retrieve updated metadata only if something has changed. This is more efficient than * calling {@link getMetadataWithChildren} if you have a cache of previous results. * * * $client = ...; * $md = $client->getMetadataWithChildren("/Photos"); * print_r($md); * assert($md["is_dir"], "expecting \"/Photos\" to be a folder"); * * sleep(10); * * // Now see if anything changed... * list($changed, $new_md) = $client->getMetadataWithChildrenIfChanged( * "/Photos", $md["hash"]); * if ($changed) { * echo "Folder changed.\n"; * print_r($new_md); * } else { * echo "Folder didn't change.\n"; * } * * * @param string $path * The Dropbox path to a folder (UTF-8). * * @param string $previousFolderHash * The "hash" field from the previously retrieved folder metadata. * * @return array * A list(boolean $changed, array $metadata). If the metadata hasn't changed, * you'll get list(false, null). If the metadata of the folder or any of its * children has changed, you'll get list(true, $newMetadata). $metadata is a * metadata object. * * @throws Exception */ function getMetadataWithChildrenIfChanged($path, $previousFolderHash) { Path::checkArg("path", $path); Checker::argStringNonEmpty("previousFolderHash", $previousFolderHash); $params = array("list" => "true", "file_limit" => "25000", "hash" => $previousFolderHash); $response = $this->doGet( $this->apiHost, $this->appendFilePath("1/metadata", $path), $params); if ($response->statusCode === 304) return array(false, null); if ($response->statusCode === 404) return array(true, null); if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); $metadata = RequestUtil::parseResponseJson($response->body); if (array_key_exists("is_deleted", $metadata) && $metadata["is_deleted"]) { return array(true, null); } return array(true, $metadata); } /** * A way of letting you keep up with changes to files and folders in a user's Dropbox. * * @param string|null $cursor * If this is the first time you're calling this, pass in null. Otherwise, * pass in whatever cursor was returned by the previous call. * * @param string|null $pathPrefix * If null, you'll get results for the entire folder (either the user's * entire Dropbox or your App Folder). If you set $path_prefix to * "/Photos/Vacation", you'll only get results for that path and any files and folders * under it. * * @return array * A delta page, which * contains a list of changes to apply along with a new "cursor" that should be passed into * future getDelta calls. If the "reset" field is true, you * should clear your local state before applying the changes. If the "has_more" field is * true, call getDelta immediately to get more results, otherwise * wait a while (at least 5 minutes) before calling getDelta again. * * @throws Exception */ function getDelta($cursor = null, $pathPrefix = null) { Checker::argStringNonEmptyOrNull("cursor", $cursor); Path::checkArgOrNull("pathPrefix", $pathPrefix); $response = $this->doPost($this->apiHost, "1/delta", array( "cursor" => $cursor, "path_prefix" => $pathPrefix)); if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); return RequestUtil::parseResponseJson($response->body); } /** * Gets the metadata for all the file revisions (up to a limit) for a given path. * * See /revisions. * * @param string path * The Dropbox path that you want file revision metadata for (UTF-8). * * @param int|null limit * The maximum number of revisions to return. * * @return array|null * A list of doGet( $this->apiHost, $this->appendFilePath("1/revisions", $path), array("rev_limit" => $limit)); if ($response->statusCode === 406) return null; if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); return RequestUtil::parseResponseJson($response->body); } /** * Takes a copy of the file at the given revision and saves it over the current copy. This * will create a new revision, but the file contents will match the revision you specified. * * See /restore. * * @param string $path * The Dropbox path of the file to restore (UTF-8). * * @param string $rev * The revision to restore the contents to. * * @return mixed * The metadata * object * * @throws Exception */ function restoreFile($path, $rev) { Path::checkArgNonRoot("path", $path); Checker::argStringNonEmpty("rev", $rev); $response = $this->doPost( $this->apiHost, $this->appendFilePath("1/restore", $path), array("rev" => $rev)); if ($response->statusCode === 404) return null; if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); return RequestUtil::parseResponseJson($response->body); } /** * Returns metadata for all files and folders whose filename matches the query string. * * See /search. * * @param string $basePath * The path to limit the search to (UTF-8). Pass in "/" to search everything. * * @param string $query * A space-separated list of substrings to search for. A file matches only if it contains * all the substrings. * * @param int|null $limit * The maximum number of results to return. * * @param bool $includeDeleted * Whether to include deleted files in the results. * * @return mixed * A list of doPost( $this->apiHost, $this->appendFilePath("1/search", $basePath), array( "query" => $query, "file_limit" => $limit, "include_deleted" => $includeDeleted, )); if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); return RequestUtil::parseResponseJson($response->body); } /** * Creates and returns a public link to a file or folder's "preview page". This link can be * used without authentication. The preview page may contain a thumbnail or some other * preview of the file, along with a download link to download the actual file. * * See /shares. * * @param string $path * The Dropbox path to the file or folder you want to create a shareable link to (UTF-8). * * @return string * The URL of the preview page. * * @throws Exception */ function createShareableLink($path) { Path::checkArg("path", $path); $response = $this->doPost( $this->apiHost, $this->appendFilePath("1/shares", $path), array( "short_url" => "false", )); if ($response->statusCode === 404) return null; if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); $j = RequestUtil::parseResponseJson($response->body); return self::getField($j, "url"); } /** * Creates and returns a direct link to a file. This link can be used without authentication. * This link will expire in a few hours. * * See /media. * * @param string $path * The Dropbox path to a file or folder (UTF-8). * * @return array * A list(string $url, \DateTime $expires) where $url is a direct * link to the requested file and $expires is a standard PHP * \DateTime representing when $url will stop working. * * @throws Exception */ function createTemporaryDirectLink($path) { Path::checkArgNonRoot("path", $path); $response = $this->doPost( $this->apiHost, $this->appendFilePath("1/media", $path)); if ($response->statusCode === 404) return null; if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); $j = RequestUtil::parseResponseJson($response->body); $url = self::getField($j, "url"); $expires = self::parseDateTime(self::getField($j, "expires")); return array($url, $expires); } /** * Creates and returns a "copy ref" to a file. A copy ref can be used to copy a file across * different Dropbox accounts without downloading and re-uploading. * * For example: Create a Client using the access token from one account and call * createCopyRef. Then, create a Client using the access token for * another account and call copyFromCopyRef using the copy ref. (You need to use * the same app key both times.) * * See /copy_ref. * * @param string path * The Dropbox path of the file or folder you want to create a copy ref for (UTF-8). * * @return string * The copy ref (just a string that you keep track of). * * @throws Exception */ function createCopyRef($path) { Path::checkArg("path", $path); $response = $this->doGet( $this->apiHost, $this->appendFilePath("1/copy_ref", $path)); if ($response->statusCode === 404) return null; if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); $j = RequestUtil::parseResponseJson($response->body); return self::getField($j, "copy_ref"); } /** * Gets a thumbnail image representation of the file at the given path. * * See /thumbnails. * * @param string $path * The path to the file you want a thumbnail for (UTF-8). * * @param string $format * One of the two image formats: "jpeg" or "png". * * @param string $size * One of the predefined image size names, as a string: *
    *
  • "xs" - 32x32
  • *
  • "s" - 64x64
  • *
  • "m" - 128x128
  • *
  • "l" - 640x480
  • *
  • "xl" - 1024x768
  • *
* * @return array|null * If the file exists, you'll get list(array $metadata, string $data) where * $metadata is the file's * metadata object * and $data is the raw data for the thumbnail image. If the file doesn't exist, you'll * get null. * * @throws Exception */ function getThumbnail($path, $format, $size) { Path::checkArgNonRoot("path", $path); Checker::argString("format", $format); Checker::argString("size", $size); if (!in_array($format, array("jpeg", "png"))) { throw new \InvalidArgumentException("Invalid 'format': ".Util::q($format)); } if (!in_array($size, array("xs", "s", "m", "l", "xl"))) { throw new \InvalidArgumentException("Invalid 'size': ".Util::q($format)); } $url = $this->buildUrlForGetOrPut( $this->contentHost, $this->appendFilePath("1/thumbnails", $path), array("size" => $size, "format" => $format)); $curl = $this->mkCurl($url); $metadataCatcher = new DropboxMetadataHeaderCatcher($curl->handle); $curl->set(CURLOPT_RETURNTRANSFER, true); $response = $curl->exec(); if ($response->statusCode === 404) return null; if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); $metadata = $metadataCatcher->getMetadata(); return array($metadata, $response->body); } /** * Copies a file or folder to a new location * * See /fileops/copy. * * @param string $fromPath * The Dropbox path of the file or folder you want to copy (UTF-8). * * @param string $toPath * The destination Dropbox path (UTF-8). * * @return mixed * The metadata * object for the new file or folder. * * @throws Exception */ function copy($fromPath, $toPath) { Path::checkArg("fromPath", $fromPath); Path::checkArgNonRoot("toPath", $toPath); $response = $this->doPost( $this->apiHost, "1/fileops/copy", array( "root" => "auto", "from_path" => $fromPath, "to_path" => $toPath, )); if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); return RequestUtil::parseResponseJson($response->body); } /** * Creates a file or folder based on an existing copy ref (possibly from a different Dropbox * account). * * See /fileops/copy. * * @param string $copyRef * A copy ref obtained via the {@link createCopyRef()} call. * * @param string $toPath * The Dropbox path you want to copy the file or folder to (UTF-8). * * @return mixed * The metadata * object for the new file or folder. * * @throws Exception */ function copyFromCopyRef($copyRef, $toPath) { Checker::argStringNonEmpty("copyRef", $copyRef); Path::checkArgNonRoot("toPath", $toPath); $response = $this->doPost( $this->apiHost, "1/fileops/copy", array( "root" => "auto", "from_copy_ref" => $copyRef, "to_path" => $toPath, ) ); if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); return RequestUtil::parseResponseJson($response->body); } /** * Creates a folder. * * See /fileops/create_folder. * * @param string $path * The Dropbox path at which to create the folder (UTF-8). * * @return array|null * If successful, you'll get back the * metadata object * for the newly-created folder. If not successful, you'll get null. * * @throws Exception */ function createFolder($path) { Path::checkArgNonRoot("path", $path); $response = $this->doPost( $this->apiHost, "1/fileops/create_folder", array( "root" => "auto", "path" => $path, )); if ($response->statusCode === 403) return null; if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); return RequestUtil::parseResponseJson($response->body); } /** * Deletes a file or folder * * See /fileops/delete. * * @param string $path * The Dropbox path of the file or folder to delete (UTF-8). * * @return mixed * The metadata * object for the deleted file or folder. * * @throws Exception */ function delete($path) { Path::checkArgNonRoot("path", $path); $response = $this->doPost( $this->apiHost, "1/fileops/delete", array( "root" => "auto", "path" => $path, )); if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); return RequestUtil::parseResponseJson($response->body); } /** * Moves a file or folder to a new location. * * See /fileops/move. * * @param string $fromPath * The source Dropbox path (UTF-8). * * @param string $toPath * The destination Dropbox path (UTF-8). * * @return mixed * The metadata * object for the destination file or folder. * * @throws Exception */ function move($fromPath, $toPath) { Path::checkArgNonRoot("fromPath", $fromPath); Path::checkArgNonRoot("toPath", $toPath); $response = $this->doPost( $this->apiHost, "1/fileops/move", array( "root" => "auto", "from_path" => $fromPath, "to_path" => $toPath, )); if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); return RequestUtil::parseResponseJson($response->body); } /** * Build a URL for making a GET or PUT request. Will add the "locale" * parameter. * * @param string $host * Either the "API" or "API content" hostname from {@link getHost()}. * @param string $path * The "path" part of the URL. For example, "/account/info". * @param array|null $params * URL parameters. For POST requests, do not put the parameters here. * Include them in the request body instead. * * @return string */ function buildUrlForGetOrPut($host, $path, $params = null) { return RequestUtil::buildUrlForGetOrPut($this->userLocale, $host, $path, $params); } /** * Perform an OAuth-2-authorized GET request to the Dropbox API. Will automatically * fill in "User-Agent" and "locale" as well. * * @param string $host * Either the "API" or "API content" hostname from {@link getHost()}. * @param string $path * The "path" part of the URL. For example, "/account/info". * @param array|null $params * GET parameters. * @return HttpResponse * * @throws Exception */ function doGet($host, $path, $params = null) { Checker::argString("host", $host); Checker::argString("path", $path); return RequestUtil::doGet($this->clientIdentifier, $this->accessToken, $this->userLocale, $host, $path, $params); } /** * Perform an OAuth-2-authorized POST request to the Dropbox API. Will automatically * fill in "User-Agent" and "locale" as well. * * @param string $host * Either the "API" or "API content" hostname from {@link getHost()}. * @param string $path * The "path" part of the URL. For example, "/commit_chunked_upload". * @param array|null $params * POST parameters. * @return HttpResponse * * @throws Exception */ function doPost($host, $path, $params = null) { Checker::argString("host", $host); Checker::argString("path", $path); return RequestUtil::doPost($this->clientIdentifier, $this->accessToken, $this->userLocale, $host, $path, $params); } /** * Create a {@link Curl} object that is pre-configured with {@link getClientIdentifier()}, * and the proper OAuth 2 "Authorization" header. * * @param string $url * Generate this URL using {@link buildUrl()}. * * @return Curl */ function mkCurl($url) { return RequestUtil::mkCurlWithOAuth($this->clientIdentifier, $url, $this->accessToken); } /** * Parses date/time strings returned by the Dropbox API. The Dropbox API returns date/times * formatted like: "Sat, 21 Aug 2010 22:31:20 +0000". * * @param string $apiDateTimeString * A date/time string returned by the API. * * @return \DateTime * A standard PHP \DateTime instance. * * @throws Exception_BadResponse * Thrown if $apiDateTimeString isn't correctly formatted. */ static function parseDateTime($apiDateTimeString) { $dt = \DateTime::createFromFormat(self::$dateTimeFormat, $apiDateTimeString); if ($dt === false) throw new Exception_BadResponse( "Bad date/time from server: ".Util::q($apiDateTimeString)); return $dt; } private static $dateTimeFormat = "D, d M Y H:i:s T"; /** * @internal */ static function getField($j, $fieldName) { if (!array_key_exists($fieldName, $j)) throw new Exception_BadResponse( "missing field \"$fieldName\" in ".Util::q($j)); return $j[$fieldName]; } /** * Given an OAuth 2 access token, returns null if it is well-formed (though * not necessarily valid). Otherwise, returns a string describing what's wrong with it. * * @param string $s * * @return string */ static function getAccessTokenError($s) { if ($s === null) return "can't be null"; if (strlen($s) === 0) return "can't be empty"; if (preg_match('@[^-=_~/A-Za-z0-9\.\+]@', $s) === 1) return "contains invalid character"; return null; } /** * @internal */ static function checkAccessTokenArg($argName, $accessToken) { $error = self::getAccessTokenError($accessToken); if ($error !== null) throw new \InvalidArgumentException("'$argName' invalid: $error"); } /** * @internal */ static function getClientIdentifierError($s) { if ($s === null) return "can't be null"; if (strlen($s) === 0) return "can't be empty"; if (preg_match('@[\x00-\x1f\x7f]@', $s) === 1) return "contains control character"; return null; } /** * @internal */ static function checkClientIdentifierArg($argName, $accessToken) { $error = self::getClientIdentifierError($accessToken); if ($error !== null) throw new \InvalidArgumentException("'$argName' invalid: $error"); } } handle = curl_init($url); // NOTE: Though we turn on all the correct SSL settings, many PHP installations // don't respect these settings. Run "examples/test-ssl.php" to run some basic // SSL tests to see how well your PHP implementation behaves. // Use our own certificate list. $this->set(CURLOPT_SSL_VERIFYPEER, true); // Enforce certificate validation $this->set(CURLOPT_SSL_VERIFYHOST, 2); // Enforce hostname validation // Force the use of TLS (SSL v2 and v3 are not secure). // TODO: Use "CURL_SSLVERSION_TLSv1" instead of "1" once we can rely on PHP 5.5+. $this->set(CURLOPT_SSLVERSION, 1); // Limit the set of ciphersuites used. global $sslCiphersuiteList; if ($sslCiphersuiteList !== null) { $this->set(CURLOPT_SSL_CIPHER_LIST, $sslCiphersuiteList); } list($rootCertsFilePath, $rootCertsFolderPath) = RootCertificates::getPaths(); // Certificate file. $this->set(CURLOPT_CAINFO, $rootCertsFilePath); // Certificate folder. If not specified, some PHP installations will use // the system default, even when CURLOPT_CAINFO is specified. $this->set(CURLOPT_CAPATH, $rootCertsFolderPath); // Limit vulnerability surface area. Supported in cURL 7.19.4+ if (defined('CURLOPT_PROTOCOLS')) $this->set(CURLOPT_PROTOCOLS, CURLPROTO_HTTPS); if (defined('CURLOPT_REDIR_PROTOCOLS')) $this->set(CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS); } /** * @param string $header */ function addHeader($header) { $this->headers[] = $header; } function exec() { $this->set(CURLOPT_HTTPHEADER, $this->headers); $body = curl_exec($this->handle); if ($body === false) { throw new Exception_NetworkIO("Error executing HTTP request: " . curl_error($this->handle)); } $statusCode = curl_getinfo($this->handle, CURLINFO_HTTP_CODE); return new HttpResponse($statusCode, $body); } /** * @param int $option * @param mixed $value */ function set($option, $value) { curl_setopt($this->handle, $option, $value); } function __destruct() { curl_close($this->handle); } } // Different cURL SSL backends use different names for ciphersuites. $curlVersion = \curl_version(); $curlSslBackend = $curlVersion['ssl_version']; if (\substr_compare($curlSslBackend, "NSS/", 0, strlen("NSS/")) === 0) { // Can't figure out how to reliably set ciphersuites for NSS. $sslCiphersuiteList = null; } else { // Use the OpenSSL names for all other backends. We may have to // refine this if users report errors. $sslCiphersuiteList = 'ECDHE-RSA-AES256-GCM-SHA384:'. 'ECDHE-RSA-AES128-GCM-SHA256:'. 'ECDHE-RSA-AES256-SHA384:'. 'ECDHE-RSA-AES128-SHA256:'. 'ECDHE-RSA-AES256-SHA:'. 'ECDHE-RSA-AES128-SHA:'. 'ECDHE-RSA-RC4-SHA:'. 'DHE-RSA-AES256-GCM-SHA384:'. 'DHE-RSA-AES128-GCM-SHA256:'. 'DHE-RSA-AES256-SHA256:'. 'DHE-RSA-AES128-SHA256:'. 'DHE-RSA-AES256-SHA:'. 'DHE-RSA-AES128-SHA:'. 'AES256-GCM-SHA384:'. 'AES128-GCM-SHA256:'. 'AES256-SHA256:'. 'AES128-SHA256:'. 'AES256-SHA:'. 'AES128-SHA'; } outStream = $outStream; $this->errorData = array(); $isError = null; curl_setopt($ch, CURLOPT_WRITEFUNCTION, array($this, 'writeData')); } function writeData($ch, $data) { if ($this->isError === null) { $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $this->isError = ($statusCode !== 200); } if ($this->isError) { $this->errorData[] = $data; } else { fwrite($this->outStream, $data); } return strlen($data); } function getErrorBody() { return implode($this->errorData); } } skippedFirstLine) { $this->skippedFirstLine = true; return strlen($header); } // If we've encountered an error on a previous callback, then there's nothing left to do. if ($this->error !== null) { return strlen($header); } // case-insensitive starts-with check. if (\substr_compare($header, "x-dropbox-metadata:", 0, 19, true) !== 0) { return strlen($header); } if ($this->metadata !== null) { $this->error = "Duplicate X-Dropbox-Metadata header"; return strlen($header); } $headerValue = substr($header, 19); $parsed = json_decode($headerValue, true, 10); if ($parsed === null) { $this->error = "Bad JSON in X-Dropbox-Metadata header"; return strlen($header); } $this->metadata = $parsed; return strlen($header); } function getMetadata() { if ($this->error !== null) { throw new Exception_BadResponse($this->error); } if ($this->metadata === null) { throw new Exception_BadResponse("Missing X-Dropbox-Metadata header"); } return $this->metadata; } } statusCode = $statusCode; } /** * The HTTP status code returned by the Dropbox server. * * @return int */ public function getStatusCode() { return $this->statusCode; } } api = $api; $this->content = $content; $this->web = $web; } /** * Returns the host name of the main Dropbox API server. * The default is "api.dropbox.com". * * @return string */ function getApi() { return $this->api; } /** * Returns the host name of the Dropbox API content server. * The default is "api-content.dropbox.com". * * @return string */ function getContent() { return $this->content; } /** * Returns the host name of the Dropbox web server. Used during user authorization. * The default is "www.dropbox.com". * * @return string */ function getWeb() { return $this->web; } /** * Check that a function argument is of type Host. * * @internal */ static function checkArg($argName, $argValue) { if (!($argValue instanceof self)) Checker::throwError($argName, $argValue, __CLASS__); } /** * Check that a function argument is either null or of type * Host. * * @internal */ static function checkArgOrNull($argName, $argValue) { if ($argValue === null) return; if (!($argValue instanceof self)) Checker::throwError($argName, $argValue, __CLASS__); } } statusCode = $statusCode; $this->body = $body; } } Copyright (c) 2013 Dropbox Inc., http://www.dropbox.com/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. key; } /** @var string */ private $key; /** * The OAuth 1 access token secret. * * Make sure that this is kept a secret. Someone with your app secret can impesonate your * application. People sometimes ask for help on the Dropbox API forums and * copy/paste code that includes their app secret. Do not do that. * * @return string */ function getSecret() { return $this->secret; } /** @var secret */ private $secret; /** * Constructor. * * @param string $key * {@link getKey()} * @param string $secret * {@link getSecret()} */ function __construct($key, $secret) { AppInfo::checkKeyArg($key); AppInfo::checkSecretArg($secret); $this->key = $key; $this->secret = $secret; } /** * Use this to check that a function argument is of type AppInfo * * @internal */ static function checkArg($argName, $argValue) { if (!($argValue instanceof self)) Checker::throwError($argName, $argValue, __CLASS__); } } * use \Dropbox as dbx; * $appInfo = dbx\AppInfo::loadFromJsonFile(...); * $clientIdentifier = "my-app/1.0"; * $oauth1AccessToken = dbx\OAuth1AccessToken(...); * * $upgrader = new dbx\OAuth1AccessTokenUpgrader($appInfo, $clientIdentifier, ...); * $oauth2AccessToken = $upgrader->getOAuth2AccessToken($oauth1AccessToken); * $upgrader->disableOAuth1AccessToken($oauth1AccessToken); * */ class OAuth1Upgrader extends AuthBase { /** * Given an existing active OAuth 1 access token, make a Dropbox API call to get a new OAuth 2 * access token that represents the same user and app. * * See /oauth2/token_from_oauth1. * * @param OAuth1AccessToken $oauth1AccessToken * * @return string * The OAuth 2 access token. * * @throws Exception */ function createOAuth2AccessToken($oauth1AccessToken) { OAuth1AccessToken::checkArg("oauth1AccessToken", $oauth1AccessToken); $response = self::doPost($oauth1AccessToken, "1/oauth2/token_from_oauth1"); if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); $parts = RequestUtil::parseResponseJson($response->body); if (!array_key_exists('token_type', $parts) || !is_string($parts['token_type'])) { throw new Exception_BadResponse("Missing \"token_type\" field."); } $tokenType = $parts['token_type']; if (!array_key_exists('access_token', $parts) || !is_string($parts['access_token'])) { throw new Exception_BadResponse("Missing \"access_token\" field."); } $accessToken = $parts['access_token']; if ($tokenType !== "Bearer" && $tokenType !== "bearer") { throw new Exception_BadResponse("Unknown \"token_type\"; expecting \"Bearer\", got " . Util::q($tokenType)); } return $accessToken; } /** * Make a Dropbox API call to disable the given OAuth 1 access token. * * See /disable_access_token. * * @param OAuth1AccessToken $oauth1AccessToken * * @throws Exception */ function disableOAuth1AccessToken($oauth1AccessToken) { OAuth1AccessToken::checkArg("oauth1AccessToken", $oauth1AccessToken); $response = self::doPost($oauth1AccessToken, "1/disable_access_token"); if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); } /** * @param OAuth1AccessToken $oauth1AccessToken * @param string $path * * @return HttpResponse * * @throws Exception */ private function doPost($oauth1AccessToken, $path) { // Construct the OAuth 1 header. $signature = rawurlencode($this->appInfo->getSecret()) . "&" . rawurlencode($oauth1AccessToken->getSecret()); $authHeaderValue = "OAuth oauth_signature_method=\"PLAINTEXT\"" . ", oauth_consumer_key=\"" . rawurlencode($this->appInfo->getKey()) . "\"" . ", oauth_token=\"" . rawurlencode($oauth1AccessToken->getKey()) . "\"" . ", oauth_signature=\"" . $signature . "\""; return RequestUtil::doPostWithSpecificAuth( $this->clientIdentifier, $authHeaderValue, $this->userLocale, $this->appInfo->getHost()->getApi(), $path, null); } } "/" is not allowed. * * @param string $path * The path you want to check for validity. * * @return bool * Whether the path was valid or not. */ static function isValidNonRoot($path) { $error = self::findErrorNonRoot($path); return ($error === null); } /** * If the given path is a valid Dropbox path, return null, * otherwise return an English string error message describing what is wrong with the path. * * @param string $path * The path you want to check for validity. * * @return string|null * If the path was valid, return null. Otherwise, returns * an English string describing the problem. */ static function findError($path) { Checker::argString("path", $path); $matchResult = preg_match('%^(?: [\x09\x0A\x0D\x20-\x7E] # ASCII | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte | \xE0[\xA0-\xBF][\x80-\xBD] # excluding overlongs, FFFE, and FFFF | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates )*$%xs', $path); if ($matchResult !== 1) { return "must be valid UTF-8; BMP only, no surrogates, no U+FFFE or U+FFFF"; } if (\substr_compare($path, "/", 0, 1) !== 0) return "must start with \"/\""; $l = strlen($path); if ($l === 1) return null; // Special case for "/" if ($path[$l-1] === "/") return "must not end with \"/\""; // TODO: More checks. return null; } /** * If the given path is a valid non-root Dropbox path, return null, * otherwise return an English string error message describing what is wrong with the path. * This is the same as {@link findError} except "/" will yield an error message. * * @param string $path * The path you want to check for validity. * * @return string|null * If the path was valid, return null. Otherwise, returns * an English string describing the problem. */ static function findErrorNonRoot($path) { if ($path == "/") return "root path not allowed"; return self::findError($path); } /** * Return the last component of a path (the file or folder name). * * * Path::getName("/Misc/Notes.txt") // "Notes.txt" * Path::getName("/Misc") // "Misc" * Path::getName("/") // null * * * @param string $path * The full path you want to get the last component of. * * @return null|string * The last component of $path or null if the given * $path was "/". */ static function getName($path) { Checker::argString("path", $path); if (\substr_compare($path, "/", 0, 1) !== 0) { throw new \InvalidArgumentException("'path' must start with \"/\""); } $l = strlen($path); if ($l === 1) return null; if ($path[$l-1] === "/") { throw new \InvalidArgumentException("'path' must not end with \"/\""); } $lastSlash = strrpos($path, "/"); return substr($path, $lastSlash+1); } /** * @internal * * @param string $argName * @param mixed $value * @throws \InvalidArgumentException */ static function checkArg($argName, $value) { if ($value === null) throw new \InvalidArgumentException("'$argName' must not be null"); if (!is_string($value)) throw new \InvalidArgumentException("'$argName' must be a string"); $error = self::findError($value); if ($error !== null) throw new \InvalidArgumentException("'$argName'': bad path: $error: ".var_export($value, true)); } /** * @internal * * @param string $argName * @param mixed $value * @throws \InvalidArgumentException */ static function checkArgOrNull($argName, $value) { if ($value === null) return; self::checkArg($argName, $value); } /** * @internal * * @param string $argName * @param mixed $value * @throws \InvalidArgumentException */ static function checkArgNonRoot($argName, $value) { if ($value === null) throw new \InvalidArgumentException("'$argName' must not be null"); if (!is_string($value)) throw new \InvalidArgumentException("'$argName' must be a string"); $error = self::findErrorNonRoot($value); if ($error !== null) throw new \InvalidArgumentException("'$argName'': bad path: $error: ".var_export($value, true)); } } $value) { Checker::argStringNonEmpty("key in 'params'", $key); if ($value !== null) { if (is_bool($value)) { $value = $value ? "true" : "false"; } else if (is_int($value)) { $value = (string) $value; } else if (!is_string($value)) { throw new \InvalidArgumentException("params['$key'] is not a string, int, or bool"); } $url .= "&" . rawurlencode($key) . "=" . rawurlencode($value); } } } return $url; } /** * @param string $host * @param string $path * @return string */ static function buildUri($host, $path) { Checker::argStringNonEmpty("host", $host); Checker::argStringNonEmpty("path", $path); return "https://" . $host . "/" . $path; } /** * @param string $clientIdentifier * @param string $url * @return Curl */ static function mkCurl($clientIdentifier, $url) { $curl = new Curl($url); $curl->set(CURLOPT_CONNECTTIMEOUT, 10); // If the transfer speed is below 1kB/sec for 10 sec, abort. $curl->set(CURLOPT_LOW_SPEED_LIMIT, 1024); $curl->set(CURLOPT_LOW_SPEED_TIME, 10); //$curl->set(CURLOPT_VERBOSE, true); // For debugging. // TODO: Figure out how to encode clientIdentifier (urlencode?) $curl->addHeader("User-Agent: ".$clientIdentifier." Dropbox-PHP-SDK"); return $curl; } /** * @param string $clientIdentifier * @param string $url * @param string $authHeaderValue * @return Curl */ static function mkCurlWithAuth($clientIdentifier, $url, $authHeaderValue) { $curl = self::mkCurl($clientIdentifier, $url); $curl->addHeader("Authorization: $authHeaderValue"); return $curl; } /** * @param string $clientIdentifier * @param string $url * @param string $accessToken * @return Curl */ static function mkCurlWithOAuth($clientIdentifier, $url, $accessToken) { return self::mkCurlWithAuth($clientIdentifier, $url, "Bearer $accessToken"); } static function buildPostBody($params) { if ($params === null) return ""; $pairs = array(); foreach ($params as $key => $value) { Checker::argStringNonEmpty("key in 'params'", $key); if ($value !== null) { if (is_bool($value)) { $value = $value ? "true" : "false"; } else if (is_int($value)) { $value = (string) $value; } else if (!is_string($value)) { throw new \InvalidArgumentException("params['$key'] is not a string, int, or bool"); } $pairs[] = rawurlencode($key) . "=" . rawurlencode((string) $value); } } return implode("&", $pairs); } /** * @param string $clientIdentifier * @param string $accessToken * @param string $userLocale * @param string $host * @param string $path * @param array|null $params * * @return HttpResponse * * @throws Exception */ static function doPost($clientIdentifier, $accessToken, $userLocale, $host, $path, $params = null) { Checker::argStringNonEmpty("accessToken", $accessToken); $url = self::buildUri($host, $path); if ($params === null) $params = array(); $params['locale'] = $userLocale; $curl = self::mkCurlWithOAuth($clientIdentifier, $url, $accessToken); $curl->set(CURLOPT_POST, true); $curl->set(CURLOPT_POSTFIELDS, self::buildPostBody($params)); $curl->set(CURLOPT_RETURNTRANSFER, true); return $curl->exec(); } /** * @param string $clientIdentifier * @param string $authHeaderValue * @param string $userLocale * @param string $host * @param string $path * @param array|null $params * * @return HttpResponse * * @throws Exception */ static function doPostWithSpecificAuth($clientIdentifier, $authHeaderValue, $userLocale, $host, $path, $params = null) { Checker::argStringNonEmpty("authHeaderValue", $authHeaderValue); $url = self::buildUri($host, $path); if ($params === null) $params = array(); $params['locale'] = $userLocale; $curl = self::mkCurlWithAuth($clientIdentifier, $url, $authHeaderValue); $curl->set(CURLOPT_POST, true); $curl->set(CURLOPT_POSTFIELDS, self::buildPostBody($params)); $curl->set(CURLOPT_RETURNTRANSFER, true); return $curl->exec(); } /** * @param string $clientIdentifier * @param string $accessToken * @param string $userLocale * @param string $host * @param string $path * @param array|null $params * * @return HttpResponse * * @throws Exception */ static function doGet($clientIdentifier, $accessToken, $userLocale, $host, $path, $params = null) { Checker::argStringNonEmpty("accessToken", $accessToken); $url = self::buildUrlForGetOrPut($userLocale, $host, $path, $params); $curl = self::mkCurlWithOAuth($clientIdentifier, $url, $accessToken); $curl->set(CURLOPT_HTTPGET, true); $curl->set(CURLOPT_RETURNTRANSFER, true); return $curl->exec(); } /** * @param string $responseBody * @return mixed * @throws Exception_BadResponse */ static function parseResponseJson($responseBody) { $obj = json_decode($responseBody, true, 10); if ($obj === null) { throw new Exception_BadResponse("Got bad JSON from server: $responseBody"); } return $obj; } static function unexpectedStatus($httpResponse) { $sc = $httpResponse->statusCode; $message = "HTTP status $sc"; if (is_string($httpResponse->body)) { // TODO: Maybe only include the first ~200 chars of the body? $message .= "\n".$httpResponse->body; } if ($sc === 400) return new Exception_BadRequest($message); if ($sc === 401) return new Exception_InvalidAccessToken($message); if ($sc === 500 || $sc === 502) return new Exception_ServerError($message); if ($sc === 503) return new Exception_RetryLater($message); return new Exception_BadResponseCode("Unexpected $message", $sc); } /** * @param int $maxRetries * The number of times to retry it the action if it fails with one of the transient * API errors. A value of 1 means we'll try the action once and if it fails, we * will retry once. * * @param callable $action * The the action you want to retry. * * @return mixed * Whatever is returned by the $action callable. */ static function runWithRetry($maxRetries, $action) { Checker::argNat("maxRetries", $maxRetries); $retryDelay = 1; $numRetries = 0; while (true) { try { return $action(); } // These exception types are the ones we think are possibly transient errors. catch (Exception_NetworkIO $ex) { $savedEx = $ex; } catch (Exception_ServerError $ex) { $savedEx = $ex; } catch (Exception_RetryLater $ex) { $savedEx = $ex; } // We maxed out our retries. Propagate the last exception we got. if ($numRetries >= $maxRetries) throw $savedEx; $numRetries++; sleep($retryDelay); $retryDelay *= 2; // Exponential back-off. } throw new \RuntimeException("unreachable"); } } getMessage()); } } else { if (substr(__DIR__, 0, 7) === 'phar://') { throw new \Exception("The code appears to be running in a PHAR. You need to call \\Dropbox\\RootCertificates\\useExternalPaths() before making any API calls."); } $file = __DIR__.self::$originalPath; $folder = \dirname($file); } self::$paths = array($file, $folder); } return self::$paths; } /** * @param string $baseFolder * * @return string */ private static function createExternalCaFolder($baseFolder) { // This is hacky, but I can't find a simple way to do this. // This process isn't atomic, so give it three tries. for ($i = 0; $i < 3; $i++) { $path = \tempnam($baseFolder, "dropbox-php-sdk-trusted-certs-empty-dir"); if ($path === false) { throw new \Exception("Couldn't create temp file in folder ".Util::q($baseFolder)."."); } if (!\unlink($path)) { throw new \Exception("Couldn't remove temp file to make way for temp dir: ".Util::q($path)); } // TODO: Figure out how to make the folder private on Windows. The '700' only works on Unix. if (!\mkdir($path, 700)) { // Someone snuck in between the unlink() and the mkdir() and stole our path. throw new \Exception("Couldn't create temp dir: ".Util::q($path)); } \register_shutdown_function(function() use ($path) { \rmdir($path); }); return $path; } throw new \Exception("Unable to create temp dir in ".Util::q($baseFolder).", there's always something in the way."); } /** * @param string $baseFolder * * @return string */ private static function createExternalCaFile($baseFolder) { $path = \tempnam($baseFolder, "dropbox-php-sdk-trusted-certs"); if ($path === false) { throw new \Exception("Couldn't create temp file in folder ".Util::q($baseFolder)."."); } \register_shutdown_function(function() use ($path) { \unlink($path); }); // NOTE: Can't use the standard PHP copy(). That would clobber the locked-down // permissions set by tempnam(). self::copyInto(__DIR__.self::$originalPath, $path); return $path; } /** * @param string $src * @param string $dest */ private static function copyInto($src, $dest) { $srcFd = \fopen($src, "r"); if ($srcFd === false) { throw new \Exception("Couldn't open " . Util::q($src) . " for reading."); } $destFd = \fopen($dest, "w"); if ($destFd === false) { \fclose($srcFd); throw new \Exception("Couldn't open " . Util::q($dest) . " for writing."); } \stream_copy_to_stream($srcFd, $destFd); fclose($srcFd); if (!\fclose($destFd)) { throw new \Exception("Error closing file ".Util::q($dest)."."); } } } = 0) { $s = openssl_random_pseudo_bytes($numBytes, $isCryptoStrong); if ($isCryptoStrong) return $s; } if (function_exists('mcrypt_create_iv')) { return mcrypt_create_iv($numBytes); } // Hopefully the above two options cover all our users. But if not, there are // other platform-specific options we could add. throw new \Exception("no suitable random number source available"); } } test() method. */ class SSLTester { /** * Peforms a few basic tests of your PHP installation's SSL implementation to see * if it insecure in an obvious way. Results are written with "echo" and the output * is HTML-safe. * * @return bool * Returns true if all the tests passed. */ static function test() { $hostOs = php_uname('s').' '.php_uname('r'); $phpVersion = phpversion(); $curlVersionInfo = \curl_version(); $curlVersion = $curlVersionInfo['version']; $curlSslBackend = $curlVersionInfo['ssl_version']; echo "-----------------------------------------------------------------------------\n"; echo "Testing your PHP installation's SSL implementation for a few obvious problems...\n"; echo "-----------------------------------------------------------------------------\n"; echo "- Host OS: $hostOs\n"; echo "- PHP version: $phpVersion\n"; echo "- cURL version: $curlVersion\n"; echo "- cURL SSL backend: $curlSslBackend\n"; echo "Basic SSL tests\n"; $basicFailures = self::testMulti(array( array("www.dropbox.com", 'testAllowed'), array("www.digicert.com", 'testAllowed'), array("www.v.dropbox.com", 'testHostnameMismatch'), array("testssl-expire.disig.sk", 'testUntrustedCert'), )); echo "Pinned certificate tests\n"; $pinnedCertFailures = self::testMulti(array( array("www.verisign.com", 'testUntrustedCert'), array("www.globalsign.fr", 'testUntrustedCert'), )); if ($basicFailures) { echo "-----------------------------------------------------------------------------\n"; echo "WARNING: Your PHP installation's SSL support is COMPLETELY INSECURE.\n"; echo "Your app's communication with the Dropbox API servers can be viewed and\n"; echo "manipulated by others. Try upgrading your version of PHP.\n"; echo "-----------------------------------------------------------------------------\n"; return false; } else if ($pinnedCertFailures) { echo "-----------------------------------------------------------------------------\n"; echo "WARNING: Your PHP installation's cURL module doesn't support SSL certificate\n"; echo "pinning, which is an important security feature of the Dropbox SDK.\n"; echo "\n"; echo "This SDK uses CURLOPT_CAINFO and CURLOPT_CAPATH to tell PHP cURL to only trust\n"; echo "our custom certificate list. But your PHP installation's cURL module seems to\n"; echo "trust certificates that aren't on that list.\n"; echo "\n"; echo "More information on SSL certificate pinning:\n"; echo "https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#What_Is_Pinning.3F\n"; echo "-----------------------------------------------------------------------------\n"; return false; } else { return true; } } private static function testMulti($tests) { $anyFailed = false; foreach ($tests as $test) { list($host, $testType) = $test; echo " - ".str_pad("$testType ($host) ", 50, "."); $url = "https://$host/"; $passed = self::$testType($url); if ($passed) { echo " ok\n"; } else { echo " FAILED\n"; $anyFailed = true; } } return $anyFailed; } private static function testAllowed($url) { $curl = RequestUtil::mkCurl("test-ssl", $url); $curl->set(CURLOPT_RETURNTRANSFER, true); $curl->exec(); return true; } private static function testUntrustedCert($url) { return self::testDisallowed($url, 'Error executing HTTP request: SSL certificate problem, verify that the CA cert is OK'); } private static function testHostnameMismatch($url) { return self::testDisallowed($url, 'Error executing HTTP request: SSL certificate problem: Invalid certificate chain'); } private static function testDisallowed($url, $expectedExceptionMessage) { $curl = RequestUtil::mkCurl("test-ssl", $url); $curl->set(CURLOPT_RETURNTRANSFER, true); try { $curl->exec(); } catch (Exception_NetworkIO $ex) { if (strpos($ex->getMessage(), $expectedExceptionMessage) == 0) { return true; } else { throw $ex; } } return false; } } * class MemcacheValueStore implements ValueStore * { * private $key; * private $memcache; * * function __construct($memcache, $key) * { * $this->memcache = $memcache; * $this->key = $key; * } * * function get() * { * $value = $this->memcache->get($this->getKey()); * return $value === false ? null : base64_decode($value); * } * * function set($value) * { * $this->memcache->set($this->key, base64_encode($value)); * } * * function clear() * { * $this->memcache->delete($this->key); * } * } * */ interface ValueStore { /** * Returns the entry's current value or null if nothing is set. * * @return string */ function get(); /** * Set the entry to the given value. * * @param string $value */ function set($value); /** * Remove the value. */ function clear(); } * use \Dropbox as dbx; * * function getWebAuth() * { * $appInfo = dbx\AppInfo::loadFromJsonFile(...); * $clientIdentifier = "my-app/1.0"; * $redirectUri = "https://example.org/dropbox-auth-finish"; * $csrfTokenStore = new dbx\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token'); * return new dbx\WebAuth($appInfo, $clientIdentifier, $redirectUri, $csrfTokenStore, ...); * } * * // ---------------------------------------------------------- * // In the URL handler for "/dropbox-auth-start" * * $authorizeUrl = getWebAuth()->start(); * header("Location: $authorizeUrl"); * * // ---------------------------------------------------------- * // In the URL handler for "/dropbox-auth-finish" * * try { * list($accessToken, $userId, $urlState) = getWebAuth()->finish($_GET); * assert($urlState === null); // Since we didn't pass anything in start() * } * catch (dbx\WebAuthException_BadRequest $ex) { * error_log("/dropbox-auth-finish: bad request: " . $ex->getMessage()); * // Respond with an HTTP 400 and display error page... * } * catch (dbx\WebAuthException_BadState $ex) { * // Auth session expired. Restart the auth process. * header('Location: /dropbox-auth-start'); * } * catch (dbx\WebAuthException_Csrf $ex) { * error_log("/dropbox-auth-finish: CSRF mismatch: " . $ex->getMessage()); * // Respond with HTTP 403 and display error page... * } * catch (dbx\WebAuthException_NotApproved $ex) { * error_log("/dropbox-auth-finish: not approved: " . $ex->getMessage()); * } * catch (dbx\WebAuthException_Provider $ex) { * error_log("/dropbox-auth-finish: error redirect from Dropbox: " . $ex->getMessage()); * } * catch (dbx\Exception $ex) { * error_log("/dropbox-auth-finish: error communicating with Dropbox API: " . $ex->getMessage()); * } * * // We can now use $accessToken to make API requests. * $client = dbx\Client($accessToken, ...); * * */ class WebAuth extends WebAuthBase { /** * The URI that the Dropbox server will redirect the user to after the user finishes * authorizing your app. This URI must be HTTPS-based and * pre-registered with Dropbox, * though "localhost"-based and "127.0.0.1"-based URIs are allowed without pre-registration * and can be either HTTP or HTTPS. * * @return string */ function getRedirectUri() { return $this->redirectUri; } /** @var string */ private $redirectUri; /** * A object that lets us save CSRF token string to the user's session. If you're using the * standard PHP $_SESSION, you can pass in something like * new ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token'). * * If you're not using $_SESSION, you might have to create your own class that provides * the same get()/set()/clear() methods as * {@link ArrayEntryStore}. * * @return ValueStore */ function getCsrfTokenStore() { return $this->csrfTokenStore; } /** @var object */ private $csrfTokenStore; /** * Constructor. * * @param AppInfo $appInfo * See {@link getAppInfo()} * @param string $clientIdentifier * See {@link getClientIdentifier()} * @param null|string $redirectUri * See {@link getRedirectUri()} * @param null|ValueStore $csrfTokenStore * See {@link getCsrfTokenStore()} * @param null|string $userLocale * See {@link getUserLocale()} */ function __construct($appInfo, $clientIdentifier, $redirectUri, $csrfTokenStore, $userLocale = null) { parent::__construct($appInfo, $clientIdentifier, $userLocale); Checker::argStringNonEmpty("redirectUri", $redirectUri); $this->csrfTokenStore = $csrfTokenStore; $this->redirectUri = $redirectUri; } /** * Starts the OAuth 2 authorization process, which involves redirecting the user to the * returned authorization URL (a URL on the Dropbox website). When the user then * either approves or denies your app access, Dropbox will redirect them to the * $redirectUri given to constructor, at which point you should * call {@link finish()} to complete the authorization process. * * This function will also save a CSRF token using the $csrfTokenStore given to * the constructor. This CSRF token will be checked on {@link finish()} to prevent * request forgery. * * See /oauth2/authorize. * * @param string|null $urlState * Any data you would like to keep in the URL through the authorization process. * This exact state will be returned to you by {@link finish()}. * * @return array * The URL to redirect the user to. * * @throws Exception */ function start($urlState = null) { Checker::argStringOrNull("urlState", $urlState); $csrfToken = self::encodeCsrfToken(Security::getRandomBytes(16)); $state = $csrfToken; if ($urlState !== null) { $state .= "|"; $state .= $urlState; } $this->csrfTokenStore->set($csrfToken); return $this->_getAuthorizeUrl($this->redirectUri, $state); } private static function encodeCsrfToken($string) { return strtr(base64_encode($string), '+/', '-_'); } /** * Call this after the user has visited the authorize URL ({@link start()}), approved your app, * and was redirected to your redirect URI. * * See /oauth2/token. * * @param array $queryParams * The query parameters on the GET request to your redirect URI. * * @return array * A list(string $accessToken, string $userId, string $urlState), where * $accessToken can be used to construct a {@link Client}, $userId * is the user ID of the user's Dropbox account, and $urlState is the * value you originally passed in to {@link start()}. * * @throws Exception * Thrown if there's an error getting the access token from Dropbox. * @throws WebAuthException_BadRequest * @throws WebAuthException_BadState * @throws WebAuthException_Csrf * @throws WebAuthException_NotApproved * @throws WebAuthException_Provider */ function finish($queryParams) { Checker::argArray("queryParams", $queryParams); $csrfTokenFromSession = $this->csrfTokenStore->get(); Checker::argStringOrNull("this->csrfTokenStore->get()", $csrfTokenFromSession); // Check well-formedness of request. if (!isset($queryParams['state'])) { throw new WebAuthException_BadRequest("Missing query parameter 'state'."); } $state = $queryParams['state']; Checker::argString("queryParams['state']", $state); $error = null; $errorDescription = null; if (isset($queryParams['error'])) { $error = $queryParams['error']; Checker::argString("queryParams['error']", $error); if (isset($queryParams['error_description'])) { $errorDescription = $queryParams['error_description']; Checker::argString("queryParams['error_description']", $errorDescription); } } $code = null; if (isset($queryParams['code'])) { $code = $queryParams['code']; Checker::argString("queryParams['code']", $code); } if ($code !== null && $error !== null) { throw new WebAuthException_BadRequest("Query parameters 'code' and 'error' are both set;". " only one must be set."); } if ($code === null && $error === null) { throw new WebAuthException_BadRequest("Neither query parameter 'code' or 'error' is set."); } // Check CSRF token if ($csrfTokenFromSession === null) { throw new WebAuthException_BadState(); } $splitPos = strpos($state, "|"); if ($splitPos === false) { $givenCsrfToken = $state; $urlState = null; } else { $givenCsrfToken = substr($state, 0, $splitPos); $urlState = substr($state, $splitPos + 1); } if (!Security::stringEquals($csrfTokenFromSession, $givenCsrfToken)) { throw new WebAuthException_Csrf("Expected ".Util::q($csrfTokenFromSession) . ", got ".Util::q($givenCsrfToken) ."."); } $this->csrfTokenStore->clear(); // Check for error identifier if ($error !== null) { if ($error === 'access_denied') { // When the user clicks "Deny". if ($errorDescription === null) { throw new WebAuthException_NotApproved("No additional description from Dropbox."); } else { throw new WebAuthException_NotApproved("Additional description from Dropbox: $errorDescription"); } } else { // All other errors. $fullMessage = $error; if ($errorDescription !== null) { $fullMessage .= ": "; $fullMessage .= $errorDescription; } throw new WebAuthException_Provider($fullMessage); } } // If everything went ok, make the network call to get an access token. list($accessToken, $userId) = $this->_finish($code, $this->redirectUri); return array($accessToken, $userId, $urlState); } } userLocale, $this->appInfo->getHost()->getWeb(), "1/oauth2/authorize", array( "client_id" => $this->appInfo->getKey(), "response_type" => "code", "redirect_uri" => $redirectUri, "state" => $state, )); } protected function _finish($code, $originalRedirectUri) { // This endpoint requires "Basic" auth. $clientCredentials = $this->appInfo->getKey().":".$this->appInfo->getSecret(); $authHeaderValue = "Basic ".base64_encode($clientCredentials); $response = RequestUtil::doPostWithSpecificAuth( $this->clientIdentifier, $authHeaderValue, $this->userLocale, $this->appInfo->getHost()->getApi(), "1/oauth2/token", array( "grant_type" => "authorization_code", "code" => $code, "redirect_uri" => $originalRedirectUri, )); if ($response->statusCode !== 200) throw RequestUtil::unexpectedStatus($response); $parts = RequestUtil::parseResponseJson($response->body); if (!array_key_exists('token_type', $parts) || !is_string($parts['token_type'])) { throw new Exception_BadResponse("Missing \"token_type\" field."); } $tokenType = $parts['token_type']; if (!array_key_exists('access_token', $parts) || !is_string($parts['access_token'])) { throw new Exception_BadResponse("Missing \"access_token\" field."); } $accessToken = $parts['access_token']; if (!array_key_exists('uid', $parts) || !is_string($parts['uid'])) { throw new Exception_BadResponse("Missing \"uid\" string field."); } $userId = $parts['uid']; if ($tokenType !== "Bearer" && $tokenType !== "bearer") { throw new Exception_BadResponse("Unknown \"token_type\"; expecting \"Bearer\", got " .Util::q($tokenType)); } return array($accessToken, $userId); } } * use \Dropbox as dbx; * $appInfo = dbx\AppInfo::loadFromJsonFile(...); * $clientIdentifier = "my-app/1.0"; * $webAuth = new dbx\WebAuthNoRedirect($appInfo, $clientIdentifier, ...); * * $authorizeUrl = $webAuth->start(); * * print("1. Go to: $authorizeUrl\n"); * print("2. Click "Allow" (you might have to log in first).\n"); * print("3. Copy the authorization code.\n"); * print("Enter the authorization code here: "); * $code = \trim(\fgets(STDIN)); * * try { * list($accessToken, $userId) = $webAuth->finish($code); * } * catch (dbx\Exception $ex) { * print("Error communicating with Dropbox API: " . $ex->getMessage() . "\n"); * } * * $client = dbx\Client($accessToken, $clientIdentifier, ...); * */ class WebAuthNoRedirect extends WebAuthBase { /** * Returns the URL of the authorization page the user must visit. If the user approves * your app, they will be shown the authorization code on the web page. They will need to * copy/paste that code into your application so your app can pass it to * {@link finish}. * * See /oauth2/authorize. * * @return string * An authorization URL. Direct the user's browser to this URL. After the user decides * whether to authorize your app or not, Dropbox will show the user an authorization code, * which the user will need to give to your application (e.g. via copy/paste). */ function start() { return $this->_getAuthorizeUrl(null, null); } /** * Call this after the user has visited the authorize URL returned by {@link start()}, * approved your app, was presented with an authorization code by Dropbox, and has copy/paste'd * that authorization code into your app. * * See /oauth2/token. * * @param string $code * The authorization code provided to the user by Dropbox. * * @return array * A list(string $accessToken, string $userId), where * $accessToken can be used to construct a {@link Client} and * $userId is the user ID of the user's Dropbox account. * * @throws Exception * Thrown if there's an error getting the access token from Dropbox. */ function finish($code) { Checker::argStringNonEmpty("code", $code); return $this->_finish($code, null); } } extraParams = $extraParams; } /** * @internal */ function getExtraParams() { return $this->extraParams; } /** * Returns a {@link WriteMode} for adding a new file. If a file at the specified path already * exists, the new file will be renamed automatically. * * For example, if you're trying to upload a file to "/Notes/Groceries.txt", but there's * already a file there, your file will be written to "/Notes/Groceries (1).txt". * * You can determine whether your file was renamed by checking the "path" field of the * metadata object returned by the API call. * * @return WriteMode */ static function add() { if (self::$addInstance === null) { self::$addInstance = new WriteMode(array("overwrite" => "false")); } return self::$addInstance; } private static $addInstance = null; /** * Returns a {@link WriteMode} for forcing a file to be at a certain path. If there's already * a file at that path, the existing file will be overwritten. If there's a folder at that * path, however, it will not be overwritten and the API call will fail. * * @return WriteMode */ static function force() { if (self::$forceInstance === null) { self::$forceInstance = new WriteMode(array("overwrite" => "true")); } return self::$forceInstance; } private static $forceInstance = null; /** * Returns a {@link WriteMode} for updating an existing file. This is useful for when you * have downloaded a file, made modifications, and want to save your modifications back to * Dropbox. You need to specify the revision of the copy of the file you downloaded (it's * the "rev" parameter of the file's metadata object). * * If, when you attempt to save, the revision of the file currently on Dropbox matches * $revToReplace, the file on Dropbox will be overwritten with the new contents you provide. * * If the revision of the file currently on Dropbox doesn't match $revToReplace, Dropbox will * create a new file and save your contents to that file. For example, if the original file * path is "/Notes/Groceries.txt", the new file's path might be * "/Notes/Groceries (conflicted copy).txt". * * You can determine whether your file was renamed by checking the "path" field of the * metadata object returned by the API call. * * @param string $revToReplace * @return WriteMode */ static function update($revToReplace) { return new WriteMode(array("parent_rev" => $revToReplace)); } /** * Check that a function argument is of type WriteMode. * * @internal */ static function checkArg($argName, $argValue) { if (!($argValue instanceof self)) Checker::throwError($argName, $argValue, __CLASS__); } /** * Check that a function argument is either null or of type * WriteMode. * * @internal */ static function checkArgOrNull($argName, $argValue) { if ($argValue === null) return; if (!($argValue instanceof self)) Checker::throwError($argName, $argValue, __CLASS__); } } key = $key; $this->secret = $secret; $this->callback_url = $callback_url; } function __toString() { return "Consumer[key=$this->key,secret=$this->secret]"; } } get_signature_base_string(); $request->base_string = $base_string; $key_parts = array( $consumer->secret, ($token) ? $token->secret : "" ); $key_parts = Util::urlencode_rfc3986($key_parts); $key = implode('&', $key_parts); return base64_encode(hash_hmac('sha1', $base_string, $key, true)); } } data_store = $data_store; } public function add_signature_method($signature_method) { $this->signature_methods[$signature_method->get_name()] = $signature_method; } // high level functions /** * process a request_token request * returns the request token on success */ public function fetch_request_token(&$request) { $this->get_version($request); $consumer = $this->get_consumer($request); // no token required for the initial token request $token = NULL; $this->check_signature($request, $consumer, $token); // Rev A change $callback = $request->get_parameter('oauth_callback'); $new_token = $this->data_store->new_request_token($consumer, $callback); return $new_token; } /** * process an access_token request * returns the access token on success */ public function fetch_access_token(&$request) { $this->get_version($request); $consumer = $this->get_consumer($request); // requires authorized request token $token = $this->get_token($request, $consumer, "request"); $this->check_signature($request, $consumer, $token); // Rev A change $verifier = $request->get_parameter('oauth_verifier'); $new_token = $this->data_store->new_access_token($token, $consumer, $verifier); return $new_token; } /** * verify an api call, checks all the parameters */ public function verify_request(&$request) { $this->get_version($request); $consumer = $this->get_consumer($request); $token = $this->get_token($request, $consumer, "access"); $this->check_signature($request, $consumer, $token); return array($consumer, $token); } // Internals from here /** * version 1 */ private function get_version(&$request) { $version = $request->get_parameter("oauth_version"); if (!$version) { // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present. // Chapter 7.0 ("Accessing Protected Ressources") $version = '1.0'; } if ($version !== $this->version) { throw new OAuthException("OAuth version '$version' not supported"); } return $version; } /** * figure out the signature with some defaults */ private function get_signature_method($request) { $signature_method = $request instanceof Request ? $request->get_parameter("oauth_signature_method") : NULL; if (!$signature_method) { // According to chapter 7 ("Accessing Protected Ressources") the signature-method // parameter is required, and we can't just fallback to PLAINTEXT throw new OAuthException('No signature method parameter. This parameter is required'); } if (!in_array($signature_method, array_keys($this->signature_methods))) { throw new OAuthException( "Signature method '$signature_method' not supported " . "try one of the following: " . implode(", ", array_keys($this->signature_methods)) ); } return $this->signature_methods[$signature_method]; } /** * try to find the consumer for the provided request's consumer key */ private function get_consumer($request) { $consumer_key = $request instanceof Request ? $request->get_parameter("oauth_consumer_key") : NULL; if (!$consumer_key) { throw new OAuthException("Invalid consumer key"); } $consumer = $this->data_store->lookup_consumer($consumer_key); if (!$consumer) { throw new OAuthException("Invalid consumer"); } return $consumer; } /** * try to find the token for the provided request's token key */ private function get_token($request, $consumer, $token_type="access") { $token_field = $request instanceof Request ? $request->get_parameter('oauth_token') : NULL; $token = $this->data_store->lookup_token( $consumer, $token_type, $token_field ); if (!$token) { throw new OAuthException("Invalid $token_type token: $token_field"); } return $token; } /** * all-in-one function to check the signature on a request * should guess the signature method appropriately */ private function check_signature($request, $consumer, $token) { // this should probably be in a different method $timestamp = $request instanceof Request ? $request->get_parameter('oauth_timestamp') : NULL; $nonce = $request instanceof Request ? $request->get_parameter('oauth_nonce') : NULL; $this->check_timestamp($timestamp); $this->check_nonce($consumer, $token, $nonce, $timestamp); $signature_method = $this->get_signature_method($request); $signature = $request->get_parameter('oauth_signature'); $valid_sig = $signature_method->check_signature( $request, $consumer, $token, Util::urldecode_rfc3986($signature) ); if (!$valid_sig) { throw new OAuthException("Invalid signature"); } } /** * check that the timestamp is new enough */ private function check_timestamp($timestamp) { if( ! $timestamp ) throw new OAuthException( 'Missing timestamp parameter. The parameter is required' ); // verify that timestamp is recentish $now = time(); if (abs($now - $timestamp) > $this->timestamp_threshold) { throw new OAuthException( "Expired timestamp, yours $timestamp, ours $now" ); } } /** * check that the nonce is not repeated */ private function check_nonce($consumer, $token, $nonce, $timestamp) { if( ! $nonce ) throw new OAuthException( 'Missing nonce parameter. The parameter is required' ); // verify that the nonce is uniqueish $found = $this->data_store->lookup_nonce( $consumer, $token, $nonce, $timestamp ); if ($found) { throw new OAuthException("Nonce already used: $nonce"); } } } secret, ($token) ? $token->secret : "" ); $key_parts = Util::urlencode_rfc3986($key_parts); $key = implode('&', $key_parts); $request->base_string = $key; return $key; } } parameters = $parameters; $this->http_method = $http_method; $this->http_url = $http_url; } /** * attempt to build up a request from what was passed to the server */ public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) { $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") ? 'http' : 'https'; $http_url = ($http_url) ? $http_url : $scheme . '://' . $_SERVER['HTTP_HOST'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI']; $http_method = ($http_method) ? $http_method : $_SERVER['REQUEST_METHOD']; // We weren't handed any parameters, so let's find the ones relevant to // this request. // If you run XML-RPC or similar you should use this to provide your own // parsed parameter-list if (!$parameters) { // Find request headers $request_headers = Util::get_headers(); // Parse the query-string to find GET parameters $parameters = Util::parse_parameters($_SERVER['QUERY_STRING']); // It's a POST request of the proper content-type, so parse POST // parameters and add those overriding any duplicates from GET if ($http_method == "POST" && isset($request_headers['Content-Type']) && strstr($request_headers['Content-Type'], 'application/x-www-form-urlencoded') ) { $post_data = Util::parse_parameters( file_get_contents(self::$POST_INPUT) ); $parameters = array_merge($parameters, $post_data); } // We have a Authorization-header with OAuth data. Parse the header // and add those overriding any duplicates from GET or POST if (isset($request_headers['Authorization']) && substr($request_headers['Authorization'], 0, 6) == 'OAuth ') { $header_parameters = Util::split_header( $request_headers['Authorization'] ); $parameters = array_merge($parameters, $header_parameters); } } return new Request($http_method, $http_url, $parameters); } /** * pretty much a helper function to set up the request */ public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) { $parameters = ($parameters) ? $parameters : array(); $defaults = array("oauth_version" => Request::$version, "oauth_nonce" => Request::generate_nonce(), "oauth_timestamp" => Request::generate_timestamp(), "oauth_consumer_key" => $consumer->key); if ($token) $defaults['oauth_token'] = $token->key; $parameters = array_merge($defaults, $parameters); return new Request($http_method, $http_url, $parameters); } public function set_parameter($name, $value, $allow_duplicates = true) { if ($allow_duplicates && isset($this->parameters[$name])) { // We have already added parameter(s) with this name, so add to the list if (is_scalar($this->parameters[$name])) { // This is the first duplicate, so transform scalar (string) // into an array so we can add the duplicates $this->parameters[$name] = array($this->parameters[$name]); } $this->parameters[$name][] = $value; } else { $this->parameters[$name] = $value; } } public function get_parameter($name) { return isset($this->parameters[$name]) ? $this->parameters[$name] : null; } public function get_parameters() { return $this->parameters; } public function unset_parameter($name) { unset($this->parameters[$name]); } /** * The request parameters, sorted and concatenated into a normalized string. * @return string */ public function get_signable_parameters() { // Grab all parameters $params = $this->parameters; // Remove oauth_signature if present // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.") if (isset($params['oauth_signature'])) { unset($params['oauth_signature']); } return Util::build_http_query($params); } /** * Returns the base string of this request * * The base string defined as the method, the url * and the parameters (normalized), each urlencoded * and the concated with &. */ public function get_signature_base_string() { $parts = array( $this->get_normalized_http_method(), $this->get_normalized_http_url(), $this->get_signable_parameters() ); $parts = Util::urlencode_rfc3986($parts); return implode('&', $parts); } /** * just uppercases the http method */ public function get_normalized_http_method() { return strtoupper($this->http_method); } /** * parses the url and rebuilds it to be * scheme://host/path */ public function get_normalized_http_url() { $parts = parse_url($this->http_url); $scheme = (isset($parts['scheme'])) ? $parts['scheme'] : 'http'; $port = (isset($parts['port'])) ? $parts['port'] : (($scheme == 'https') ? '443' : '80'); $host = (isset($parts['host'])) ? $parts['host'] : ''; $path = (isset($parts['path'])) ? $parts['path'] : ''; if (($scheme == 'https' && $port != '443') || ($scheme == 'http' && $port != '80')) { $host = "$host:$port"; } return "$scheme://$host$path"; } /** * builds a url usable for a GET request */ public function to_url() { $post_data = $this->to_postdata(); $out = $this->get_normalized_http_url(); if ($post_data) { $out .= '?'.$post_data; } return $out; } /** * builds the data one would send in a POST request */ public function to_postdata() { return Util::build_http_query($this->parameters); } /** * builds the Authorization: header */ public function to_header($realm=null) { $first = true; if($realm) { $out = 'Authorization: OAuth realm="' . Util::urlencode_rfc3986($realm) . '"'; $first = false; } else $out = 'Authorization: OAuth'; $total = array(); foreach ($this->parameters as $k => $v) { if (substr($k, 0, 5) != "oauth") continue; if (is_array($v)) { throw new OAuthException('Arrays not supported in headers'); } $out .= ($first) ? ' ' : ','; $out .= Util::urlencode_rfc3986($k) . '="' . Util::urlencode_rfc3986($v) . '"'; $first = false; } return $out; } public function __toString() { return $this->to_url(); } public function sign_request($signature_method, $consumer, $token) { $this->set_parameter( "oauth_signature_method", $signature_method->get_name(), false ); $signature = $this->build_signature($signature_method, $consumer, $token); $this->set_parameter("oauth_signature", $signature, false); } public function build_signature($signature_method, $consumer, $token) { $signature = $signature_method->build_signature($this, $consumer, $token); return $signature; } /** * util function: current timestamp */ private static function generate_timestamp() { return time(); } /** * util function: current nonce */ private static function generate_nonce() { $mt = microtime(); $rand = mt_rand(); return md5($mt . $rand); // md5s look nicer than numbers } } get_signature_base_string(); $request->base_string = $base_string; // Fetch the private key cert based on the request $cert = $this->fetch_private_cert($request); // Pull the private key ID from the certificate $privatekeyid = openssl_get_privatekey($cert); // Sign using the key $ok = openssl_sign($base_string, $signature, $privatekeyid); // Release the key resource openssl_free_key($privatekeyid); return base64_encode($signature); } public function check_signature($request, $consumer, $token, $signature) { $decoded_sig = base64_decode($signature); $base_string = $request->get_signature_base_string(); // Fetch the public key cert based on the request $cert = $this->fetch_public_cert($request); // Pull the public key ID from the certificate $publickeyid = openssl_get_publickey($cert); // Check the computed signature against the one passed in the query $ok = openssl_verify($base_string, $decoded_sig, $publickeyid); // Release the key resource openssl_free_key($publickeyid); return $ok == 1; } } build_signature($request, $consumer, $token); return $built == $signature; } } key = $key; $this->secret = $secret; } /** * generates the basic string serialization of a token that a server * would respond to request_token and access_token calls with */ function to_string() { return "oauth_token=" . Util::urlencode_rfc3986($this->key) . "&oauth_token_secret=" . Util::urlencode_rfc3986($this->secret); } function __toString() { return $this->to_string(); } } $h) { $params[$h] = Util::urldecode_rfc3986(empty($matches[3][$i]) ? $matches[4][$i] : $matches[3][$i]); } if (isset($params['realm'])) { unset($params['realm']); } } return $params; } // helper to try to sort out headers for people who aren't running apache public static function get_headers() { if (function_exists('apache_request_headers')) { // we need this to get the actual Authorization: header // because apache tends to tell us it doesn't exist $headers = apache_request_headers(); // sanitize the output of apache_request_headers because // we always want the keys to be Cased-Like-This and arh() // returns the headers in the same case as they are in the // request $out = array(); foreach ($headers AS $key => $value) { $key = str_replace( " ", "-", ucwords(strtolower(str_replace("-", " ", $key))) ); $out[$key] = $value; } } else { // otherwise we don't have apache and are just going to have to hope // that $_SERVER actually contains what we need $out = array(); if( isset($_SERVER['CONTENT_TYPE']) ) $out['Content-Type'] = $_SERVER['CONTENT_TYPE']; if( isset($_ENV['CONTENT_TYPE']) ) $out['Content-Type'] = $_ENV['CONTENT_TYPE']; foreach ($_SERVER as $key => $value) { if (substr($key, 0, 5) == "HTTP_") { // this is chaos, basically it is just there to capitalize the first // letter of every word that is not an initial HTTP and strip HTTP // code from przemek $key = str_replace( " ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))) ); $out[$key] = $value; } } } return $out; } // This function takes a input like a=b&a=c&d=e and returns the parsed // parameters like this // array('a' => array('b','c'), 'd' => 'e') public static function parse_parameters( $input ) { if (!isset($input) || !$input) return array(); $pairs = explode('&', $input); $parsed_parameters = array(); foreach ($pairs as $pair) { $split = explode('=', $pair, 2); $parameter = Util::urldecode_rfc3986($split[0]); $value = isset($split[1]) ? Util::urldecode_rfc3986($split[1]) : ''; if (isset($parsed_parameters[$parameter])) { // We have already recieved parameter(s) with this name, so add to the list // of parameters with this name if (is_scalar($parsed_parameters[$parameter])) { // This is the first duplicate, so transform scalar (string) into an array // so we can add the duplicates $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]); } $parsed_parameters[$parameter][] = $value; } else { $parsed_parameters[$parameter] = $value; } } return $parsed_parameters; } public static function build_http_query($params) { if (!$params) return ''; // Urlencode both keys and values $keys = Util::urlencode_rfc3986(array_keys($params)); $values = Util::urlencode_rfc3986(array_values($params)); $params = array_combine($keys, $values); // Parameters are sorted by name, using lexicographical byte value ordering. // Ref: Spec: 9.1.1 (1) uksort($params, 'strcmp'); $pairs = array(); foreach ($params as $parameter => $value) { if (is_array($value)) { // If two or more parameters share the same name, they are sorted by their value // Ref: Spec: 9.1.1 (1) // June 12th, 2010 - changed to sort because of issue 164 by hidetaka sort($value, SORT_STRING); foreach ($value as $duplicate_value) { $pairs[] = $parameter . '=' . $duplicate_value; } } else { $pairs[] = $parameter . '=' . $value; } } // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61) // Each name-value pair is separated by an '&' character (ASCII code 38) return implode('&', $pairs); } } decoratedBatch = $decoratedBatch; } /** * Allow decorators to implement custom methods * * @param string $method Missing method name * @param array $args Method arguments * * @return mixed * @codeCoverageIgnore */ public function __call($method, array $args) { return call_user_func_array(array($this->decoratedBatch, $method), $args); } public function add($item) { $this->decoratedBatch->add($item); return $this; } public function flush() { return $this->decoratedBatch->flush(); } public function isEmpty() { return $this->decoratedBatch->isEmpty(); } /** * Trace the decorators associated with the batch * * @return array */ public function getDecorators() { $found = array($this); if (method_exists($this->decoratedBatch, 'getDecorators')) { $found = array_merge($found, $this->decoratedBatch->getDecorators()); } return $found; } } transferStrategy = $transferStrategy; $this->divisionStrategy = $divisionStrategy; $this->queue = new \SplQueue(); $this->queue->setIteratorMode(\SplQueue::IT_MODE_DELETE); $this->dividedBatches = array(); } public function add($item) { $this->queue->enqueue($item); return $this; } public function flush() { $this->createBatches(); $items = array(); foreach ($this->dividedBatches as $batchIndex => $dividedBatch) { while ($dividedBatch->valid()) { $batch = $dividedBatch->current(); $dividedBatch->next(); try { $this->transferStrategy->transfer($batch); $items = array_merge($items, $batch); } catch (\Exception $e) { throw new BatchTransferException($batch, $items, $e, $this->transferStrategy, $this->divisionStrategy); } } // Keep the divided batch down to a minimum in case of a later exception unset($this->dividedBatches[$batchIndex]); } return $items; } public function isEmpty() { return count($this->queue) == 0 && count($this->dividedBatches) == 0; } /** * Create batches for any queued items */ protected function createBatches() { if (count($this->queue)) { if ($batches = $this->divisionStrategy->createBatches($this->queue)) { // Convert arrays into iterators if (is_array($batches)) { $batches = new \ArrayIterator($batches); } $this->dividedBatches[] = $batches; } } } } 'Guzzle\Batch\BatchRequestTransfer', 'command' => 'Guzzle\Batch\BatchCommandTransfer' ); /** * Create a new instance of the BatchBuilder * * @return BatchBuilder */ public static function factory() { return new self(); } /** * Automatically flush the batch when the size of the queue reaches a certain threshold. Adds {@see FlushingBatch}. * * @param $threshold Number of items to allow in the queue before a flush * * @return BatchBuilder */ public function autoFlushAt($threshold) { $this->autoFlush = $threshold; return $this; } /** * Maintain a history of all items that have been transferred using the batch. Adds {@see HistoryBatch}. * * @return BatchBuilder */ public function keepHistory() { $this->history = true; return $this; } /** * Buffer exceptions thrown during transfer so that you can transfer as much as possible, and after a transfer * completes, inspect each exception that was thrown. Enables the {@see ExceptionBufferingBatch} decorator. * * @return BatchBuilder */ public function bufferExceptions() { $this->exceptionBuffering = true; return $this; } /** * Notify a callable each time a batch flush completes. Enables the {@see NotifyingBatch} decorator. * * @param mixed $callable Callable function to notify * * @return BatchBuilder * @throws InvalidArgumentException if the argument is not callable */ public function notify($callable) { $this->afterFlush = $callable; return $this; } /** * Configures the batch to transfer batches of requests. Associates a {@see \Guzzle\Http\BatchRequestTransfer} * object as both the transfer and divisor strategy. * * @param int $batchSize Batch size for each batch of requests * * @return BatchBuilder */ public function transferRequests($batchSize = 50) { $className = self::$mapping['request']; $this->transferStrategy = new $className($batchSize); $this->divisorStrategy = $this->transferStrategy; return $this; } /** * Configures the batch to transfer batches commands. Associates as * {@see \Guzzle\Service\Command\BatchCommandTransfer} as both the transfer and divisor strategy. * * @param int $batchSize Batch size for each batch of commands * * @return BatchBuilder */ public function transferCommands($batchSize = 50) { $className = self::$mapping['command']; $this->transferStrategy = new $className($batchSize); $this->divisorStrategy = $this->transferStrategy; return $this; } /** * Specify the strategy used to divide the queue into an array of batches * * @param BatchDivisorInterface $divisorStrategy Strategy used to divide a batch queue into batches * * @return BatchBuilder */ public function createBatchesWith(BatchDivisorInterface $divisorStrategy) { $this->divisorStrategy = $divisorStrategy; return $this; } /** * Specify the strategy used to transport the items when flush is called * * @param BatchTransferInterface $transferStrategy How items are transferred * * @return BatchBuilder */ public function transferWith(BatchTransferInterface $transferStrategy) { $this->transferStrategy = $transferStrategy; return $this; } /** * Create and return the instantiated batch * * @return BatchInterface * @throws RuntimeException if no transfer strategy has been specified */ public function build() { if (!$this->transferStrategy) { throw new RuntimeException('No transfer strategy has been specified'); } if (!$this->divisorStrategy) { throw new RuntimeException('No divisor strategy has been specified'); } $batch = new Batch($this->transferStrategy, $this->divisorStrategy); if ($this->exceptionBuffering) { $batch = new ExceptionBufferingBatch($batch); } if ($this->afterFlush) { $batch = new NotifyingBatch($batch, $this->afterFlush); } if ($this->autoFlush) { $batch = new FlushingBatch($batch, $this->autoFlush); } if ($this->history) { $batch = new HistoryBatch($batch); } return $batch; } } callable = $callable; $this->context = $context; } public function createBatches(\SplQueue $queue) { return call_user_func($this->callable, $queue, $this->context); } } callable = $callable; $this->context = $context; } public function transfer(array $batch) { return empty($batch) ? null : call_user_func($this->callable, $batch, $this->context); } } batchSize = $batchSize; } /** * Creates batches by grouping commands by their associated client * {@inheritdoc} */ public function createBatches(\SplQueue $queue) { $groups = new \SplObjectStorage(); foreach ($queue as $item) { if (!$item instanceof CommandInterface) { throw new InvalidArgumentException('All items must implement Guzzle\Service\Command\CommandInterface'); } $client = $item->getClient(); if (!$groups->contains($client)) { $groups->attach($client, new \ArrayObject(array($item))); } else { $groups[$client]->append($item); } } $batches = array(); foreach ($groups as $batch) { $batches = array_merge($batches, array_chunk($groups[$batch]->getArrayCopy(), $this->batchSize)); } return $batches; } public function transfer(array $batch) { if (empty($batch)) { return; } // Get the client of the first found command $client = reset($batch)->getClient(); // Keep a list of all commands with invalid clients $invalid = array_filter($batch, function ($command) use ($client) { return $command->getClient() !== $client; }); if (!empty($invalid)) { throw new InconsistentClientTransferException($invalid); } $client->execute($batch); } } batchSize = $batchSize; } /** * Creates batches of requests by grouping requests by their associated curl multi object. * {@inheritdoc} */ public function createBatches(\SplQueue $queue) { // Create batches by client objects $groups = new \SplObjectStorage(); foreach ($queue as $item) { if (!$item instanceof RequestInterface) { throw new InvalidArgumentException('All items must implement Guzzle\Http\Message\RequestInterface'); } $client = $item->getClient(); if (!$groups->contains($client)) { $groups->attach($client, array($item)); } else { $current = $groups[$client]; $current[] = $item; $groups[$client] = $current; } } $batches = array(); foreach ($groups as $batch) { $batches = array_merge($batches, array_chunk($groups[$batch], $this->batchSize)); } return $batches; } public function transfer(array $batch) { if ($batch) { reset($batch)->getClient()->send($batch); } } } size = $size; } /** * Set the size of each batch * * @param int $size Size of each batch * * @return BatchSizeDivisor */ public function setSize($size) { $this->size = $size; return $this; } /** * Get the size of each batch * * @return int */ public function getSize() { return $this->size; } public function createBatches(\SplQueue $queue) { return array_chunk(iterator_to_array($queue, false), $this->size); } } batch = $batch; $this->transferredItems = $transferredItems; $this->transferStrategy = $transferStrategy; $this->divisorStrategy = $divisorStrategy; parent::__construct( 'Exception encountered while transferring batch: ' . $exception->getMessage(), $exception->getCode(), $exception ); } /** * Get the batch that we being sent when the exception occurred * * @return array */ public function getBatch() { return $this->batch; } /** * Get the items transferred at the point in which the exception was encountered * * @return array */ public function getTransferredItems() { return $this->transferredItems; } /** * Get the transfer strategy * * @return TransferStrategy */ public function getTransferStrategy() { return $this->transferStrategy; } /** * Get the divisor strategy * * @return DivisorStrategy */ public function getDivisorStrategy() { return $this->divisorStrategy; } } decoratedBatch->isEmpty()) { try { $transferredItems = $this->decoratedBatch->flush(); } catch (BatchTransferException $e) { $this->exceptions[] = $e; $transferredItems = $e->getTransferredItems(); } $items = array_merge($items, $transferredItems); } return $items; } /** * Get the buffered exceptions * * @return array Array of BatchTransferException objects */ public function getExceptions() { return $this->exceptions; } /** * Clear the buffered exceptions */ public function clearExceptions() { $this->exceptions = array(); } } threshold = $threshold; parent::__construct($decoratedBatch); } /** * Set the auto-flush threshold * * @param int $threshold The auto-flush threshold * * @return FlushingBatch */ public function setThreshold($threshold) { $this->threshold = $threshold; return $this; } /** * Get the auto-flush threshold * * @return int */ public function getThreshold() { return $this->threshold; } public function add($item) { $this->decoratedBatch->add($item); if (++$this->currentTotal >= $this->threshold) { $this->currentTotal = 0; $this->decoratedBatch->flush(); } return $this; } } history[] = $item; $this->decoratedBatch->add($item); return $this; } /** * Get the batch history * * @return array */ public function getHistory() { return $this->history; } /** * Clear the batch history */ public function clearHistory() { $this->history = array(); } } callable = $callable; parent::__construct($decoratedBatch); } public function flush() { $items = $this->decoratedBatch->flush(); call_user_func($this->callable, $items); return $items; } } cache; } } newInstanceArgs($args); } } catch (\Exception $e) { throw new RuntimeException($e->getMessage(), $e->getCode(), $e); } } } callables = $callables; } public function contains($id, array $options = null) { return call_user_func($this->callables['contains'], $id, $options); } public function delete($id, array $options = null) { return call_user_func($this->callables['delete'], $id, $options); } public function fetch($id, array $options = null) { return call_user_func($this->callables['fetch'], $id, $options); } public function save($id, $data, $lifeTime = false, array $options = null) { return call_user_func($this->callables['save'], $id, $data, $lifeTime, $options); } } cache = $cache; } public function contains($id, array $options = null) { return $this->cache->contains($id); } public function delete($id, array $options = null) { return $this->cache->delete($id); } public function fetch($id, array $options = null) { return $this->cache->fetch($id); } public function save($id, $data, $lifeTime = false, array $options = null) { return $this->cache->save($id, $data, $lifeTime); } } cache = $cache; } public function contains($id, array $options = null) { return $this->cache->test($id); } public function delete($id, array $options = null) { return $this->cache->remove($id); } public function fetch($id, array $options = null) { return $this->cache->load($id); } public function save($id, $data, $lifeTime = false, array $options = null) { return $this->cache->save($data, $id, array(), $lifeTime); } } cache = $cache; } public function contains($id, array $options = null) { return $this->cache->hasItem($id); } public function delete($id, array $options = null) { return $this->cache->removeItem($id); } public function fetch($id, array $options = null) { return $this->cache->getItem($id); } public function save($id, $data, $lifeTime = false, array $options = null) { return $this->cache->setItem($id, $data); } } eventDispatcher = $eventDispatcher; return $this; } public function getEventDispatcher() { if (!$this->eventDispatcher) { $this->eventDispatcher = new EventDispatcher(); } return $this->eventDispatcher; } public function dispatch($eventName, array $context = array()) { return $this->getEventDispatcher()->dispatch($eventName, new Event($context)); } public function addSubscriber(EventSubscriberInterface $subscriber) { $this->getEventDispatcher()->addSubscriber($subscriber); return $this; } } data = $data; } /** * Create a new collection from an array, validate the keys, and add default values where missing * * @param array $config Configuration values to apply. * @param array $defaults Default parameters * @param array $required Required parameter names * * @return self * @throws InvalidArgumentException if a parameter is missing */ public static function fromConfig(array $config = array(), array $defaults = array(), array $required = array()) { $data = $config + $defaults; if ($missing = array_diff($required, array_keys($data))) { throw new InvalidArgumentException('Config is missing the following keys: ' . implode(', ', $missing)); } return new self($data); } public function count() { return count($this->data); } public function getIterator() { return new \ArrayIterator($this->data); } public function toArray() { return $this->data; } /** * Removes all key value pairs * * @return Collection */ public function clear() { $this->data = array(); return $this; } /** * Get all or a subset of matching key value pairs * * @param array $keys Pass an array of keys to retrieve only a subset of key value pairs * * @return array Returns an array of all matching key value pairs */ public function getAll(array $keys = null) { return $keys ? array_intersect_key($this->data, array_flip($keys)) : $this->data; } /** * Get a specific key value. * * @param string $key Key to retrieve. * * @return mixed|null Value of the key or NULL */ public function get($key) { return isset($this->data[$key]) ? $this->data[$key] : null; } /** * Set a key value pair * * @param string $key Key to set * @param mixed $value Value to set * * @return Collection Returns a reference to the object */ public function set($key, $value) { $this->data[$key] = $value; return $this; } /** * Add a value to a key. If a key of the same name has already been added, the key value will be converted into an * array and the new value will be pushed to the end of the array. * * @param string $key Key to add * @param mixed $value Value to add to the key * * @return Collection Returns a reference to the object. */ public function add($key, $value) { if (!array_key_exists($key, $this->data)) { $this->data[$key] = $value; } elseif (is_array($this->data[$key])) { $this->data[$key][] = $value; } else { $this->data[$key] = array($this->data[$key], $value); } return $this; } /** * Remove a specific key value pair * * @param string $key A key to remove * * @return Collection */ public function remove($key) { unset($this->data[$key]); return $this; } /** * Get all keys in the collection * * @return array */ public function getKeys() { return array_keys($this->data); } /** * Returns whether or not the specified key is present. * * @param string $key The key for which to check the existence. * * @return bool */ public function hasKey($key) { return array_key_exists($key, $this->data); } /** * Case insensitive search the keys in the collection * * @param string $key Key to search for * * @return bool|string Returns false if not found, otherwise returns the key */ public function keySearch($key) { foreach (array_keys($this->data) as $k) { if (!strcasecmp($k, $key)) { return $k; } } return false; } /** * Checks if any keys contains a certain value * * @param string $value Value to search for * * @return mixed Returns the key if the value was found FALSE if the value was not found. */ public function hasValue($value) { return array_search($value, $this->data); } /** * Replace the data of the object with the value of an array * * @param array $data Associative array of data * * @return Collection Returns a reference to the object */ public function replace(array $data) { $this->data = $data; return $this; } /** * Add and merge in a Collection or array of key value pair data. * * @param Collection|array $data Associative array of key value pair data * * @return Collection Returns a reference to the object. */ public function merge($data) { foreach ($data as $key => $value) { $this->add($key, $value); } return $this; } /** * Over write key value pairs in this collection with all of the data from an array or collection. * * @param array|\Traversable $data Values to override over this config * * @return self */ public function overwriteWith($data) { if (is_array($data)) { $this->data = $data + $this->data; } elseif ($data instanceof Collection) { $this->data = $data->toArray() + $this->data; } else { foreach ($data as $key => $value) { $this->data[$key] = $value; } } return $this; } /** * Returns a Collection containing all the elements of the collection after applying the callback function to each * one. The Closure should accept three parameters: (string) $key, (string) $value, (array) $context and return a * modified value * * @param \Closure $closure Closure to apply * @param array $context Context to pass to the closure * @param bool $static Set to TRUE to use the same class as the return rather than returning a Collection * * @return Collection */ public function map(\Closure $closure, array $context = array(), $static = true) { $collection = $static ? new static() : new self(); foreach ($this as $key => $value) { $collection->add($key, $closure($key, $value, $context)); } return $collection; } /** * Iterates over each key value pair in the collection passing them to the Closure. If the Closure function returns * true, the current value from input is returned into the result Collection. The Closure must accept three * parameters: (string) $key, (string) $value and return Boolean TRUE or FALSE for each value. * * @param \Closure $closure Closure evaluation function * @param bool $static Set to TRUE to use the same class as the return rather than returning a Collection * * @return Collection */ public function filter(\Closure $closure, $static = true) { $collection = ($static) ? new static() : new self(); foreach ($this->data as $key => $value) { if ($closure($key, $value)) { $collection->add($key, $value); } } return $collection; } public function offsetExists($offset) { return isset($this->data[$offset]); } public function offsetGet($offset) { return isset($this->data[$offset]) ? $this->data[$offset] : null; } public function offsetSet($offset, $value) { $this->data[$offset] = $value; } public function offsetUnset($offset) { unset($this->data[$offset]); } /** * Set a value into a nested array key. Keys will be created as needed to set the value. * * @param string $path Path to set * @param mixed $value Value to set at the key * * @return self * @throws RuntimeException when trying to setPath using a nested path that travels through a scalar value */ public function setPath($path, $value) { $current =& $this->data; $queue = explode('/', $path); while (null !== ($key = array_shift($queue))) { if (!is_array($current)) { throw new RuntimeException("Trying to setPath {$path}, but {$key} is set and is not an array"); } elseif (!$queue) { $current[$key] = $value; } elseif (isset($current[$key])) { $current =& $current[$key]; } else { $current[$key] = array(); $current =& $current[$key]; } } return $this; } /** * Gets a value from the collection using an array path (e.g. foo/baz/bar would retrieve bar from two nested arrays) * Allows for wildcard searches which recursively combine matches up to the level at which the wildcard occurs. This * can be useful for accepting any key of a sub-array and combining matching keys from each diverging path. * * @param string $path Path to traverse and retrieve a value from * @param string $separator Character used to add depth to the search * @param mixed $data Optional data to descend into (used when wildcards are encountered) * * @return mixed|null */ public function getPath($path, $separator = '/', $data = null) { if ($data === null) { $data =& $this->data; } $path = is_array($path) ? $path : explode($separator, $path); while (null !== ($part = array_shift($path))) { if (!is_array($data)) { return null; } elseif (isset($data[$part])) { $data =& $data[$part]; } elseif ($part != '*') { return null; } else { // Perform a wildcard search by diverging and merging paths $result = array(); foreach ($data as $value) { if (!$path) { $result = array_merge_recursive($result, (array) $value); } elseif (null !== ($test = $this->getPath($path, $separator, $value))) { $result = array_merge_recursive($result, (array) $test); } } return $result; } } return $data; } /** * Inject configuration settings into an input string * * @param string $input Input to inject * * @return string * @deprecated */ public function inject($input) { Version::warn(__METHOD__ . ' is deprecated'); $replace = array(); foreach ($this->data as $key => $val) { $replace['{' . $key . '}'] = $val; } return strtr($input, $replace); } } context = $context; } public function getIterator() { return new \ArrayIterator($this->context); } public function offsetGet($offset) { return isset($this->context[$offset]) ? $this->context[$offset] : null; } public function offsetSet($offset, $value) { $this->context[$offset] = $value; } public function offsetExists($offset) { return isset($this->context[$offset]); } public function offsetUnset($offset) { unset($this->context[$offset]); } public function toArray() { return $this->context; } } shortMessage = $message; } /** * Set all of the exceptions * * @param array $exceptions Array of exceptions * * @return self */ public function setExceptions(array $exceptions) { $this->exceptions = array(); foreach ($exceptions as $exception) { $this->add($exception); } return $this; } /** * Add exceptions to the collection * * @param ExceptionCollection|\Exception $e Exception to add * * @return ExceptionCollection; */ public function add($e) { $this->exceptions[] = $e; if ($this->message) { $this->message .= "\n"; } $this->message .= $this->getExceptionMessage($e, 0); return $this; } /** * Get the total number of request exceptions * * @return int */ public function count() { return count($this->exceptions); } /** * Allows array-like iteration over the request exceptions * * @return \ArrayIterator */ public function getIterator() { return new \ArrayIterator($this->exceptions); } /** * Get the first exception in the collection * * @return \Exception */ public function getFirst() { return $this->exceptions ? $this->exceptions[0] : null; } private function getExceptionMessage(\Exception $e, $depth = 0) { static $sp = ' '; $prefix = $depth ? str_repeat($sp, $depth) : ''; $message = "{$prefix}(" . get_class($e) . ') ' . $e->getFile() . ' line ' . $e->getLine() . "\n"; if ($e instanceof self) { if ($e->shortMessage) { $message .= "\n{$prefix}{$sp}" . str_replace("\n", "\n{$prefix}{$sp}", $e->shortMessage) . "\n"; } foreach ($e as $ee) { $message .= "\n" . $this->getExceptionMessage($ee, $depth + 1); } } else { $message .= "\n{$prefix}{$sp}" . str_replace("\n", "\n{$prefix}{$sp}", $e->getMessage()) . "\n"; $message .= "\n{$prefix}{$sp}" . str_replace("\n", "\n{$prefix}{$sp}", $e->getTraceAsString()) . "\n"; } return str_replace(getcwd(), '.', $message); } } body = $body; } public function __toString() { return (string) $this->body; } /** * Allow decorators to implement custom methods * * @param string $method Missing method name * @param array $args Method arguments * * @return mixed */ public function __call($method, array $args) { return call_user_func_array(array($this->body, $method), $args); } public function close() { return $this->body->close(); } public function setRewindFunction($callable) { $this->body->setRewindFunction($callable); return $this; } public function rewind() { return $this->body->rewind(); } public function compress($filter = 'zlib.deflate') { return $this->body->compress($filter); } public function uncompress($filter = 'zlib.inflate') { return $this->body->uncompress($filter); } public function getContentLength() { return $this->getSize(); } public function getContentType() { return $this->body->getContentType(); } public function getContentMd5($rawOutput = false, $base64Encode = false) { $hash = Stream::getHash($this, 'md5', $rawOutput); return $hash && $base64Encode ? base64_encode($hash) : $hash; } public function getContentEncoding() { return $this->body->getContentEncoding(); } public function getMetaData($key = null) { return $this->body->getMetaData($key); } public function getStream() { return $this->body->getStream(); } public function setStream($stream, $size = 0) { $this->body->setStream($stream, $size); return $this; } public function detachStream() { $this->body->detachStream(); return $this; } public function getWrapper() { return $this->body->getWrapper(); } public function getWrapperData() { return $this->body->getWrapperData(); } public function getStreamType() { return $this->body->getStreamType(); } public function getUri() { return $this->body->getUri(); } public function getSize() { return $this->body->getSize(); } public function isReadable() { return $this->body->isReadable(); } public function isRepeatable() { return $this->isSeekable() && $this->isReadable(); } public function isWritable() { return $this->body->isWritable(); } public function isConsumed() { return $this->body->isConsumed(); } /** * Alias of isConsumed() * {@inheritdoc} */ public function feof() { return $this->isConsumed(); } public function isLocal() { return $this->body->isLocal(); } public function isSeekable() { return $this->body->isSeekable(); } public function setSize($size) { $this->body->setSize($size); return $this; } public function seek($offset, $whence = SEEK_SET) { return $this->body->seek($offset, $whence); } public function read($length) { return $this->body->read($length); } public function write($string) { return $this->body->write($string); } public function readLine($maxLength = null) { return $this->body->readLine($maxLength); } public function ftell() { return $this->body->ftell(); } public function getCustomData($key) { return $this->body->getCustomData($key); } public function setCustomData($key, $value) { $this->body->setCustomData($key, $value); return $this; } } remoteStream = $body; $this->body = new EntityBody(fopen('php://temp', 'r+')); } /** * Will give the contents of the buffer followed by the exhausted remote stream. * * Warning: Loads the entire stream into memory * * @return string */ public function __toString() { $pos = $this->ftell(); $this->rewind(); $str = ''; while (!$this->isConsumed()) { $str .= $this->read(16384); } $this->seek($pos); return $str; } public function getSize() { return max($this->body->getSize(), $this->remoteStream->getSize()); } /** * {@inheritdoc} * @throws RuntimeException When seeking with SEEK_END or when seeking past the total size of the buffer stream */ public function seek($offset, $whence = SEEK_SET) { if ($whence == SEEK_SET) { $byte = $offset; } elseif ($whence == SEEK_CUR) { $byte = $offset + $this->ftell(); } else { throw new RuntimeException(__CLASS__ . ' supports only SEEK_SET and SEEK_CUR seek operations'); } // You cannot skip ahead past where you've read from the remote stream if ($byte > $this->body->getSize()) { throw new RuntimeException( "Cannot seek to byte {$byte} when the buffered stream only contains {$this->body->getSize()} bytes" ); } return $this->body->seek($byte); } public function rewind() { return $this->seek(0); } /** * Does not support custom rewind functions * * @throws RuntimeException */ public function setRewindFunction($callable) { throw new RuntimeException(__CLASS__ . ' does not support custom stream rewind functions'); } public function read($length) { // Perform a regular read on any previously read data from the buffer $data = $this->body->read($length); $remaining = $length - strlen($data); // More data was requested so read from the remote stream if ($remaining) { // If data was written to the buffer in a position that would have been filled from the remote stream, // then we must skip bytes on the remote stream to emulate overwriting bytes from that position. This // mimics the behavior of other PHP stream wrappers. $remoteData = $this->remoteStream->read($remaining + $this->skipReadBytes); if ($this->skipReadBytes) { $len = strlen($remoteData); $remoteData = substr($remoteData, $this->skipReadBytes); $this->skipReadBytes = max(0, $this->skipReadBytes - $len); } $data .= $remoteData; $this->body->write($remoteData); } return $data; } public function write($string) { // When appending to the end of the currently read stream, you'll want to skip bytes from being read from // the remote stream to emulate other stream wrappers. Basically replacing bytes of data of a fixed length. $overflow = (strlen($string) + $this->ftell()) - $this->remoteStream->ftell(); if ($overflow > 0) { $this->skipReadBytes += $overflow; } return $this->body->write($string); } /** * {@inheritdoc} * @link http://php.net/manual/en/function.fgets.php */ public function readLine($maxLength = null) { $buffer = ''; $size = 0; while (!$this->isConsumed()) { $byte = $this->read(1); $buffer .= $byte; // Break when a new line is found or the max length - 1 is reached if ($byte == PHP_EOL || ++$size == $maxLength - 1) { break; } } return $buffer; } public function isConsumed() { return $this->body->isConsumed() && $this->remoteStream->isConsumed(); } /** * Close both the remote stream and buffer stream */ public function close() { return $this->remoteStream->close() && $this->body->close(); } public function setStream($stream, $size = 0) { $this->remoteStream->setStream($stream, $size); } public function getContentType() { return $this->remoteStream->getContentType(); } public function getContentEncoding() { return $this->remoteStream->getContentEncoding(); } public function getMetaData($key = null) { return $this->remoteStream->getMetaData($key); } public function getStream() { return $this->remoteStream->getStream(); } public function getWrapper() { return $this->remoteStream->getWrapper(); } public function getWrapperData() { return $this->remoteStream->getWrapperData(); } public function getStreamType() { return $this->remoteStream->getStreamType(); } public function getUri() { return $this->remoteStream->getUri(); } /** * Always retrieve custom data from the remote stream * {@inheritdoc} */ public function getCustomData($key) { return $this->remoteStream->getCustomData($key); } /** * Always set custom data on the remote stream * {@inheritdoc} */ public function setCustomData($key, $value) { $this->remoteStream->setCustomData($key, $value); return $this; } } setConfig($config ?: new Collection()); $this->initSsl(); $this->setBaseUrl($baseUrl); $this->defaultHeaders = new Collection(); $this->setRequestFactory(RequestFactory::getInstance()); $this->userAgent = $this->getDefaultUserAgent(); if (!$this->config[self::DISABLE_REDIRECTS]) { $this->addSubscriber(new RedirectPlugin()); } } final public function setConfig($config) { if ($config instanceof Collection) { $this->config = $config; } elseif (is_array($config)) { $this->config = new Collection($config); } else { throw new InvalidArgumentException('Config must be an array or Collection'); } return $this; } final public function getConfig($key = false) { return $key ? $this->config[$key] : $this->config; } /** * Set a default request option on the client that will be used as a default for each request * * @param string $keyOrPath request.options key (e.g. allow_redirects) or path to a nested key (e.g. headers/foo) * @param mixed $value Value to set * * @return $this */ public function setDefaultOption($keyOrPath, $value) { $keyOrPath = self::REQUEST_OPTIONS . '/' . $keyOrPath; $this->config->setPath($keyOrPath, $value); return $this; } /** * Retrieve a default request option from the client * * @param string $keyOrPath request.options key (e.g. allow_redirects) or path to a nested key (e.g. headers/foo) * * @return mixed|null */ public function getDefaultOption($keyOrPath) { $keyOrPath = self::REQUEST_OPTIONS . '/' . $keyOrPath; return $this->config->getPath($keyOrPath); } final public function setSslVerification($certificateAuthority = true, $verifyPeer = true, $verifyHost = 2) { $opts = $this->config[self::CURL_OPTIONS] ?: array(); if ($certificateAuthority === true) { // use bundled CA bundle, set secure defaults $opts[CURLOPT_CAINFO] = __DIR__ . '/Resources/cacert.pem'; $opts[CURLOPT_SSL_VERIFYPEER] = true; $opts[CURLOPT_SSL_VERIFYHOST] = 2; } elseif ($certificateAuthority === false) { unset($opts[CURLOPT_CAINFO]); $opts[CURLOPT_SSL_VERIFYPEER] = false; $opts[CURLOPT_SSL_VERIFYHOST] = 0; } elseif ($verifyPeer !== true && $verifyPeer !== false && $verifyPeer !== 1 && $verifyPeer !== 0) { throw new InvalidArgumentException('verifyPeer must be 1, 0 or boolean'); } elseif ($verifyHost !== 0 && $verifyHost !== 1 && $verifyHost !== 2) { throw new InvalidArgumentException('verifyHost must be 0, 1 or 2'); } else { $opts[CURLOPT_SSL_VERIFYPEER] = $verifyPeer; $opts[CURLOPT_SSL_VERIFYHOST] = $verifyHost; if (is_file($certificateAuthority)) { unset($opts[CURLOPT_CAPATH]); $opts[CURLOPT_CAINFO] = $certificateAuthority; } elseif (is_dir($certificateAuthority)) { unset($opts[CURLOPT_CAINFO]); $opts[CURLOPT_CAPATH] = $certificateAuthority; } else { throw new RuntimeException( 'Invalid option passed to ' . self::SSL_CERT_AUTHORITY . ': ' . $certificateAuthority ); } } $this->config->set(self::CURL_OPTIONS, $opts); return $this; } public function createRequest($method = 'GET', $uri = null, $headers = null, $body = null, array $options = array()) { if (!$uri) { $url = $this->getBaseUrl(); } else { if (!is_array($uri)) { $templateVars = null; } else { list($uri, $templateVars) = $uri; } if (strpos($uri, '://')) { // Use absolute URLs as-is $url = $this->expandTemplate($uri, $templateVars); } else { $url = Url::factory($this->getBaseUrl())->combine($this->expandTemplate($uri, $templateVars)); } } // If default headers are provided, then merge them under any explicitly provided headers for the request if (count($this->defaultHeaders)) { if (!$headers) { $headers = $this->defaultHeaders->toArray(); } elseif (is_array($headers)) { $headers += $this->defaultHeaders->toArray(); } elseif ($headers instanceof Collection) { $headers = $headers->toArray() + $this->defaultHeaders->toArray(); } } return $this->prepareRequest($this->requestFactory->create($method, (string) $url, $headers, $body), $options); } public function getBaseUrl($expand = true) { return $expand ? $this->expandTemplate($this->baseUrl) : $this->baseUrl; } public function setBaseUrl($url) { $this->baseUrl = $url; return $this; } public function setUserAgent($userAgent, $includeDefault = false) { if ($includeDefault) { $userAgent .= ' ' . $this->getDefaultUserAgent(); } $this->userAgent = $userAgent; return $this; } /** * Get the default User-Agent string to use with Guzzle * * @return string */ public function getDefaultUserAgent() { return 'Guzzle/' . Version::VERSION . ' curl/' . CurlVersion::getInstance()->get('version') . ' PHP/' . PHP_VERSION; } public function get($uri = null, $headers = null, $options = array()) { // BC compat: $options can be a string, resource, etc to specify where the response body is downloaded return is_array($options) ? $this->createRequest('GET', $uri, $headers, null, $options) : $this->createRequest('GET', $uri, $headers, $options); } public function head($uri = null, $headers = null, array $options = array()) { return $this->createRequest('HEAD', $uri, $headers, null, $options); } public function delete($uri = null, $headers = null, $body = null, array $options = array()) { return $this->createRequest('DELETE', $uri, $headers, $body, $options); } public function put($uri = null, $headers = null, $body = null, array $options = array()) { return $this->createRequest('PUT', $uri, $headers, $body, $options); } public function patch($uri = null, $headers = null, $body = null, array $options = array()) { return $this->createRequest('PATCH', $uri, $headers, $body, $options); } public function post($uri = null, $headers = null, $postBody = null, array $options = array()) { return $this->createRequest('POST', $uri, $headers, $postBody, $options); } public function options($uri = null, array $options = array()) { return $this->createRequest('OPTIONS', $uri, $options); } public function send($requests) { if (!($requests instanceof RequestInterface)) { return $this->sendMultiple($requests); } try { /** @var $requests RequestInterface */ $this->getCurlMulti()->add($requests)->send(); return $requests->getResponse(); } catch (ExceptionCollection $e) { throw $e->getFirst(); } } /** * Set a curl multi object to be used internally by the client for transferring requests. * * @param CurlMultiInterface $curlMulti Multi object * * @return self */ public function setCurlMulti(CurlMultiInterface $curlMulti) { $this->curlMulti = $curlMulti; return $this; } /** * @return CurlMultiInterface|CurlMultiProxy */ public function getCurlMulti() { if (!$this->curlMulti) { $this->curlMulti = new CurlMultiProxy( self::MAX_HANDLES, $this->getConfig('select_timeout') ?: self::DEFAULT_SELECT_TIMEOUT ); } return $this->curlMulti; } public function setRequestFactory(RequestFactoryInterface $factory) { $this->requestFactory = $factory; return $this; } /** * Set the URI template expander to use with the client * * @param UriTemplateInterface $uriTemplate URI template expander * * @return self */ public function setUriTemplate(UriTemplateInterface $uriTemplate) { $this->uriTemplate = $uriTemplate; return $this; } /** * Expand a URI template while merging client config settings into the template variables * * @param string $template Template to expand * @param array $variables Variables to inject * * @return string */ protected function expandTemplate($template, array $variables = null) { $expansionVars = $this->getConfig()->toArray(); if ($variables) { $expansionVars = $variables + $expansionVars; } return $this->getUriTemplate()->expand($template, $expansionVars); } /** * Get the URI template expander used by the client * * @return UriTemplateInterface */ protected function getUriTemplate() { if (!$this->uriTemplate) { $this->uriTemplate = ParserRegistry::getInstance()->getParser('uri_template'); } return $this->uriTemplate; } /** * Send multiple requests in parallel * * @param array $requests Array of RequestInterface objects * * @return array Returns an array of Response objects */ protected function sendMultiple(array $requests) { $curlMulti = $this->getCurlMulti(); foreach ($requests as $request) { $curlMulti->add($request); } $curlMulti->send(); /** @var $request RequestInterface */ $result = array(); foreach ($requests as $request) { $result[] = $request->getResponse(); } return $result; } /** * Prepare a request to be sent from the Client by adding client specific behaviors and properties to the request. * * @param RequestInterface $request Request to prepare for the client * @param array $options Options to apply to the request * * @return RequestInterface */ protected function prepareRequest(RequestInterface $request, array $options = array()) { $request->setClient($this)->setEventDispatcher(clone $this->getEventDispatcher()); if ($curl = $this->config[self::CURL_OPTIONS]) { $request->getCurlOptions()->overwriteWith(CurlHandle::parseCurlConfig($curl)); } if ($params = $this->config[self::REQUEST_PARAMS]) { Version::warn('request.params is deprecated. Use request.options to add default request options.'); $request->getParams()->overwriteWith($params); } if ($this->userAgent && !$request->hasHeader('User-Agent')) { $request->setHeader('User-Agent', $this->userAgent); } if ($defaults = $this->config[self::REQUEST_OPTIONS]) { $this->requestFactory->applyOptions($request, $defaults, RequestFactoryInterface::OPTIONS_AS_DEFAULTS); } if ($options) { $this->requestFactory->applyOptions($request, $options); } $this->dispatch('client.create_request', array('client' => $this, 'request' => $request)); return $request; } /** * Initializes SSL settings */ protected function initSsl() { $authority = $this->config[self::SSL_CERT_AUTHORITY]; if ($authority === 'system') { return; } if ($authority === null) { $authority = true; } if ($authority === true && substr(__FILE__, 0, 7) == 'phar://') { $authority = self::extractPharCacert(__DIR__ . '/Resources/cacert.pem'); } $this->setSslVerification($authority); } /** * @deprecated */ public function getDefaultHeaders() { Version::warn(__METHOD__ . ' is deprecated. Use the request.options array to retrieve default request options'); return $this->defaultHeaders; } /** * @deprecated */ public function setDefaultHeaders($headers) { Version::warn(__METHOD__ . ' is deprecated. Use the request.options array to specify default request options'); if ($headers instanceof Collection) { $this->defaultHeaders = $headers; } elseif (is_array($headers)) { $this->defaultHeaders = new Collection($headers); } else { throw new InvalidArgumentException('Headers must be an array or Collection'); } return $this; } /** * @deprecated */ public function preparePharCacert($md5Check = true) { return sys_get_temp_dir() . '/guzzle-cacert.pem'; } /** * Copies the phar cacert from a phar into the temp directory. * * @param string $pharCacertPath Path to the phar cacert. For example: * 'phar://aws.phar/Guzzle/Http/Resources/cacert.pem' * * @return string Returns the path to the extracted cacert file. * @throws \RuntimeException Throws if the phar cacert cannot be found or * the file cannot be copied to the temp dir. */ public static function extractPharCacert($pharCacertPath) { // Copy the cacert.pem file from the phar if it is not in the temp // folder. $certFile = sys_get_temp_dir() . '/guzzle-cacert.pem'; if (!file_exists($pharCacertPath)) { throw new \RuntimeException("Could not find $pharCacertPath"); } if (!file_exists($certFile) || filesize($certFile) != filesize($pharCacertPath) ) { if (!copy($pharCacertPath, $certFile)) { throw new \RuntimeException( "Could not copy {$pharCacertPath} to {$certFile}: " . var_export(error_get_last(), true) ); } } return $certFile; } } getCurlOptions(); $mediator = new RequestMediator($request, $requestCurlOptions->get('emit_io')); $tempContentLength = null; $method = $request->getMethod(); $bodyAsString = $requestCurlOptions->get(self::BODY_AS_STRING); // Prepare url $url = (string)$request->getUrl(); if(($pos = strpos($url, '#')) !== false ){ // strip fragment from url $url = substr($url, 0, $pos); } // Array of default cURL options. $curlOptions = array( CURLOPT_URL => $url, CURLOPT_CONNECTTIMEOUT => 150, CURLOPT_RETURNTRANSFER => false, CURLOPT_HEADER => false, CURLOPT_PORT => $request->getPort(), CURLOPT_HTTPHEADER => array(), CURLOPT_WRITEFUNCTION => array($mediator, 'writeResponseBody'), CURLOPT_HEADERFUNCTION => array($mediator, 'receiveResponseHeader'), CURLOPT_HTTP_VERSION => $request->getProtocolVersion() === '1.0' ? CURL_HTTP_VERSION_1_0 : CURL_HTTP_VERSION_1_1, // Verifies the authenticity of the peer's certificate CURLOPT_SSL_VERIFYPEER => 1, // Certificate must indicate that the server is the server to which you meant to connect CURLOPT_SSL_VERIFYHOST => 2 ); if (defined('CURLOPT_PROTOCOLS')) { // Allow only HTTP and HTTPS protocols $curlOptions[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS; } // Add CURLOPT_ENCODING if Accept-Encoding header is provided if ($acceptEncodingHeader = $request->getHeader('Accept-Encoding')) { $curlOptions[CURLOPT_ENCODING] = (string) $acceptEncodingHeader; // Let cURL set the Accept-Encoding header, prevents duplicate values $request->removeHeader('Accept-Encoding'); } // Enable curl debug information if the 'debug' param was set if ($requestCurlOptions->get('debug')) { $curlOptions[CURLOPT_STDERR] = fopen('php://temp', 'r+'); // @codeCoverageIgnoreStart if (false === $curlOptions[CURLOPT_STDERR]) { throw new RuntimeException('Unable to create a stream for CURLOPT_STDERR'); } // @codeCoverageIgnoreEnd $curlOptions[CURLOPT_VERBOSE] = true; } // Specify settings according to the HTTP method if ($method == 'GET') { $curlOptions[CURLOPT_HTTPGET] = true; } elseif ($method == 'HEAD') { $curlOptions[CURLOPT_NOBODY] = true; // HEAD requests do not use a write function unset($curlOptions[CURLOPT_WRITEFUNCTION]); } elseif (!($request instanceof EntityEnclosingRequest)) { $curlOptions[CURLOPT_CUSTOMREQUEST] = $method; } else { $curlOptions[CURLOPT_CUSTOMREQUEST] = $method; // Handle sending raw bodies in a request if ($request->getBody()) { // You can send the body as a string using curl's CURLOPT_POSTFIELDS if ($bodyAsString) { $curlOptions[CURLOPT_POSTFIELDS] = (string) $request->getBody(); // Allow curl to add the Content-Length for us to account for the times when // POST redirects are followed by GET requests if ($tempContentLength = $request->getHeader('Content-Length')) { $tempContentLength = (int) (string) $tempContentLength; } // Remove the curl generated Content-Type header if none was set manually if (!$request->hasHeader('Content-Type')) { $curlOptions[CURLOPT_HTTPHEADER][] = 'Content-Type:'; } } else { $curlOptions[CURLOPT_UPLOAD] = true; // Let cURL handle setting the Content-Length header if ($tempContentLength = $request->getHeader('Content-Length')) { $tempContentLength = (int) (string) $tempContentLength; $curlOptions[CURLOPT_INFILESIZE] = $tempContentLength; } // Add a callback for curl to read data to send with the request only if a body was specified $curlOptions[CURLOPT_READFUNCTION] = array($mediator, 'readRequestBody'); // Attempt to seek to the start of the stream $request->getBody()->seek(0); } } else { // Special handling for POST specific fields and files $postFields = false; if (count($request->getPostFiles())) { $postFields = $request->getPostFields()->useUrlEncoding(false)->urlEncode(); foreach ($request->getPostFiles() as $key => $data) { $prefixKeys = count($data) > 1; foreach ($data as $index => $file) { // Allow multiple files in the same key $fieldKey = $prefixKeys ? "{$key}[{$index}]" : $key; $postFields[$fieldKey] = $file->getCurlValue(); } } } elseif (count($request->getPostFields())) { $postFields = (string) $request->getPostFields()->useUrlEncoding(true); } if ($postFields !== false) { if ($method == 'POST') { unset($curlOptions[CURLOPT_CUSTOMREQUEST]); $curlOptions[CURLOPT_POST] = true; } $curlOptions[CURLOPT_POSTFIELDS] = $postFields; $request->removeHeader('Content-Length'); } } // If the Expect header is not present, prevent curl from adding it if (!$request->hasHeader('Expect')) { $curlOptions[CURLOPT_HTTPHEADER][] = 'Expect:'; } } // If a Content-Length header was specified but we want to allow curl to set one for us if (null !== $tempContentLength) { $request->removeHeader('Content-Length'); } // Set custom cURL options foreach ($requestCurlOptions->toArray() as $key => $value) { if (is_numeric($key)) { $curlOptions[$key] = $value; } } // Do not set an Accept header by default if (!isset($curlOptions[CURLOPT_ENCODING])) { $curlOptions[CURLOPT_HTTPHEADER][] = 'Accept:'; } // Add any custom headers to the request. Empty headers will cause curl to not send the header at all. foreach ($request->getHeaderLines() as $line) { $curlOptions[CURLOPT_HTTPHEADER][] = $line; } // Add the content-length header back if it was temporarily removed if ($tempContentLength) { $request->setHeader('Content-Length', $tempContentLength); } // Apply the options to a new cURL handle. $handle = curl_init(); // Enable the progress function if the 'progress' param was set if ($requestCurlOptions->get('progress')) { // Wrap the function in a function that provides the curl handle to the mediator's progress function // Using this rather than injecting the handle into the mediator prevents a circular reference $curlOptions[CURLOPT_PROGRESSFUNCTION] = function () use ($mediator, $handle) { $args = func_get_args(); $args[] = $handle; // PHP 5.5 pushed the handle onto the start of the args if (is_resource($args[0])) { array_shift($args); } call_user_func_array(array($mediator, 'progress'), $args); }; $curlOptions[CURLOPT_NOPROGRESS] = false; } curl_setopt_array($handle, $curlOptions); return new static($handle, $curlOptions); } /** * Construct a new CurlHandle object that wraps a cURL handle * * @param resource $handle Configured cURL handle resource * @param Collection|array $options Curl options to use with the handle * * @throws InvalidArgumentException */ public function __construct($handle, $options) { if (!is_resource($handle)) { throw new InvalidArgumentException('Invalid handle provided'); } if (is_array($options)) { $this->options = new Collection($options); } elseif ($options instanceof Collection) { $this->options = $options; } else { throw new InvalidArgumentException('Expected array or Collection'); } $this->handle = $handle; } /** * Destructor */ public function __destruct() { $this->close(); } /** * Close the curl handle */ public function close() { if (is_resource($this->handle)) { curl_close($this->handle); } $this->handle = null; } /** * Check if the handle is available and still OK * * @return bool */ public function isAvailable() { return is_resource($this->handle); } /** * Get the last error that occurred on the cURL handle * * @return string */ public function getError() { return $this->isAvailable() ? curl_error($this->handle) : ''; } /** * Get the last error number that occurred on the cURL handle * * @return int */ public function getErrorNo() { if ($this->errorNo) { return $this->errorNo; } return $this->isAvailable() ? curl_errno($this->handle) : CURLE_OK; } /** * Set the curl error number * * @param int $error Error number to set * * @return CurlHandle */ public function setErrorNo($error) { $this->errorNo = $error; return $this; } /** * Get cURL curl_getinfo data * * @param int $option Option to retrieve. Pass null to retrieve all data as an array. * * @return array|mixed */ public function getInfo($option = null) { if (!is_resource($this->handle)) { return null; } if (null !== $option) { return curl_getinfo($this->handle, $option) ?: null; } return curl_getinfo($this->handle) ?: array(); } /** * Get the stderr output * * @param bool $asResource Set to TRUE to get an fopen resource * * @return string|resource|null */ public function getStderr($asResource = false) { $stderr = $this->getOptions()->get(CURLOPT_STDERR); if (!$stderr) { return null; } if ($asResource) { return $stderr; } fseek($stderr, 0); $e = stream_get_contents($stderr); fseek($stderr, 0, SEEK_END); return $e; } /** * Get the URL that this handle is connecting to * * @return Url */ public function getUrl() { return Url::factory($this->options->get(CURLOPT_URL)); } /** * Get the wrapped curl handle * * @return resource|null Returns the cURL handle or null if it was closed */ public function getHandle() { return $this->isAvailable() ? $this->handle : null; } /** * Get the cURL setopt options of the handle. Changing values in the return object will have no effect on the curl * handle after it is created. * * @return Collection */ public function getOptions() { return $this->options; } /** * Update a request based on the log messages of the CurlHandle * * @param RequestInterface $request Request to update */ public function updateRequestFromTransfer(RequestInterface $request) { if (!$request->getResponse()) { return; } // Update the transfer stats of the response $request->getResponse()->setInfo($this->getInfo()); if (!$log = $this->getStderr(true)) { return; } // Parse the cURL stderr output for outgoing requests $headers = ''; fseek($log, 0); while (($line = fgets($log)) !== false) { if ($line && $line[0] == '>') { $headers = substr(trim($line), 2) . "\r\n"; while (($line = fgets($log)) !== false) { if ($line[0] == '*' || $line[0] == '<') { break; } else { $headers .= trim($line) . "\r\n"; } } } } // Add request headers to the request exactly as they were sent if ($headers) { $parsed = ParserRegistry::getInstance()->getParser('message')->parseRequest($headers); if (!empty($parsed['headers'])) { $request->setHeaders(array()); foreach ($parsed['headers'] as $name => $value) { $request->setHeader($name, $value); } } if (!empty($parsed['version'])) { $request->setProtocolVersion($parsed['version']); } } } /** * Parse the config and replace curl.* configurators into the constant based values so it can be used elsewhere * * @param array|Collection $config The configuration we want to parse * * @return array */ public static function parseCurlConfig($config) { $curlOptions = array(); foreach ($config as $key => $value) { if (is_string($key) && defined($key)) { // Convert constants represented as string to constant int values $key = constant($key); } if (is_string($value) && defined($value)) { $value = constant($value); } $curlOptions[$key] = $value; } return $curlOptions; } } array('CURLM_BAD_HANDLE', 'The passed-in handle is not a valid CURLM handle.'), CURLM_BAD_EASY_HANDLE => array('CURLM_BAD_EASY_HANDLE', "An easy handle was not good/valid. It could mean that it isn't an easy handle at all, or possibly that the handle already is in used by this or another multi handle."), CURLM_OUT_OF_MEMORY => array('CURLM_OUT_OF_MEMORY', 'You are doomed.'), CURLM_INTERNAL_ERROR => array('CURLM_INTERNAL_ERROR', 'This can only be returned if libcurl bugs. Please report it to us!') ); /** @var float */ protected $selectTimeout; public function __construct($selectTimeout = 1.0) { $this->selectTimeout = $selectTimeout; $this->multiHandle = curl_multi_init(); // @codeCoverageIgnoreStart if ($this->multiHandle === false) { throw new CurlException('Unable to create multi handle'); } // @codeCoverageIgnoreEnd $this->reset(); } public function __destruct() { if (is_resource($this->multiHandle)) { curl_multi_close($this->multiHandle); } } public function add(RequestInterface $request) { $this->requests[] = $request; // If requests are currently transferring and this is async, then the // request must be prepared now as the send() method is not called. $this->beforeSend($request); $this->dispatch(self::ADD_REQUEST, array('request' => $request)); return $this; } public function all() { return $this->requests; } public function remove(RequestInterface $request) { $this->removeHandle($request); if (($index = array_search($request, $this->requests, true)) !== false) { $request = $this->requests[$index]; unset($this->requests[$index]); $this->requests = array_values($this->requests); $this->dispatch(self::REMOVE_REQUEST, array('request' => $request)); return true; } return false; } public function reset($hard = false) { // Remove each request if ($this->requests) { foreach ($this->requests as $request) { $this->remove($request); } } $this->handles = new \SplObjectStorage(); $this->requests = $this->resourceHash = $this->exceptions = $this->successful = array(); } public function send() { $this->perform(); $exceptions = $this->exceptions; $successful = $this->successful; $this->reset(); if ($exceptions) { $this->throwMultiException($exceptions, $successful); } } public function count() { return count($this->requests); } /** * Build and throw a MultiTransferException * * @param array $exceptions Exceptions encountered * @param array $successful Successful requests * @throws MultiTransferException */ protected function throwMultiException(array $exceptions, array $successful) { $multiException = new MultiTransferException('Errors during multi transfer'); while ($e = array_shift($exceptions)) { $multiException->addFailedRequestWithException($e['request'], $e['exception']); } // Add successful requests foreach ($successful as $request) { if (!$multiException->containsRequest($request)) { $multiException->addSuccessfulRequest($request); } } throw $multiException; } /** * Prepare for sending * * @param RequestInterface $request Request to prepare * @throws \Exception on error preparing the request */ protected function beforeSend(RequestInterface $request) { try { $state = $request->setState(RequestInterface::STATE_TRANSFER); if ($state == RequestInterface::STATE_TRANSFER) { $this->addHandle($request); } else { // Requests might decide they don't need to be sent just before // transfer (e.g. CachePlugin) $this->remove($request); if ($state == RequestInterface::STATE_COMPLETE) { $this->successful[] = $request; } } } catch (\Exception $e) { // Queue the exception to be thrown when sent $this->removeErroredRequest($request, $e); } } private function addHandle(RequestInterface $request) { $handle = $this->createCurlHandle($request)->getHandle(); $this->checkCurlResult( curl_multi_add_handle($this->multiHandle, $handle) ); } /** * Create a curl handle for a request * * @param RequestInterface $request Request * * @return CurlHandle */ protected function createCurlHandle(RequestInterface $request) { $wrapper = CurlHandle::factory($request); $this->handles[$request] = $wrapper; $this->resourceHash[(int) $wrapper->getHandle()] = $request; return $wrapper; } /** * Get the data from the multi handle */ protected function perform() { $event = new Event(array('curl_multi' => $this)); while ($this->requests) { // Notify each request as polling $blocking = $total = 0; foreach ($this->requests as $request) { ++$total; $event['request'] = $request; $request->getEventDispatcher()->dispatch(self::POLLING_REQUEST, $event); // The blocking variable just has to be non-falsey to block the loop if ($request->getParams()->hasKey(self::BLOCKING)) { ++$blocking; } } if ($blocking == $total) { // Sleep to prevent eating CPU because no requests are actually pending a select call usleep(500); } else { $this->executeHandles(); } } } /** * Execute and select curl handles */ private function executeHandles() { // The first curl_multi_select often times out no matter what, but is usually required for fast transfers $selectTimeout = 0.001; $active = false; do { while (($mrc = curl_multi_exec($this->multiHandle, $active)) == CURLM_CALL_MULTI_PERFORM); $this->checkCurlResult($mrc); $this->processMessages(); if ($active && curl_multi_select($this->multiHandle, $selectTimeout) === -1) { // Perform a usleep if a select returns -1: https://bugs.php.net/bug.php?id=61141 usleep(150); } $selectTimeout = $this->selectTimeout; } while ($active); } /** * Process any received curl multi messages */ private function processMessages() { while ($done = curl_multi_info_read($this->multiHandle)) { $request = $this->resourceHash[(int) $done['handle']]; try { $this->processResponse($request, $this->handles[$request], $done); $this->successful[] = $request; } catch (\Exception $e) { $this->removeErroredRequest($request, $e); } } } /** * Remove a request that encountered an exception * * @param RequestInterface $request Request to remove * @param \Exception $e Exception encountered */ protected function removeErroredRequest(RequestInterface $request, \Exception $e = null) { $this->exceptions[] = array('request' => $request, 'exception' => $e); $this->remove($request); $this->dispatch(self::MULTI_EXCEPTION, array('exception' => $e, 'all_exceptions' => $this->exceptions)); } /** * Check for errors and fix headers of a request based on a curl response * * @param RequestInterface $request Request to process * @param CurlHandle $handle Curl handle object * @param array $curl Array returned from curl_multi_info_read * * @throws CurlException on Curl error */ protected function processResponse(RequestInterface $request, CurlHandle $handle, array $curl) { // Set the transfer stats on the response $handle->updateRequestFromTransfer($request); // Check if a cURL exception occurred, and if so, notify things $curlException = $this->isCurlException($request, $handle, $curl); // Always remove completed curl handles. They can be added back again // via events if needed (e.g. ExponentialBackoffPlugin) $this->removeHandle($request); if (!$curlException) { if ($this->validateResponseWasSet($request)) { $state = $request->setState( RequestInterface::STATE_COMPLETE, array('handle' => $handle) ); // Only remove the request if it wasn't resent as a result of // the state change if ($state != RequestInterface::STATE_TRANSFER) { $this->remove($request); } } return; } // Set the state of the request to an error $state = $request->setState(RequestInterface::STATE_ERROR, array('exception' => $curlException)); // Allow things to ignore the error if possible if ($state != RequestInterface::STATE_TRANSFER) { $this->remove($request); } // The error was not handled, so fail if ($state == RequestInterface::STATE_ERROR) { /** @var CurlException $curlException */ throw $curlException; } } /** * Remove a curl handle from the curl multi object * * @param RequestInterface $request Request that owns the handle */ protected function removeHandle(RequestInterface $request) { if (isset($this->handles[$request])) { $handle = $this->handles[$request]; curl_multi_remove_handle($this->multiHandle, $handle->getHandle()); unset($this->handles[$request]); unset($this->resourceHash[(int) $handle->getHandle()]); $handle->close(); } } /** * Check if a cURL transfer resulted in what should be an exception * * @param RequestInterface $request Request to check * @param CurlHandle $handle Curl handle object * @param array $curl Array returned from curl_multi_info_read * * @return CurlException|bool */ private function isCurlException(RequestInterface $request, CurlHandle $handle, array $curl) { if (CURLM_OK == $curl['result'] || CURLM_CALL_MULTI_PERFORM == $curl['result']) { return false; } $handle->setErrorNo($curl['result']); $e = new CurlException(sprintf('[curl] %s: %s [url] %s', $handle->getErrorNo(), $handle->getError(), $handle->getUrl())); $e->setCurlHandle($handle) ->setRequest($request) ->setCurlInfo($handle->getInfo()) ->setError($handle->getError(), $handle->getErrorNo()); return $e; } /** * Throw an exception for a cURL multi response if needed * * @param int $code Curl response code * @throws CurlException */ private function checkCurlResult($code) { if ($code != CURLM_OK && $code != CURLM_CALL_MULTI_PERFORM) { throw new CurlException(isset($this->multiErrors[$code]) ? "cURL error: {$code} ({$this->multiErrors[$code][0]}): cURL message: {$this->multiErrors[$code][1]}" : 'Unexpected cURL error: ' . $code ); } } /** * @link https://github.com/guzzle/guzzle/issues/710 */ private function validateResponseWasSet(RequestInterface $request) { if ($request->getResponse()) { return true; } $body = $request instanceof EntityEnclosingRequestInterface ? $request->getBody() : null; if (!$body) { $rex = new RequestException( 'No response was received for a request with no body. This' . ' could mean that you are saturating your network.' ); $rex->setRequest($request); $this->removeErroredRequest($request, $rex); } elseif (!$body->isSeekable() || !$body->seek(0)) { // Nothing we can do with this. Sorry! $rex = new RequestException( 'The connection was unexpectedly closed. The request would' . ' have been retried, but attempting to rewind the' . ' request body failed.' ); $rex->setRequest($request); $this->removeErroredRequest($request, $rex); } else { $this->remove($request); // Add the request back to the batch to retry automatically. $this->requests[] = $request; $this->addHandle($request); } return false; } } maxHandles = $maxHandles; $this->selectTimeout = $selectTimeout; // You can get some weird "Too many open files" errors when sending a large amount of requests in parallel. // These two statements autoload classes before a system runs out of file descriptors so that you can get back // valuable error messages if you run out. class_exists('Guzzle\Http\Message\Response'); class_exists('Guzzle\Http\Exception\CurlException'); } public function add(RequestInterface $request) { $this->queued[] = $request; return $this; } public function all() { $requests = $this->queued; foreach ($this->handles as $handle) { $requests = array_merge($requests, $handle->all()); } return $requests; } public function remove(RequestInterface $request) { foreach ($this->queued as $i => $r) { if ($request === $r) { unset($this->queued[$i]); return true; } } foreach ($this->handles as $handle) { if ($handle->remove($request)) { return true; } } return false; } public function reset($hard = false) { $this->queued = array(); $this->groups = array(); foreach ($this->handles as $handle) { $handle->reset(); } if ($hard) { $this->handles = array(); } return $this; } public function send() { if ($this->queued) { $group = $this->getAvailableHandle(); // Add this handle to a list of handles than is claimed $this->groups[] = $group; while ($request = array_shift($this->queued)) { $group->add($request); } try { $group->send(); array_pop($this->groups); $this->cleanupHandles(); } catch (\Exception $e) { // Remove the group and cleanup if an exception was encountered and no more requests in group if (!$group->count()) { array_pop($this->groups); $this->cleanupHandles(); } throw $e; } } } public function count() { return count($this->all()); } /** * Get an existing available CurlMulti handle or create a new one * * @return CurlMulti */ protected function getAvailableHandle() { // Grab a handle that is not claimed foreach ($this->handles as $h) { if (!in_array($h, $this->groups, true)) { return $h; } } // All are claimed, so create one $handle = new CurlMulti($this->selectTimeout); $handle->setEventDispatcher($this->getEventDispatcher()); $this->handles[] = $handle; return $handle; } /** * Trims down unused CurlMulti handles to limit the number of open connections */ protected function cleanupHandles() { if ($diff = max(0, count($this->handles) - $this->maxHandles)) { for ($i = count($this->handles) - 1; $i > 0 && $diff > 0; $i--) { if (!count($this->handles[$i])) { unset($this->handles[$i]); $diff--; } } $this->handles = array_values($this->handles); } } } version) { $this->version = curl_version(); } return $this->version; } /** * Get a specific type of curl information * * @param string $type Version information to retrieve. This value is one of: * - version_number: cURL 24 bit version number * - version: cURL version number, as a string * - ssl_version_number: OpenSSL 24 bit version number * - ssl_version: OpenSSL version number, as a string * - libz_version: zlib version number, as a string * - host: Information about the host where cURL was built * - features: A bitmask of the CURL_VERSION_XXX constants * - protocols: An array of protocols names supported by cURL * * @return string|float|bool if the $type is found, and false if not found */ public function get($type) { $version = $this->getAll(); return isset($version[$type]) ? $version[$type] : false; } } request = $request; $this->emitIo = $emitIo; } /** * Receive a response header from curl * * @param resource $curl Curl handle * @param string $header Received header * * @return int */ public function receiveResponseHeader($curl, $header) { static $normalize = array("\r", "\n"); $length = strlen($header); $header = str_replace($normalize, '', $header); if (strpos($header, 'HTTP/') === 0) { $startLine = explode(' ', $header, 3); $code = $startLine[1]; $status = isset($startLine[2]) ? $startLine[2] : ''; // Only download the body of the response to the specified response // body when a successful response is received. if ($code >= 200 && $code < 300) { $body = $this->request->getResponseBody(); } else { $body = EntityBody::factory(); } $response = new Response($code, null, $body); $response->setStatus($code, $status); $this->request->startResponse($response); $this->request->dispatch('request.receive.status_line', array( 'request' => $this, 'line' => $header, 'status_code' => $code, 'reason_phrase' => $status )); } elseif ($pos = strpos($header, ':')) { $this->request->getResponse()->addHeader( trim(substr($header, 0, $pos)), trim(substr($header, $pos + 1)) ); } return $length; } /** * Received a progress notification * * @param int $downloadSize Total download size * @param int $downloaded Amount of bytes downloaded * @param int $uploadSize Total upload size * @param int $uploaded Amount of bytes uploaded * @param resource $handle CurlHandle object */ public function progress($downloadSize, $downloaded, $uploadSize, $uploaded, $handle = null) { $this->request->dispatch('curl.callback.progress', array( 'request' => $this->request, 'handle' => $handle, 'download_size' => $downloadSize, 'downloaded' => $downloaded, 'upload_size' => $uploadSize, 'uploaded' => $uploaded )); } /** * Write data to the response body of a request * * @param resource $curl Curl handle * @param string $write Data that was received * * @return int */ public function writeResponseBody($curl, $write) { if ($this->emitIo) { $this->request->dispatch('curl.callback.write', array( 'request' => $this->request, 'write' => $write )); } if ($response = $this->request->getResponse()) { return $response->getBody()->write($write); } else { // Unexpected data received before response headers - abort transfer return 0; } } /** * Read data from the request body and send it to curl * * @param resource $ch Curl handle * @param resource $fd File descriptor * @param int $length Amount of data to read * * @return string */ public function readRequestBody($ch, $fd, $length) { if (!($body = $this->request->getBody())) { return ''; } $read = (string) $body->read($length); if ($this->emitIo) { $this->request->dispatch('curl.callback.read', array('request' => $this->request, 'read' => $read)); } return $read; } } rewindFunction = $callable; return $this; } public function rewind() { return $this->rewindFunction ? call_user_func($this->rewindFunction, $this) : parent::rewind(); } /** * Create a new EntityBody from a string * * @param string $string String of data * * @return EntityBody */ public static function fromString($string) { $stream = fopen('php://temp', 'r+'); if ($string !== '') { fwrite($stream, $string); rewind($stream); } return new static($stream); } public function compress($filter = 'zlib.deflate') { $result = $this->handleCompression($filter); $this->contentEncoding = $result ? $filter : false; return $result; } public function uncompress($filter = 'zlib.inflate') { $offsetStart = 0; // When inflating gzipped data, the first 10 bytes must be stripped // if a gzip header is present if ($filter == 'zlib.inflate') { // @codeCoverageIgnoreStart if (!$this->isReadable() || ($this->isConsumed() && !$this->isSeekable())) { return false; } // @codeCoverageIgnoreEnd if (stream_get_contents($this->stream, 3, 0) === "\x1f\x8b\x08") { $offsetStart = 10; } } $this->contentEncoding = false; return $this->handleCompression($filter, $offsetStart); } public function getContentLength() { return $this->getSize(); } public function getContentType() { return $this->getUri() ? Mimetypes::getInstance()->fromFilename($this->getUri()) : null; } public function getContentMd5($rawOutput = false, $base64Encode = false) { if ($hash = self::getHash($this, 'md5', $rawOutput)) { return $hash && $base64Encode ? base64_encode($hash) : $hash; } else { return false; } } /** * Calculate the MD5 hash of an entity body * * @param EntityBodyInterface $body Entity body to calculate the hash for * @param bool $rawOutput Whether or not to use raw output * @param bool $base64Encode Whether or not to base64 encode raw output (only if raw output is true) * * @return bool|string Returns an MD5 string on success or FALSE on failure * @deprecated This will be deprecated soon * @codeCoverageIgnore */ public static function calculateMd5(EntityBodyInterface $body, $rawOutput = false, $base64Encode = false) { Version::warn(__CLASS__ . ' is deprecated. Use getContentMd5()'); return $body->getContentMd5($rawOutput, $base64Encode); } public function setStreamFilterContentEncoding($streamFilterContentEncoding) { $this->contentEncoding = $streamFilterContentEncoding; return $this; } public function getContentEncoding() { return strtr($this->contentEncoding, array( 'zlib.deflate' => 'gzip', 'bzip2.compress' => 'compress' )) ?: false; } protected function handleCompression($filter, $offsetStart = 0) { // @codeCoverageIgnoreStart if (!$this->isReadable() || ($this->isConsumed() && !$this->isSeekable())) { return false; } // @codeCoverageIgnoreEnd $handle = fopen('php://temp', 'r+'); $filter = @stream_filter_append($handle, $filter, STREAM_FILTER_WRITE); if (!$filter) { return false; } // Seek to the offset start if possible $this->seek($offsetStart); while ($data = fread($this->stream, 8096)) { fwrite($handle, $data); } fclose($this->stream); $this->stream = $handle; stream_filter_remove($filter); $stat = fstat($this->stream); $this->size = $stat['size']; $this->rebuildCache(); $this->seek(0); // Remove any existing rewind function as the underlying stream has been replaced $this->rewindFunction = null; return true; } } isClientError()) { $label = 'Client error response'; $class = __NAMESPACE__ . '\\ClientErrorResponseException'; } elseif ($response->isServerError()) { $label = 'Server error response'; $class = __NAMESPACE__ . '\\ServerErrorResponseException'; } else { $label = 'Unsuccessful response'; $class = __CLASS__; } $message = $label . PHP_EOL . implode(PHP_EOL, array( '[status code] ' . $response->getStatusCode(), '[reason phrase] ' . $response->getReasonPhrase(), '[url] ' . $request->getUrl(), )); $e = new $class($message); $e->setResponse($response); $e->setRequest($request); return $e; } /** * Set the response that caused the exception * * @param Response $response Response to set */ public function setResponse(Response $response) { $this->response = $response; } /** * Get the response that caused the exception * * @return Response */ public function getResponse() { return $this->response; } } curlError = $error; $this->curlErrorNo = $number; return $this; } /** * Set the associated curl handle * * @param CurlHandle $handle Curl handle * * @return self */ public function setCurlHandle(CurlHandle $handle) { $this->handle = $handle; return $this; } /** * Get the associated cURL handle * * @return CurlHandle|null */ public function getCurlHandle() { return $this->handle; } /** * Get the associated cURL error message * * @return string|null */ public function getError() { return $this->curlError; } /** * Get the associated cURL error number * * @return int|null */ public function getErrorNo() { return $this->curlErrorNo; } /** * Returns curl information about the transfer * * @return array */ public function getCurlInfo() { return $this->curlInfo; } /** * Set curl transfer information * * @param array $info Array of curl transfer information * * @return self * @link http://php.net/manual/en/function.curl-getinfo.php */ public function setCurlInfo(array $info) { $this->curlInfo = $info; return $this; } } successfulRequests, $this->failedRequests); } /** * Add to the array of successful requests * * @param RequestInterface $request Successful request * * @return self */ public function addSuccessfulRequest(RequestInterface $request) { $this->successfulRequests[] = $request; return $this; } /** * Add to the array of failed requests * * @param RequestInterface $request Failed request * * @return self */ public function addFailedRequest(RequestInterface $request) { $this->failedRequests[] = $request; return $this; } /** * Add to the array of failed requests and associate with exceptions * * @param RequestInterface $request Failed request * @param \Exception $exception Exception to add and associate with * * @return self */ public function addFailedRequestWithException(RequestInterface $request, \Exception $exception) { $this->add($exception) ->addFailedRequest($request) ->exceptionForRequest[spl_object_hash($request)] = $exception; return $this; } /** * Get the Exception that caused the given $request to fail * * @param RequestInterface $request Failed command * * @return \Exception|null */ public function getExceptionForFailedRequest(RequestInterface $request) { $oid = spl_object_hash($request); return isset($this->exceptionForRequest[$oid]) ? $this->exceptionForRequest[$oid] : null; } /** * Set all of the successful requests * * @param array Array of requests * * @return self */ public function setSuccessfulRequests(array $requests) { $this->successfulRequests = $requests; return $this; } /** * Set all of the failed requests * * @param array Array of requests * * @return self */ public function setFailedRequests(array $requests) { $this->failedRequests = $requests; return $this; } /** * Get an array of successful requests sent in the multi transfer * * @return array */ public function getSuccessfulRequests() { return $this->successfulRequests; } /** * Get an array of failed requests sent in the multi transfer * * @return array */ public function getFailedRequests() { return $this->failedRequests; } /** * Check if the exception object contains a request * * @param RequestInterface $request Request to check * * @return bool */ public function containsRequest(RequestInterface $request) { return in_array($request, $this->failedRequests, true) || in_array($request, $this->successfulRequests, true); } } request = $request; return $this; } /** * Get the request that caused the exception * * @return RequestInterface */ public function getRequest() { return $this->request; } } eventDispatcher = $eventDispatcher; return $this; } public function getEventDispatcher() { if (!$this->eventDispatcher) { $this->eventDispatcher = new EventDispatcher(); } return $this->eventDispatcher; } public function dispatch($eventName, array $context = array()) { return $this->getEventDispatcher()->dispatch($eventName, new Event($context)); } /** * {@inheritdoc} * @codeCoverageIgnore */ public function addSubscriber(EventSubscriberInterface $subscriber) { $this->getEventDispatcher()->addSubscriber($subscriber); return $this; } public function read($length) { $event = array( 'body' => $this, 'length' => $length, 'read' => $this->body->read($length) ); $this->dispatch('body.read', $event); return $event['read']; } public function write($string) { $event = array( 'body' => $this, 'write' => $string, 'result' => $this->body->write($string) ); $this->dispatch('body.write', $event); return $event['result']; } } params = new Collection(); $this->headerFactory = new HeaderFactory(); $this->headers = new HeaderCollection(); } /** * Set the header factory to use to create headers * * @param HeaderFactoryInterface $factory * * @return self */ public function setHeaderFactory(HeaderFactoryInterface $factory) { $this->headerFactory = $factory; return $this; } public function getParams() { return $this->params; } public function addHeader($header, $value) { if (isset($this->headers[$header])) { $this->headers[$header]->add($value); } elseif ($value instanceof HeaderInterface) { $this->headers[$header] = $value; } else { $this->headers[$header] = $this->headerFactory->createHeader($header, $value); } return $this; } public function addHeaders(array $headers) { foreach ($headers as $key => $value) { $this->addHeader($key, $value); } return $this; } public function getHeader($header) { return $this->headers[$header]; } public function getHeaders() { return $this->headers; } public function getHeaderLines() { $headers = array(); foreach ($this->headers as $value) { $headers[] = $value->getName() . ': ' . $value; } return $headers; } public function setHeader($header, $value) { unset($this->headers[$header]); $this->addHeader($header, $value); return $this; } public function setHeaders(array $headers) { $this->headers->clear(); foreach ($headers as $key => $value) { $this->addHeader($key, $value); } return $this; } public function hasHeader($header) { return isset($this->headers[$header]); } public function removeHeader($header) { unset($this->headers[$header]); return $this; } /** * @deprecated Use $message->getHeader()->parseParams() * @codeCoverageIgnore */ public function getTokenizedHeader($header, $token = ';') { Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader()->parseParams()'); if ($this->hasHeader($header)) { $data = new Collection(); foreach ($this->getHeader($header)->parseParams() as $values) { foreach ($values as $key => $value) { if ($value === '') { $data->set($data->count(), $key); } else { $data->add($key, $value); } } } return $data; } } /** * @deprecated * @codeCoverageIgnore */ public function setTokenizedHeader($header, $data, $token = ';') { Version::warn(__METHOD__ . ' is deprecated.'); return $this; } /** * @deprecated * @codeCoverageIgnore */ public function getCacheControlDirective($directive) { Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader(\'Cache-Control\')->getDirective()'); if (!($header = $this->getHeader('Cache-Control'))) { return null; } return $header->getDirective($directive); } /** * @deprecated * @codeCoverageIgnore */ public function hasCacheControlDirective($directive) { Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader(\'Cache-Control\')->hasDirective()'); if ($header = $this->getHeader('Cache-Control')) { return $header->hasDirective($directive); } else { return false; } } /** * @deprecated * @codeCoverageIgnore */ public function addCacheControlDirective($directive, $value = true) { Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader(\'Cache-Control\')->addDirective()'); if (!($header = $this->getHeader('Cache-Control'))) { $this->addHeader('Cache-Control', ''); $header = $this->getHeader('Cache-Control'); } $header->addDirective($directive, $value); return $this; } /** * @deprecated * @codeCoverageIgnore */ public function removeCacheControlDirective($directive) { Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader(\'Cache-Control\')->removeDirective()'); if ($header = $this->getHeader('Cache-Control')) { $header->removeDirective($directive); } return $this; } } postFields = new QueryString(); parent::__construct($method, $url, $headers); } /** * @return string */ public function __toString() { // Only attempt to include the POST data if it's only fields if (count($this->postFields) && empty($this->postFiles)) { return parent::__toString() . (string) $this->postFields; } return parent::__toString() . $this->body; } public function setState($state, array $context = array()) { parent::setState($state, $context); if ($state == self::STATE_TRANSFER && !$this->body && !count($this->postFields) && !count($this->postFiles)) { $this->setHeader('Content-Length', 0)->removeHeader('Transfer-Encoding'); } return $this->state; } public function setBody($body, $contentType = null) { $this->body = EntityBody::factory($body); // Auto detect the Content-Type from the path of the request if possible if ($contentType === null && !$this->hasHeader('Content-Type')) { $contentType = $this->body->getContentType(); } if ($contentType) { $this->setHeader('Content-Type', $contentType); } // Always add the Expect 100-Continue header if the body cannot be rewound. This helps with redirects. if (!$this->body->isSeekable() && $this->expectCutoff !== false) { $this->setHeader('Expect', '100-Continue'); } // Set the Content-Length header if it can be determined $size = $this->body->getContentLength(); if ($size !== null && $size !== false) { $this->setHeader('Content-Length', $size); if ($size > $this->expectCutoff) { $this->setHeader('Expect', '100-Continue'); } } elseif (!$this->hasHeader('Content-Length')) { if ('1.1' == $this->protocolVersion) { $this->setHeader('Transfer-Encoding', 'chunked'); } else { throw new RequestException( 'Cannot determine Content-Length and cannot use chunked Transfer-Encoding when using HTTP/1.0' ); } } return $this; } public function getBody() { return $this->body; } /** * Set the size that the entity body of the request must exceed before adding the Expect: 100-Continue header. * * @param int|bool $size Cutoff in bytes. Set to false to never send the expect header (even with non-seekable data) * * @return self */ public function setExpectHeaderCutoff($size) { $this->expectCutoff = $size; if ($size === false || !$this->body) { $this->removeHeader('Expect'); } elseif ($this->body && $this->body->getSize() && $this->body->getSize() > $size) { $this->setHeader('Expect', '100-Continue'); } return $this; } public function configureRedirects($strict = false, $maxRedirects = 5) { $this->getParams()->set(RedirectPlugin::STRICT_REDIRECTS, $strict); if ($maxRedirects == 0) { $this->getParams()->set(RedirectPlugin::DISABLE, true); } else { $this->getParams()->set(RedirectPlugin::MAX_REDIRECTS, $maxRedirects); } return $this; } public function getPostField($field) { return $this->postFields->get($field); } public function getPostFields() { return $this->postFields; } public function setPostField($key, $value) { $this->postFields->set($key, $value); $this->processPostFields(); return $this; } public function addPostFields($fields) { $this->postFields->merge($fields); $this->processPostFields(); return $this; } public function removePostField($field) { $this->postFields->remove($field); $this->processPostFields(); return $this; } public function getPostFiles() { return $this->postFiles; } public function getPostFile($fieldName) { return isset($this->postFiles[$fieldName]) ? $this->postFiles[$fieldName] : null; } public function removePostFile($fieldName) { unset($this->postFiles[$fieldName]); $this->processPostFields(); return $this; } public function addPostFile($field, $filename = null, $contentType = null, $postname = null) { $data = null; if ($field instanceof PostFileInterface) { $data = $field; } elseif (is_array($filename)) { // Allow multiple values to be set in a single key foreach ($filename as $file) { $this->addPostFile($field, $file, $contentType); } return $this; } elseif (!is_string($filename)) { throw new RequestException('The path to a file must be a string'); } elseif (!empty($filename)) { // Adding an empty file will cause cURL to error out $data = new PostFile($field, $filename, $contentType, $postname); } if ($data) { if (!isset($this->postFiles[$data->getFieldName()])) { $this->postFiles[$data->getFieldName()] = array($data); } else { $this->postFiles[$data->getFieldName()][] = $data; } $this->processPostFields(); } return $this; } public function addPostFiles(array $files) { foreach ($files as $key => $file) { if ($file instanceof PostFileInterface) { $this->addPostFile($file, null, null, false); } elseif (is_string($file)) { // Convert non-associative array keys into 'file' if (is_numeric($key)) { $key = 'file'; } $this->addPostFile($key, $file, null, false); } else { throw new RequestException('File must be a string or instance of PostFileInterface'); } } return $this; } /** * Determine what type of request should be sent based on post fields */ protected function processPostFields() { if (!$this->postFiles) { $this->removeHeader('Expect')->setHeader('Content-Type', self::URL_ENCODED); } else { $this->setHeader('Content-Type', self::MULTIPART); if ($this->expectCutoff !== false) { $this->setHeader('Expect', '100-Continue'); } } } } filenames where filename can be a string or PostFileInterface * * @return self */ public function addPostFiles(array $files); /** * Configure how redirects are handled for the request * * @param bool $strict Set to true to follow strict RFC compliance when redirecting POST requests. Most * browsers with follow a 301-302 redirect for a POST request with a GET request. This is * the default behavior of Guzzle. Enable strict redirects to redirect these responses * with a POST rather than a GET request. * @param int $maxRedirects Specify the maximum number of allowed redirects. Set to 0 to disable redirects. * * @return self */ public function configureRedirects($strict = false, $maxRedirects = 5); } directives = null; } public function removeValue($searchValue) { parent::removeValue($searchValue); $this->directives = null; } /** * Check if a specific cache control directive exists * * @param string $param Directive to retrieve * * @return bool */ public function hasDirective($param) { $directives = $this->getDirectives(); return isset($directives[$param]); } /** * Get a specific cache control directive * * @param string $param Directive to retrieve * * @return string|bool|null */ public function getDirective($param) { $directives = $this->getDirectives(); return isset($directives[$param]) ? $directives[$param] : null; } /** * Add a cache control directive * * @param string $param Directive to add * @param string $value Value to set * * @return self */ public function addDirective($param, $value) { $directives = $this->getDirectives(); $directives[$param] = $value; $this->updateFromDirectives($directives); return $this; } /** * Remove a cache control directive by name * * @param string $param Directive to remove * * @return self */ public function removeDirective($param) { $directives = $this->getDirectives(); unset($directives[$param]); $this->updateFromDirectives($directives); return $this; } /** * Get an associative array of cache control directives * * @return array */ public function getDirectives() { if ($this->directives === null) { $this->directives = array(); foreach ($this->parseParams() as $collection) { foreach ($collection as $key => $value) { $this->directives[$key] = $value === '' ? true : $value; } } } return $this->directives; } /** * Updates the header value based on the parsed directives * * @param array $directives Array of cache control directives */ protected function updateFromDirectives(array $directives) { $this->directives = $directives; $this->values = array(); foreach ($directives as $key => $value) { $this->values[] = $value === true ? $key : "{$key}={$value}"; } } } headers = $headers; } public function __clone() { foreach ($this->headers as &$header) { $header = clone $header; } } /** * Clears the header collection */ public function clear() { $this->headers = array(); } /** * Set a header on the collection * * @param HeaderInterface $header Header to add * * @return self */ public function add(HeaderInterface $header) { $this->headers[strtolower($header->getName())] = $header; return $this; } /** * Get an array of header objects * * @return array */ public function getAll() { return $this->headers; } /** * Alias of offsetGet */ public function get($key) { return $this->offsetGet($key); } public function count() { return count($this->headers); } public function offsetExists($offset) { return isset($this->headers[strtolower($offset)]); } public function offsetGet($offset) { $l = strtolower($offset); return isset($this->headers[$l]) ? $this->headers[$l] : null; } public function offsetSet($offset, $value) { $this->add($value); } public function offsetUnset($offset) { unset($this->headers[strtolower($offset)]); } public function getIterator() { return new \ArrayIterator($this->headers); } public function toArray() { $result = array(); foreach ($this->headers as $header) { $result[$header->getName()] = $header->toArray(); } return $result; } } 'Guzzle\Http\Message\Header\CacheControl', 'link' => 'Guzzle\Http\Message\Header\Link', ); public function createHeader($header, $value = null) { $lowercase = strtolower($header); return isset($this->mapping[$lowercase]) ? new $this->mapping[$lowercase]($header, $value) : new Header($header, $value); } } ", "rel=\"{$rel}\""); foreach ($params as $k => $v) { $values[] = "{$k}=\"{$v}\""; } return $this->add(implode('; ', $values)); } /** * Check if a specific link exists for a given rel attribute * * @param string $rel rel value * * @return bool */ public function hasLink($rel) { return $this->getLink($rel) !== null; } /** * Get a specific link for a given rel attribute * * @param string $rel Rel value * * @return array|null */ public function getLink($rel) { foreach ($this->getLinks() as $link) { if (isset($link['rel']) && $link['rel'] == $rel) { return $link; } } return null; } /** * Get an associative array of links * * For example: * Link: ; rel=front; type="image/jpeg", ; rel=back; type="image/jpeg" * * * var_export($response->getLinks()); * array( * array( * 'url' => 'http:/.../front.jpeg', * 'rel' => 'back', * 'type' => 'image/jpeg', * ) * ) * * * @return array */ public function getLinks() { $links = $this->parseParams(); foreach ($links as &$link) { $key = key($link); unset($link[$key]); $link['url'] = trim($key, '<> '); } return $links; } } header = trim($header); $this->glue = $glue; foreach ((array) $values as $value) { foreach ((array) $value as $v) { $this->values[] = $v; } } } public function __toString() { return implode($this->glue . ' ', $this->toArray()); } public function add($value) { $this->values[] = $value; return $this; } public function getName() { return $this->header; } public function setName($name) { $this->header = $name; return $this; } public function setGlue($glue) { $this->glue = $glue; return $this; } public function getGlue() { return $this->glue; } /** * Normalize the header to be a single header with an array of values. * * If any values of the header contains the glue string value (e.g. ","), then the value will be exploded into * multiple entries in the header. * * @return self */ public function normalize() { $values = $this->toArray(); for ($i = 0, $total = count($values); $i < $total; $i++) { if (strpos($values[$i], $this->glue) !== false) { // Explode on glue when the glue is not inside of a comma foreach (preg_split('/' . preg_quote($this->glue) . '(?=([^"]*"[^"]*")*[^"]*$)/', $values[$i]) as $v) { $values[] = trim($v); } unset($values[$i]); } } $this->values = array_values($values); return $this; } public function hasValue($searchValue) { return in_array($searchValue, $this->toArray()); } public function removeValue($searchValue) { $this->values = array_values(array_filter($this->values, function ($value) use ($searchValue) { return $value != $searchValue; })); return $this; } public function toArray() { return $this->values; } public function count() { return count($this->toArray()); } public function getIterator() { return new \ArrayIterator($this->toArray()); } public function parseParams() { $params = $matches = array(); $callback = array($this, 'trimHeader'); // Normalize the header into a single array and iterate over all values foreach ($this->normalize()->toArray() as $val) { $part = array(); foreach (preg_split('/;(?=([^"]*"[^"]*")*[^"]*$)/', $val) as $kvp) { if (!preg_match_all('/<[^>]+>|[^=]+/', $kvp, $matches)) { continue; } $pieces = array_map($callback, $matches[0]); $part[$pieces[0]] = isset($pieces[1]) ? $pieces[1] : ''; } if ($part) { $params[] = $part; } } return $params; } /** * @deprecated * @codeCoverageIgnore */ public function hasExactHeader($header) { Version::warn(__METHOD__ . ' is deprecated'); return $this->header == $header; } /** * @deprecated * @codeCoverageIgnore */ public function raw() { Version::warn(__METHOD__ . ' is deprecated. Use toArray()'); return $this->toArray(); } /** * Trim a header by removing excess spaces and wrapping quotes * * @param $str * * @return string */ protected function trimHeader($str) { static $trimmed = "\"' \n\t"; return trim($str, $trimmed); } } fieldName = $fieldName; $this->setFilename($filename); $this->postname = $postname ? $postname : basename($filename); $this->contentType = $contentType ?: $this->guessContentType(); } public function setFieldName($name) { $this->fieldName = $name; return $this; } public function getFieldName() { return $this->fieldName; } public function setFilename($filename) { // Remove leading @ symbol if (strpos($filename, '@') === 0) { $filename = substr($filename, 1); } if (!is_readable($filename)) { throw new InvalidArgumentException("Unable to open {$filename} for reading"); } $this->filename = $filename; return $this; } public function setPostname($postname) { $this->postname = $postname; return $this; } public function getFilename() { return $this->filename; } public function getPostname() { return $this->postname; } public function setContentType($type) { $this->contentType = $type; return $this; } public function getContentType() { return $this->contentType; } public function getCurlValue() { // PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax // See: https://wiki.php.net/rfc/curl-file-upload if (function_exists('curl_file_create')) { return curl_file_create($this->filename, $this->contentType, $this->postname); } // Use the old style if using an older version of PHP $value = "@{$this->filename};filename=" . $this->postname; if ($this->contentType) { $value .= ';type=' . $this->contentType; } return $value; } /** * @deprecated * @codeCoverageIgnore */ public function getCurlString() { Version::warn(__METHOD__ . ' is deprecated. Use getCurlValue()'); return $this->getCurlValue(); } /** * Determine the Content-Type of the file */ protected function guessContentType() { return Mimetypes::getInstance()->fromFilename($this->filename) ?: 'application/octet-stream'; } } method = strtoupper($method); $this->curlOptions = new Collection(); $this->setUrl($url); if ($headers) { // Special handling for multi-value headers foreach ($headers as $key => $value) { // Deal with collisions with Host and Authorization if ($key == 'host' || $key == 'Host') { $this->setHeader($key, $value); } elseif ($value instanceof HeaderInterface) { $this->addHeader($key, $value); } else { foreach ((array) $value as $v) { $this->addHeader($key, $v); } } } } $this->setState(self::STATE_NEW); } public function __clone() { if ($this->eventDispatcher) { $this->eventDispatcher = clone $this->eventDispatcher; } $this->curlOptions = clone $this->curlOptions; $this->params = clone $this->params; $this->url = clone $this->url; $this->response = $this->responseBody = null; $this->headers = clone $this->headers; $this->setState(RequestInterface::STATE_NEW); $this->dispatch('request.clone', array('request' => $this)); } /** * Get the HTTP request as a string * * @return string */ public function __toString() { return $this->getRawHeaders() . "\r\n\r\n"; } /** * Default method that will throw exceptions if an unsuccessful response is received. * * @param Event $event Received * @throws BadResponseException if the response is not successful */ public static function onRequestError(Event $event) { $e = BadResponseException::factory($event['request'], $event['response']); $event['request']->setState(self::STATE_ERROR, array('exception' => $e) + $event->toArray()); throw $e; } public function setClient(ClientInterface $client) { $this->client = $client; return $this; } public function getClient() { return $this->client; } public function getRawHeaders() { $protocolVersion = $this->protocolVersion ?: '1.1'; return trim($this->method . ' ' . $this->getResource()) . ' ' . strtoupper(str_replace('https', 'http', $this->url->getScheme())) . '/' . $protocolVersion . "\r\n" . implode("\r\n", $this->getHeaderLines()); } public function setUrl($url) { if ($url instanceof Url) { $this->url = $url; } else { $this->url = Url::factory($url); } // Update the port and host header $this->setPort($this->url->getPort()); if ($this->url->getUsername() || $this->url->getPassword()) { $this->setAuth($this->url->getUsername(), $this->url->getPassword()); // Remove the auth info from the URL $this->url->setUsername(null); $this->url->setPassword(null); } return $this; } public function send() { if (!$this->client) { throw new RuntimeException('A client must be set on the request'); } return $this->client->send($this); } public function getResponse() { return $this->response; } public function getQuery($asString = false) { return $asString ? (string) $this->url->getQuery() : $this->url->getQuery(); } public function getMethod() { return $this->method; } public function getScheme() { return $this->url->getScheme(); } public function setScheme($scheme) { $this->url->setScheme($scheme); return $this; } public function getHost() { return $this->url->getHost(); } public function setHost($host) { $this->url->setHost($host); $this->setPort($this->url->getPort()); return $this; } public function getProtocolVersion() { return $this->protocolVersion; } public function setProtocolVersion($protocol) { $this->protocolVersion = $protocol; return $this; } public function getPath() { return '/' . ltrim($this->url->getPath(), '/'); } public function setPath($path) { $this->url->setPath($path); return $this; } public function getPort() { return $this->url->getPort(); } public function setPort($port) { $this->url->setPort($port); // Include the port in the Host header if it is not the default port for the scheme of the URL $scheme = $this->url->getScheme(); if ($port && (($scheme == 'http' && $port != 80) || ($scheme == 'https' && $port != 443))) { $this->headers['host'] = $this->headerFactory->createHeader('Host', $this->url->getHost() . ':' . $port); } else { $this->headers['host'] = $this->headerFactory->createHeader('Host', $this->url->getHost()); } return $this; } public function getUsername() { return $this->username; } public function getPassword() { return $this->password; } public function setAuth($user, $password = '', $scheme = CURLAUTH_BASIC) { static $authMap = array( 'basic' => CURLAUTH_BASIC, 'digest' => CURLAUTH_DIGEST, 'ntlm' => CURLAUTH_NTLM, 'any' => CURLAUTH_ANY ); // If we got false or null, disable authentication if (!$user) { $this->password = $this->username = null; $this->removeHeader('Authorization'); $this->getCurlOptions()->remove(CURLOPT_HTTPAUTH); return $this; } if (!is_numeric($scheme)) { $scheme = strtolower($scheme); if (!isset($authMap[$scheme])) { throw new InvalidArgumentException($scheme . ' is not a valid authentication type'); } $scheme = $authMap[$scheme]; } $this->username = $user; $this->password = $password; // Bypass CURL when using basic auth to promote connection reuse if ($scheme == CURLAUTH_BASIC) { $this->getCurlOptions()->remove(CURLOPT_HTTPAUTH); $this->setHeader('Authorization', 'Basic ' . base64_encode($this->username . ':' . $this->password)); } else { $this->getCurlOptions() ->set(CURLOPT_HTTPAUTH, $scheme) ->set(CURLOPT_USERPWD, $this->username . ':' . $this->password); } return $this; } public function getResource() { $resource = $this->getPath(); if ($query = (string) $this->url->getQuery()) { $resource .= '?' . $query; } return $resource; } public function getUrl($asObject = false) { return $asObject ? clone $this->url : (string) $this->url; } public function getState() { return $this->state; } public function setState($state, array $context = array()) { $oldState = $this->state; $this->state = $state; switch ($state) { case self::STATE_NEW: $this->response = null; break; case self::STATE_TRANSFER: if ($oldState !== $state) { // Fix Content-Length and Transfer-Encoding collisions if ($this->hasHeader('Transfer-Encoding') && $this->hasHeader('Content-Length')) { $this->removeHeader('Transfer-Encoding'); } $this->dispatch('request.before_send', array('request' => $this)); } break; case self::STATE_COMPLETE: if ($oldState !== $state) { $this->processResponse($context); $this->responseBody = null; } break; case self::STATE_ERROR: if (isset($context['exception'])) { $this->dispatch('request.exception', array( 'request' => $this, 'response' => isset($context['response']) ? $context['response'] : $this->response, 'exception' => isset($context['exception']) ? $context['exception'] : null )); } } return $this->state; } public function getCurlOptions() { return $this->curlOptions; } public function startResponse(Response $response) { $this->state = self::STATE_TRANSFER; $response->setEffectiveUrl((string) $this->getUrl()); $this->response = $response; return $this; } public function setResponse(Response $response, $queued = false) { $response->setEffectiveUrl((string) $this->url); if ($queued) { $ed = $this->getEventDispatcher(); $ed->addListener('request.before_send', $f = function ($e) use ($response, &$f, $ed) { $e['request']->setResponse($response); $ed->removeListener('request.before_send', $f); }, -9999); } else { $this->response = $response; // If a specific response body is specified, then use it instead of the response's body if ($this->responseBody && !$this->responseBody->getCustomData('default') && !$response->isRedirect()) { $this->getResponseBody()->write((string) $this->response->getBody()); } else { $this->responseBody = $this->response->getBody(); } $this->setState(self::STATE_COMPLETE); } return $this; } public function setResponseBody($body) { // Attempt to open a file for writing if a string was passed if (is_string($body)) { // @codeCoverageIgnoreStart if (!($body = fopen($body, 'w+'))) { throw new InvalidArgumentException('Could not open ' . $body . ' for writing'); } // @codeCoverageIgnoreEnd } $this->responseBody = EntityBody::factory($body); return $this; } public function getResponseBody() { if ($this->responseBody === null) { $this->responseBody = EntityBody::factory()->setCustomData('default', true); } return $this->responseBody; } /** * Determine if the response body is repeatable (readable + seekable) * * @return bool * @deprecated Use getResponseBody()->isSeekable() * @codeCoverageIgnore */ public function isResponseBodyRepeatable() { Version::warn(__METHOD__ . ' is deprecated. Use $request->getResponseBody()->isRepeatable()'); return !$this->responseBody ? true : $this->responseBody->isRepeatable(); } public function getCookies() { if ($cookie = $this->getHeader('Cookie')) { $data = ParserRegistry::getInstance()->getParser('cookie')->parseCookie($cookie); return $data['cookies']; } return array(); } public function getCookie($name) { $cookies = $this->getCookies(); return isset($cookies[$name]) ? $cookies[$name] : null; } public function addCookie($name, $value) { if (!$this->hasHeader('Cookie')) { $this->setHeader('Cookie', "{$name}={$value}"); } else { $this->getHeader('Cookie')->add("{$name}={$value}"); } // Always use semicolons to separate multiple cookie headers $this->getHeader('Cookie')->setGlue(';'); return $this; } public function removeCookie($name) { if ($cookie = $this->getHeader('Cookie')) { foreach ($cookie as $cookieValue) { if (strpos($cookieValue, $name . '=') === 0) { $cookie->removeValue($cookieValue); } } } return $this; } public function setEventDispatcher(EventDispatcherInterface $eventDispatcher) { $this->eventDispatcher = $eventDispatcher; $this->eventDispatcher->addListener('request.error', array(__CLASS__, 'onRequestError'), -255); return $this; } public function getEventDispatcher() { if (!$this->eventDispatcher) { $this->setEventDispatcher(new EventDispatcher()); } return $this->eventDispatcher; } public function dispatch($eventName, array $context = array()) { $context['request'] = $this; return $this->getEventDispatcher()->dispatch($eventName, new Event($context)); } public function addSubscriber(EventSubscriberInterface $subscriber) { $this->getEventDispatcher()->addSubscriber($subscriber); return $this; } /** * Get an array containing the request and response for event notifications * * @return array */ protected function getEventArray() { return array( 'request' => $this, 'response' => $this->response ); } /** * Process a received response * * @param array $context Contextual information * @throws RequestException|BadResponseException on unsuccessful responses */ protected function processResponse(array $context = array()) { if (!$this->response) { // If no response, then processResponse shouldn't have been called $e = new RequestException('Error completing request'); $e->setRequest($this); throw $e; } $this->state = self::STATE_COMPLETE; // A request was sent, but we don't know if we'll send more or if the final response will be successful $this->dispatch('request.sent', $this->getEventArray() + $context); // Some response processors will remove the response or reset the state (example: ExponentialBackoffPlugin) if ($this->state == RequestInterface::STATE_COMPLETE) { // The request completed, so the HTTP transaction is complete $this->dispatch('request.complete', $this->getEventArray()); // If the response is bad, allow listeners to modify it or throw exceptions. You can change the response by // modifying the Event object in your listeners or calling setResponse() on the request if ($this->response->isError()) { $event = new Event($this->getEventArray()); $this->getEventDispatcher()->dispatch('request.error', $event); // Allow events of request.error to quietly change the response if ($event['response'] !== $this->response) { $this->response = $event['response']; } } // If a successful response was received, dispatch an event if ($this->response->isSuccessful()) { $this->dispatch('request.success', $this->getEventArray()); } } } /** * @deprecated Use Guzzle\Plugin\Cache\DefaultCanCacheStrategy * @codeCoverageIgnore */ public function canCache() { Version::warn(__METHOD__ . ' is deprecated. Use Guzzle\Plugin\Cache\DefaultCanCacheStrategy.'); if (class_exists('Guzzle\Plugin\Cache\DefaultCanCacheStrategy')) { $canCache = new \Guzzle\Plugin\Cache\DefaultCanCacheStrategy(); return $canCache->canCacheRequest($this); } else { return false; } } /** * @deprecated Use the history plugin (not emitting a warning as this is built-into the RedirectPlugin for now) * @codeCoverageIgnore */ public function setIsRedirect($isRedirect) { $this->isRedirect = $isRedirect; return $this; } /** * @deprecated Use the history plugin * @codeCoverageIgnore */ public function isRedirect() { Version::warn(__METHOD__ . ' is deprecated. Use the HistoryPlugin to track this.'); return $this->isRedirect; } } methods = array_flip(get_class_methods(__CLASS__)); } public function fromMessage($message) { $parsed = ParserRegistry::getInstance()->getParser('message')->parseRequest($message); if (!$parsed) { return false; } $request = $this->fromParts($parsed['method'], $parsed['request_url'], $parsed['headers'], $parsed['body'], $parsed['protocol'], $parsed['version']); // EntityEnclosingRequest adds an "Expect: 100-Continue" header when using a raw request body for PUT or POST // requests. This factory method should accurately reflect the message, so here we are removing the Expect // header if one was not supplied in the message. if (!isset($parsed['headers']['Expect']) && !isset($parsed['headers']['expect'])) { $request->removeHeader('Expect'); } return $request; } public function fromParts( $method, array $urlParts, $headers = null, $body = null, $protocol = 'HTTP', $protocolVersion = '1.1' ) { return $this->create($method, Url::buildUrl($urlParts), $headers, $body) ->setProtocolVersion($protocolVersion); } public function create($method, $url, $headers = null, $body = null, array $options = array()) { $method = strtoupper($method); if ($method == 'GET' || $method == 'HEAD' || $method == 'TRACE') { // Handle non-entity-enclosing request methods $request = new $this->requestClass($method, $url, $headers); if ($body) { // The body is where the response body will be stored $type = gettype($body); if ($type == 'string' || $type == 'resource' || $type == 'object') { $request->setResponseBody($body); } } } else { // Create an entity enclosing request by default $request = new $this->entityEnclosingRequestClass($method, $url, $headers); if ($body || $body === '0') { // Add POST fields and files to an entity enclosing request if an array is used if (is_array($body) || $body instanceof Collection) { // Normalize PHP style cURL uploads with a leading '@' symbol foreach ($body as $key => $value) { if (is_string($value) && substr($value, 0, 1) == '@') { $request->addPostFile($key, $value); unset($body[$key]); } } // Add the fields if they are still present and not all files $request->addPostFields($body); } else { // Add a raw entity body body to the request $request->setBody($body, (string) $request->getHeader('Content-Type')); if ((string) $request->getHeader('Transfer-Encoding') == 'chunked') { $request->removeHeader('Content-Length'); } } } } if ($options) { $this->applyOptions($request, $options); } return $request; } /** * Clone a request while changing the method. Emulates the behavior of * {@see Guzzle\Http\Message\Request::clone}, but can change the HTTP method. * * @param RequestInterface $request Request to clone * @param string $method Method to set * * @return RequestInterface */ public function cloneRequestWithMethod(RequestInterface $request, $method) { // Create the request with the same client if possible if ($request->getClient()) { $cloned = $request->getClient()->createRequest($method, $request->getUrl(), $request->getHeaders()); } else { $cloned = $this->create($method, $request->getUrl(), $request->getHeaders()); } $cloned->getCurlOptions()->replace($request->getCurlOptions()->toArray()); $cloned->setEventDispatcher(clone $request->getEventDispatcher()); // Ensure that that the Content-Length header is not copied if changing to GET or HEAD if (!($cloned instanceof EntityEnclosingRequestInterface)) { $cloned->removeHeader('Content-Length'); } elseif ($request instanceof EntityEnclosingRequestInterface) { $cloned->setBody($request->getBody()); } $cloned->getParams()->replace($request->getParams()->toArray()); $cloned->dispatch('request.clone', array('request' => $cloned)); return $cloned; } public function applyOptions(RequestInterface $request, array $options = array(), $flags = self::OPTIONS_NONE) { // Iterate over each key value pair and attempt to apply a config using function visitors foreach ($options as $key => $value) { $method = "visit_{$key}"; if (isset($this->methods[$method])) { $this->{$method}($request, $value, $flags); } } } protected function visit_headers(RequestInterface $request, $value, $flags) { if (!is_array($value)) { throw new InvalidArgumentException('headers value must be an array'); } if ($flags & self::OPTIONS_AS_DEFAULTS) { // Merge headers in but do not overwrite existing values foreach ($value as $key => $header) { if (!$request->hasHeader($key)) { $request->setHeader($key, $header); } } } else { $request->addHeaders($value); } } protected function visit_body(RequestInterface $request, $value, $flags) { if ($request instanceof EntityEnclosingRequestInterface) { $request->setBody($value); } else { throw new InvalidArgumentException('Attempting to set a body on a non-entity-enclosing request'); } } protected function visit_allow_redirects(RequestInterface $request, $value, $flags) { if ($value === false) { $request->getParams()->set(RedirectPlugin::DISABLE, true); } } protected function visit_auth(RequestInterface $request, $value, $flags) { if (!is_array($value)) { throw new InvalidArgumentException('auth value must be an array'); } $request->setAuth($value[0], isset($value[1]) ? $value[1] : null, isset($value[2]) ? $value[2] : 'basic'); } protected function visit_query(RequestInterface $request, $value, $flags) { if (!is_array($value)) { throw new InvalidArgumentException('query value must be an array'); } if ($flags & self::OPTIONS_AS_DEFAULTS) { // Merge query string values in but do not overwrite existing values $query = $request->getQuery(); $query->overwriteWith(array_diff_key($value, $query->toArray())); } else { $request->getQuery()->overwriteWith($value); } } protected function visit_cookies(RequestInterface $request, $value, $flags) { if (!is_array($value)) { throw new InvalidArgumentException('cookies value must be an array'); } foreach ($value as $name => $v) { $request->addCookie($name, $v); } } protected function visit_events(RequestInterface $request, $value, $flags) { if (!is_array($value)) { throw new InvalidArgumentException('events value must be an array'); } foreach ($value as $name => $method) { if (is_array($method)) { $request->getEventDispatcher()->addListener($name, $method[0], $method[1]); } else { $request->getEventDispatcher()->addListener($name, $method); } } } protected function visit_plugins(RequestInterface $request, $value, $flags) { if (!is_array($value)) { throw new InvalidArgumentException('plugins value must be an array'); } foreach ($value as $plugin) { $request->addSubscriber($plugin); } } protected function visit_exceptions(RequestInterface $request, $value, $flags) { if ($value === false || $value === 0) { $dispatcher = $request->getEventDispatcher(); foreach ($dispatcher->getListeners('request.error') as $listener) { if (is_array($listener) && $listener[0] == 'Guzzle\Http\Message\Request' && $listener[1] = 'onRequestError') { $dispatcher->removeListener('request.error', $listener); break; } } } } protected function visit_save_to(RequestInterface $request, $value, $flags) { $request->setResponseBody($value); } protected function visit_params(RequestInterface $request, $value, $flags) { if (!is_array($value)) { throw new InvalidArgumentException('params value must be an array'); } $request->getParams()->overwriteWith($value); } protected function visit_timeout(RequestInterface $request, $value, $flags) { if (defined('CURLOPT_TIMEOUT_MS')) { $request->getCurlOptions()->set(CURLOPT_TIMEOUT_MS, $value * 1000); } else { $request->getCurlOptions()->set(CURLOPT_TIMEOUT, $value); } } protected function visit_connect_timeout(RequestInterface $request, $value, $flags) { if (defined('CURLOPT_CONNECTTIMEOUT_MS')) { $request->getCurlOptions()->set(CURLOPT_CONNECTTIMEOUT_MS, $value * 1000); } else { $request->getCurlOptions()->set(CURLOPT_CONNECTTIMEOUT, $value); } } protected function visit_debug(RequestInterface $request, $value, $flags) { if ($value) { $request->getCurlOptions()->set(CURLOPT_VERBOSE, true); } } protected function visit_verify(RequestInterface $request, $value, $flags) { $curl = $request->getCurlOptions(); if ($value === true || is_string($value)) { $curl[CURLOPT_SSL_VERIFYHOST] = 2; $curl[CURLOPT_SSL_VERIFYPEER] = true; if ($value !== true) { $curl[CURLOPT_CAINFO] = $value; } } elseif ($value === false) { unset($curl[CURLOPT_CAINFO]); $curl[CURLOPT_SSL_VERIFYHOST] = 0; $curl[CURLOPT_SSL_VERIFYPEER] = false; } } protected function visit_proxy(RequestInterface $request, $value, $flags) { $request->getCurlOptions()->set(CURLOPT_PROXY, $value, $flags); } protected function visit_cert(RequestInterface $request, $value, $flags) { if (is_array($value)) { $request->getCurlOptions()->set(CURLOPT_SSLCERT, $value[0]); $request->getCurlOptions()->set(CURLOPT_SSLCERTPASSWD, $value[1]); } else { $request->getCurlOptions()->set(CURLOPT_SSLCERT, $value); } } protected function visit_ssl_key(RequestInterface $request, $value, $flags) { if (is_array($value)) { $request->getCurlOptions()->set(CURLOPT_SSLKEY, $value[0]); $request->getCurlOptions()->set(CURLOPT_SSLKEYPASSWD, $value[1]); } else { $request->getCurlOptions()->set(CURLOPT_SSLKEY, $value); } } } 'Continue', 101 => 'Switching Protocols', 102 => 'Processing', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 207 => 'Multi-Status', 208 => 'Already Reported', 226 => 'IM Used', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect', 308 => 'Permanent Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', 422 => 'Unprocessable Entity', 423 => 'Locked', 424 => 'Failed Dependency', 425 => 'Reserved for WebDAV advanced collections expired proposal', 426 => 'Upgrade required', 428 => 'Precondition Required', 429 => 'Too Many Requests', 431 => 'Request Header Fields Too Large', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported', 506 => 'Variant Also Negotiates (Experimental)', 507 => 'Insufficient Storage', 508 => 'Loop Detected', 510 => 'Not Extended', 511 => 'Network Authentication Required', ); /** @var EntityBodyInterface The response body */ protected $body; /** @var string The reason phrase of the response (human readable code) */ protected $reasonPhrase; /** @var string The status code of the response */ protected $statusCode; /** @var array Information about the request */ protected $info = array(); /** @var string The effective URL that returned this response */ protected $effectiveUrl; /** @var array Cacheable response codes (see RFC 2616:13.4) */ protected static $cacheResponseCodes = array(200, 203, 206, 300, 301, 410); /** * Create a new Response based on a raw response message * * @param string $message Response message * * @return self|bool Returns false on error */ public static function fromMessage($message) { $data = ParserRegistry::getInstance()->getParser('message')->parseResponse($message); if (!$data) { return false; } $response = new static($data['code'], $data['headers'], $data['body']); $response->setProtocol($data['protocol'], $data['version']) ->setStatus($data['code'], $data['reason_phrase']); // Set the appropriate Content-Length if the one set is inaccurate (e.g. setting to X) $contentLength = (string) $response->getHeader('Content-Length'); $actualLength = strlen($data['body']); if (strlen($data['body']) > 0 && $contentLength != $actualLength) { $response->setHeader('Content-Length', $actualLength); } return $response; } /** * Construct the response * * @param string $statusCode The response status code (e.g. 200, 404, etc) * @param ToArrayInterface|array $headers The response headers * @param string|resource|EntityBodyInterface $body The body of the response * * @throws BadResponseException if an invalid response code is given */ public function __construct($statusCode, $headers = null, $body = null) { parent::__construct(); $this->setStatus($statusCode); $this->body = EntityBody::factory($body !== null ? $body : ''); if ($headers) { if (is_array($headers)) { $this->setHeaders($headers); } elseif ($headers instanceof ToArrayInterface) { $this->setHeaders($headers->toArray()); } else { throw new BadResponseException('Invalid headers argument received'); } } } /** * @return string */ public function __toString() { return $this->getMessage(); } public function serialize() { return json_encode(array( 'status' => $this->statusCode, 'body' => (string) $this->body, 'headers' => $this->headers->toArray() )); } public function unserialize($serialize) { $data = json_decode($serialize, true); $this->__construct($data['status'], $data['headers'], $data['body']); } /** * Get the response entity body * * @param bool $asString Set to TRUE to return a string of the body rather than a full body object * * @return EntityBodyInterface|string */ public function getBody($asString = false) { return $asString ? (string) $this->body : $this->body; } /** * Set the response entity body * * @param EntityBodyInterface|string $body Body to set * * @return self */ public function setBody($body) { $this->body = EntityBody::factory($body); return $this; } /** * Set the protocol and protocol version of the response * * @param string $protocol Response protocol * @param string $version Protocol version * * @return self */ public function setProtocol($protocol, $version) { $this->protocol = $protocol; $this->protocolVersion = $version; return $this; } /** * Get the protocol used for the response (e.g. HTTP) * * @return string */ public function getProtocol() { return $this->protocol; } /** * Get the HTTP protocol version * * @return string */ public function getProtocolVersion() { return $this->protocolVersion; } /** * Get a cURL transfer information * * @param string $key A single statistic to check * * @return array|string|null Returns all stats if no key is set, a single stat if a key is set, or null if a key * is set and not found * @link http://www.php.net/manual/en/function.curl-getinfo.php */ public function getInfo($key = null) { if ($key === null) { return $this->info; } elseif (array_key_exists($key, $this->info)) { return $this->info[$key]; } else { return null; } } /** * Set the transfer information * * @param array $info Array of cURL transfer stats * * @return self */ public function setInfo(array $info) { $this->info = $info; return $this; } /** * Set the response status * * @param int $statusCode Response status code to set * @param string $reasonPhrase Response reason phrase * * @return self * @throws BadResponseException when an invalid response code is received */ public function setStatus($statusCode, $reasonPhrase = '') { $this->statusCode = (int) $statusCode; if (!$reasonPhrase && isset(self::$statusTexts[$this->statusCode])) { $this->reasonPhrase = self::$statusTexts[$this->statusCode]; } else { $this->reasonPhrase = $reasonPhrase; } return $this; } /** * Get the response status code * * @return integer */ public function getStatusCode() { return $this->statusCode; } /** * Get the entire response as a string * * @return string */ public function getMessage() { $message = $this->getRawHeaders(); // Only include the body in the message if the size is < 2MB $size = $this->body->getSize(); if ($size < 2097152) { $message .= (string) $this->body; } return $message; } /** * Get the the raw message headers as a string * * @return string */ public function getRawHeaders() { $headers = 'HTTP/1.1 ' . $this->statusCode . ' ' . $this->reasonPhrase . "\r\n"; $lines = $this->getHeaderLines(); if (!empty($lines)) { $headers .= implode("\r\n", $lines) . "\r\n"; } return $headers . "\r\n"; } /** * Get the response reason phrase- a human readable version of the numeric * status code * * @return string */ public function getReasonPhrase() { return $this->reasonPhrase; } /** * Get the Accept-Ranges HTTP header * * @return string Returns what partial content range types this server supports. */ public function getAcceptRanges() { return (string) $this->getHeader('Accept-Ranges'); } /** * Calculate the age of the response * * @return integer */ public function calculateAge() { $age = $this->getHeader('Age'); if ($age === null && $this->getDate()) { $age = time() - strtotime($this->getDate()); } return $age === null ? null : (int) (string) $age; } /** * Get the Age HTTP header * * @return integer|null Returns the age the object has been in a proxy cache in seconds. */ public function getAge() { return (string) $this->getHeader('Age'); } /** * Get the Allow HTTP header * * @return string|null Returns valid actions for a specified resource. To be used for a 405 Method not allowed. */ public function getAllow() { return (string) $this->getHeader('Allow'); } /** * Check if an HTTP method is allowed by checking the Allow response header * * @param string $method Method to check * * @return bool */ public function isMethodAllowed($method) { $allow = $this->getHeader('Allow'); if ($allow) { foreach (explode(',', $allow) as $allowable) { if (!strcasecmp(trim($allowable), $method)) { return true; } } } return false; } /** * Get the Cache-Control HTTP header * * @return string */ public function getCacheControl() { return (string) $this->getHeader('Cache-Control'); } /** * Get the Connection HTTP header * * @return string */ public function getConnection() { return (string) $this->getHeader('Connection'); } /** * Get the Content-Encoding HTTP header * * @return string|null */ public function getContentEncoding() { return (string) $this->getHeader('Content-Encoding'); } /** * Get the Content-Language HTTP header * * @return string|null Returns the language the content is in. */ public function getContentLanguage() { return (string) $this->getHeader('Content-Language'); } /** * Get the Content-Length HTTP header * * @return integer Returns the length of the response body in bytes */ public function getContentLength() { return (int) (string) $this->getHeader('Content-Length'); } /** * Get the Content-Location HTTP header * * @return string|null Returns an alternate location for the returned data (e.g /index.htm) */ public function getContentLocation() { return (string) $this->getHeader('Content-Location'); } /** * Get the Content-Disposition HTTP header * * @return string|null Returns the Content-Disposition header */ public function getContentDisposition() { return (string) $this->getHeader('Content-Disposition'); } /** * Get the Content-MD5 HTTP header * * @return string|null Returns a Base64-encoded binary MD5 sum of the content of the response. */ public function getContentMd5() { return (string) $this->getHeader('Content-MD5'); } /** * Get the Content-Range HTTP header * * @return string Returns where in a full body message this partial message belongs (e.g. bytes 21010-47021/47022). */ public function getContentRange() { return (string) $this->getHeader('Content-Range'); } /** * Get the Content-Type HTTP header * * @return string Returns the mime type of this content. */ public function getContentType() { return (string) $this->getHeader('Content-Type'); } /** * Checks if the Content-Type is of a certain type. This is useful if the * Content-Type header contains charset information and you need to know if * the Content-Type matches a particular type. * * @param string $type Content type to check against * * @return bool */ public function isContentType($type) { return stripos($this->getHeader('Content-Type'), $type) !== false; } /** * Get the Date HTTP header * * @return string|null Returns the date and time that the message was sent. */ public function getDate() { return (string) $this->getHeader('Date'); } /** * Get the ETag HTTP header * * @return string|null Returns an identifier for a specific version of a resource, often a Message digest. */ public function getEtag() { return (string) $this->getHeader('ETag'); } /** * Get the Expires HTTP header * * @return string|null Returns the date/time after which the response is considered stale. */ public function getExpires() { return (string) $this->getHeader('Expires'); } /** * Get the Last-Modified HTTP header * * @return string|null Returns the last modified date for the requested object, in RFC 2822 format * (e.g. Tue, 15 Nov 1994 12:45:26 GMT) */ public function getLastModified() { return (string) $this->getHeader('Last-Modified'); } /** * Get the Location HTTP header * * @return string|null Used in redirection, or when a new resource has been created. */ public function getLocation() { return (string) $this->getHeader('Location'); } /** * Get the Pragma HTTP header * * @return Header|null Returns the implementation-specific headers that may have various effects anywhere along * the request-response chain. */ public function getPragma() { return (string) $this->getHeader('Pragma'); } /** * Get the Proxy-Authenticate HTTP header * * @return string|null Authentication to access the proxy (e.g. Basic) */ public function getProxyAuthenticate() { return (string) $this->getHeader('Proxy-Authenticate'); } /** * Get the Retry-After HTTP header * * @return int|null If an entity is temporarily unavailable, this instructs the client to try again after a * specified period of time. */ public function getRetryAfter() { return (string) $this->getHeader('Retry-After'); } /** * Get the Server HTTP header * * @return string|null A name for the server */ public function getServer() { return (string) $this->getHeader('Server'); } /** * Get the Set-Cookie HTTP header * * @return string|null An HTTP cookie. */ public function getSetCookie() { return (string) $this->getHeader('Set-Cookie'); } /** * Get the Trailer HTTP header * * @return string|null The Trailer general field value indicates that the given set of header fields is present in * the trailer of a message encoded with chunked transfer-coding. */ public function getTrailer() { return (string) $this->getHeader('Trailer'); } /** * Get the Transfer-Encoding HTTP header * * @return string|null The form of encoding used to safely transfer the entity to the user */ public function getTransferEncoding() { return (string) $this->getHeader('Transfer-Encoding'); } /** * Get the Vary HTTP header * * @return string|null Tells downstream proxies how to match future request headers to decide whether the cached * response can be used rather than requesting a fresh one from the origin server. */ public function getVary() { return (string) $this->getHeader('Vary'); } /** * Get the Via HTTP header * * @return string|null Informs the client of proxies through which the response was sent. */ public function getVia() { return (string) $this->getHeader('Via'); } /** * Get the Warning HTTP header * * @return string|null A general warning about possible problems with the entity body */ public function getWarning() { return (string) $this->getHeader('Warning'); } /** * Get the WWW-Authenticate HTTP header * * @return string|null Indicates the authentication scheme that should be used to access the requested entity */ public function getWwwAuthenticate() { return (string) $this->getHeader('WWW-Authenticate'); } /** * Checks if HTTP Status code is a Client Error (4xx) * * @return bool */ public function isClientError() { return $this->statusCode >= 400 && $this->statusCode < 500; } /** * Checks if HTTP Status code is Server OR Client Error (4xx or 5xx) * * @return boolean */ public function isError() { return $this->isClientError() || $this->isServerError(); } /** * Checks if HTTP Status code is Information (1xx) * * @return bool */ public function isInformational() { return $this->statusCode < 200; } /** * Checks if HTTP Status code is a Redirect (3xx) * * @return bool */ public function isRedirect() { return $this->statusCode >= 300 && $this->statusCode < 400; } /** * Checks if HTTP Status code is Server Error (5xx) * * @return bool */ public function isServerError() { return $this->statusCode >= 500 && $this->statusCode < 600; } /** * Checks if HTTP Status code is Successful (2xx | 304) * * @return bool */ public function isSuccessful() { return ($this->statusCode >= 200 && $this->statusCode < 300) || $this->statusCode == 304; } /** * Check if the response can be cached based on the response headers * * @return bool Returns TRUE if the response can be cached or false if not */ public function canCache() { // Check if the response is cacheable based on the code if (!in_array((int) $this->getStatusCode(), self::$cacheResponseCodes)) { return false; } // Make sure a valid body was returned and can be cached if ((!$this->getBody()->isReadable() || !$this->getBody()->isSeekable()) && ($this->getContentLength() > 0 || $this->getTransferEncoding() == 'chunked')) { return false; } // Never cache no-store resources (this is a private cache, so private // can be cached) if ($this->getHeader('Cache-Control') && $this->getHeader('Cache-Control')->hasDirective('no-store')) { return false; } return $this->isFresh() || $this->getFreshness() === null || $this->canValidate(); } /** * Gets the number of seconds from the current time in which this response is still considered fresh * * @return int|null Returns the number of seconds */ public function getMaxAge() { if ($header = $this->getHeader('Cache-Control')) { // s-max-age, then max-age, then Expires if ($age = $header->getDirective('s-maxage')) { return $age; } if ($age = $header->getDirective('max-age')) { return $age; } } if ($this->getHeader('Expires')) { return strtotime($this->getExpires()) - time(); } return null; } /** * Check if the response is considered fresh. * * A response is considered fresh when its age is less than or equal to the freshness lifetime (maximum age) of the * response. * * @return bool|null */ public function isFresh() { $fresh = $this->getFreshness(); return $fresh === null ? null : $fresh >= 0; } /** * Check if the response can be validated against the origin server using a conditional GET request. * * @return bool */ public function canValidate() { return $this->getEtag() || $this->getLastModified(); } /** * Get the freshness of the response by returning the difference of the maximum lifetime of the response and the * age of the response (max-age - age). * * Freshness values less than 0 mean that the response is no longer fresh and is ABS(freshness) seconds expired. * Freshness values of greater than zero is the number of seconds until the response is no longer fresh. A NULL * result means that no freshness information is available. * * @return int */ public function getFreshness() { $maxAge = $this->getMaxAge(); $age = $this->calculateAge(); return $maxAge && $age ? ($maxAge - $age) : null; } /** * Parse the JSON response body and return an array * * @return array|string|int|bool|float * @throws RuntimeException if the response body is not in JSON format */ public function json() { $data = json_decode((string) $this->body, true); if (JSON_ERROR_NONE !== json_last_error()) { throw new RuntimeException('Unable to parse response body into JSON: ' . json_last_error()); } return $data === null ? array() : $data; } /** * Parse the XML response body and return a \SimpleXMLElement. * * In order to prevent XXE attacks, this method disables loading external * entities. If you rely on external entities, then you must parse the * XML response manually by accessing the response body directly. * * @return \SimpleXMLElement * @throws RuntimeException if the response body is not in XML format * @link http://websec.io/2012/08/27/Preventing-XXE-in-PHP.html */ public function xml() { $errorMessage = null; $internalErrors = libxml_use_internal_errors(true); $disableEntities = libxml_disable_entity_loader(true); libxml_clear_errors(); try { $xml = new \SimpleXMLElement((string) $this->body ?: '', LIBXML_NONET); if ($error = libxml_get_last_error()) { $errorMessage = $error->message; } } catch (\Exception $e) { $errorMessage = $e->getMessage(); } libxml_clear_errors(); libxml_use_internal_errors($internalErrors); libxml_disable_entity_loader($disableEntities); if ($errorMessage) { throw new RuntimeException('Unable to parse response body into XML: ' . $errorMessage); } return $xml; } /** * Get the redirect count of this response * * @return int */ public function getRedirectCount() { return (int) $this->params->get(RedirectPlugin::REDIRECT_COUNT); } /** * Set the effective URL that resulted in this response (e.g. the last redirect URL) * * @param string $url The effective URL * * @return self */ public function setEffectiveUrl($url) { $this->effectiveUrl = $url; return $this; } /** * Get the effective URL that resulted in this response (e.g. the last redirect URL) * * @return string */ public function getEffectiveUrl() { return $this->effectiveUrl; } /** * @deprecated * @codeCoverageIgnore */ public function getPreviousResponse() { Version::warn(__METHOD__ . ' is deprecated. Use the HistoryPlugin.'); return null; } /** * @deprecated * @codeCoverageIgnore */ public function setRequest($request) { Version::warn(__METHOD__ . ' is deprecated'); return $this; } /** * @deprecated * @codeCoverageIgnore */ public function getRequest() { Version::warn(__METHOD__ . ' is deprecated'); return null; } } 'text/vnd.in3d.3dml', '3g2' => 'video/3gpp2', '3gp' => 'video/3gpp', '7z' => 'application/x-7z-compressed', 'aab' => 'application/x-authorware-bin', 'aac' => 'audio/x-aac', 'aam' => 'application/x-authorware-map', 'aas' => 'application/x-authorware-seg', 'abw' => 'application/x-abiword', 'ac' => 'application/pkix-attr-cert', 'acc' => 'application/vnd.americandynamics.acc', 'ace' => 'application/x-ace-compressed', 'acu' => 'application/vnd.acucobol', 'acutc' => 'application/vnd.acucorp', 'adp' => 'audio/adpcm', 'aep' => 'application/vnd.audiograph', 'afm' => 'application/x-font-type1', 'afp' => 'application/vnd.ibm.modcap', 'ahead' => 'application/vnd.ahead.space', 'ai' => 'application/postscript', 'aif' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'air' => 'application/vnd.adobe.air-application-installer-package+zip', 'ait' => 'application/vnd.dvb.ait', 'ami' => 'application/vnd.amiga.ami', 'apk' => 'application/vnd.android.package-archive', 'application' => 'application/x-ms-application', 'apr' => 'application/vnd.lotus-approach', 'asa' => 'text/plain', 'asax' => 'application/octet-stream', 'asc' => 'application/pgp-signature', 'ascx' => 'text/plain', 'asf' => 'video/x-ms-asf', 'ashx' => 'text/plain', 'asm' => 'text/x-asm', 'asmx' => 'text/plain', 'aso' => 'application/vnd.accpac.simply.aso', 'asp' => 'text/plain', 'aspx' => 'text/plain', 'asx' => 'video/x-ms-asf', 'atc' => 'application/vnd.acucorp', 'atom' => 'application/atom+xml', 'atomcat' => 'application/atomcat+xml', 'atomsvc' => 'application/atomsvc+xml', 'atx' => 'application/vnd.antix.game-component', 'au' => 'audio/basic', 'avi' => 'video/x-msvideo', 'aw' => 'application/applixware', 'axd' => 'text/plain', 'azf' => 'application/vnd.airzip.filesecure.azf', 'azs' => 'application/vnd.airzip.filesecure.azs', 'azw' => 'application/vnd.amazon.ebook', 'bat' => 'application/x-msdownload', 'bcpio' => 'application/x-bcpio', 'bdf' => 'application/x-font-bdf', 'bdm' => 'application/vnd.syncml.dm+wbxml', 'bed' => 'application/vnd.realvnc.bed', 'bh2' => 'application/vnd.fujitsu.oasysprs', 'bin' => 'application/octet-stream', 'bmi' => 'application/vnd.bmi', 'bmp' => 'image/bmp', 'book' => 'application/vnd.framemaker', 'box' => 'application/vnd.previewsystems.box', 'boz' => 'application/x-bzip2', 'bpk' => 'application/octet-stream', 'btif' => 'image/prs.btif', 'bz' => 'application/x-bzip', 'bz2' => 'application/x-bzip2', 'c' => 'text/x-c', 'c11amc' => 'application/vnd.cluetrust.cartomobile-config', 'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg', 'c4d' => 'application/vnd.clonk.c4group', 'c4f' => 'application/vnd.clonk.c4group', 'c4g' => 'application/vnd.clonk.c4group', 'c4p' => 'application/vnd.clonk.c4group', 'c4u' => 'application/vnd.clonk.c4group', 'cab' => 'application/vnd.ms-cab-compressed', 'car' => 'application/vnd.curl.car', 'cat' => 'application/vnd.ms-pki.seccat', 'cc' => 'text/x-c', 'cct' => 'application/x-director', 'ccxml' => 'application/ccxml+xml', 'cdbcmsg' => 'application/vnd.contact.cmsg', 'cdf' => 'application/x-netcdf', 'cdkey' => 'application/vnd.mediastation.cdkey', 'cdmia' => 'application/cdmi-capability', 'cdmic' => 'application/cdmi-container', 'cdmid' => 'application/cdmi-domain', 'cdmio' => 'application/cdmi-object', 'cdmiq' => 'application/cdmi-queue', 'cdx' => 'chemical/x-cdx', 'cdxml' => 'application/vnd.chemdraw+xml', 'cdy' => 'application/vnd.cinderella', 'cer' => 'application/pkix-cert', 'cfc' => 'application/x-coldfusion', 'cfm' => 'application/x-coldfusion', 'cgm' => 'image/cgm', 'chat' => 'application/x-chat', 'chm' => 'application/vnd.ms-htmlhelp', 'chrt' => 'application/vnd.kde.kchart', 'cif' => 'chemical/x-cif', 'cii' => 'application/vnd.anser-web-certificate-issue-initiation', 'cil' => 'application/vnd.ms-artgalry', 'cla' => 'application/vnd.claymore', 'class' => 'application/java-vm', 'clkk' => 'application/vnd.crick.clicker.keyboard', 'clkp' => 'application/vnd.crick.clicker.palette', 'clkt' => 'application/vnd.crick.clicker.template', 'clkw' => 'application/vnd.crick.clicker.wordbank', 'clkx' => 'application/vnd.crick.clicker', 'clp' => 'application/x-msclip', 'cmc' => 'application/vnd.cosmocaller', 'cmdf' => 'chemical/x-cmdf', 'cml' => 'chemical/x-cml', 'cmp' => 'application/vnd.yellowriver-custom-menu', 'cmx' => 'image/x-cmx', 'cod' => 'application/vnd.rim.cod', 'com' => 'application/x-msdownload', 'conf' => 'text/plain', 'cpio' => 'application/x-cpio', 'cpp' => 'text/x-c', 'cpt' => 'application/mac-compactpro', 'crd' => 'application/x-mscardfile', 'crl' => 'application/pkix-crl', 'crt' => 'application/x-x509-ca-cert', 'cryptonote' => 'application/vnd.rig.cryptonote', 'cs' => 'text/plain', 'csh' => 'application/x-csh', 'csml' => 'chemical/x-csml', 'csp' => 'application/vnd.commonspace', 'css' => 'text/css', 'cst' => 'application/x-director', 'csv' => 'text/csv', 'cu' => 'application/cu-seeme', 'curl' => 'text/vnd.curl', 'cww' => 'application/prs.cww', 'cxt' => 'application/x-director', 'cxx' => 'text/x-c', 'dae' => 'model/vnd.collada+xml', 'daf' => 'application/vnd.mobius.daf', 'dataless' => 'application/vnd.fdsn.seed', 'davmount' => 'application/davmount+xml', 'dcr' => 'application/x-director', 'dcurl' => 'text/vnd.curl.dcurl', 'dd2' => 'application/vnd.oma.dd2+xml', 'ddd' => 'application/vnd.fujixerox.ddd', 'deb' => 'application/x-debian-package', 'def' => 'text/plain', 'deploy' => 'application/octet-stream', 'der' => 'application/x-x509-ca-cert', 'dfac' => 'application/vnd.dreamfactory', 'dic' => 'text/x-c', 'dir' => 'application/x-director', 'dis' => 'application/vnd.mobius.dis', 'dist' => 'application/octet-stream', 'distz' => 'application/octet-stream', 'djv' => 'image/vnd.djvu', 'djvu' => 'image/vnd.djvu', 'dll' => 'application/x-msdownload', 'dmg' => 'application/octet-stream', 'dms' => 'application/octet-stream', 'dna' => 'application/vnd.dna', 'doc' => 'application/msword', 'docm' => 'application/vnd.ms-word.document.macroenabled.12', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'dot' => 'application/msword', 'dotm' => 'application/vnd.ms-word.template.macroenabled.12', 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'dp' => 'application/vnd.osgi.dp', 'dpg' => 'application/vnd.dpgraph', 'dra' => 'audio/vnd.dra', 'dsc' => 'text/prs.lines.tag', 'dssc' => 'application/dssc+der', 'dtb' => 'application/x-dtbook+xml', 'dtd' => 'application/xml-dtd', 'dts' => 'audio/vnd.dts', 'dtshd' => 'audio/vnd.dts.hd', 'dump' => 'application/octet-stream', 'dvi' => 'application/x-dvi', 'dwf' => 'model/vnd.dwf', 'dwg' => 'image/vnd.dwg', 'dxf' => 'image/vnd.dxf', 'dxp' => 'application/vnd.spotfire.dxp', 'dxr' => 'application/x-director', 'ecelp4800' => 'audio/vnd.nuera.ecelp4800', 'ecelp7470' => 'audio/vnd.nuera.ecelp7470', 'ecelp9600' => 'audio/vnd.nuera.ecelp9600', 'ecma' => 'application/ecmascript', 'edm' => 'application/vnd.novadigm.edm', 'edx' => 'application/vnd.novadigm.edx', 'efif' => 'application/vnd.picsel', 'ei6' => 'application/vnd.pg.osasli', 'elc' => 'application/octet-stream', 'eml' => 'message/rfc822', 'emma' => 'application/emma+xml', 'eol' => 'audio/vnd.digital-winds', 'eot' => 'application/vnd.ms-fontobject', 'eps' => 'application/postscript', 'epub' => 'application/epub+zip', 'es3' => 'application/vnd.eszigno3+xml', 'esf' => 'application/vnd.epson.esf', 'et3' => 'application/vnd.eszigno3+xml', 'etx' => 'text/x-setext', 'exe' => 'application/x-msdownload', 'exi' => 'application/exi', 'ext' => 'application/vnd.novadigm.ext', 'ez' => 'application/andrew-inset', 'ez2' => 'application/vnd.ezpix-album', 'ez3' => 'application/vnd.ezpix-package', 'f' => 'text/x-fortran', 'f4v' => 'video/x-f4v', 'f77' => 'text/x-fortran', 'f90' => 'text/x-fortran', 'fbs' => 'image/vnd.fastbidsheet', 'fcs' => 'application/vnd.isac.fcs', 'fdf' => 'application/vnd.fdf', 'fe_launch' => 'application/vnd.denovo.fcselayout-link', 'fg5' => 'application/vnd.fujitsu.oasysgp', 'fgd' => 'application/x-director', 'fh' => 'image/x-freehand', 'fh4' => 'image/x-freehand', 'fh5' => 'image/x-freehand', 'fh7' => 'image/x-freehand', 'fhc' => 'image/x-freehand', 'fig' => 'application/x-xfig', 'fli' => 'video/x-fli', 'flo' => 'application/vnd.micrografx.flo', 'flv' => 'video/x-flv', 'flw' => 'application/vnd.kde.kivio', 'flx' => 'text/vnd.fmi.flexstor', 'fly' => 'text/vnd.fly', 'fm' => 'application/vnd.framemaker', 'fnc' => 'application/vnd.frogans.fnc', 'for' => 'text/x-fortran', 'fpx' => 'image/vnd.fpx', 'frame' => 'application/vnd.framemaker', 'fsc' => 'application/vnd.fsc.weblaunch', 'fst' => 'image/vnd.fst', 'ftc' => 'application/vnd.fluxtime.clip', 'fti' => 'application/vnd.anser-web-funds-transfer-initiation', 'fvt' => 'video/vnd.fvt', 'fxp' => 'application/vnd.adobe.fxp', 'fxpl' => 'application/vnd.adobe.fxp', 'fzs' => 'application/vnd.fuzzysheet', 'g2w' => 'application/vnd.geoplan', 'g3' => 'image/g3fax', 'g3w' => 'application/vnd.geospace', 'gac' => 'application/vnd.groove-account', 'gdl' => 'model/vnd.gdl', 'geo' => 'application/vnd.dynageo', 'gex' => 'application/vnd.geometry-explorer', 'ggb' => 'application/vnd.geogebra.file', 'ggt' => 'application/vnd.geogebra.tool', 'ghf' => 'application/vnd.groove-help', 'gif' => 'image/gif', 'gim' => 'application/vnd.groove-identity-message', 'gmx' => 'application/vnd.gmx', 'gnumeric' => 'application/x-gnumeric', 'gph' => 'application/vnd.flographit', 'gqf' => 'application/vnd.grafeq', 'gqs' => 'application/vnd.grafeq', 'gram' => 'application/srgs', 'gre' => 'application/vnd.geometry-explorer', 'grv' => 'application/vnd.groove-injector', 'grxml' => 'application/srgs+xml', 'gsf' => 'application/x-font-ghostscript', 'gtar' => 'application/x-gtar', 'gtm' => 'application/vnd.groove-tool-message', 'gtw' => 'model/vnd.gtw', 'gv' => 'text/vnd.graphviz', 'gxt' => 'application/vnd.geonext', 'h' => 'text/x-c', 'h261' => 'video/h261', 'h263' => 'video/h263', 'h264' => 'video/h264', 'hal' => 'application/vnd.hal+xml', 'hbci' => 'application/vnd.hbci', 'hdf' => 'application/x-hdf', 'hh' => 'text/x-c', 'hlp' => 'application/winhlp', 'hpgl' => 'application/vnd.hp-hpgl', 'hpid' => 'application/vnd.hp-hpid', 'hps' => 'application/vnd.hp-hps', 'hqx' => 'application/mac-binhex40', 'hta' => 'application/octet-stream', 'htc' => 'text/html', 'htke' => 'application/vnd.kenameaapp', 'htm' => 'text/html', 'html' => 'text/html', 'hvd' => 'application/vnd.yamaha.hv-dic', 'hvp' => 'application/vnd.yamaha.hv-voice', 'hvs' => 'application/vnd.yamaha.hv-script', 'i2g' => 'application/vnd.intergeo', 'icc' => 'application/vnd.iccprofile', 'ice' => 'x-conference/x-cooltalk', 'icm' => 'application/vnd.iccprofile', 'ico' => 'image/x-icon', 'ics' => 'text/calendar', 'ief' => 'image/ief', 'ifb' => 'text/calendar', 'ifm' => 'application/vnd.shana.informed.formdata', 'iges' => 'model/iges', 'igl' => 'application/vnd.igloader', 'igm' => 'application/vnd.insors.igm', 'igs' => 'model/iges', 'igx' => 'application/vnd.micrografx.igx', 'iif' => 'application/vnd.shana.informed.interchange', 'imp' => 'application/vnd.accpac.simply.imp', 'ims' => 'application/vnd.ms-ims', 'in' => 'text/plain', 'ini' => 'text/plain', 'ipfix' => 'application/ipfix', 'ipk' => 'application/vnd.shana.informed.package', 'irm' => 'application/vnd.ibm.rights-management', 'irp' => 'application/vnd.irepository.package+xml', 'iso' => 'application/octet-stream', 'itp' => 'application/vnd.shana.informed.formtemplate', 'ivp' => 'application/vnd.immervision-ivp', 'ivu' => 'application/vnd.immervision-ivu', 'jad' => 'text/vnd.sun.j2me.app-descriptor', 'jam' => 'application/vnd.jam', 'jar' => 'application/java-archive', 'java' => 'text/x-java-source', 'jisp' => 'application/vnd.jisp', 'jlt' => 'application/vnd.hp-jlyt', 'jnlp' => 'application/x-java-jnlp-file', 'joda' => 'application/vnd.joost.joda-archive', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'jpgm' => 'video/jpm', 'jpgv' => 'video/jpeg', 'jpm' => 'video/jpm', 'js' => 'text/javascript', 'json' => 'application/json', 'kar' => 'audio/midi', 'karbon' => 'application/vnd.kde.karbon', 'kfo' => 'application/vnd.kde.kformula', 'kia' => 'application/vnd.kidspiration', 'kml' => 'application/vnd.google-earth.kml+xml', 'kmz' => 'application/vnd.google-earth.kmz', 'kne' => 'application/vnd.kinar', 'knp' => 'application/vnd.kinar', 'kon' => 'application/vnd.kde.kontour', 'kpr' => 'application/vnd.kde.kpresenter', 'kpt' => 'application/vnd.kde.kpresenter', 'ksp' => 'application/vnd.kde.kspread', 'ktr' => 'application/vnd.kahootz', 'ktx' => 'image/ktx', 'ktz' => 'application/vnd.kahootz', 'kwd' => 'application/vnd.kde.kword', 'kwt' => 'application/vnd.kde.kword', 'lasxml' => 'application/vnd.las.las+xml', 'latex' => 'application/x-latex', 'lbd' => 'application/vnd.llamagraphics.life-balance.desktop', 'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml', 'les' => 'application/vnd.hhe.lesson-player', 'lha' => 'application/octet-stream', 'link66' => 'application/vnd.route66.link66+xml', 'list' => 'text/plain', 'list3820' => 'application/vnd.ibm.modcap', 'listafp' => 'application/vnd.ibm.modcap', 'log' => 'text/plain', 'lostxml' => 'application/lost+xml', 'lrf' => 'application/octet-stream', 'lrm' => 'application/vnd.ms-lrm', 'ltf' => 'application/vnd.frogans.ltf', 'lvp' => 'audio/vnd.lucent.voice', 'lwp' => 'application/vnd.lotus-wordpro', 'lzh' => 'application/octet-stream', 'm13' => 'application/x-msmediaview', 'm14' => 'application/x-msmediaview', 'm1v' => 'video/mpeg', 'm21' => 'application/mp21', 'm2a' => 'audio/mpeg', 'm2v' => 'video/mpeg', 'm3a' => 'audio/mpeg', 'm3u' => 'audio/x-mpegurl', 'm3u8' => 'application/vnd.apple.mpegurl', 'm4a' => 'audio/mp4', 'm4u' => 'video/vnd.mpegurl', 'm4v' => 'video/mp4', 'ma' => 'application/mathematica', 'mads' => 'application/mads+xml', 'mag' => 'application/vnd.ecowin.chart', 'maker' => 'application/vnd.framemaker', 'man' => 'text/troff', 'mathml' => 'application/mathml+xml', 'mb' => 'application/mathematica', 'mbk' => 'application/vnd.mobius.mbk', 'mbox' => 'application/mbox', 'mc1' => 'application/vnd.medcalcdata', 'mcd' => 'application/vnd.mcd', 'mcurl' => 'text/vnd.curl.mcurl', 'mdb' => 'application/x-msaccess', 'mdi' => 'image/vnd.ms-modi', 'me' => 'text/troff', 'mesh' => 'model/mesh', 'meta4' => 'application/metalink4+xml', 'mets' => 'application/mets+xml', 'mfm' => 'application/vnd.mfmp', 'mgp' => 'application/vnd.osgeo.mapguide.package', 'mgz' => 'application/vnd.proteus.magazine', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mif' => 'application/vnd.mif', 'mime' => 'message/rfc822', 'mj2' => 'video/mj2', 'mjp2' => 'video/mj2', 'mlp' => 'application/vnd.dolby.mlp', 'mmd' => 'application/vnd.chipnuts.karaoke-mmd', 'mmf' => 'application/vnd.smaf', 'mmr' => 'image/vnd.fujixerox.edmics-mmr', 'mny' => 'application/x-msmoney', 'mobi' => 'application/x-mobipocket-ebook', 'mods' => 'application/mods+xml', 'mov' => 'video/quicktime', 'movie' => 'video/x-sgi-movie', 'mp2' => 'audio/mpeg', 'mp21' => 'application/mp21', 'mp2a' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'mp4' => 'video/mp4', 'mp4a' => 'audio/mp4', 'mp4s' => 'application/mp4', 'mp4v' => 'video/mp4', 'mpc' => 'application/vnd.mophun.certificate', 'mpe' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpg4' => 'video/mp4', 'mpga' => 'audio/mpeg', 'mpkg' => 'application/vnd.apple.installer+xml', 'mpm' => 'application/vnd.blueice.multipass', 'mpn' => 'application/vnd.mophun.application', 'mpp' => 'application/vnd.ms-project', 'mpt' => 'application/vnd.ms-project', 'mpy' => 'application/vnd.ibm.minipay', 'mqy' => 'application/vnd.mobius.mqy', 'mrc' => 'application/marc', 'mrcx' => 'application/marcxml+xml', 'ms' => 'text/troff', 'mscml' => 'application/mediaservercontrol+xml', 'mseed' => 'application/vnd.fdsn.mseed', 'mseq' => 'application/vnd.mseq', 'msf' => 'application/vnd.epson.msf', 'msh' => 'model/mesh', 'msi' => 'application/x-msdownload', 'msl' => 'application/vnd.mobius.msl', 'msty' => 'application/vnd.muvee.style', 'mts' => 'model/vnd.mts', 'mus' => 'application/vnd.musician', 'musicxml' => 'application/vnd.recordare.musicxml+xml', 'mvb' => 'application/x-msmediaview', 'mwf' => 'application/vnd.mfer', 'mxf' => 'application/mxf', 'mxl' => 'application/vnd.recordare.musicxml', 'mxml' => 'application/xv+xml', 'mxs' => 'application/vnd.triscape.mxs', 'mxu' => 'video/vnd.mpegurl', 'n-gage' => 'application/vnd.nokia.n-gage.symbian.install', 'n3' => 'text/n3', 'nb' => 'application/mathematica', 'nbp' => 'application/vnd.wolfram.player', 'nc' => 'application/x-netcdf', 'ncx' => 'application/x-dtbncx+xml', 'ngdat' => 'application/vnd.nokia.n-gage.data', 'nlu' => 'application/vnd.neurolanguage.nlu', 'nml' => 'application/vnd.enliven', 'nnd' => 'application/vnd.noblenet-directory', 'nns' => 'application/vnd.noblenet-sealer', 'nnw' => 'application/vnd.noblenet-web', 'npx' => 'image/vnd.net-fpx', 'nsf' => 'application/vnd.lotus-notes', 'oa2' => 'application/vnd.fujitsu.oasys2', 'oa3' => 'application/vnd.fujitsu.oasys3', 'oas' => 'application/vnd.fujitsu.oasys', 'obd' => 'application/x-msbinder', 'oda' => 'application/oda', 'odb' => 'application/vnd.oasis.opendocument.database', 'odc' => 'application/vnd.oasis.opendocument.chart', 'odf' => 'application/vnd.oasis.opendocument.formula', 'odft' => 'application/vnd.oasis.opendocument.formula-template', 'odg' => 'application/vnd.oasis.opendocument.graphics', 'odi' => 'application/vnd.oasis.opendocument.image', 'odm' => 'application/vnd.oasis.opendocument.text-master', 'odp' => 'application/vnd.oasis.opendocument.presentation', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', 'odt' => 'application/vnd.oasis.opendocument.text', 'oga' => 'audio/ogg', 'ogg' => 'audio/ogg', 'ogv' => 'video/ogg', 'ogx' => 'application/ogg', 'onepkg' => 'application/onenote', 'onetmp' => 'application/onenote', 'onetoc' => 'application/onenote', 'onetoc2' => 'application/onenote', 'opf' => 'application/oebps-package+xml', 'oprc' => 'application/vnd.palm', 'org' => 'application/vnd.lotus-organizer', 'osf' => 'application/vnd.yamaha.openscoreformat', 'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml', 'otc' => 'application/vnd.oasis.opendocument.chart-template', 'otf' => 'application/x-font-otf', 'otg' => 'application/vnd.oasis.opendocument.graphics-template', 'oth' => 'application/vnd.oasis.opendocument.text-web', 'oti' => 'application/vnd.oasis.opendocument.image-template', 'otp' => 'application/vnd.oasis.opendocument.presentation-template', 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', 'ott' => 'application/vnd.oasis.opendocument.text-template', 'oxt' => 'application/vnd.openofficeorg.extension', 'p' => 'text/x-pascal', 'p10' => 'application/pkcs10', 'p12' => 'application/x-pkcs12', 'p7b' => 'application/x-pkcs7-certificates', 'p7c' => 'application/pkcs7-mime', 'p7m' => 'application/pkcs7-mime', 'p7r' => 'application/x-pkcs7-certreqresp', 'p7s' => 'application/pkcs7-signature', 'p8' => 'application/pkcs8', 'pas' => 'text/x-pascal', 'paw' => 'application/vnd.pawaafile', 'pbd' => 'application/vnd.powerbuilder6', 'pbm' => 'image/x-portable-bitmap', 'pcf' => 'application/x-font-pcf', 'pcl' => 'application/vnd.hp-pcl', 'pclxl' => 'application/vnd.hp-pclxl', 'pct' => 'image/x-pict', 'pcurl' => 'application/vnd.curl.pcurl', 'pcx' => 'image/x-pcx', 'pdb' => 'application/vnd.palm', 'pdf' => 'application/pdf', 'pfa' => 'application/x-font-type1', 'pfb' => 'application/x-font-type1', 'pfm' => 'application/x-font-type1', 'pfr' => 'application/font-tdpfr', 'pfx' => 'application/x-pkcs12', 'pgm' => 'image/x-portable-graymap', 'pgn' => 'application/x-chess-pgn', 'pgp' => 'application/pgp-encrypted', 'php' => 'text/x-php', 'phps' => 'application/x-httpd-phps', 'pic' => 'image/x-pict', 'pkg' => 'application/octet-stream', 'pki' => 'application/pkixcmp', 'pkipath' => 'application/pkix-pkipath', 'plb' => 'application/vnd.3gpp.pic-bw-large', 'plc' => 'application/vnd.mobius.plc', 'plf' => 'application/vnd.pocketlearn', 'pls' => 'application/pls+xml', 'pml' => 'application/vnd.ctc-posml', 'png' => 'image/png', 'pnm' => 'image/x-portable-anymap', 'portpkg' => 'application/vnd.macports.portpkg', 'pot' => 'application/vnd.ms-powerpoint', 'potm' => 'application/vnd.ms-powerpoint.template.macroenabled.12', 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', 'ppam' => 'application/vnd.ms-powerpoint.addin.macroenabled.12', 'ppd' => 'application/vnd.cups-ppd', 'ppm' => 'image/x-portable-pixmap', 'pps' => 'application/vnd.ms-powerpoint', 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroenabled.12', 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'ppt' => 'application/vnd.ms-powerpoint', 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroenabled.12', 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'pqa' => 'application/vnd.palm', 'prc' => 'application/x-mobipocket-ebook', 'pre' => 'application/vnd.lotus-freelance', 'prf' => 'application/pics-rules', 'ps' => 'application/postscript', 'psb' => 'application/vnd.3gpp.pic-bw-small', 'psd' => 'image/vnd.adobe.photoshop', 'psf' => 'application/x-font-linux-psf', 'pskcxml' => 'application/pskc+xml', 'ptid' => 'application/vnd.pvi.ptid1', 'pub' => 'application/x-mspublisher', 'pvb' => 'application/vnd.3gpp.pic-bw-var', 'pwn' => 'application/vnd.3m.post-it-notes', 'pya' => 'audio/vnd.ms-playready.media.pya', 'pyv' => 'video/vnd.ms-playready.media.pyv', 'qam' => 'application/vnd.epson.quickanime', 'qbo' => 'application/vnd.intu.qbo', 'qfx' => 'application/vnd.intu.qfx', 'qps' => 'application/vnd.publishare-delta-tree', 'qt' => 'video/quicktime', 'qwd' => 'application/vnd.quark.quarkxpress', 'qwt' => 'application/vnd.quark.quarkxpress', 'qxb' => 'application/vnd.quark.quarkxpress', 'qxd' => 'application/vnd.quark.quarkxpress', 'qxl' => 'application/vnd.quark.quarkxpress', 'qxt' => 'application/vnd.quark.quarkxpress', 'ra' => 'audio/x-pn-realaudio', 'ram' => 'audio/x-pn-realaudio', 'rar' => 'application/x-rar-compressed', 'ras' => 'image/x-cmu-raster', 'rb' => 'text/plain', 'rcprofile' => 'application/vnd.ipunplugged.rcprofile', 'rdf' => 'application/rdf+xml', 'rdz' => 'application/vnd.data-vision.rdz', 'rep' => 'application/vnd.businessobjects', 'res' => 'application/x-dtbresource+xml', 'resx' => 'text/xml', 'rgb' => 'image/x-rgb', 'rif' => 'application/reginfo+xml', 'rip' => 'audio/vnd.rip', 'rl' => 'application/resource-lists+xml', 'rlc' => 'image/vnd.fujixerox.edmics-rlc', 'rld' => 'application/resource-lists-diff+xml', 'rm' => 'application/vnd.rn-realmedia', 'rmi' => 'audio/midi', 'rmp' => 'audio/x-pn-realaudio-plugin', 'rms' => 'application/vnd.jcp.javame.midlet-rms', 'rnc' => 'application/relax-ng-compact-syntax', 'roff' => 'text/troff', 'rp9' => 'application/vnd.cloanto.rp9', 'rpss' => 'application/vnd.nokia.radio-presets', 'rpst' => 'application/vnd.nokia.radio-preset', 'rq' => 'application/sparql-query', 'rs' => 'application/rls-services+xml', 'rsd' => 'application/rsd+xml', 'rss' => 'application/rss+xml', 'rtf' => 'application/rtf', 'rtx' => 'text/richtext', 's' => 'text/x-asm', 'saf' => 'application/vnd.yamaha.smaf-audio', 'sbml' => 'application/sbml+xml', 'sc' => 'application/vnd.ibm.secure-container', 'scd' => 'application/x-msschedule', 'scm' => 'application/vnd.lotus-screencam', 'scq' => 'application/scvp-cv-request', 'scs' => 'application/scvp-cv-response', 'scurl' => 'text/vnd.curl.scurl', 'sda' => 'application/vnd.stardivision.draw', 'sdc' => 'application/vnd.stardivision.calc', 'sdd' => 'application/vnd.stardivision.impress', 'sdkd' => 'application/vnd.solent.sdkm+xml', 'sdkm' => 'application/vnd.solent.sdkm+xml', 'sdp' => 'application/sdp', 'sdw' => 'application/vnd.stardivision.writer', 'see' => 'application/vnd.seemail', 'seed' => 'application/vnd.fdsn.seed', 'sema' => 'application/vnd.sema', 'semd' => 'application/vnd.semd', 'semf' => 'application/vnd.semf', 'ser' => 'application/java-serialized-object', 'setpay' => 'application/set-payment-initiation', 'setreg' => 'application/set-registration-initiation', 'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data', 'sfs' => 'application/vnd.spotfire.sfs', 'sgl' => 'application/vnd.stardivision.writer-global', 'sgm' => 'text/sgml', 'sgml' => 'text/sgml', 'sh' => 'application/x-sh', 'shar' => 'application/x-shar', 'shf' => 'application/shf+xml', 'sig' => 'application/pgp-signature', 'silo' => 'model/mesh', 'sis' => 'application/vnd.symbian.install', 'sisx' => 'application/vnd.symbian.install', 'sit' => 'application/x-stuffit', 'sitx' => 'application/x-stuffitx', 'skd' => 'application/vnd.koan', 'skm' => 'application/vnd.koan', 'skp' => 'application/vnd.koan', 'skt' => 'application/vnd.koan', 'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12', 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', 'slt' => 'application/vnd.epson.salt', 'sm' => 'application/vnd.stepmania.stepchart', 'smf' => 'application/vnd.stardivision.math', 'smi' => 'application/smil+xml', 'smil' => 'application/smil+xml', 'snd' => 'audio/basic', 'snf' => 'application/x-font-snf', 'so' => 'application/octet-stream', 'spc' => 'application/x-pkcs7-certificates', 'spf' => 'application/vnd.yamaha.smaf-phrase', 'spl' => 'application/x-futuresplash', 'spot' => 'text/vnd.in3d.spot', 'spp' => 'application/scvp-vp-response', 'spq' => 'application/scvp-vp-request', 'spx' => 'audio/ogg', 'src' => 'application/x-wais-source', 'sru' => 'application/sru+xml', 'srx' => 'application/sparql-results+xml', 'sse' => 'application/vnd.kodak-descriptor', 'ssf' => 'application/vnd.epson.ssf', 'ssml' => 'application/ssml+xml', 'st' => 'application/vnd.sailingtracker.track', 'stc' => 'application/vnd.sun.xml.calc.template', 'std' => 'application/vnd.sun.xml.draw.template', 'stf' => 'application/vnd.wt.stf', 'sti' => 'application/vnd.sun.xml.impress.template', 'stk' => 'application/hyperstudio', 'stl' => 'application/vnd.ms-pki.stl', 'str' => 'application/vnd.pg.format', 'stw' => 'application/vnd.sun.xml.writer.template', 'sub' => 'image/vnd.dvb.subtitle', 'sus' => 'application/vnd.sus-calendar', 'susp' => 'application/vnd.sus-calendar', 'sv4cpio' => 'application/x-sv4cpio', 'sv4crc' => 'application/x-sv4crc', 'svc' => 'application/vnd.dvb.service', 'svd' => 'application/vnd.svd', 'svg' => 'image/svg+xml', 'svgz' => 'image/svg+xml', 'swa' => 'application/x-director', 'swf' => 'application/x-shockwave-flash', 'swi' => 'application/vnd.aristanetworks.swi', 'sxc' => 'application/vnd.sun.xml.calc', 'sxd' => 'application/vnd.sun.xml.draw', 'sxg' => 'application/vnd.sun.xml.writer.global', 'sxi' => 'application/vnd.sun.xml.impress', 'sxm' => 'application/vnd.sun.xml.math', 'sxw' => 'application/vnd.sun.xml.writer', 't' => 'text/troff', 'tao' => 'application/vnd.tao.intent-module-archive', 'tar' => 'application/x-tar', 'tcap' => 'application/vnd.3gpp2.tcap', 'tcl' => 'application/x-tcl', 'teacher' => 'application/vnd.smart.teacher', 'tei' => 'application/tei+xml', 'teicorpus' => 'application/tei+xml', 'tex' => 'application/x-tex', 'texi' => 'application/x-texinfo', 'texinfo' => 'application/x-texinfo', 'text' => 'text/plain', 'tfi' => 'application/thraud+xml', 'tfm' => 'application/x-tex-tfm', 'thmx' => 'application/vnd.ms-officetheme', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'tmo' => 'application/vnd.tmobile-livetv', 'torrent' => 'application/x-bittorrent', 'tpl' => 'application/vnd.groove-tool-template', 'tpt' => 'application/vnd.trid.tpt', 'tr' => 'text/troff', 'tra' => 'application/vnd.trueapp', 'trm' => 'application/x-msterminal', 'tsd' => 'application/timestamped-data', 'tsv' => 'text/tab-separated-values', 'ttc' => 'application/x-font-ttf', 'ttf' => 'application/x-font-ttf', 'ttl' => 'text/turtle', 'twd' => 'application/vnd.simtech-mindmapper', 'twds' => 'application/vnd.simtech-mindmapper', 'txd' => 'application/vnd.genomatix.tuxedo', 'txf' => 'application/vnd.mobius.txf', 'txt' => 'text/plain', 'u32' => 'application/x-authorware-bin', 'udeb' => 'application/x-debian-package', 'ufd' => 'application/vnd.ufdl', 'ufdl' => 'application/vnd.ufdl', 'umj' => 'application/vnd.umajin', 'unityweb' => 'application/vnd.unity', 'uoml' => 'application/vnd.uoml+xml', 'uri' => 'text/uri-list', 'uris' => 'text/uri-list', 'urls' => 'text/uri-list', 'ustar' => 'application/x-ustar', 'utz' => 'application/vnd.uiq.theme', 'uu' => 'text/x-uuencode', 'uva' => 'audio/vnd.dece.audio', 'uvd' => 'application/vnd.dece.data', 'uvf' => 'application/vnd.dece.data', 'uvg' => 'image/vnd.dece.graphic', 'uvh' => 'video/vnd.dece.hd', 'uvi' => 'image/vnd.dece.graphic', 'uvm' => 'video/vnd.dece.mobile', 'uvp' => 'video/vnd.dece.pd', 'uvs' => 'video/vnd.dece.sd', 'uvt' => 'application/vnd.dece.ttml+xml', 'uvu' => 'video/vnd.uvvu.mp4', 'uvv' => 'video/vnd.dece.video', 'uvva' => 'audio/vnd.dece.audio', 'uvvd' => 'application/vnd.dece.data', 'uvvf' => 'application/vnd.dece.data', 'uvvg' => 'image/vnd.dece.graphic', 'uvvh' => 'video/vnd.dece.hd', 'uvvi' => 'image/vnd.dece.graphic', 'uvvm' => 'video/vnd.dece.mobile', 'uvvp' => 'video/vnd.dece.pd', 'uvvs' => 'video/vnd.dece.sd', 'uvvt' => 'application/vnd.dece.ttml+xml', 'uvvu' => 'video/vnd.uvvu.mp4', 'uvvv' => 'video/vnd.dece.video', 'uvvx' => 'application/vnd.dece.unspecified', 'uvx' => 'application/vnd.dece.unspecified', 'vcd' => 'application/x-cdlink', 'vcf' => 'text/x-vcard', 'vcg' => 'application/vnd.groove-vcard', 'vcs' => 'text/x-vcalendar', 'vcx' => 'application/vnd.vcx', 'vis' => 'application/vnd.visionary', 'viv' => 'video/vnd.vivo', 'vor' => 'application/vnd.stardivision.writer', 'vox' => 'application/x-authorware-bin', 'vrml' => 'model/vrml', 'vsd' => 'application/vnd.visio', 'vsf' => 'application/vnd.vsf', 'vss' => 'application/vnd.visio', 'vst' => 'application/vnd.visio', 'vsw' => 'application/vnd.visio', 'vtu' => 'model/vnd.vtu', 'vxml' => 'application/voicexml+xml', 'w3d' => 'application/x-director', 'wad' => 'application/x-doom', 'wav' => 'audio/x-wav', 'wax' => 'audio/x-ms-wax', 'wbmp' => 'image/vnd.wap.wbmp', 'wbs' => 'application/vnd.criticaltools.wbs+xml', 'wbxml' => 'application/vnd.wap.wbxml', 'wcm' => 'application/vnd.ms-works', 'wdb' => 'application/vnd.ms-works', 'weba' => 'audio/webm', 'webm' => 'video/webm', 'webp' => 'image/webp', 'wg' => 'application/vnd.pmi.widget', 'wgt' => 'application/widget', 'wks' => 'application/vnd.ms-works', 'wm' => 'video/x-ms-wm', 'wma' => 'audio/x-ms-wma', 'wmd' => 'application/x-ms-wmd', 'wmf' => 'application/x-msmetafile', 'wml' => 'text/vnd.wap.wml', 'wmlc' => 'application/vnd.wap.wmlc', 'wmls' => 'text/vnd.wap.wmlscript', 'wmlsc' => 'application/vnd.wap.wmlscriptc', 'wmv' => 'video/x-ms-wmv', 'wmx' => 'video/x-ms-wmx', 'wmz' => 'application/x-ms-wmz', 'woff' => 'application/x-font-woff', 'wpd' => 'application/vnd.wordperfect', 'wpl' => 'application/vnd.ms-wpl', 'wps' => 'application/vnd.ms-works', 'wqd' => 'application/vnd.wqd', 'wri' => 'application/x-mswrite', 'wrl' => 'model/vrml', 'wsdl' => 'application/wsdl+xml', 'wspolicy' => 'application/wspolicy+xml', 'wtb' => 'application/vnd.webturbo', 'wvx' => 'video/x-ms-wvx', 'x32' => 'application/x-authorware-bin', 'x3d' => 'application/vnd.hzn-3d-crossword', 'xap' => 'application/x-silverlight-app', 'xar' => 'application/vnd.xara', 'xbap' => 'application/x-ms-xbap', 'xbd' => 'application/vnd.fujixerox.docuworks.binder', 'xbm' => 'image/x-xbitmap', 'xdf' => 'application/xcap-diff+xml', 'xdm' => 'application/vnd.syncml.dm+xml', 'xdp' => 'application/vnd.adobe.xdp+xml', 'xdssc' => 'application/dssc+xml', 'xdw' => 'application/vnd.fujixerox.docuworks', 'xenc' => 'application/xenc+xml', 'xer' => 'application/patch-ops-error+xml', 'xfdf' => 'application/vnd.adobe.xfdf', 'xfdl' => 'application/vnd.xfdl', 'xht' => 'application/xhtml+xml', 'xhtml' => 'application/xhtml+xml', 'xhvml' => 'application/xv+xml', 'xif' => 'image/vnd.xiff', 'xla' => 'application/vnd.ms-excel', 'xlam' => 'application/vnd.ms-excel.addin.macroenabled.12', 'xlc' => 'application/vnd.ms-excel', 'xlm' => 'application/vnd.ms-excel', 'xls' => 'application/vnd.ms-excel', 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroenabled.12', 'xlsm' => 'application/vnd.ms-excel.sheet.macroenabled.12', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xlt' => 'application/vnd.ms-excel', 'xltm' => 'application/vnd.ms-excel.template.macroenabled.12', 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'xlw' => 'application/vnd.ms-excel', 'xml' => 'application/xml', 'xo' => 'application/vnd.olpc-sugar', 'xop' => 'application/xop+xml', 'xpi' => 'application/x-xpinstall', 'xpm' => 'image/x-xpixmap', 'xpr' => 'application/vnd.is-xpr', 'xps' => 'application/vnd.ms-xpsdocument', 'xpw' => 'application/vnd.intercon.formnet', 'xpx' => 'application/vnd.intercon.formnet', 'xsl' => 'application/xml', 'xslt' => 'application/xslt+xml', 'xsm' => 'application/vnd.syncml+xml', 'xspf' => 'application/xspf+xml', 'xul' => 'application/vnd.mozilla.xul+xml', 'xvm' => 'application/xv+xml', 'xvml' => 'application/xv+xml', 'xwd' => 'image/x-xwindowdump', 'xyz' => 'chemical/x-xyz', 'yaml' => 'text/yaml', 'yang' => 'application/yang', 'yin' => 'application/yin+xml', 'yml' => 'text/yaml', 'zaz' => 'application/vnd.zzazz.deck+xml', 'zip' => 'application/zip', 'zir' => 'application/vnd.zul', 'zirz' => 'application/vnd.zul', 'zmm' => 'application/vnd.handheld-entertainment+xml' ); /** * Get a singleton instance of the class * * @return self * @codeCoverageIgnore */ public static function getInstance() { if (!self::$instance) { self::$instance = new self(); } return self::$instance; } /** * Get a mimetype value from a file extension * * @param string $extension File extension * * @return string|null * */ public function fromExtension($extension) { $extension = strtolower($extension); return isset($this->mimetypes[$extension]) ? $this->mimetypes[$extension] : null; } /** * Get a mimetype from a filename * * @param string $filename Filename to generate a mimetype from * * @return string|null */ public function fromFilename($filename) { return $this->fromExtension(pathinfo($filename, PATHINFO_EXTENSION)); } } isUrlEncoding()) { return array($query->encodeValue($key) => implode(',', array_map(array($query, 'encodeValue'), $value))); } else { return array($key => implode(',', $value)); } } } isUrlEncoding()) { return array($query->encodeValue($key) => array_map(array($query, 'encodeValue'), $value)); } else { return array($key => $value); } } } $v) { $k = "{$key}[{$k}]"; if (is_array($v)) { $ret = array_merge($ret, self::aggregate($k, $v, $query)); } else { $ret[$query->encodeValue($k)] = $query->encodeValue($v); } } return $ret; } } add($key, $value); $foundDuplicates = true; } elseif ($paramIsPhpStyleArray) { $q[$key] = array($value); } else { $q[$key] = $value; } } else { // Uses false by default to represent keys with no trailing "=" sign. $q->add($key, false); } } // Use the duplicate aggregator if duplicates were found and not using PHP style arrays if ($foundDuplicates && !$foundPhpStyle) { $q->setAggregator(new DuplicateAggregator()); } return $q; } /** * Convert the query string parameters to a query string string * * @return string * @throws RuntimeException */ public function __toString() { if (!$this->data) { return ''; } $queryList = array(); foreach ($this->prepareData($this->data) as $name => $value) { $queryList[] = $this->convertKvp($name, $value); } return implode($this->fieldSeparator, $queryList); } /** * Get the query string field separator * * @return string */ public function getFieldSeparator() { return $this->fieldSeparator; } /** * Get the query string value separator * * @return string */ public function getValueSeparator() { return $this->valueSeparator; } /** * Returns the type of URL encoding used by the query string * * One of: false, "RFC 3986", or "application/x-www-form-urlencoded" * * @return bool|string */ public function getUrlEncoding() { return $this->urlEncode; } /** * Returns true or false if using URL encoding * * @return bool */ public function isUrlEncoding() { return $this->urlEncode !== false; } /** * Provide a function for combining multi-valued query string parameters into a single or multiple fields * * @param null|QueryAggregatorInterface $aggregator Pass in a QueryAggregatorInterface object to handle converting * deeply nested query string variables into a flattened array. * Pass null to use the default PHP style aggregator. For legacy * reasons, this function accepts a callable that must accepts a * $key, $value, and query object. * @return self * @see \Guzzle\Http\QueryString::aggregateUsingComma() */ public function setAggregator(QueryAggregatorInterface $aggregator = null) { // Use the default aggregator if none was set if (!$aggregator) { if (!self::$defaultAggregator) { self::$defaultAggregator = new PhpAggregator(); } $aggregator = self::$defaultAggregator; } $this->aggregator = $aggregator; return $this; } /** * Set whether or not field names and values should be rawurlencoded * * @param bool|string $encode Set to TRUE to use RFC 3986 encoding (rawurlencode), false to disable encoding, or * form_urlencoding to use application/x-www-form-urlencoded encoding (urlencode) * @return self */ public function useUrlEncoding($encode) { $this->urlEncode = ($encode === true) ? self::RFC_3986 : $encode; return $this; } /** * Set the query string separator * * @param string $separator The query string separator that will separate fields * * @return self */ public function setFieldSeparator($separator) { $this->fieldSeparator = $separator; return $this; } /** * Set the query string value separator * * @param string $separator The query string separator that will separate values from fields * * @return self */ public function setValueSeparator($separator) { $this->valueSeparator = $separator; return $this; } /** * Returns an array of url encoded field names and values * * @return array */ public function urlEncode() { return $this->prepareData($this->data); } /** * URL encodes a value based on the url encoding type of the query string object * * @param string $value Value to encode * * @return string */ public function encodeValue($value) { if ($this->urlEncode == self::RFC_3986) { return rawurlencode($value); } elseif ($this->urlEncode == self::FORM_URLENCODED) { return urlencode($value); } else { return (string) $value; } } /** * Url encode parameter data and convert nested query strings into a flattened hash. * * @param array $data The data to encode * * @return array Returns an array of encoded values and keys */ protected function prepareData(array $data) { // If no aggregator is present then set the default if (!$this->aggregator) { $this->setAggregator(null); } $temp = array(); foreach ($data as $key => $value) { if ($value === false || $value === null) { // False and null will not include the "=". Use an empty string to include the "=". $temp[$this->encodeValue($key)] = $value; } elseif (is_array($value)) { $temp = array_merge($temp, $this->aggregator->aggregate($key, $value, $this)); } else { $temp[$this->encodeValue($key)] = $this->encodeValue($value); } } return $temp; } /** * Converts a key value pair that can contain strings, nulls, false, or arrays * into a single string. * * @param string $name Name of the field * @param mixed $value Value of the field * @return string */ private function convertKvp($name, $value) { if ($value === self::BLANK || $value === null || $value === false) { return $name; } elseif (!is_array($value)) { return $name . $this->valueSeparator . $value; } $result = ''; foreach ($value as $v) { $result .= $this->convertKvp($name, $v) . $this->fieldSeparator; } return rtrim($result, $this->fieldSeparator); } } setLimit($limit)->setOffset($offset); } /** * Returns only a subset of the decorated entity body when cast as a string * {@inheritdoc} */ public function __toString() { return substr((string) $this->body, $this->offset, $this->limit) ?: ''; } public function isConsumed() { return $this->body->isConsumed() || ($this->body->ftell() >= $this->offset + $this->limit); } /** * Returns the Content-Length of the limited subset of data * {@inheritdoc} */ public function getContentLength() { $length = $this->body->getContentLength(); return $length === false ? $this->limit : min($this->limit, min($length, $this->offset + $this->limit) - $this->offset); } /** * Allow for a bounded seek on the read limited entity body * {@inheritdoc} */ public function seek($offset, $whence = SEEK_SET) { return $whence === SEEK_SET ? $this->body->seek(max($this->offset, min($this->offset + $this->limit, $offset))) : false; } /** * Set the offset to start limiting from * * @param int $offset Offset to seek to and begin byte limiting from * * @return self */ public function setOffset($offset) { $this->body->seek($offset); $this->offset = $offset; return $this; } /** * Set the limit of bytes that the decorator allows to be read from the stream * * @param int $limit Total number of bytes to allow to be read from the stream * * @return self */ public function setLimit($limit) { $this->limit = $limit; return $this; } public function read($length) { // Check if the current position is less than the total allowed bytes + original offset $remaining = ($this->offset + $this->limit) - $this->body->ftell(); if ($remaining > 0) { // Only return the amount of requested data, ensuring that the byte limit is not exceeded return $this->body->read(min($remaining, $length)); } else { return false; } } } array('onRequestSent', 100), 'request.clone' => 'cleanupRequest', 'request.before_send' => 'cleanupRequest' ); } /** * Clean up the parameters of a request when it is cloned * * @param Event $event Event emitted */ public function cleanupRequest(Event $event) { $params = $event['request']->getParams(); unset($params[self::REDIRECT_COUNT]); unset($params[self::PARENT_REQUEST]); } /** * Called when a request receives a redirect response * * @param Event $event Event emitted */ public function onRequestSent(Event $event) { $response = $event['response']; $request = $event['request']; // Only act on redirect requests with Location headers if (!$response || $request->getParams()->get(self::DISABLE)) { return; } // Trace the original request based on parameter history $original = $this->getOriginalRequest($request); // Terminating condition to set the effective response on the original request if (!$response->isRedirect() || !$response->hasHeader('Location')) { if ($request !== $original) { // This is a terminating redirect response, so set it on the original request $response->getParams()->set(self::REDIRECT_COUNT, $original->getParams()->get(self::REDIRECT_COUNT)); $original->setResponse($response); $response->setEffectiveUrl($request->getUrl()); } return; } $this->sendRedirectRequest($original, $request, $response); } /** * Get the original request that initiated a series of redirects * * @param RequestInterface $request Request to get the original request from * * @return RequestInterface */ protected function getOriginalRequest(RequestInterface $request) { $original = $request; // The number of redirects is held on the original request, so determine which request that is while ($parent = $original->getParams()->get(self::PARENT_REQUEST)) { $original = $parent; } return $original; } /** * Create a redirect request for a specific request object * * Takes into account strict RFC compliant redirection (e.g. redirect POST with POST) vs doing what most clients do * (e.g. redirect POST with GET). * * @param RequestInterface $request Request being redirected * @param RequestInterface $original Original request * @param int $statusCode Status code of the redirect * @param string $location Location header of the redirect * * @return RequestInterface Returns a new redirect request * @throws CouldNotRewindStreamException If the body needs to be rewound but cannot */ protected function createRedirectRequest( RequestInterface $request, $statusCode, $location, RequestInterface $original ) { $redirectRequest = null; $strict = $original->getParams()->get(self::STRICT_REDIRECTS); // Switch method to GET for 303 redirects. 301 and 302 redirects also switch to GET unless we are forcing RFC // compliance to emulate what most browsers do. NOTE: IE only switches methods on 301/302 when coming from a POST. if ($request instanceof EntityEnclosingRequestInterface && ($statusCode == 303 || (!$strict && $statusCode <= 302))) { $redirectRequest = RequestFactory::getInstance()->cloneRequestWithMethod($request, 'GET'); } else { $redirectRequest = clone $request; } $redirectRequest->setIsRedirect(true); // Always use the same response body when redirecting $redirectRequest->setResponseBody($request->getResponseBody()); $location = Url::factory($location); // If the location is not absolute, then combine it with the original URL if (!$location->isAbsolute()) { $originalUrl = $redirectRequest->getUrl(true); // Remove query string parameters and just take what is present on the redirect Location header $originalUrl->getQuery()->clear(); $location = $originalUrl->combine((string) $location, true); } $redirectRequest->setUrl($location); // Add the parent request to the request before it sends (make sure it's before the onRequestClone event too) $redirectRequest->getEventDispatcher()->addListener( 'request.before_send', $func = function ($e) use (&$func, $request, $redirectRequest) { $redirectRequest->getEventDispatcher()->removeListener('request.before_send', $func); $e['request']->getParams()->set(RedirectPlugin::PARENT_REQUEST, $request); } ); // Rewind the entity body of the request if needed if ($redirectRequest instanceof EntityEnclosingRequestInterface && $redirectRequest->getBody()) { $body = $redirectRequest->getBody(); // Only rewind the body if some of it has been read already, and throw an exception if the rewind fails if ($body->ftell() && !$body->rewind()) { throw new CouldNotRewindStreamException( 'Unable to rewind the non-seekable entity body of the request after redirecting. cURL probably ' . 'sent part of body before the redirect occurred. Try adding acustom rewind function using on the ' . 'entity body of the request using setRewindFunction().' ); } } return $redirectRequest; } /** * Prepare the request for redirection and enforce the maximum number of allowed redirects per client * * @param RequestInterface $original Original request * @param RequestInterface $request Request to prepare and validate * @param Response $response The current response * * @return RequestInterface */ protected function prepareRedirection(RequestInterface $original, RequestInterface $request, Response $response) { $params = $original->getParams(); // This is a new redirect, so increment the redirect counter $current = $params[self::REDIRECT_COUNT] + 1; $params[self::REDIRECT_COUNT] = $current; // Use a provided maximum value or default to a max redirect count of 5 $max = isset($params[self::MAX_REDIRECTS]) ? $params[self::MAX_REDIRECTS] : $this->defaultMaxRedirects; // Throw an exception if the redirect count is exceeded if ($current > $max) { $this->throwTooManyRedirectsException($original, $max); return false; } else { // Create a redirect request based on the redirect rules set on the request return $this->createRedirectRequest( $request, $response->getStatusCode(), trim($response->getLocation()), $original ); } } /** * Send a redirect request and handle any errors * * @param RequestInterface $original The originating request * @param RequestInterface $request The current request being redirected * @param Response $response The response of the current request * * @throws BadResponseException|\Exception */ protected function sendRedirectRequest(RequestInterface $original, RequestInterface $request, Response $response) { // Validate and create a redirect request based on the original request and current response if ($redirectRequest = $this->prepareRedirection($original, $request, $response)) { try { $redirectRequest->send(); } catch (BadResponseException $e) { $e->getResponse(); if (!$e->getResponse()) { throw $e; } } } } /** * Throw a too many redirects exception for a request * * @param RequestInterface $original Request * @param int $max Max allowed redirects * * @throws TooManyRedirectsException when too many redirects have been issued */ protected function throwTooManyRedirectsException(RequestInterface $original, $max) { $original->getEventDispatcher()->addListener( 'request.complete', $func = function ($e) use (&$func, $original, $max) { $original->getEventDispatcher()->removeListener('request.complete', $func); $str = "{$max} redirects were issued for this request:\n" . $e['request']->getRawHeaders(); throw new TooManyRedirectsException($str); } ); } } ## ## ca-bundle.crt -- Bundle of CA Root Certificates ## ## Certificate data from Mozilla as of: Tue Apr 22 08:29:31 2014 ## ## This is a bundle of X.509 certificates of public Certificate Authorities ## (CA). These were automatically extracted from Mozilla's root certificates ## file (certdata.txt). This file can be found in the mozilla source tree: ## http://mxr.mozilla.org/mozilla-release/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1 ## ## It contains the certificates in PEM format and therefore ## can be directly used with curl / libcurl / php_curl, or with ## an Apache+mod_ssl webserver for SSL client authentication. ## Just configure this file as the SSLCACertificateFile. ## GTE CyberTrust Global Root ========================== -----BEGIN CERTIFICATE----- MIICWjCCAcMCAgGlMA0GCSqGSIb3DQEBBAUAMHUxCzAJBgNVBAYTAlVTMRgwFgYDVQQKEw9HVEUg Q29ycG9yYXRpb24xJzAlBgNVBAsTHkdURSBDeWJlclRydXN0IFNvbHV0aW9ucywgSW5jLjEjMCEG A1UEAxMaR1RFIEN5YmVyVHJ1c3QgR2xvYmFsIFJvb3QwHhcNOTgwODEzMDAyOTAwWhcNMTgwODEz MjM1OTAwWjB1MQswCQYDVQQGEwJVUzEYMBYGA1UEChMPR1RFIENvcnBvcmF0aW9uMScwJQYDVQQL Ex5HVEUgQ3liZXJUcnVzdCBTb2x1dGlvbnMsIEluYy4xIzAhBgNVBAMTGkdURSBDeWJlclRydXN0 IEdsb2JhbCBSb290MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVD6C28FCc6HrHiM3dFw4u sJTQGz0O9pTAipTHBsiQl8i4ZBp6fmw8U+E3KHNgf7KXUwefU/ltWJTSr41tiGeA5u2ylc9yMcql HHK6XALnZELn+aks1joNrI1CqiQBOeacPwGFVw1Yh0X404Wqk2kmhXBIgD8SFcd5tB8FLztimQID AQABMA0GCSqGSIb3DQEBBAUAA4GBAG3rGwnpXtlR22ciYaQqPEh346B8pt5zohQDhT37qw4wxYMW M4ETCJ57NE7fQMh017l93PR2VX2bY1QY6fDq81yx2YtCHrnAlU66+tXifPVoYb+O7AWXX1uw16OF NMQkpw0PlZPvy5TYnh+dXIVtx6quTx8itc2VrbqnzPmrC3p/ -----END CERTIFICATE----- Thawte Server CA ================ -----BEGIN CERTIFICATE----- MIIDEzCCAnygAwIBAgIBATANBgkqhkiG9w0BAQQFADCBxDELMAkGA1UEBhMCWkExFTATBgNVBAgT DFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYDVQQKExRUaGF3dGUgQ29uc3Vs dGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjEZMBcGA1UE AxMQVGhhd3RlIFNlcnZlciBDQTEmMCQGCSqGSIb3DQEJARYXc2VydmVyLWNlcnRzQHRoYXd0ZS5j b20wHhcNOTYwODAxMDAwMDAwWhcNMjAxMjMxMjM1OTU5WjCBxDELMAkGA1UEBhMCWkExFTATBgNV BAgTDFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYDVQQKExRUaGF3dGUgQ29u c3VsdGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjEZMBcG A1UEAxMQVGhhd3RlIFNlcnZlciBDQTEmMCQGCSqGSIb3DQEJARYXc2VydmVyLWNlcnRzQHRoYXd0 ZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANOkUG7I/1Zr5s9dtuoMaHVHoqrC2oQl /Kj0R1HahbUgdJSGHg91yekIYfUGbTBuFRkC6VLAYttNmZ7iagxEOM3+vuNkCXDF/rFrKbYvScg7 1CcEJRCXL+eQbcAoQpnXTEPew/UhbVSfXcNY4cDk2VuwuNy0e982OsK1ZiIS1ocNAgMBAAGjEzAR MA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEEBQADgYEAB/pMaVz7lcxG7oWDTSEwjsrZqG9J GubaUeNgcGyEYRGhGshIPllDfU+VPaGLtwtimHp1it2ITk6eQNuozDJ0uW8NxuOzRAvZim+aKZuZ GCg70eNAKJpaPNW15yAbi8qkq43pUdniTCxZqdq5snUb9kLy78fyGPmJvKP/iiMucEc= -----END CERTIFICATE----- Thawte Premium Server CA ======================== -----BEGIN CERTIFICATE----- MIIDJzCCApCgAwIBAgIBATANBgkqhkiG9w0BAQQFADCBzjELMAkGA1UEBhMCWkExFTATBgNVBAgT DFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYDVQQKExRUaGF3dGUgQ29uc3Vs dGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjEhMB8GA1UE AxMYVGhhd3RlIFByZW1pdW0gU2VydmVyIENBMSgwJgYJKoZIhvcNAQkBFhlwcmVtaXVtLXNlcnZl ckB0aGF3dGUuY29tMB4XDTk2MDgwMTAwMDAwMFoXDTIwMTIzMTIzNTk1OVowgc4xCzAJBgNVBAYT AlpBMRUwEwYDVQQIEwxXZXN0ZXJuIENhcGUxEjAQBgNVBAcTCUNhcGUgVG93bjEdMBsGA1UEChMU VGhhd3RlIENvbnN1bHRpbmcgY2MxKDAmBgNVBAsTH0NlcnRpZmljYXRpb24gU2VydmljZXMgRGl2 aXNpb24xITAfBgNVBAMTGFRoYXd0ZSBQcmVtaXVtIFNlcnZlciBDQTEoMCYGCSqGSIb3DQEJARYZ cHJlbWl1bS1zZXJ2ZXJAdGhhd3RlLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0jY2 aovXwlue2oFBYo847kkEVdbQ7xwblRZH7xhINTpS9CtqBo87L+pW46+GjZ4X9560ZXUCTe/LCaIh Udib0GfQug2SBhRz1JPLlyoAnFxODLz6FVL88kRu2hFKbgifLy3j+ao6hnO2RlNYyIkFvYMRuHM/ qgeN9EJN50CdHDcCAwEAAaMTMBEwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQQFAAOBgQAm SCwWwlj66BZ0DKqqX1Q/8tfJeGBeXm43YyJ3Nn6yF8Q0ufUIhfzJATj/Tb7yFkJD57taRvvBxhEf 8UqwKEbJw8RCfbz6q1lu1bdRiBHjpIUZa4JMpAwSremkrj/xw0llmozFyD4lt5SZu5IycQfwhl7t UCemDaYj+bvLpgcUQg== -----END CERTIFICATE----- Equifax Secure CA ================= -----BEGIN CERTIFICATE----- MIIDIDCCAomgAwIBAgIENd70zzANBgkqhkiG9w0BAQUFADBOMQswCQYDVQQGEwJVUzEQMA4GA1UE ChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2VydGlmaWNhdGUgQXV0aG9yaXR5 MB4XDTk4MDgyMjE2NDE1MVoXDTE4MDgyMjE2NDE1MVowTjELMAkGA1UEBhMCVVMxEDAOBgNVBAoT B0VxdWlmYXgxLTArBgNVBAsTJEVxdWlmYXggU2VjdXJlIENlcnRpZmljYXRlIEF1dGhvcml0eTCB nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAwV2xWGcIYu6gmi0fCG2RFGiYCh7+2gRvE4RiIcPR fM6fBeC4AfBONOziipUEZKzxa1NfBbPLZ4C/QgKO/t0BCezhABRP/PvwDN1Dulsr4R+AcJkVV5MW 8Q+XarfCaCMczE1ZMKxRHjuvK9buY0V7xdlfUNLjUA86iOe/FP3gx7kCAwEAAaOCAQkwggEFMHAG A1UdHwRpMGcwZaBjoGGkXzBdMQswCQYDVQQGEwJVUzEQMA4GA1UEChMHRXF1aWZheDEtMCsGA1UE CxMkRXF1aWZheCBTZWN1cmUgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMBoG A1UdEAQTMBGBDzIwMTgwODIyMTY0MTUxWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUSOZo+SvS spXXR9gjIBBPM5iQn9QwHQYDVR0OBBYEFEjmaPkr0rKV10fYIyAQTzOYkJ/UMAwGA1UdEwQFMAMB Af8wGgYJKoZIhvZ9B0EABA0wCxsFVjMuMGMDAgbAMA0GCSqGSIb3DQEBBQUAA4GBAFjOKer89961 zgK5F7WF0bnj4JXMJTENAKaSbn+2kmOeUJXRmm/kEd5jhW6Y7qj/WsjTVbJmcVfewCHrPSqnI0kB BIZCe/zuf6IWUrVnZ9NA2zsmWLIodz2uFHdh1voqZiegDfqnc1zqcPGUIWVEX/r87yloqaKHee95 70+sB3c4 -----END CERTIFICATE----- Verisign Class 3 Public Primary Certification Authority ======================================================= -----BEGIN CERTIFICATE----- MIICPDCCAaUCEHC65B0Q2Sk0tjjKewPMur8wDQYJKoZIhvcNAQECBQAwXzELMAkGA1UEBhMCVVMx FzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAzIFB1YmxpYyBQcmltYXJ5 IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTk2MDEyOTAwMDAwMFoXDTI4MDgwMTIzNTk1OVow XzELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAz IFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGfMA0GCSqGSIb3DQEBAQUA A4GNADCBiQKBgQDJXFme8huKARS0EN8EQNvjV69qRUCPhAwL0TPZ2RHP7gJYHyX3KqhEBarsAx94 f56TuZoAqiN91qyFomNFx3InzPRMxnVx0jnvT0Lwdd8KkMaOIG+YD/isI19wKTakyYbnsZogy1Ol hec9vn2a/iRFM9x2Fe0PonFkTGUugWhFpwIDAQABMA0GCSqGSIb3DQEBAgUAA4GBALtMEivPLCYA TxQT3ab7/AoRhIzzKBxnki98tsX63/Dolbwdj2wsqFHMc9ikwFPwTtYmwHYBV4GSXiHx0bH/59Ah WM1pF+NEHJwZRDmJXNycAA9WjQKZ7aKQRUzkuxCkPfAyAw7xzvjoyVGM5mKf5p/AfbdynMk2Omuf Tqj/ZA1k -----END CERTIFICATE----- Verisign Class 3 Public Primary Certification Authority - G2 ============================================================ -----BEGIN CERTIFICATE----- MIIDAjCCAmsCEH3Z/gfPqB63EHln+6eJNMYwDQYJKoZIhvcNAQEFBQAwgcExCzAJBgNVBAYTAlVT MRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE8MDoGA1UECxMzQ2xhc3MgMyBQdWJsaWMgUHJpbWFy eSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMTowOAYDVQQLEzEoYykgMTk5OCBWZXJpU2ln biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MR8wHQYDVQQLExZWZXJpU2lnbiBUcnVz dCBOZXR3b3JrMB4XDTk4MDUxODAwMDAwMFoXDTI4MDgwMTIzNTk1OVowgcExCzAJBgNVBAYTAlVT MRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE8MDoGA1UECxMzQ2xhc3MgMyBQdWJsaWMgUHJpbWFy eSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMTowOAYDVQQLEzEoYykgMTk5OCBWZXJpU2ln biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MR8wHQYDVQQLExZWZXJpU2lnbiBUcnVz dCBOZXR3b3JrMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDMXtERXVxp0KvTuWpMmR9ZmDCO FoUgRm1HP9SFIIThbbP4pO0M8RcPO/mn+SXXwc+EY/J8Y8+iR/LGWzOOZEAEaMGAuWQcRXfH2G71 lSk8UOg013gfqLptQ5GVj0VXXn7F+8qkBOvqlzdUMG+7AUcyM83cV5tkaWH4mx0ciU9cZwIDAQAB MA0GCSqGSIb3DQEBBQUAA4GBAFFNzb5cy5gZnBWyATl4Lk0PZ3BwmcYQWpSkU01UbSuvDV1Ai2TT 1+7eVmGSX6bEHRBhNtMsJzzoKQm5EWR0zLVznxxIqbxhAe7iF6YM40AIOw7n60RzKprxaZLvcRTD Oaxxp5EJb+RxBrO6WVcmeQD2+A2iMzAo1KpYoJ2daZH9 -----END CERTIFICATE----- GlobalSign Root CA ================== -----BEGIN CERTIFICATE----- MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A== -----END CERTIFICATE----- GlobalSign Root CA - R2 ======================= -----BEGIN CERTIFICATE----- MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4GA1UECxMXR2xv YmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2Jh bFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxT aWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2ln bjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6 ErPLv4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8eoLrvozp s6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklqtTleiDTsvHgMCJiEbKjN S7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzdC9XZzPnqJworc5HGnRusyMvo4KD0L5CL TfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pazq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6C ygPCm48CAwEAAaOBnDCBmTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E FgQUm+IHV2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9i YWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG3lm0mi3f3BmGLjAN BgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4GsJ0/WwbgcQ3izDJr86iw8bmEbTUsp 9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu 01yiPqFbQfXf5WRDLenVOavSot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG7 9G+dwfCMNYxdAfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7 TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg== -----END CERTIFICATE----- ValiCert Class 1 VA =================== -----BEGIN CERTIFICATE----- MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRp b24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs YXNzIDEgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZh bGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNTIy MjM0OFoXDTE5MDYyNTIyMjM0OFowgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0 d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENsYXNzIDEg UG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0 LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMIGfMA0GCSqGSIb3DQEBAQUA A4GNADCBiQKBgQDYWYJ6ibiWuqYvaG9YLqdUHAZu9OqNSLwxlBfw8068srg1knaw0KWlAdcAAxIi GQj4/xEjm84H9b9pGib+TunRf50sQB1ZaG6m+FiwnRqP0z/x3BkGgagO4DrdyFNFCQbmD3DD+kCm DuJWBQ8YTfwggtFzVXSNdnKgHZ0dwN0/cQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAFBoPUn0LBwG lN+VYH+Wexf+T3GtZMjdd9LvWVXoP+iOBSoh8gfStadS/pyxtuJbdxdA6nLWI8sogTLDAHkY7FkX icnGah5xyf23dKUlRWnFSKsZ4UWKJWsZ7uW7EvV/96aNUcPwnXS3qT6gpf+2SQMT2iLM7XGCK5nP Orf1LXLI -----END CERTIFICATE----- ValiCert Class 2 VA =================== -----BEGIN CERTIFICATE----- MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRp b24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs YXNzIDIgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZh bGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNjAw MTk1NFoXDTE5MDYyNjAwMTk1NFowgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0 d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENsYXNzIDIg UG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0 LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMIGfMA0GCSqGSIb3DQEBAQUA A4GNADCBiQKBgQDOOnHK5avIWZJV16vYdA757tn2VUdZZUcOBVXc65g2PFxTXdMwzzjsvUGJ7SVC CSRrCl6zfN1SLUzm1NZ9WlmpZdRJEy0kTRxQb7XBhVQ7/nHk01xC+YDgkRoKWzk2Z/M/VXwbP7Rf ZHM047QSv4dk+NoS/zcnwbNDu+97bi5p9wIDAQABMA0GCSqGSIb3DQEBBQUAA4GBADt/UG9vUJSZ SWI4OB9L+KXIPqeCgfYrx+jFzug6EILLGACOTb2oWH+heQC1u+mNr0HZDzTuIYEZoDJJKPTEjlbV UjP9UNV+mWwD5MlM/Mtsq2azSiGM5bUMMj4QssxsodyamEwCW/POuZ6lcg5Ktz885hZo+L7tdEy8 W9ViH0Pd -----END CERTIFICATE----- RSA Root Certificate 1 ====================== -----BEGIN CERTIFICATE----- MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRp b24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs YXNzIDMgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZh bGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNjAw MjIzM1oXDTE5MDYyNjAwMjIzM1owgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0 d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENsYXNzIDMg UG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0 LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMIGfMA0GCSqGSIb3DQEBAQUA A4GNADCBiQKBgQDjmFGWHOjVsQaBalfDcnWTq8+epvzzFlLWLU2fNUSoLgRNB0mKOCn1dzfnt6td 3zZxFJmP3MKS8edgkpfs2Ejcv8ECIMYkpChMMFp2bbFc893enhBxoYjHW5tBbcqwuI4V7q0zK89H BFx1cQqYJJgpp0lZpd34t0NiYfPT4tBVPwIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAFa7AliEZwgs 3x/be0kz9dNnnfS0ChCzycUs4pJqcXgn8nCDQtM+z6lU9PHYkhaM0QTLS6vJn0WuPIqpsHEzXcjF V9+vqDWzf4mH6eglkrh/hXqu1rweN1gqZ8mRzyqBPu3GOd/APhmcGcwTTYJBtYze4D1gCCAPRX5r on+jjBXu -----END CERTIFICATE----- Verisign Class 3 Public Primary Certification Authority - G3 ============================================================ -----BEGIN CERTIFICATE----- MIIEGjCCAwICEQCbfgZJoz5iudXukEhxKe9XMA0GCSqGSIb3DQEBBQUAMIHKMQswCQYDVQQGEwJV UzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv cmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl IG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNh dGlvbiBBdXRob3JpdHkgLSBHMzAeFw05OTEwMDEwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMIHKMQsw CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRy dXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhv cml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1hcnkg Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC ggEBAMu6nFL8eB8aHm8bN3O9+MlrlBIwT/A2R/XQkQr1F8ilYcEWQE37imGQ5XYgwREGfassbqb1 EUGO+i2tKmFZpGcmTNDovFJbcCAEWNF6yaRpvIMXZK0Fi7zQWM6NjPXr8EJJC52XJ2cybuGukxUc cLwgTS8Y3pKI6GyFVxEa6X7jJhFUokWWVYPKMIno3Nij7SqAP395ZVc+FSBmCC+Vk7+qRy+oRpfw EuL+wgorUeZ25rdGt+INpsyow0xZVYnm6FNcHOqd8GIWC6fJXwzw3sJ2zq/3avL6QaaiMxTJ5Xpj 055iN9WFZZ4O5lMkdBteHRJTW8cs54NJOxWuimi5V5cCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEA ERSWwauSCPc/L8my/uRan2Te2yFPhpk0djZX3dAVL8WtfxUfN2JzPtTnX84XA9s1+ivbrmAJXx5f j267Cz3qWhMeDGBvtcC1IyIuBwvLqXTLR7sdwdela8wv0kL9Sd2nic9TutoAWii/gt/4uhMdUIaC /Y4wjylGsB49Ndo4YhYYSq3mtlFs3q9i6wHQHiT+eo8SGhJouPtmmRQURVyu565pF4ErWjfJXir0 xuKhXFSbplQAz/DxwceYMBo7Nhbbo27q/a2ywtrvAkcTisDxszGtTxzhT5yvDwyd93gN2PQ1VoDa t20Xj50egWTh/sVFuq1ruQp6Tk9LhO5L8X3dEQ== -----END CERTIFICATE----- Verisign Class 4 Public Primary Certification Authority - G3 ============================================================ -----BEGIN CERTIFICATE----- MIIEGjCCAwICEQDsoKeLbnVqAc/EfMwvlF7XMA0GCSqGSIb3DQEBBQUAMIHKMQswCQYDVQQGEwJV UzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv cmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl IG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDQgUHVibGljIFByaW1hcnkgQ2VydGlmaWNh dGlvbiBBdXRob3JpdHkgLSBHMzAeFw05OTEwMDEwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMIHKMQsw CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRy dXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhv cml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDQgUHVibGljIFByaW1hcnkg Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC ggEBAK3LpRFpxlmr8Y+1GQ9Wzsy1HyDkniYlS+BzZYlZ3tCD5PUPtbut8XzoIfzk6AzufEUiGXaS tBO3IFsJ+mGuqPKljYXCKtbeZjbSmwL0qJJgfJxptI8kHtCGUvYynEFYHiK9zUVilQhu0GbdU6LM 8BDcVHOLBKFGMzNcF0C5nk3T875Vg+ixiY5afJqWIpA7iCXy0lOIAgwLePLmNxdLMEYH5IBtptiW Lugs+BGzOA1mppvqySNb247i8xOOGlktqgLw7KSHZtzBP/XYufTsgsbSPZUd5cBPhMnZo0QoBmrX Razwa2rvTl/4EYIeOGM0ZlDUPpNz+jDDZq3/ky2X7wMCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEA j/ola09b5KROJ1WrIhVZPMq1CtRK26vdoV9TxaBXOcLORyu+OshWv8LZJxA6sQU8wHcxuzrTBXtt mhwwjIDLk5Mqg6sFUYICABFna/OIYUdfA5PVWw3g8dShMjWFsjrbsIKr0csKvE+MW8VLADsfKoKm fjaF3H48ZwC15DtS4KjrXRX5xm3wrR0OhbepmnMUWluPQSjA1egtTaRezarZ7c7c2NU8Qh0XwRJd RTjDOPP8hS6DRkiy1yBfkjaP53kPmF6Z6PDQpLv1U70qzlmwr25/bLvSHgCwIe34QWKCudiyxLtG UPMxxY8BqHTr9Xgn2uf3ZkPznoM+IKrDNWCRzg== -----END CERTIFICATE----- Entrust.net Secure Server CA ============================ -----BEGIN CERTIFICATE----- MIIE2DCCBEGgAwIBAgIEN0rSQzANBgkqhkiG9w0BAQUFADCBwzELMAkGA1UEBhMCVVMxFDASBgNV BAoTC0VudHJ1c3QubmV0MTswOQYDVQQLEzJ3d3cuZW50cnVzdC5uZXQvQ1BTIGluY29ycC4gYnkg cmVmLiAobGltaXRzIGxpYWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRl ZDE6MDgGA1UEAxMxRW50cnVzdC5uZXQgU2VjdXJlIFNlcnZlciBDZXJ0aWZpY2F0aW9uIEF1dGhv cml0eTAeFw05OTA1MjUxNjA5NDBaFw0xOTA1MjUxNjM5NDBaMIHDMQswCQYDVQQGEwJVUzEUMBIG A1UEChMLRW50cnVzdC5uZXQxOzA5BgNVBAsTMnd3dy5lbnRydXN0Lm5ldC9DUFMgaW5jb3JwLiBi eSByZWYuIChsaW1pdHMgbGlhYi4pMSUwIwYDVQQLExwoYykgMTk5OSBFbnRydXN0Lm5ldCBMaW1p dGVkMTowOAYDVQQDEzFFbnRydXN0Lm5ldCBTZWN1cmUgU2VydmVyIENlcnRpZmljYXRpb24gQXV0 aG9yaXR5MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQDNKIM0VBuJ8w+vN5Ex/68xYMmo6LIQ aO2f55M28Qpku0f1BBc/I0dNxScZgSYMVHINiC3ZH5oSn7yzcdOAGT9HZnuMNSjSuQrfJNqc1lB5 gXpa0zf3wkrYKZImZNHkmGw6AIr1NJtl+O3jEP/9uElY3KDegjlrgbEWGWG5VLbmQwIBA6OCAdcw ggHTMBEGCWCGSAGG+EIBAQQEAwIABzCCARkGA1UdHwSCARAwggEMMIHeoIHboIHYpIHVMIHSMQsw CQYDVQQGEwJVUzEUMBIGA1UEChMLRW50cnVzdC5uZXQxOzA5BgNVBAsTMnd3dy5lbnRydXN0Lm5l dC9DUFMgaW5jb3JwLiBieSByZWYuIChsaW1pdHMgbGlhYi4pMSUwIwYDVQQLExwoYykgMTk5OSBF bnRydXN0Lm5ldCBMaW1pdGVkMTowOAYDVQQDEzFFbnRydXN0Lm5ldCBTZWN1cmUgU2VydmVyIENl cnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMCmgJ6AlhiNodHRwOi8vd3d3LmVu dHJ1c3QubmV0L0NSTC9uZXQxLmNybDArBgNVHRAEJDAigA8xOTk5MDUyNTE2MDk0MFqBDzIwMTkw NTI1MTYwOTQwWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAU8BdiE1U9s/8KAGv7UISX8+1i0Bow HQYDVR0OBBYEFPAXYhNVPbP/CgBr+1CEl/PtYtAaMAwGA1UdEwQFMAMBAf8wGQYJKoZIhvZ9B0EA BAwwChsEVjQuMAMCBJAwDQYJKoZIhvcNAQEFBQADgYEAkNwwAvpkdMKnCqV8IY00F6j7Rw7/JXyN Ewr75Ji174z4xRAN95K+8cPV1ZVqBLssziY2ZcgxxufuP+NXdYR6Ee9GTxj005i7qIcyunL2POI9 n9cd2cNgQ4xYDiKWL2KjLB+6rQXvqzJ4h6BUcxm1XAX5Uj5tLUUL9wqT6u0G+bI= -----END CERTIFICATE----- Entrust.net Premium 2048 Secure Server CA ========================================= -----BEGIN CERTIFICATE----- MIIEKjCCAxKgAwIBAgIEOGPe+DANBgkqhkiG9w0BAQUFADCBtDEUMBIGA1UEChMLRW50cnVzdC5u ZXQxQDA+BgNVBAsUN3d3dy5lbnRydXN0Lm5ldC9DUFNfMjA0OCBpbmNvcnAuIGJ5IHJlZi4gKGxp bWl0cyBsaWFiLikxJTAjBgNVBAsTHChjKSAxOTk5IEVudHJ1c3QubmV0IExpbWl0ZWQxMzAxBgNV BAMTKkVudHJ1c3QubmV0IENlcnRpZmljYXRpb24gQXV0aG9yaXR5ICgyMDQ4KTAeFw05OTEyMjQx NzUwNTFaFw0yOTA3MjQxNDE1MTJaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3 d3d3LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxpYWIuKTEl MCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50cnVzdC5u ZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgpMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A MIIBCgKCAQEArU1LqRKGsuqjIAcVFmQqK0vRvwtKTY7tgHalZ7d4QMBzQshowNtTK91euHaYNZOL Gp18EzoOH1u3Hs/lJBQesYGpjX24zGtLA/ECDNyrpUAkAH90lKGdCCmziAv1h3edVc3kw37XamSr hRSGlVuXMlBvPci6Zgzj/L24ScF2iUkZ/cCovYmjZy/Gn7xxGWC4LeksyZB2ZnuU4q941mVTXTzW nLLPKQP5L6RQstRIzgUyVYr9smRMDuSYB3Xbf9+5CFVghTAp+XtIpGmG4zU/HoZdenoVve8AjhUi VBcAkCaTvA5JaJG/+EfTnZVCwQ5N328mz8MYIWJmQ3DW1cAH4QIDAQABo0IwQDAOBgNVHQ8BAf8E BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUVeSB0RGAvtiJuQijMfmhJAkWuXAwDQYJ KoZIhvcNAQEFBQADggEBADubj1abMOdTmXx6eadNl9cZlZD7Bh/KM3xGY4+WZiT6QBshJ8rmcnPy T/4xmf3IDExoU8aAghOY+rat2l098c5u9hURlIIM7j+VrxGrD9cv3h8Dj1csHsm7mhpElesYT6Yf zX1XEC+bBAlahLVu2B064dae0Wx5XnkcFMXj0EyTO2U87d89vqbllRrDtRnDvV5bu/8j72gZyxKT J1wDLW8w0B62GqzeWvfRqqgnpv55gcR5mTNXuhKwqeBCbJPKVt7+bYQLCIt+jerXmCHG8+c8eS9e nNFMFY3h7CI3zJpDC5fcgJCNs2ebb0gIFVbPv/ErfF6adulZkMV8gzURZVE= -----END CERTIFICATE----- Baltimore CyberTrust Root ========================= -----BEGIN CERTIFICATE----- MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJRTESMBAGA1UE ChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYDVQQDExlCYWx0aW1vcmUgQ3li ZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoXDTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMC SUUxEjAQBgNVBAoTCUJhbHRpbW9yZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFs dGltb3JlIEN5YmVyVHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKME uyKrmD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjrIZ3AQSsB UnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeKmpYcqWe4PwzV9/lSEy/C G9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSuXmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9 XbIGevOF6uvUA65ehD5f/xXtabz5OTZydc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjpr l3RjM71oGDHweI12v/yejl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoI VDaGezq1BE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEB BQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT929hkTI7gQCvlYpNRh cL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3WgxjkzSswF07r51XgdIGn9w/xZchMB5 hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0Epn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsa Y71k5h+3zvDyny67G7fyUIhzksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9H RCwBXbsdtTLSR9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp -----END CERTIFICATE----- Equifax Secure Global eBusiness CA ================================== -----BEGIN CERTIFICATE----- MIICkDCCAfmgAwIBAgIBATANBgkqhkiG9w0BAQQFADBaMQswCQYDVQQGEwJVUzEcMBoGA1UEChMT RXF1aWZheCBTZWN1cmUgSW5jLjEtMCsGA1UEAxMkRXF1aWZheCBTZWN1cmUgR2xvYmFsIGVCdXNp bmVzcyBDQS0xMB4XDTk5MDYyMTA0MDAwMFoXDTIwMDYyMTA0MDAwMFowWjELMAkGA1UEBhMCVVMx HDAaBgNVBAoTE0VxdWlmYXggU2VjdXJlIEluYy4xLTArBgNVBAMTJEVxdWlmYXggU2VjdXJlIEds b2JhbCBlQnVzaW5lc3MgQ0EtMTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAuucXkAJlsTRV PEnCUdXfp9E3j9HngXNBUmCbnaEXJnitx7HoJpQytd4zjTov2/KaelpzmKNc6fuKcxtc58O/gGzN qfTWK8D3+ZmqY6KxRwIP1ORROhI8bIpaVIRw28HFkM9yRcuoWcDNM50/o5brhTMhHD4ePmBudpxn hcXIw2ECAwEAAaNmMGQwEQYJYIZIAYb4QgEBBAQDAgAHMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0j BBgwFoAUvqigdHJQa0S3ySPY+6j/s1draGwwHQYDVR0OBBYEFL6ooHRyUGtEt8kj2Puo/7NXa2hs MA0GCSqGSIb3DQEBBAUAA4GBADDiAVGqx+pf2rnQZQ8w1j7aDRRJbpGTJxQx78T3LUX47Me/okEN I7SS+RkAZ70Br83gcfxaz2TE4JaY0KNA4gGK7ycH8WUBikQtBmV1UsCGECAhX2xrD2yuCRyv8qIY NMR1pHMc8Y3c7635s3a0kr/clRAevsvIO1qEYBlWlKlV -----END CERTIFICATE----- Equifax Secure eBusiness CA 1 ============================= -----BEGIN CERTIFICATE----- MIICgjCCAeugAwIBAgIBBDANBgkqhkiG9w0BAQQFADBTMQswCQYDVQQGEwJVUzEcMBoGA1UEChMT RXF1aWZheCBTZWN1cmUgSW5jLjEmMCQGA1UEAxMdRXF1aWZheCBTZWN1cmUgZUJ1c2luZXNzIENB LTEwHhcNOTkwNjIxMDQwMDAwWhcNMjAwNjIxMDQwMDAwWjBTMQswCQYDVQQGEwJVUzEcMBoGA1UE ChMTRXF1aWZheCBTZWN1cmUgSW5jLjEmMCQGA1UEAxMdRXF1aWZheCBTZWN1cmUgZUJ1c2luZXNz IENBLTEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAM4vGbwXt3fek6lfWg0XTzQaDJj0ItlZ 1MRoRvC0NcWFAyDGr0WlIVFFQesWWDYyb+JQYmT5/VGcqiTZ9J2DKocKIdMSODRsjQBuWqDZQu4a IZX5UkxVWsUPOE9G+m34LjXWHXzr4vCwdYDIqROsvojvOm6rXyo4YgKwEnv+j6YDAgMBAAGjZjBk MBEGCWCGSAGG+EIBAQQEAwIABzAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFEp4MlIR21kW Nl7fwRQ2QGpHfEyhMB0GA1UdDgQWBBRKeDJSEdtZFjZe38EUNkBqR3xMoTANBgkqhkiG9w0BAQQF AAOBgQB1W6ibAxHm6VZMzfmpTMANmvPMZWnmJXbMWbfWVMMdzZmsGd20hdXgPfxiIKeES1hl8eL5 lSE/9dR+WB5Hh1Q+WKG1tfgq73HnvMP2sUlG4tega+VWeponmHxGYhTnyfxuAxJ5gDgdSIKN/Bf+ KpYrtWKmpj29f5JZzVoqgrI3eQ== -----END CERTIFICATE----- AddTrust Low-Value Services Root ================================ -----BEGIN CERTIFICATE----- MIIEGDCCAwCgAwIBAgIBATANBgkqhkiG9w0BAQUFADBlMQswCQYDVQQGEwJTRTEUMBIGA1UEChML QWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSEwHwYDVQQDExhBZGRU cnVzdCBDbGFzcyAxIENBIFJvb3QwHhcNMDAwNTMwMTAzODMxWhcNMjAwNTMwMTAzODMxWjBlMQsw CQYDVQQGEwJTRTEUMBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBO ZXR3b3JrMSEwHwYDVQQDExhBZGRUcnVzdCBDbGFzcyAxIENBIFJvb3QwggEiMA0GCSqGSIb3DQEB AQUAA4IBDwAwggEKAoIBAQCWltQhSWDia+hBBwzexODcEyPNwTXH+9ZOEQpnXvUGW2ulCDtbKRY6 54eyNAbFvAWlA3yCyykQruGIgb3WntP+LVbBFc7jJp0VLhD7Bo8wBN6ntGO0/7Gcrjyvd7ZWxbWr oulpOj0OM3kyP3CCkplhbY0wCI9xP6ZIVxn4JdxLZlyldI+Yrsj5wAYi56xz36Uu+1LcsRVlIPo1 Zmne3yzxbrww2ywkEtvrNTVokMsAsJchPXQhI2U0K7t4WaPW4XY5mqRJjox0r26kmqPZm9I4XJui GMx1I4S+6+JNM3GOGvDC+Mcdoq0Dlyz4zyXG9rgkMbFjXZJ/Y/AlyVMuH79NAgMBAAGjgdIwgc8w HQYDVR0OBBYEFJWxtPCUtr3H2tERCSG+wa9J/RB7MAsGA1UdDwQEAwIBBjAPBgNVHRMBAf8EBTAD AQH/MIGPBgNVHSMEgYcwgYSAFJWxtPCUtr3H2tERCSG+wa9J/RB7oWmkZzBlMQswCQYDVQQGEwJT RTEUMBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSEw HwYDVQQDExhBZGRUcnVzdCBDbGFzcyAxIENBIFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBACxt ZBsfzQ3duQH6lmM0MkhHma6X7f1yFqZzR1r0693p9db7RcwpiURdv0Y5PejuvE1Uhh4dbOMXJ0Ph iVYrqW9yTkkz43J8KiOavD7/KCrto/8cI7pDVwlnTUtiBi34/2ydYB7YHEt9tTEv2dB8Xfjea4MY eDdXL+gzB2ffHsdrKpV2ro9Xo/D0UrSpUwjP4E/TelOL/bscVjby/rK25Xa71SJlpz/+0WatC7xr mYbvP33zGDLKe8bjq2RGlfgmadlVg3sslgf/WSxEo8bl6ancoWOAWiFeIc9TVPC6b4nbqKqVz4vj ccweGyBECMB6tkD9xOQ14R0WHNC8K47Wcdk= -----END CERTIFICATE----- AddTrust External Root ====================== -----BEGIN CERTIFICATE----- MIIENjCCAx6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBvMQswCQYDVQQGEwJTRTEUMBIGA1UEChML QWRkVHJ1c3QgQUIxJjAkBgNVBAsTHUFkZFRydXN0IEV4dGVybmFsIFRUUCBOZXR3b3JrMSIwIAYD VQQDExlBZGRUcnVzdCBFeHRlcm5hbCBDQSBSb290MB4XDTAwMDUzMDEwNDgzOFoXDTIwMDUzMDEw NDgzOFowbzELMAkGA1UEBhMCU0UxFDASBgNVBAoTC0FkZFRydXN0IEFCMSYwJAYDVQQLEx1BZGRU cnVzdCBFeHRlcm5hbCBUVFAgTmV0d29yazEiMCAGA1UEAxMZQWRkVHJ1c3QgRXh0ZXJuYWwgQ0Eg Um9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALf3GjPm8gAELTngTlvtH7xsD821 +iO2zt6bETOXpClMfZOfvUq8k+0DGuOPz+VtUFrWlymUWoCwSXrbLpX9uMq/NzgtHj6RQa1wVsfw Tz/oMp50ysiQVOnGXw94nZpAPA6sYapeFI+eh6FqUNzXmk6vBbOmcZSccbNQYArHE504B4YCqOmo aSYYkKtMsE8jqzpPhNjfzp/haW+710LXa0Tkx63ubUFfclpxCDezeWWkWaCUN/cALw3CknLa0Dhy 2xSoRcRdKn23tNbE7qzNE0S3ySvdQwAl+mG5aWpYIxG3pzOPVnVZ9c0p10a3CitlttNCbxWyuHv7 7+ldU9U0WicCAwEAAaOB3DCB2TAdBgNVHQ4EFgQUrb2YejS0Jvf6xCZU7wO94CTLVBowCwYDVR0P BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wgZkGA1UdIwSBkTCBjoAUrb2YejS0Jvf6xCZU7wO94CTL VBqhc6RxMG8xCzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRUcnVzdCBBQjEmMCQGA1UECxMdQWRk VHJ1c3QgRXh0ZXJuYWwgVFRQIE5ldHdvcmsxIjAgBgNVBAMTGUFkZFRydXN0IEV4dGVybmFsIENB IFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBALCb4IUlwtYj4g+WBpKdQZic2YR5gdkeWxQHIzZl j7DYd7usQWxHYINRsPkyPef89iYTx4AWpb9a/IfPeHmJIZriTAcKhjW88t5RxNKWt9x+Tu5w/Rw5 6wwCURQtjr0W4MHfRnXnJK3s9EK0hZNwEGe6nQY1ShjTK3rMUUKhemPR5ruhxSvCNr4TDea9Y355 e6cJDUCrat2PisP29owaQgVR1EX1n6diIWgVIEM8med8vSTYqZEXc4g/VhsxOBi0cQ+azcgOno4u G+GMmIPLHzHxREzGBHNJdmAPx/i9F4BrLunMTA5amnkPIAou1Z5jJh5VkpTYghdae9C8x49OhgQ= -----END CERTIFICATE----- AddTrust Public Services Root ============================= -----BEGIN CERTIFICATE----- MIIEFTCCAv2gAwIBAgIBATANBgkqhkiG9w0BAQUFADBkMQswCQYDVQQGEwJTRTEUMBIGA1UEChML QWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSAwHgYDVQQDExdBZGRU cnVzdCBQdWJsaWMgQ0EgUm9vdDAeFw0wMDA1MzAxMDQxNTBaFw0yMDA1MzAxMDQxNTBaMGQxCzAJ BgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRUcnVzdCBBQjEdMBsGA1UECxMUQWRkVHJ1c3QgVFRQIE5l dHdvcmsxIDAeBgNVBAMTF0FkZFRydXN0IFB1YmxpYyBDQSBSb290MIIBIjANBgkqhkiG9w0BAQEF AAOCAQ8AMIIBCgKCAQEA6Rowj4OIFMEg2Dybjxt+A3S72mnTRqX4jsIMEZBRpS9mVEBV6tsfSlbu nyNu9DnLoblv8n75XYcmYZ4c+OLspoH4IcUkzBEMP9smcnrHAZcHF/nXGCwwfQ56HmIexkvA/X1i d9NEHif2P0tEs7c42TkfYNVRknMDtABp4/MUTu7R3AnPdzRGULD4EfL+OHn3Bzn+UZKXC1sIXzSG Aa2Il+tmzV7R/9x98oTaunet3IAIx6eH1lWfl2royBFkuucZKT8Rs3iQhCBSWxHveNCD9tVIkNAw HM+A+WD+eeSI8t0A65RF62WUaUC6wNW0uLp9BBGo6zEFlpROWCGOn9Bg/QIDAQABo4HRMIHOMB0G A1UdDgQWBBSBPjfYkrAfd59ctKtzquf2NGAv+jALBgNVHQ8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB /zCBjgYDVR0jBIGGMIGDgBSBPjfYkrAfd59ctKtzquf2NGAv+qFopGYwZDELMAkGA1UEBhMCU0Ux FDASBgNVBAoTC0FkZFRydXN0IEFCMR0wGwYDVQQLExRBZGRUcnVzdCBUVFAgTmV0d29yazEgMB4G A1UEAxMXQWRkVHJ1c3QgUHVibGljIENBIFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBAAP3FUr4 JNojVhaTdt02KLmuG7jD8WS6IBh4lSknVwW8fCr0uVFV2ocC3g8WFzH4qnkuCRO7r7IgGRLlk/lL +YPoRNWyQSW/iHVv/xD8SlTQX/D67zZzfRs2RcYhbbQVuE7PnFylPVoAjgbjPGsye/Kf8Lb93/Ao GEjwxrzQvzSAlsJKsW2Ox5BF3i9nrEUEo3rcVZLJR2bYGozH7ZxOmuASu7VqTITh4SINhwBk/ox9 Yjllpu9CtoAlEmEBqCQTcAARJl/6NVDFSMwGR+gn2HCNX2TmoUQmXiLsks3/QppEIW1cxeMiHV9H EufOX1362KqxMy3ZdvJOOjMMK7MtkAY= -----END CERTIFICATE----- AddTrust Qualified Certificates Root ==================================== -----BEGIN CERTIFICATE----- MIIEHjCCAwagAwIBAgIBATANBgkqhkiG9w0BAQUFADBnMQswCQYDVQQGEwJTRTEUMBIGA1UEChML QWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSMwIQYDVQQDExpBZGRU cnVzdCBRdWFsaWZpZWQgQ0EgUm9vdDAeFw0wMDA1MzAxMDQ0NTBaFw0yMDA1MzAxMDQ0NTBaMGcx CzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRUcnVzdCBBQjEdMBsGA1UECxMUQWRkVHJ1c3QgVFRQ IE5ldHdvcmsxIzAhBgNVBAMTGkFkZFRydXN0IFF1YWxpZmllZCBDQSBSb290MIIBIjANBgkqhkiG 9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5B6a/twJWoekn0e+EV+vhDTbYjx5eLfpMLXsDBwqxBb/4Oxx 64r1EW7tTw2R0hIYLUkVAcKkIhPHEWT/IhKauY5cLwjPcWqzZwFZ8V1G87B4pfYOQnrjfxvM0PC3 KP0q6p6zsLkEqv32x7SxuCqg+1jxGaBvcCV+PmlKfw8i2O+tCBGaKZnhqkRFmhJePp1tUvznoD1o L/BLcHwTOK28FSXx1s6rosAx1i+f4P8UWfyEk9mHfExUE+uf0S0R+Bg6Ot4l2ffTQO2kBhLEO+GR wVY18BTcZTYJbqukB8c10cIDMzZbdSZtQvESa0NvS3GU+jQd7RNuyoB/mC9suWXY6QIDAQABo4HU MIHRMB0GA1UdDgQWBBQ5lYtii1zJ1IC6WA+XPxUIQ8yYpzALBgNVHQ8EBAMCAQYwDwYDVR0TAQH/ BAUwAwEB/zCBkQYDVR0jBIGJMIGGgBQ5lYtii1zJ1IC6WA+XPxUIQ8yYp6FrpGkwZzELMAkGA1UE BhMCU0UxFDASBgNVBAoTC0FkZFRydXN0IEFCMR0wGwYDVQQLExRBZGRUcnVzdCBUVFAgTmV0d29y azEjMCEGA1UEAxMaQWRkVHJ1c3QgUXVhbGlmaWVkIENBIFJvb3SCAQEwDQYJKoZIhvcNAQEFBQAD ggEBABmrder4i2VhlRO6aQTvhsoToMeqT2QbPxj2qC0sVY8FtzDqQmodwCVRLae/DLPt7wh/bDxG GuoYQ992zPlmhpwsaPXpF/gxsxjE1kh9I0xowX67ARRvxdlu3rsEQmr49lx95dr6h+sNNVJn0J6X dgWTP5XHAeZpVTh/EGGZyeNfpso+gmNIquIISD6q8rKFYqa0p9m9N5xotS1WfbC3P6CxB9bpT9ze RXEwMn8bLgn5v1Kh7sKAPgZcLlVAwRv1cEWw3F369nJad9Jjzc9YiQBCYz95OdBEsIJuQRno3eDB iFrRHnGTHyQwdOUeqN48Jzd/g66ed8/wMLH/S5noxqE= -----END CERTIFICATE----- Entrust Root Certification Authority ==================================== -----BEGIN CERTIFICATE----- MIIEkTCCA3mgAwIBAgIERWtQVDANBgkqhkiG9w0BAQUFADCBsDELMAkGA1UEBhMCVVMxFjAUBgNV BAoTDUVudHJ1c3QsIEluYy4xOTA3BgNVBAsTMHd3dy5lbnRydXN0Lm5ldC9DUFMgaXMgaW5jb3Jw b3JhdGVkIGJ5IHJlZmVyZW5jZTEfMB0GA1UECxMWKGMpIDIwMDYgRW50cnVzdCwgSW5jLjEtMCsG A1UEAxMkRW50cnVzdCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA2MTEyNzIwMjM0 MloXDTI2MTEyNzIwNTM0MlowgbAxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMu MTkwNwYDVQQLEzB3d3cuZW50cnVzdC5uZXQvQ1BTIGlzIGluY29ycG9yYXRlZCBieSByZWZlcmVu Y2UxHzAdBgNVBAsTFihjKSAyMDA2IEVudHJ1c3QsIEluYy4xLTArBgNVBAMTJEVudHJ1c3QgUm9v dCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB ALaVtkNC+sZtKm9I35RMOVcF7sN5EUFoNu3s/poBj6E4KPz3EEZmLk0eGrEaTsbRwJWIsMn/MYsz A9u3g3s+IIRe7bJWKKf44LlAcTfFy0cOlypowCKVYhXbR9n10Cv/gkvJrT7eTNuQgFA/CYqEAOww Cj0Yzfv9KlmaI5UXLEWeH25DeW0MXJj+SKfFI0dcXv1u5x609mhF0YaDW6KKjbHjKYD+JXGIrb68 j6xSlkuqUY3kEzEZ6E5Nn9uss2rVvDlUccp6en+Q3X0dgNmBu1kmwhH+5pPi94DkZfs0Nw4pgHBN rziGLp5/V6+eF67rHMsoIV+2HNjnogQi+dPa2MsCAwEAAaOBsDCBrTAOBgNVHQ8BAf8EBAMCAQYw DwYDVR0TAQH/BAUwAwEB/zArBgNVHRAEJDAigA8yMDA2MTEyNzIwMjM0MlqBDzIwMjYxMTI3MjA1 MzQyWjAfBgNVHSMEGDAWgBRokORnpKZTgMeGZqTx90tD+4S9bTAdBgNVHQ4EFgQUaJDkZ6SmU4DH hmak8fdLQ/uEvW0wHQYJKoZIhvZ9B0EABBAwDhsIVjcuMTo0LjADAgSQMA0GCSqGSIb3DQEBBQUA A4IBAQCT1DCw1wMgKtD5Y+iRDAUgqV8ZyntyTtSx29CW+1RaGSwMCPeyvIWonX9tO1KzKtvn1ISM Y/YPyyYBkVBs9F8U4pN0wBOeMDpQ47RgxRzwIkSNcUesyBrJ6ZuaAGAT/3B+XxFNSRuzFVJ7yVTa v52Vr2ua2J7p8eRDjeIRRDq/r72DQnNSi6q7pynP9WQcCk3RvKqsnyrQ/39/2n3qse0wJcGE2jTS W3iDVuycNsMm4hH2Z0kdkquM++v/eu6FSqdQgPCnXEqULl8FmTxSQeDNtGPPAUO6nIPcj2A781q0 tHuu2guQOHXvgR1m0vdXcDazv/wor3ElhVsT/h5/WrQ8 -----END CERTIFICATE----- RSA Security 2048 v3 ==================== -----BEGIN CERTIFICATE----- MIIDYTCCAkmgAwIBAgIQCgEBAQAAAnwAAAAKAAAAAjANBgkqhkiG9w0BAQUFADA6MRkwFwYDVQQK ExBSU0EgU2VjdXJpdHkgSW5jMR0wGwYDVQQLExRSU0EgU2VjdXJpdHkgMjA0OCBWMzAeFw0wMTAy MjIyMDM5MjNaFw0yNjAyMjIyMDM5MjNaMDoxGTAXBgNVBAoTEFJTQSBTZWN1cml0eSBJbmMxHTAb BgNVBAsTFFJTQSBTZWN1cml0eSAyMDQ4IFYzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC AQEAt49VcdKA3XtpeafwGFAyPGJn9gqVB93mG/Oe2dJBVGutn3y+Gc37RqtBaB4Y6lXIL5F4iSj7 Jylg/9+PjDvJSZu1pJTOAeo+tWN7fyb9Gd3AIb2E0S1PRsNO3Ng3OTsor8udGuorryGlwSMiuLgb WhOHV4PR8CDn6E8jQrAApX2J6elhc5SYcSa8LWrg903w8bYqODGBDSnhAMFRD0xS+ARaqn1y07iH KrtjEAMqs6FPDVpeRrc9DvV07Jmf+T0kgYim3WBU6JU2PcYJk5qjEoAAVZkZR73QpXzDuvsf9/UP +Ky5tfQ3mBMY3oVbtwyCO4dvlTlYMNpuAWgXIszACwIDAQABo2MwYTAPBgNVHRMBAf8EBTADAQH/ MA4GA1UdDwEB/wQEAwIBBjAfBgNVHSMEGDAWgBQHw1EwpKrpRa41JPr/JCwz0LGdjDAdBgNVHQ4E FgQUB8NRMKSq6UWuNST6/yQsM9CxnYwwDQYJKoZIhvcNAQEFBQADggEBAF8+hnZuuDU8TjYcHnmY v/3VEhF5Ug7uMYm83X/50cYVIeiKAVQNOvtUudZj1LGqlk2iQk3UUx+LEN5/Zb5gEydxiKRz44Rj 0aRV4VCT5hsOedBnvEbIvz8XDZXmxpBp3ue0L96VfdASPz0+f00/FGj1EVDVwfSQpQgdMWD/YIwj VAqv/qFuxdF6Kmh4zx6CCiC0H63lhbJqaHVOrSU3lIW+vaHU6rcMSzyd6BIA8F+sDeGscGNz9395 nzIlQnQFgCi/vcEkllgVsRch6YlL2weIZ/QVrXA+L02FO8K32/6YaCOJ4XQP3vTFhGMpG8zLB8kA pKnXwiJPZ9d37CAFYd4= -----END CERTIFICATE----- GeoTrust Global CA ================== -----BEGIN CERTIFICATE----- MIIDVDCCAjygAwIBAgIDAjRWMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVTMRYwFAYDVQQK Ew1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9iYWwgQ0EwHhcNMDIwNTIxMDQw MDAwWhcNMjIwNTIxMDQwMDAwWjBCMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5j LjEbMBkGA1UEAxMSR2VvVHJ1c3QgR2xvYmFsIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB CgKCAQEA2swYYzD99BcjGlZ+W988bDjkcbd4kdS8odhM+KhDtgPpTSEHCIjaWC9mOSm9BXiLnTjo BbdqfnGk5sRgprDvgOSJKA+eJdbtg/OtppHHmMlCGDUUna2YRpIuT8rxh0PBFpVXLVDviS2Aelet 8u5fa9IAjbkU+BQVNdnARqN7csiRv8lVK83Qlz6cJmTM386DGXHKTubU1XupGc1V3sjs0l44U+Vc T4wt/lAjNvxm5suOpDkZALeVAjmRCw7+OC7RHQWa9k0+bw8HHa8sHo9gOeL6NlMTOdReJivbPagU vTLrGAMoUgRx5aszPeE4uwc2hGKceeoWMPRfwCvocWvk+QIDAQABo1MwUTAPBgNVHRMBAf8EBTAD AQH/MB0GA1UdDgQWBBTAephojYn7qwVkDBF9qn1luMrMTjAfBgNVHSMEGDAWgBTAephojYn7qwVk DBF9qn1luMrMTjANBgkqhkiG9w0BAQUFAAOCAQEANeMpauUvXVSOKVCUn5kaFOSPeCpilKInZ57Q zxpeR+nBsqTP3UEaBU6bS+5Kb1VSsyShNwrrZHYqLizz/Tt1kL/6cdjHPTfStQWVYrmm3ok9Nns4 d0iXrKYgjy6myQzCsplFAMfOEVEiIuCl6rYVSAlk6l5PdPcFPseKUgzbFbS9bZvlxrFUaKnjaZC2 mqUPuLk/IH2uSrW4nOQdtqvmlKXBx4Ot2/Unhw4EbNX/3aBd7YdStysVAq45pmp06drE57xNNB6p XE0zX5IJL4hmXXeXxx12E6nV5fEWCRE11azbJHFwLJhWC9kXtNHjUStedejV0NxPNO3CBWaAocvm Mw== -----END CERTIFICATE----- GeoTrust Global CA 2 ==================== -----BEGIN CERTIFICATE----- MIIDZjCCAk6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBEMQswCQYDVQQGEwJVUzEWMBQGA1UEChMN R2VvVHJ1c3QgSW5jLjEdMBsGA1UEAxMUR2VvVHJ1c3QgR2xvYmFsIENBIDIwHhcNMDQwMzA0MDUw MDAwWhcNMTkwMzA0MDUwMDAwWjBEMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5j LjEdMBsGA1UEAxMUR2VvVHJ1c3QgR2xvYmFsIENBIDIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw ggEKAoIBAQDvPE1APRDfO1MA4Wf+lGAVPoWI8YkNkMgoI5kF6CsgncbzYEbYwbLVjDHZ3CB5JIG/ NTL8Y2nbsSpr7iFY8gjpeMtvy/wWUsiRxP89c96xPqfCfWbB9X5SJBri1WeR0IIQ13hLTytCOb1k LUCgsBDTOEhGiKEMuzozKmKY+wCdE1l/bztyqu6mD4b5BWHqZ38MN5aL5mkWRxHCJ1kDs6ZgwiFA Vvqgx306E+PsV8ez1q6diYD3Aecs9pYrEw15LNnA5IZ7S4wMcoKK+xfNAGw6EzywhIdLFnopsk/b HdQL82Y3vdj2V7teJHq4PIu5+pIaGoSe2HSPqht/XvT+RSIhAgMBAAGjYzBhMA8GA1UdEwEB/wQF MAMBAf8wHQYDVR0OBBYEFHE4NvICMVNHK266ZUapEBVYIAUJMB8GA1UdIwQYMBaAFHE4NvICMVNH K266ZUapEBVYIAUJMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQUFAAOCAQEAA/e1K6tdEPx7 srJerJsOflN4WT5CBP51o62sgU7XAotexC3IUnbHLB/8gTKY0UvGkpMzNTEv/NgdRN3ggX+d6Yvh ZJFiCzkIjKx0nVnZellSlxG5FntvRdOW2TF9AjYPnDtuzywNA0ZF66D0f0hExghAzN4bcLUprbqL OzRldRtxIR0sFAqwlpW41uryZfspuk/qkZN0abby/+Ea0AzRdoXLiiW9l14sbxWZJue2Kf8i7MkC x1YAzUm5s2x7UwQa4qjJqhIFI8LO57sEAszAR6LkxCkvW0VXiVHuPOtSCP8HNR6fNWpHSlaY0VqF H4z1Ir+rzoPz4iIprn2DQKi6bA== -----END CERTIFICATE----- GeoTrust Universal CA ===================== -----BEGIN CERTIFICATE----- MIIFaDCCA1CgAwIBAgIBATANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJVUzEWMBQGA1UEChMN R2VvVHJ1c3QgSW5jLjEeMBwGA1UEAxMVR2VvVHJ1c3QgVW5pdmVyc2FsIENBMB4XDTA0MDMwNDA1 MDAwMFoXDTI5MDMwNDA1MDAwMFowRTELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IElu Yy4xHjAcBgNVBAMTFUdlb1RydXN0IFVuaXZlcnNhbCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIP ADCCAgoCggIBAKYVVaCjxuAfjJ0hUNfBvitbtaSeodlyWL0AG0y/YckUHUWCq8YdgNY96xCcOq9t JPi8cQGeBvV8Xx7BDlXKg5pZMK4ZyzBIle0iN430SppyZj6tlcDgFgDgEB8rMQ7XlFTTQjOgNB0e RXbdT8oYN+yFFXoZCPzVx5zw8qkuEKmS5j1YPakWaDwvdSEYfyh3peFhF7em6fgemdtzbvQKoiFs 7tqqhZJmr/Z6a4LauiIINQ/PQvE1+mrufislzDoR5G2vc7J2Ha3QsnhnGqQ5HFELZ1aD/ThdDc7d 8Lsrlh/eezJS/R27tQahsiFepdaVaH/wmZ7cRQg+59IJDTWU3YBOU5fXtQlEIGQWFwMCTFMNaN7V qnJNk22CDtucvc+081xdVHppCZbW2xHBjXWotM85yM48vCR85mLK4b19p71XZQvk/iXttmkQ3Cga Rr0BHdCXteGYO8A3ZNY9lO4L4fUorgtWv3GLIylBjobFS1J72HGrH4oVpjuDWtdYAVHGTEHZf9hB Z3KiKN9gg6meyHv8U3NyWfWTehd2Ds735VzZC1U0oqpbtWpU5xPKV+yXbfReBi9Fi1jUIxaS5BZu KGNZMN9QAZxjiRqf2xeUgnA3wySemkfWWspOqGmJch+RbNt+nhutxx9z3SxPGWX9f5NAEC7S8O08 ni4oPmkmM8V7AgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNq7LqqwDLiIJlF0 XG0D08DYj3rWMB8GA1UdIwQYMBaAFNq7LqqwDLiIJlF0XG0D08DYj3rWMA4GA1UdDwEB/wQEAwIB hjANBgkqhkiG9w0BAQUFAAOCAgEAMXjmx7XfuJRAyXHEqDXsRh3ChfMoWIawC/yOsjmPRFWrZIRc aanQmjg8+uUfNeVE44B5lGiku8SfPeE0zTBGi1QrlaXv9z+ZhP015s8xxtxqv6fXIwjhmF7DWgh2 qaavdy+3YL1ERmrvl/9zlcGO6JP7/TG37FcREUWbMPEaiDnBTzynANXH/KttgCJwpQzgXQQpAvvL oJHRfNbDflDVnVi+QTjruXU8FdmbyUqDWcDaU/0zuzYYm4UPFd3uLax2k7nZAY1IEKj79TiG8dsK xr2EoyNB3tZ3b4XUhRxQ4K5RirqNPnbiucon8l+f725ZDQbYKxek0nxru18UGkiPGkzns0ccjkxF KyDuSN/n3QmOGKjaQI2SJhFTYXNd673nxE0pN2HrrDktZy4W1vUAg4WhzH92xH3kt0tm7wNFYGm2 DFKWkoRepqO1pD4r2czYG0eq8kTaT/kD6PAUyz/zg97QwVTjt+gKN02LIFkDMBmhLMi9ER/frslK xfMnZmaGrGiR/9nmUxwPi1xpZQomyB40w11Re9epnAahNt3ViZS82eQtDF4JbAiXfKM9fJP/P6EU p8+1Xevb2xzEdt+Iub1FBZUbrvxGakyvSOPOrg/SfuvmbJxPgWp6ZKy7PtXny3YuxadIwVyQD8vI P/rmMuGNG2+k5o7Y+SlIis5z/iw= -----END CERTIFICATE----- GeoTrust Universal CA 2 ======================= -----BEGIN CERTIFICATE----- MIIFbDCCA1SgAwIBAgIBATANBgkqhkiG9w0BAQUFADBHMQswCQYDVQQGEwJVUzEWMBQGA1UEChMN R2VvVHJ1c3QgSW5jLjEgMB4GA1UEAxMXR2VvVHJ1c3QgVW5pdmVyc2FsIENBIDIwHhcNMDQwMzA0 MDUwMDAwWhcNMjkwMzA0MDUwMDAwWjBHMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3Qg SW5jLjEgMB4GA1UEAxMXR2VvVHJ1c3QgVW5pdmVyc2FsIENBIDIwggIiMA0GCSqGSIb3DQEBAQUA A4ICDwAwggIKAoICAQCzVFLByT7y2dyxUxpZKeexw0Uo5dfR7cXFS6GqdHtXr0om/Nj1XqduGdt0 DE81WzILAePb63p3NeqqWuDW6KFXlPCQo3RWlEQwAx5cTiuFJnSCegx2oG9NzkEtoBUGFF+3Qs17 j1hhNNwqCPkuwwGmIkQcTAeC5lvO0Ep8BNMZcyfwqph/Lq9O64ceJHdqXbboW0W63MOhBW9Wjo8Q JqVJwy7XQYci4E+GymC16qFjwAGXEHm9ADwSbSsVsaxLse4YuU6W3Nx2/zu+z18DwPw76L5GG//a QMJS9/7jOvdqdzXQ2o3rXhhqMcceujwbKNZrVMaqW9eiLBsZzKIC9ptZvTdrhrVtgrrY6slWvKk2 WP0+GfPtDCapkzj4T8FdIgbQl+rhrcZV4IErKIM6+vR7IVEAvlI4zs1meaj0gVbi0IMJR1FbUGrP 20gaXT73y/Zl92zxlfgCOzJWgjl6W70viRu/obTo/3+NjN8D8WBOWBFM66M/ECuDmgFz2ZRthAAn ZqzwcEAJQpKtT5MNYQlRJNiS1QuUYbKHsu3/mjX/hVTK7URDrBs8FmtISgocQIgfksILAAX/8sgC SqSqqcyZlpwvWOB94b67B9xfBHJcMTTD7F8t4D1kkCLm0ey4Lt1ZrtmhN79UNdxzMk+MBB4zsslG 8dhcyFVQyWi9qLo2CQIDAQABo2MwYTAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR281Xh+qQ2 +/CfXGJx7Tz0RzgQKzAfBgNVHSMEGDAWgBR281Xh+qQ2+/CfXGJx7Tz0RzgQKzAOBgNVHQ8BAf8E BAMCAYYwDQYJKoZIhvcNAQEFBQADggIBAGbBxiPz2eAubl/oz66wsCVNK/g7WJtAJDday6sWSf+z dXkzoS9tcBc0kf5nfo/sm+VegqlVHy/c1FEHEv6sFj4sNcZj/NwQ6w2jqtB8zNHQL1EuxBRa3ugZ 4T7GzKQp5y6EqgYweHZUcyiYWTjgAA1i00J9IZ+uPTqM1fp3DRgrFg5fNuH8KrUwJM/gYwx7WBr+ mbpCErGR9Hxo4sjoryzqyX6uuyo9DRXcNJW2GHSoag/HtPQTxORb7QrSpJdMKu0vbBKJPfEncKpq A1Ihn0CoZ1Dy81of398j9tx4TuaYT1U6U+Pv8vSfx3zYWK8pIpe44L2RLrB27FcRz+8pRPPphXpg Y+RdM4kX2TGq2tbzGDVyz4crL2MjhF2EjD9XoIj8mZEoJmmZ1I+XRL6O1UixpCgp8RW04eWe3fiP pm8m1wk8OhwRDqZsN/etRIcsKMfYdIKz0G9KV7s1KSegi+ghp4dkNl3M2Basx7InQJJVOCiNUW7d FGdTbHFcJoRNdVq2fmBWqU2t+5sel/MN2dKXVHfaPRK34B7vCAas+YWH6aLcr34YEoP9VhdBLtUp gn2Z9DH2canPLAEnpQW5qrJITirvn5NSUZU8UnOOVkwXQMAJKOSLakhT2+zNVVXxxvjpoixMptEm X36vWkzaH6byHCx+rgIW0lbQL1dTR+iS -----END CERTIFICATE----- America Online Root Certification Authority 1 ============================================= -----BEGIN CERTIFICATE----- MIIDpDCCAoygAwIBAgIBATANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEcMBoGA1UEChMT QW1lcmljYSBPbmxpbmUgSW5jLjE2MDQGA1UEAxMtQW1lcmljYSBPbmxpbmUgUm9vdCBDZXJ0aWZp Y2F0aW9uIEF1dGhvcml0eSAxMB4XDTAyMDUyODA2MDAwMFoXDTM3MTExOTIwNDMwMFowYzELMAkG A1UEBhMCVVMxHDAaBgNVBAoTE0FtZXJpY2EgT25saW5lIEluYy4xNjA0BgNVBAMTLUFtZXJpY2Eg T25saW5lIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgMTCCASIwDQYJKoZIhvcNAQEBBQAD ggEPADCCAQoCggEBAKgv6KRpBgNHw+kqmP8ZonCaxlCyfqXfaE0bfA+2l2h9LaaLl+lkhsmj76CG v2BlnEtUiMJIxUo5vxTjWVXlGbR0yLQFOVwWpeKVBeASrlmLojNoWBym1BW32J/X3HGrfpq/m44z DyL9Hy7nBzbvYjnF3cu6JRQj3gzGPTzOggjmZj7aUTsWOqMFf6Dch9Wc/HKpoH145LcxVR5lu9Rh sCFg7RAycsWSJR74kEoYeEfffjA3PlAb2xzTa5qGUwew76wGePiEmf4hjUyAtgyC9mZweRrTT6PP 8c9GsEsPPt2IYriMqQkoO3rHl+Ee5fSfwMCuJKDIodkP1nsmgmkyPacCAwEAAaNjMGEwDwYDVR0T AQH/BAUwAwEB/zAdBgNVHQ4EFgQUAK3Zo/Z59m50qX8zPYEX10zPM94wHwYDVR0jBBgwFoAUAK3Z o/Z59m50qX8zPYEX10zPM94wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBBQUAA4IBAQB8itEf GDeC4Liwo+1WlchiYZwFos3CYiZhzRAW18y0ZTTQEYqtqKkFZu90821fnZmv9ov761KyBZiibyrF VL0lvV+uyIbqRizBs73B6UlwGBaXCBOMIOAbLjpHyx7kADCVW/RFo8AasAFOq73AI25jP4BKxQft 3OJvx8Fi8eNy1gTIdGcL+oiroQHIb/AUr9KZzVGTfu0uOMe9zkZQPXLjeSWdm4grECDdpbgyn43g Kd8hdIaC2y+CMMbHNYaz+ZZfRtsMRf3zUMNvxsNIrUam4SdHCh0Om7bCd39j8uB9Gr784N/Xx6ds sPmuujz9dLQR6FgNgLzTqIA6me11zEZ7 -----END CERTIFICATE----- America Online Root Certification Authority 2 ============================================= -----BEGIN CERTIFICATE----- MIIFpDCCA4ygAwIBAgIBATANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEcMBoGA1UEChMT QW1lcmljYSBPbmxpbmUgSW5jLjE2MDQGA1UEAxMtQW1lcmljYSBPbmxpbmUgUm9vdCBDZXJ0aWZp Y2F0aW9uIEF1dGhvcml0eSAyMB4XDTAyMDUyODA2MDAwMFoXDTM3MDkyOTE0MDgwMFowYzELMAkG A1UEBhMCVVMxHDAaBgNVBAoTE0FtZXJpY2EgT25saW5lIEluYy4xNjA0BgNVBAMTLUFtZXJpY2Eg T25saW5lIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgMjCCAiIwDQYJKoZIhvcNAQEBBQAD ggIPADCCAgoCggIBAMxBRR3pPU0Q9oyxQcngXssNt79Hc9PwVU3dxgz6sWYFas14tNwC206B89en fHG8dWOgXeMHDEjsJcQDIPT/DjsS/5uN4cbVG7RtIuOx238hZK+GvFciKtZHgVdEglZTvYYUAQv8 f3SkWq7xuhG1m1hagLQ3eAkzfDJHA1zEpYNI9FdWboE2JxhP7JsowtS013wMPgwr38oE18aO6lhO qKSlGBxsRZijQdEt0sdtjRnxrXm3gT+9BoInLRBYBbV4Bbkv2wxrkJB+FFk4u5QkE+XRnRTf04JN RvCAOVIyD+OEsnpD8l7eXz8d3eOyG6ChKiMDbi4BFYdcpnV1x5dhvt6G3NRI270qv0pV2uh9UPu0 gBe4lL8BPeraunzgWGcXuVjgiIZGZ2ydEEdYMtA1fHkqkKJaEBEjNa0vzORKW6fIJ/KD3l67Xnfn 6KVuY8INXWHQjNJsWiEOyiijzirplcdIz5ZvHZIlyMbGwcEMBawmxNJ10uEqZ8A9W6Wa6897Gqid FEXlD6CaZd4vKL3Ob5Rmg0gp2OpljK+T2WSfVVcmv2/LNzGZo2C7HK2JNDJiuEMhBnIMoVxtRsX6 Kc8w3onccVvdtjc+31D1uAclJuW8tf48ArO3+L5DwYcRlJ4jbBeKuIonDFRH8KmzwICMoCfrHRnj B453cMor9H124HhnAgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFE1FwWg4u3Op aaEg5+31IqEjFNeeMB8GA1UdIwQYMBaAFE1FwWg4u3OpaaEg5+31IqEjFNeeMA4GA1UdDwEB/wQE AwIBhjANBgkqhkiG9w0BAQUFAAOCAgEAZ2sGuV9FOypLM7PmG2tZTiLMubekJcmnxPBUlgtk87FY T15R/LKXeydlwuXK5w0MJXti4/qftIe3RUavg6WXSIylvfEWK5t2LHo1YGwRgJfMqZJS5ivmae2p +DYtLHe/YUjRYwu5W1LtGLBDQiKmsXeu3mnFzcccobGlHBD7GL4acN3Bkku+KVqdPzW+5X1R+FXg JXUjhx5c3LqdsKyzadsXg8n33gy8CNyRnqjQ1xU3c6U1uPx+xURABsPr+CKAXEfOAuMRn0T//Zoy zH1kUQ7rVyZ2OuMeIjzCpjbdGe+n/BLzJsBZMYVMnNjP36TMzCmT/5RtdlwTCJfy7aULTd3oyWgO ZtMADjMSW7yV5TKQqLPGbIOtd+6Lfn6xqavT4fG2wLHqiMDn05DpKJKUe2h7lyoKZy2FAjgQ5ANh 1NolNscIWC2hp1GvMApJ9aZphwctREZ2jirlmjvXGKL8nDgQzMY70rUXOm/9riW99XJZZLF0Kjhf GEzfz3EEWjbUvy+ZnOjZurGV5gJLIaFb1cFPj65pbVPbAZO1XB4Y3WRayhgoPmMEEf0cjQAPuDff Z4qdZqkCapH/E8ovXYO8h5Ns3CRRFgQlZvqz2cK6Kb6aSDiCmfS/O0oxGfm/jiEzFMpPVF/7zvuP cX/9XhmgD0uRuMRUvAawRY8mkaKO/qk= -----END CERTIFICATE----- Visa eCommerce Root =================== -----BEGIN CERTIFICATE----- MIIDojCCAoqgAwIBAgIQE4Y1TR0/BvLB+WUF1ZAcYjANBgkqhkiG9w0BAQUFADBrMQswCQYDVQQG EwJVUzENMAsGA1UEChMEVklTQTEvMC0GA1UECxMmVmlzYSBJbnRlcm5hdGlvbmFsIFNlcnZpY2Ug QXNzb2NpYXRpb24xHDAaBgNVBAMTE1Zpc2EgZUNvbW1lcmNlIFJvb3QwHhcNMDIwNjI2MDIxODM2 WhcNMjIwNjI0MDAxNjEyWjBrMQswCQYDVQQGEwJVUzENMAsGA1UEChMEVklTQTEvMC0GA1UECxMm VmlzYSBJbnRlcm5hdGlvbmFsIFNlcnZpY2UgQXNzb2NpYXRpb24xHDAaBgNVBAMTE1Zpc2EgZUNv bW1lcmNlIFJvb3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvV95WHm6h2mCxlCfL F9sHP4CFT8icttD0b0/Pmdjh28JIXDqsOTPHH2qLJj0rNfVIsZHBAk4ElpF7sDPwsRROEW+1QK8b RaVK7362rPKgH1g/EkZgPI2h4H3PVz4zHvtH8aoVlwdVZqW1LS7YgFmypw23RuwhY/81q6UCzyr0 TP579ZRdhE2o8mCP2w4lPJ9zcc+U30rq299yOIzzlr3xF7zSujtFWsan9sYXiwGd/BmoKoMWuDpI /k4+oKsGGelT84ATB+0tvz8KPFUgOSwsAGl0lUq8ILKpeeUYiZGo3BxN77t+Nwtd/jmliFKMAGzs GHxBvfaLdXe6YJ2E5/4tAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEG MB0GA1UdDgQWBBQVOIMPPyw/cDMezUb+B4wg4NfDtzANBgkqhkiG9w0BAQUFAAOCAQEAX/FBfXxc CLkr4NWSR/pnXKUTwwMhmytMiUbPWU3J/qVAtmPN3XEolWcRzCSs00Rsca4BIGsDoo8Ytyk6feUW YFN4PMCvFYP3j1IzJL1kk5fui/fbGKhtcbP3LBfQdCVp9/5rPJS+TUtBjE7ic9DjkCJzQ83z7+pz zkWKsKZJ/0x9nXGIxHYdkFsd7v3M9+79YKWxehZx0RbQfBI8bGmX265fOZpwLwU8GUYEmSA20GBu YQa7FkKMcPcw++DbZqMAAb3mLNqRX6BGi01qnD093QVG/na/oAo85ADmJ7f/hC3euiInlhBx6yLt 398znM/jra6O1I7mT1GvFpLgXPYHDw== -----END CERTIFICATE----- Certum Root CA ============== -----BEGIN CERTIFICATE----- MIIDDDCCAfSgAwIBAgIDAQAgMA0GCSqGSIb3DQEBBQUAMD4xCzAJBgNVBAYTAlBMMRswGQYDVQQK ExJVbml6ZXRvIFNwLiB6IG8uby4xEjAQBgNVBAMTCUNlcnR1bSBDQTAeFw0wMjA2MTExMDQ2Mzla Fw0yNzA2MTExMDQ2MzlaMD4xCzAJBgNVBAYTAlBMMRswGQYDVQQKExJVbml6ZXRvIFNwLiB6IG8u by4xEjAQBgNVBAMTCUNlcnR1bSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAM6x wS7TT3zNJc4YPk/EjG+AanPIW1H4m9LcuwBcsaD8dQPugfCI7iNS6eYVM42sLQnFdvkrOYCJ5JdL kKWoePhzQ3ukYbDYWMzhbGZ+nPMJXlVjhNWo7/OxLjBos8Q82KxujZlakE403Daaj4GIULdtlkIJ 89eVgw1BS7Bqa/j8D35in2fE7SZfECYPCE/wpFcozo+47UX2bu4lXapuOb7kky/ZR6By6/qmW6/K Uz/iDsaWVhFu9+lmqSbYf5VT7QqFiLpPKaVCjF62/IUgAKpoC6EahQGcxEZjgoi2IrHu/qpGWX7P NSzVttpd90gzFFS269lvzs2I1qsb2pY7HVkCAwEAAaMTMBEwDwYDVR0TAQH/BAUwAwEB/zANBgkq hkiG9w0BAQUFAAOCAQEAuI3O7+cUus/usESSbLQ5PqKEbq24IXfS1HeCh+YgQYHu4vgRt2PRFze+ GXYkHAQaTOs9qmdvLdTN/mUxcMUbpgIKumB7bVjCmkn+YzILa+M6wKyrO7Do0wlRjBCDxjTgxSvg GrZgFCdsMneMvLJymM/NzD+5yCRCFNZX/OYmQ6kd5YCQzgNUKD73P9P4Te1qCjqTE5s7FCMTY5w/ 0YcneeVMUeMBrYVdGjux1XMQpNPyvG5k9VpWkKjHDkx0Dy5xO/fIR/RpbxXyEV6DHpx8Uq79AtoS qFlnGNu8cN2bsWntgM6JQEhqDjXKKWYVIZQs6GAqm4VKQPNriiTsBhYscw== -----END CERTIFICATE----- Comodo AAA Services root ======================== -----BEGIN CERTIFICATE----- MIIEMjCCAxqgAwIBAgIBATANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJHQjEbMBkGA1UECAwS R3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRowGAYDVQQKDBFDb21vZG8gQ0Eg TGltaXRlZDEhMB8GA1UEAwwYQUFBIENlcnRpZmljYXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAw MFoXDTI4MTIzMTIzNTk1OVowezELMAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hl c3RlcjEQMA4GA1UEBwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNV BAMMGEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC ggEBAL5AnfRu4ep2hxxNRUSOvkbIgwadwSr+GB+O5AL686tdUIoWMQuaBtDFcCLNSS1UY8y2bmhG C1Pqy0wkwLxyTurxFa70VJoSCsN6sjNg4tqJVfMiWPPe3M/vg4aijJRPn2jymJBGhCfHdr/jzDUs i14HZGWCwEiwqJH5YZ92IFCokcdmtet4YgNW8IoaE+oxox6gmf049vYnMlhvB/VruPsUK6+3qszW Y19zjNoFmag4qMsXeDZRrOme9Hg6jc8P2ULimAyrL58OAd7vn5lJ8S3frHRNG5i1R8XlKdH5kBjH Ypy+g8cmez6KJcfA3Z3mNWgQIJ2P2N7Sw4ScDV7oL8kCAwEAAaOBwDCBvTAdBgNVHQ4EFgQUoBEK Iz6W8Qfs4q8p74Klf9AwpLQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wewYDVR0f BHQwcjA4oDagNIYyaHR0cDovL2NybC5jb21vZG9jYS5jb20vQUFBQ2VydGlmaWNhdGVTZXJ2aWNl cy5jcmwwNqA0oDKGMGh0dHA6Ly9jcmwuY29tb2RvLm5ldC9BQUFDZXJ0aWZpY2F0ZVNlcnZpY2Vz LmNybDANBgkqhkiG9w0BAQUFAAOCAQEACFb8AvCb6P+k+tZ7xkSAzk/ExfYAWMymtrwUSWgEdujm 7l3sAg9g1o1QGE8mTgHj5rCl7r+8dFRBv/38ErjHT1r0iWAFf2C3BUrz9vHCv8S5dIa2LX1rzNLz Rt0vxuBqw8M0Ayx9lt1awg6nCpnBBYurDC/zXDrPbDdVCYfeU0BsWO/8tqtlbgT2G9w84FoVxp7Z 8VlIMCFlA2zs6SFz7JsDoeA3raAVGI/6ugLOpyypEBMs1OUIJqsil2D4kF501KKaU73yqWjgom7C 12yxow+ev+to51byrvLjKzg6CYG1a4XXvi3tPxq3smPi9WIsgtRqAEFQ8TmDn5XpNpaYbg== -----END CERTIFICATE----- Comodo Secure Services root =========================== -----BEGIN CERTIFICATE----- MIIEPzCCAyegAwIBAgIBATANBgkqhkiG9w0BAQUFADB+MQswCQYDVQQGEwJHQjEbMBkGA1UECAwS R3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRowGAYDVQQKDBFDb21vZG8gQ0Eg TGltaXRlZDEkMCIGA1UEAwwbU2VjdXJlIENlcnRpZmljYXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAw MDAwMFoXDTI4MTIzMTIzNTk1OVowfjELMAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFu Y2hlc3RlcjEQMA4GA1UEBwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxJDAi BgNVBAMMG1NlY3VyZSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEP ADCCAQoCggEBAMBxM4KK0HDrc4eCQNUd5MvJDkKQ+d40uaG6EfQlhfPMcm3ye5drswfxdySRXyWP 9nQ95IDC+DwN879A6vfIUtFyb+/Iq0G4bi4XKpVpDM3SHpR7LZQdqnXXs5jLrLxkU0C8j6ysNstc rbvd4JQX7NFc0L/vpZXJkMWwrPsbQ996CF23uPJAGysnnlDOXmWCiIxe004MeuoIkbY2qitC++rC oznl2yY4rYsK7hljxxwk3wN42ubqwUcaCwtGCd0C/N7Lh1/XMGNooa7cMqG6vv5Eq2i2pRcV/b3V p6ea5EQz6YiO/O1R65NxTq0B50SOqy3LqP4BSUjwwN3HaNiS/j0CAwEAAaOBxzCBxDAdBgNVHQ4E FgQUPNiTiMLAggnMAZkGkyDpnnAJY08wDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8w gYEGA1UdHwR6MHgwO6A5oDeGNWh0dHA6Ly9jcmwuY29tb2RvY2EuY29tL1NlY3VyZUNlcnRpZmlj YXRlU2VydmljZXMuY3JsMDmgN6A1hjNodHRwOi8vY3JsLmNvbW9kby5uZXQvU2VjdXJlQ2VydGlm aWNhdGVTZXJ2aWNlcy5jcmwwDQYJKoZIhvcNAQEFBQADggEBAIcBbSMdflsXfcFhMs+P5/OKlFlm 4J4oqF7Tt/Q05qo5spcWxYJvMqTpjOev/e/C6LlLqqP05tqNZSH7uoDrJiiFGv45jN5bBAS0VPmj Z55B+glSzAVIqMk/IQQezkhr/IXownuvf7fM+F86/TXGDe+X3EyrEeFryzHRbPtIgKvcnDe4IRRL DXE97IMzbtFuMhbsmMcWi1mmNKsFVy2T96oTy9IT4rcuO81rUBcJaD61JlfutuC23bkpgHl9j6Pw pCikFcSF9CfUa7/lXORlAnZUtOM3ZiTTGWHIUhDlizeauan5Hb/qmZJhlv8BzaFfDbxxvA6sCx1H RR3B7Hzs/Sk= -----END CERTIFICATE----- Comodo Trusted Services root ============================ -----BEGIN CERTIFICATE----- MIIEQzCCAyugAwIBAgIBATANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJHQjEbMBkGA1UECAwS R3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRowGAYDVQQKDBFDb21vZG8gQ0Eg TGltaXRlZDElMCMGA1UEAwwcVHJ1c3RlZCBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczAeFw0wNDAxMDEw MDAwMDBaFw0yODEyMzEyMzU5NTlaMH8xCzAJBgNVBAYTAkdCMRswGQYDVQQIDBJHcmVhdGVyIE1h bmNoZXN0ZXIxEDAOBgNVBAcMB1NhbGZvcmQxGjAYBgNVBAoMEUNvbW9kbyBDQSBMaW1pdGVkMSUw IwYDVQQDDBxUcnVzdGVkIENlcnRpZmljYXRlIFNlcnZpY2VzMIIBIjANBgkqhkiG9w0BAQEFAAOC AQ8AMIIBCgKCAQEA33FvNlhTWvI2VFeAxHQIIO0Yfyod5jWaHiWsnOWWfnJSoBVC21ndZHoa0Lh7 3TkVvFVIxO06AOoxEbrycXQaZ7jPM8yoMa+j49d/vzMtTGo87IvDktJTdyR0nAducPy9C1t2ul/y /9c3S0pgePfw+spwtOpZqqPOSC+pw7ILfhdyFgymBwwbOM/JYrc/oJOlh0Hyt3BAd9i+FHzjqMB6 juljatEPmsbS9Is6FARW1O24zG71++IsWL1/T2sr92AkWCTOJu80kTrV44HQsvAEAtdbtz6SrGsS ivnkBbA7kUlcsutT6vifR4buv5XAwAaf0lteERv0xwQ1KdJVXOTt6wIDAQABo4HJMIHGMB0GA1Ud DgQWBBTFe1i97doladL3WRaoszLAeydb9DAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB /zCBgwYDVR0fBHwwejA8oDqgOIY2aHR0cDovL2NybC5jb21vZG9jYS5jb20vVHJ1c3RlZENlcnRp ZmljYXRlU2VydmljZXMuY3JsMDqgOKA2hjRodHRwOi8vY3JsLmNvbW9kby5uZXQvVHJ1c3RlZENl cnRpZmljYXRlU2VydmljZXMuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQDIk4E7ibSvuIQSTI3S8Ntw uleGFTQQuS9/HrCoiWChisJ3DFBKmwCL2Iv0QeLQg4pKHBQGsKNoBXAxMKdTmw7pSqBYaWcOrp32 pSxBvzwGa+RZzG0Q8ZZvH9/0BAKkn0U+yNj6NkZEUD+Cl5EfKNsYEYwq5GWDVxISjBc/lDb+XbDA BHcTuPQV1T84zJQ6VdCsmPW6AF/ghhmBeC8owH7TzEIK9a5QoNE+xqFx7D+gIIxmOom0jtTYsU0l R+4viMi14QVFwL4Ucd56/Y57fU0IlqUSc/AtyjcndBInTMu2l+nZrghtWjlA3QVHdWpaIbOjGM9O 9y5Xt5hwXsjEeLBi -----END CERTIFICATE----- QuoVadis Root CA ================ -----BEGIN CERTIFICATE----- MIIF0DCCBLigAwIBAgIEOrZQizANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJCTTEZMBcGA1UE ChMQUXVvVmFkaXMgTGltaXRlZDElMCMGA1UECxMcUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0 eTEuMCwGA1UEAxMlUXVvVmFkaXMgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wMTAz MTkxODMzMzNaFw0yMTAzMTcxODMzMzNaMH8xCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRp cyBMaW1pdGVkMSUwIwYDVQQLExxSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MS4wLAYDVQQD EyVRdW9WYWRpcyBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEF AAOCAQ8AMIIBCgKCAQEAv2G1lVO6V/z68mcLOhrfEYBklbTRvM16z/Ypli4kVEAkOPcahdxYTMuk J0KX0J+DisPkBgNbAKVRHnAEdOLB1Dqr1607BxgFjv2DrOpm2RgbaIr1VxqYuvXtdj182d6UajtL F8HVj71lODqV0D1VNk7feVcxKh7YWWVJWCCYfqtffp/p1k3sg3Spx2zY7ilKhSoGFPlU5tPaZQeL YzcS19Dsw3sgQUSj7cugF+FxZc4dZjH3dgEZyH0DWLaVSR2mEiboxgx24ONmy+pdpibu5cxfvWen AScOospUxbF6lR1xHkopigPcakXBpBlebzbNw6Kwt/5cOOJSvPhEQ+aQuwIDAQABo4ICUjCCAk4w PQYIKwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwczovL29jc3AucXVvdmFkaXNvZmZzaG9y ZS5jb20wDwYDVR0TAQH/BAUwAwEB/zCCARoGA1UdIASCAREwggENMIIBCQYJKwYBBAG+WAABMIH7 MIHUBggrBgEFBQcCAjCBxxqBxFJlbGlhbmNlIG9uIHRoZSBRdW9WYWRpcyBSb290IENlcnRpZmlj YXRlIGJ5IGFueSBwYXJ0eSBhc3N1bWVzIGFjY2VwdGFuY2Ugb2YgdGhlIHRoZW4gYXBwbGljYWJs ZSBzdGFuZGFyZCB0ZXJtcyBhbmQgY29uZGl0aW9ucyBvZiB1c2UsIGNlcnRpZmljYXRpb24gcHJh Y3RpY2VzLCBhbmQgdGhlIFF1b1ZhZGlzIENlcnRpZmljYXRlIFBvbGljeS4wIgYIKwYBBQUHAgEW Fmh0dHA6Ly93d3cucXVvdmFkaXMuYm0wHQYDVR0OBBYEFItLbe3TKbkGGew5Oanwl4Rqy+/fMIGu BgNVHSMEgaYwgaOAFItLbe3TKbkGGew5Oanwl4Rqy+/foYGEpIGBMH8xCzAJBgNVBAYTAkJNMRkw FwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMSUwIwYDVQQLExxSb290IENlcnRpZmljYXRpb24gQXV0 aG9yaXR5MS4wLAYDVQQDEyVRdW9WYWRpcyBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggQ6 tlCLMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAitQUtf70mpKnGdSkfnIYj9lo fFIk3WdvOXrEql494liwTXCYhGHoG+NpGA7O+0dQoE7/8CQfvbLO9Sf87C9TqnN7Az10buYWnuul LsS/VidQK2K6vkscPFVcQR0kvoIgR13VRH56FmjffU1RcHhXHTMe/QKZnAzNCgVPx7uOpHX6Sm2x gI4JVrmcGmD+XcHXetwReNDWXcG31a0ymQM6isxUJTkxgXsTIlG6Rmyhu576BGxJJnSP0nPrzDCi 5upZIof4l/UO/erMkqQWxFIY6iHOsfHmhIHluqmGKPJDWl0Snawe2ajlCmqnf6CHKc/yiU3U7MXi 5nrQNiOKSnQ2+Q== -----END CERTIFICATE----- QuoVadis Root CA 2 ================== -----BEGIN CERTIFICATE----- MIIFtzCCA5+gAwIBAgICBQkwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0xGTAXBgNVBAoT EFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJvb3QgQ0EgMjAeFw0wNjExMjQx ODI3MDBaFw0zMTExMjQxODIzMzNaMEUxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM aW1pdGVkMRswGQYDVQQDExJRdW9WYWRpcyBSb290IENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4IC DwAwggIKAoICAQCaGMpLlA0ALa8DKYrwD4HIrkwZhR0In6spRIXzL4GtMh6QRr+jhiYaHv5+HBg6 XJxgFyo6dIMzMH1hVBHL7avg5tKifvVrbxi3Cgst/ek+7wrGsxDp3MJGF/hd/aTa/55JWpzmM+Yk lvc/ulsrHHo1wtZn/qtmUIttKGAr79dgw8eTvI02kfN/+NsRE8Scd3bBrrcCaoF6qUWD4gXmuVbB lDePSHFjIuwXZQeVikvfj8ZaCuWw419eaxGrDPmF60Tp+ARz8un+XJiM9XOva7R+zdRcAitMOeGy lZUtQofX1bOQQ7dsE/He3fbE+Ik/0XX1ksOR1YqI0JDs3G3eicJlcZaLDQP9nL9bFqyS2+r+eXyt 66/3FsvbzSUr5R/7mp/iUcw6UwxI5g69ybR2BlLmEROFcmMDBOAENisgGQLodKcftslWZvB1Jdxn wQ5hYIizPtGo/KPaHbDRsSNU30R2be1B2MGyIrZTHN81Hdyhdyox5C315eXbyOD/5YDXC2Og/zOh D7osFRXql7PSorW+8oyWHhqPHWykYTe5hnMz15eWniN9gqRMgeKh0bpnX5UHoycR7hYQe7xFSkyy BNKr79X9DFHOUGoIMfmR2gyPZFwDwzqLID9ujWc9Otb+fVuIyV77zGHcizN300QyNQliBJIWENie J0f7OyHj+OsdWwIDAQABo4GwMIGtMA8GA1UdEwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMB0GA1Ud DgQWBBQahGK8SEwzJQTU7tD2A8QZRtGUazBuBgNVHSMEZzBlgBQahGK8SEwzJQTU7tD2A8QZRtGU a6FJpEcwRTELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMT ElF1b1ZhZGlzIFJvb3QgQ0EgMoICBQkwDQYJKoZIhvcNAQEFBQADggIBAD4KFk2fBluornFdLwUv Z+YTRYPENvbzwCYMDbVHZF34tHLJRqUDGCdViXh9duqWNIAXINzng/iN/Ae42l9NLmeyhP3ZRPx3 UIHmfLTJDQtyU/h2BwdBR5YM++CCJpNVjP4iH2BlfF/nJrP3MpCYUNQ3cVX2kiF495V5+vgtJodm VjB3pjd4M1IQWK4/YY7yarHvGH5KWWPKjaJW1acvvFYfzznB4vsKqBUsfU16Y8Zsl0Q80m/DShcK +JDSV6IZUaUtl0HaB0+pUNqQjZRG4T7wlP0QADj1O+hA4bRuVhogzG9Yje0uRY/W6ZM/57Es3zrW IozchLsib9D45MY56QSIPMO661V6bYCZJPVsAfv4l7CUW+v90m/xd2gNNWQjrLhVoQPRTUIZ3Ph1 WVaj+ahJefivDrkRoHy3au000LYmYjgahwz46P0u05B/B5EqHdZ+XIWDmbA4CD/pXvk1B+TJYm5X f6dQlfe6yJvmjqIBxdZmv3lh8zwc4bmCXF2gw+nYSL0ZohEUGW6yhhtoPkg3Goi3XZZenMfvJ2II 4pEZXNLxId26F0KCl3GBUzGpn/Z9Yr9y4aOTHcyKJloJONDO1w2AFrR4pTqHTI2KpdVGl/IsELm8 VCLAAVBpQ570su9t+Oza8eOx79+Rj1QqCyXBJhnEUhAFZdWCEOrCMc0u -----END CERTIFICATE----- QuoVadis Root CA 3 ================== -----BEGIN CERTIFICATE----- MIIGnTCCBIWgAwIBAgICBcYwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0xGTAXBgNVBAoT EFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJvb3QgQ0EgMzAeFw0wNjExMjQx OTExMjNaFw0zMTExMjQxOTA2NDRaMEUxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM aW1pdGVkMRswGQYDVQQDExJRdW9WYWRpcyBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4IC DwAwggIKAoICAQDMV0IWVJzmmNPTTe7+7cefQzlKZbPoFog02w1ZkXTPkrgEQK0CSzGrvI2RaNgg DhoB4hp7Thdd4oq3P5kazethq8Jlph+3t723j/z9cI8LoGe+AaJZz3HmDyl2/7FWeUUrH556VOij KTVopAFPD6QuN+8bv+OPEKhyq1hX51SGyMnzW9os2l2ObjyjPtr7guXd8lyyBTNvijbO0BNO/79K DDRMpsMhvVAEVeuxu537RR5kFd5VAYwCdrXLoT9CabwvvWhDFlaJKjdhkf2mrk7AyxRllDdLkgbv BNDInIjbC3uBr7E9KsRlOni27tyAsdLTmZw67mtaa7ONt9XOnMK+pUsvFrGeaDsGb659n/je7Mwp p5ijJUMv7/FfJuGITfhebtfZFG4ZM2mnO4SJk8RTVROhUXhA+LjJou57ulJCg54U7QVSWllWp5f8 nT8KKdjcT5EOE7zelaTfi5m+rJsziO+1ga8bxiJTyPbH7pcUsMV8eFLI8M5ud2CEpukqdiDtWAEX MJPpGovgc2PZapKUSU60rUqFxKMiMPwJ7Wgic6aIDFUhWMXhOp8q3crhkODZc6tsgLjoC2SToJyM Gf+z0gzskSaHirOi4XCPLArlzW1oUevaPwV/izLmE1xr/l9A4iLItLRkT9a6fUg+qGkM17uGcclz uD87nSVL2v9A6wIDAQABo4IBlTCCAZEwDwYDVR0TAQH/BAUwAwEB/zCB4QYDVR0gBIHZMIHWMIHT BgkrBgEEAb5YAAMwgcUwgZMGCCsGAQUFBwICMIGGGoGDQW55IHVzZSBvZiB0aGlzIENlcnRpZmlj YXRlIGNvbnN0aXR1dGVzIGFjY2VwdGFuY2Ugb2YgdGhlIFF1b1ZhZGlzIFJvb3QgQ0EgMyBDZXJ0 aWZpY2F0ZSBQb2xpY3kgLyBDZXJ0aWZpY2F0aW9uIFByYWN0aWNlIFN0YXRlbWVudC4wLQYIKwYB BQUHAgEWIWh0dHA6Ly93d3cucXVvdmFkaXNnbG9iYWwuY29tL2NwczALBgNVHQ8EBAMCAQYwHQYD VR0OBBYEFPLAE+CCQz777i9nMpY1XNu4ywLQMG4GA1UdIwRnMGWAFPLAE+CCQz777i9nMpY1XNu4 ywLQoUmkRzBFMQswCQYDVQQGEwJCTTEZMBcGA1UEChMQUXVvVmFkaXMgTGltaXRlZDEbMBkGA1UE AxMSUXVvVmFkaXMgUm9vdCBDQSAzggIFxjANBgkqhkiG9w0BAQUFAAOCAgEAT62gLEz6wPJv92ZV qyM07ucp2sNbtrCD2dDQ4iH782CnO11gUyeim/YIIirnv6By5ZwkajGxkHon24QRiSemd1o417+s hvzuXYO8BsbRd2sPbSQvS3pspweWyuOEn62Iix2rFo1bZhfZFvSLgNLd+LJ2w/w4E6oM3kJpK27z POuAJ9v1pkQNn1pVWQvVDVJIxa6f8i+AxeoyUDUSly7B4f/xI4hROJ/yZlZ25w9Rl6VSDE1JUZU2 Pb+iSwwQHYaZTKrzchGT5Or2m9qoXadNt54CrnMAyNojA+j56hl0YgCUyyIgvpSnWbWCar6ZeXqp 8kokUvd0/bpO5qgdAm6xDYBEwa7TIzdfu4V8K5Iu6H6li92Z4b8nby1dqnuH/grdS/yO9SbkbnBC bjPsMZ57k8HkyWkaPcBrTiJt7qtYTcbQQcEr6k8Sh17rRdhs9ZgC06DYVYoGmRmioHfRMJ6szHXu g/WwYjnPbFfiTNKRCw51KBuav/0aQ/HKd/s7j2G4aSgWQgRecCocIdiP4b0jWy10QJLZYxkNc91p vGJHvOB0K7Lrfb5BG7XARsWhIstfTsEokt4YutUqKLsRixeTmJlglFwjz1onl14LBQaTNx47aTbr qZ5hHY8y2o4M1nQ+ewkk2gF3R8Q7zTSMmfXK4SVhM7JZG+Ju1zdXtg2pEto= -----END CERTIFICATE----- Security Communication Root CA ============================== -----BEGIN CERTIFICATE----- MIIDWjCCAkKgAwIBAgIBADANBgkqhkiG9w0BAQUFADBQMQswCQYDVQQGEwJKUDEYMBYGA1UEChMP U0VDT00gVHJ1c3QubmV0MScwJQYDVQQLEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTEw HhcNMDMwOTMwMDQyMDQ5WhcNMjMwOTMwMDQyMDQ5WjBQMQswCQYDVQQGEwJKUDEYMBYGA1UEChMP U0VDT00gVHJ1c3QubmV0MScwJQYDVQQLEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTEw ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCzs/5/022x7xZ8V6UMbXaKL0u/ZPtM7orw 8yl89f/uKuDp6bpbZCKamm8sOiZpUQWZJtzVHGpxxpp9Hp3dfGzGjGdnSj74cbAZJ6kJDKaVv0uM DPpVmDvY6CKhS3E4eayXkmmziX7qIWgGmBSWh9JhNrxtJ1aeV+7AwFb9Ms+k2Y7CI9eNqPPYJayX 5HA49LY6tJ07lyZDo6G8SVlyTCMwhwFY9k6+HGhWZq/NQV3Is00qVUarH9oe4kA92819uZKAnDfd DJZkndwi92SL32HeFZRSFaB9UslLqCHJxrHty8OVYNEP8Ktw+N/LTX7s1vqr2b1/VPKl6Xn62dZ2 JChzAgMBAAGjPzA9MB0GA1UdDgQWBBSgc0mZaNyFW2XjmygvV5+9M7wHSDALBgNVHQ8EBAMCAQYw DwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAaECpqLvkT115swW1F7NgE+vGkl3g 0dNq/vu+m22/xwVtWSDEHPC32oRYAmP6SBbvT6UL90qY8j+eG61Ha2POCEfrUj94nK9NrvjVT8+a mCoQQTlSxN3Zmw7vkwGusi7KaEIkQmywszo+zenaSMQVy+n5Bw+SUEmK3TGXX8npN6o7WWWXlDLJ s58+OmJYxUmtYg5xpTKqL8aJdkNAExNnPaJUJRDL8Try2frbSVa7pv6nQTXD4IhhyYjH3zYQIphZ 6rBK+1YWc26sTfcioU+tHXotRSflMMFe8toTyyVCUZVHA4xsIcx0Qu1T/zOLjw9XARYvz6buyXAi FL39vmwLAw== -----END CERTIFICATE----- Sonera Class 2 Root CA ====================== -----BEGIN CERTIFICATE----- MIIDIDCCAgigAwIBAgIBHTANBgkqhkiG9w0BAQUFADA5MQswCQYDVQQGEwJGSTEPMA0GA1UEChMG U29uZXJhMRkwFwYDVQQDExBTb25lcmEgQ2xhc3MyIENBMB4XDTAxMDQwNjA3Mjk0MFoXDTIxMDQw NjA3Mjk0MFowOTELMAkGA1UEBhMCRkkxDzANBgNVBAoTBlNvbmVyYTEZMBcGA1UEAxMQU29uZXJh IENsYXNzMiBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJAXSjWdyvANlsdE+hY3 /Ei9vX+ALTU74W+oZ6m/AxxNjG8yR9VBaKQTBME1DJqEQ/xcHf+Js+gXGM2RX/uJ4+q/Tl18GybT dXnt5oTjV+WtKcT0OijnpXuENmmz/V52vaMtmdOQTiMofRhj8VQ7Jp12W5dCsv+u8E7s3TmVToMG f+dJQMjFAbJUWmYdPfz56TwKnoG4cPABi+QjVHzIrviQHgCWctRUz2EjvOr7nQKV0ba5cTppCD8P tOFCx4j1P5iop7oc4HFx71hXgVB6XGt0Rg6DA5jDjqhu8nYybieDwnPz3BjotJPqdURrBGAgcVeH nfO+oJAjPYok4doh28MCAwEAAaMzMDEwDwYDVR0TAQH/BAUwAwEB/zARBgNVHQ4ECgQISqCqWITT XjwwCwYDVR0PBAQDAgEGMA0GCSqGSIb3DQEBBQUAA4IBAQBazof5FnIVV0sd2ZvnoiYw7JNn39Yt 0jSv9zilzqsWuasvfDXLrNAPtEwr/IDva4yRXzZ299uzGxnq9LIR/WFxRL8oszodv7ND6J+/3DEI cbCdjdY0RzKQxmUk96BKfARzjzlvF4xytb1LyHr4e4PDKE6cCepnP7JnBBvDFNr450kkkdAdavph Oe9r5yF1BgfYErQhIHBCcYHaPJo2vqZbDWpsmh+Re/n570K6Tk6ezAyNlNzZRZxe7EJQY670XcSx EtzKO6gunRRaBXW37Ndj4ro1tgQIkejanZz2ZrUYrAqmVCY0M9IbwdR/GjqOC6oybtv8TyWf2TLH llpwrN9M -----END CERTIFICATE----- Staat der Nederlanden Root CA ============================= -----BEGIN CERTIFICATE----- MIIDujCCAqKgAwIBAgIEAJiWijANBgkqhkiG9w0BAQUFADBVMQswCQYDVQQGEwJOTDEeMBwGA1UE ChMVU3RhYXQgZGVyIE5lZGVybGFuZGVuMSYwJAYDVQQDEx1TdGFhdCBkZXIgTmVkZXJsYW5kZW4g Um9vdCBDQTAeFw0wMjEyMTcwOTIzNDlaFw0xNTEyMTYwOTE1MzhaMFUxCzAJBgNVBAYTAk5MMR4w HAYDVQQKExVTdGFhdCBkZXIgTmVkZXJsYW5kZW4xJjAkBgNVBAMTHVN0YWF0IGRlciBOZWRlcmxh bmRlbiBSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmNK1URF6gaYUmHFt vsznExvWJw56s2oYHLZhWtVhCb/ekBPHZ+7d89rFDBKeNVU+LCeIQGv33N0iYfXCxw719tV2U02P jLwYdjeFnejKScfST5gTCaI+Ioicf9byEGW07l8Y1Rfj+MX94p2i71MOhXeiD+EwR+4A5zN9RGca C1Hoi6CeUJhoNFIfLm0B8mBF8jHrqTFoKbt6QZ7GGX+UtFE5A3+y3qcym7RHjm+0Sq7lr7HcsBth vJly3uSJt3omXdozSVtSnA71iq3DuD3oBmrC1SoLbHuEvVYFy4ZlkuxEK7COudxwC0barbxjiDn6 22r+I/q85Ej0ZytqERAhSQIDAQABo4GRMIGOMAwGA1UdEwQFMAMBAf8wTwYDVR0gBEgwRjBEBgRV HSAAMDwwOgYIKwYBBQUHAgEWLmh0dHA6Ly93d3cucGtpb3ZlcmhlaWQubmwvcG9saWNpZXMvcm9v dC1wb2xpY3kwDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBSofeu8Y6R0E3QA7Jbg0zTBLL9s+DAN BgkqhkiG9w0BAQUFAAOCAQEABYSHVXQ2YcG70dTGFagTtJ+k/rvuFbQvBgwp8qiSpGEN/KtcCFtR EytNwiphyPgJWPwtArI5fZlmgb9uXJVFIGzmeafR2Bwp/MIgJ1HI8XxdNGdphREwxgDS1/PTfLbw MVcoEoJz6TMvplW0C5GUR5z6u3pCMuiufi3IvKwUv9kP2Vv8wfl6leF9fpb8cbDCTMjfRTTJzg3y nGQI0DvDKcWy7ZAEwbEpkcUwb8GpcjPM/l0WFywRaed+/sWDCN+83CI6LiBpIzlWYGeQiy52OfsR iJf2fL1LuCAWZwWN4jvBcj+UlTfHXbme2JOhF4//DGYVwSR8MnwDHTuhWEUykw== -----END CERTIFICATE----- TDC Internet Root CA ==================== -----BEGIN CERTIFICATE----- MIIEKzCCAxOgAwIBAgIEOsylTDANBgkqhkiG9w0BAQUFADBDMQswCQYDVQQGEwJESzEVMBMGA1UE ChMMVERDIEludGVybmV0MR0wGwYDVQQLExRUREMgSW50ZXJuZXQgUm9vdCBDQTAeFw0wMTA0MDUx NjMzMTdaFw0yMTA0MDUxNzAzMTdaMEMxCzAJBgNVBAYTAkRLMRUwEwYDVQQKEwxUREMgSW50ZXJu ZXQxHTAbBgNVBAsTFFREQyBJbnRlcm5ldCBSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A MIIBCgKCAQEAxLhAvJHVYx/XmaCLDEAedLdInUaMArLgJF/wGROnN4NrXceO+YQwzho7+vvOi20j xsNuZp+Jpd/gQlBn+h9sHvTQBda/ytZO5GhgbEaqHF1j4QeGDmUApy6mcca8uYGoOn0a0vnRrEvL znWv3Hv6gXPU/Lq9QYjUdLP5Xjg6PEOo0pVOd20TDJ2PeAG3WiAfAzc14izbSysseLlJ28TQx5yc 5IogCSEWVmb/Bexb4/DPqyQkXsN/cHoSxNK1EKC2IeGNeGlVRGn1ypYcNIUXJXfi9i8nmHj9eQY6 otZaQ8H/7AQ77hPv01ha/5Lr7K7a8jcDR0G2l8ktCkEiu7vmpwIDAQABo4IBJTCCASEwEQYJYIZI AYb4QgEBBAQDAgAHMGUGA1UdHwReMFwwWqBYoFakVDBSMQswCQYDVQQGEwJESzEVMBMGA1UEChMM VERDIEludGVybmV0MR0wGwYDVQQLExRUREMgSW50ZXJuZXQgUm9vdCBDQTENMAsGA1UEAxMEQ1JM MTArBgNVHRAEJDAigA8yMDAxMDQwNTE2MzMxN1qBDzIwMjEwNDA1MTcwMzE3WjALBgNVHQ8EBAMC AQYwHwYDVR0jBBgwFoAUbGQBx/2FbazI2p5QCIUItTxWqFAwHQYDVR0OBBYEFGxkAcf9hW2syNqe UAiFCLU8VqhQMAwGA1UdEwQFMAMBAf8wHQYJKoZIhvZ9B0EABBAwDhsIVjUuMDo0LjADAgSQMA0G CSqGSIb3DQEBBQUAA4IBAQBOQ8zR3R0QGwZ/t6T609lN+yOfI1Rb5osvBCiLtSdtiaHsmGnc540m gwV5dOy0uaOXwTUA/RXaOYE6lTGQ3pfphqiZdwzlWqCE/xIWrG64jcN7ksKsLtB9KOy282A4aW8+ 2ARVPp7MVdK6/rtHBNcK2RYKNCn1WBPVT8+PVkuzHu7TmHnaCB4Mb7j4Fifvwm899qNLPg7kbWzb O0ESm70NRyN/PErQr8Cv9u8btRXE64PECV90i9kR+8JWsTz4cMo0jUNAE4z9mQNUecYu6oah9jrU Cbz0vGbMPVjQV0kK7iXiQe4T+Zs4NNEA9X7nlB38aQNiuJkFBT1reBK9sG9l -----END CERTIFICATE----- UTN DATACorp SGC Root CA ======================== -----BEGIN CERTIFICATE----- MIIEXjCCA0agAwIBAgIQRL4Mi1AAIbQR0ypoBqmtaTANBgkqhkiG9w0BAQUFADCBkzELMAkGA1UE BhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2UgQ2l0eTEeMBwGA1UEChMVVGhl IFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xGzAZ BgNVBAMTElVUTiAtIERBVEFDb3JwIFNHQzAeFw05OTA2MjQxODU3MjFaFw0xOTA2MjQxOTA2MzBa MIGTMQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQgTGFrZSBDaXR5MR4w HAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNVBAsTGGh0dHA6Ly93d3cudXNlcnRy dXN0LmNvbTEbMBkGA1UEAxMSVVROIC0gREFUQUNvcnAgU0dDMIIBIjANBgkqhkiG9w0BAQEFAAOC AQ8AMIIBCgKCAQEA3+5YEKIrblXEjr8uRgnn4AgPLit6E5Qbvfa2gI5lBZMAHryv4g+OGQ0SR+ys raP6LnD43m77VkIVni5c7yPeIbkFdicZD0/Ww5y0vpQZY/KmEQrrU0icvvIpOxboGqBMpsn0GFlo wHDyUwDAXlCCpVZvNvlK4ESGoE1O1kduSUrLZ9emxAW5jh70/P/N5zbgnAVssjMiFdC04MwXwLLA 9P4yPykqlXvY8qdOD1R8oQ2AswkDwf9c3V6aPryuvEeKaq5xyh+xKrhfQgUL7EYw0XILyulWbfXv 33i+Ybqypa4ETLyorGkVl73v67SMvzX41MPRKA5cOp9wGDMgd8SirwIDAQABo4GrMIGoMAsGA1Ud DwQEAwIBxjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRTMtGzz3/64PGgXYVOktKeRR20TzA9 BgNVHR8ENjA0MDKgMKAuhixodHRwOi8vY3JsLnVzZXJ0cnVzdC5jb20vVVROLURBVEFDb3JwU0dD LmNybDAqBgNVHSUEIzAhBggrBgEFBQcDAQYKKwYBBAGCNwoDAwYJYIZIAYb4QgQBMA0GCSqGSIb3 DQEBBQUAA4IBAQAnNZcAiosovcYzMB4p/OL31ZjUQLtgyr+rFywJNn9Q+kHcrpY6CiM+iVnJowft Gzet/Hy+UUla3joKVAgWRcKZsYfNjGjgaQPpxE6YsjuMFrMOoAyYUJuTqXAJyCyjj98C5OBxOvG0 I3KgqgHf35g+FFCgMSa9KOlaMCZ1+XtgHI3zzVAmbQQnmt/VDUVHKWss5nbZqSl9Mt3JNjy9rjXx EZ4du5A/EkdOjtd+D2JzHVImOBwYSf0wdJrE5SIv2MCN7ZF6TACPcn9d2t0bi0Vr591pl6jFVkwP DPafepE39peC4N1xaf92P2BNPM/3mfnGV/TJVTl4uix5yaaIK/QI -----END CERTIFICATE----- UTN USERFirst Hardware Root CA ============================== -----BEGIN CERTIFICATE----- MIIEdDCCA1ygAwIBAgIQRL4Mi1AAJLQR0zYq/mUK/TANBgkqhkiG9w0BAQUFADCBlzELMAkGA1UE BhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2UgQ2l0eTEeMBwGA1UEChMVVGhl IFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHzAd BgNVBAMTFlVUTi1VU0VSRmlyc3QtSGFyZHdhcmUwHhcNOTkwNzA5MTgxMDQyWhcNMTkwNzA5MTgx OTIyWjCBlzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2UgQ2l0 eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8vd3d3LnVz ZXJ0cnVzdC5jb20xHzAdBgNVBAMTFlVUTi1VU0VSRmlyc3QtSGFyZHdhcmUwggEiMA0GCSqGSIb3 DQEBAQUAA4IBDwAwggEKAoIBAQCx98M4P7Sof885glFn0G2f0v9Y8+efK+wNiVSZuTiZFvfgIXlI wrthdBKWHTxqctU8EGc6Oe0rE81m65UJM6Rsl7HoxuzBdXmcRl6Nq9Bq/bkqVRcQVLMZ8Jr28bFd tqdt++BxF2uiiPsA3/4aMXcMmgF6sTLjKwEHOG7DpV4jvEWbe1DByTCP2+UretNb+zNAHqDVmBe8 i4fDidNdoI6yqqr2jmmIBsX6iSHzCJ1pLgkzmykNRg+MzEk0sGlRvfkGzWitZky8PqxhvQqIDsjf Pe58BEydCl5rkdbux+0ojatNh4lz0G6k0B4WixThdkQDf2Os5M1JnMWS9KsyoUhbAgMBAAGjgbkw gbYwCwYDVR0PBAQDAgHGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFKFyXyYbKJhDlV0HN9WF lp1L0sNFMEQGA1UdHwQ9MDswOaA3oDWGM2h0dHA6Ly9jcmwudXNlcnRydXN0LmNvbS9VVE4tVVNF UkZpcnN0LUhhcmR3YXJlLmNybDAxBgNVHSUEKjAoBggrBgEFBQcDAQYIKwYBBQUHAwUGCCsGAQUF BwMGBggrBgEFBQcDBzANBgkqhkiG9w0BAQUFAAOCAQEARxkP3nTGmZev/K0oXnWO6y1n7k57K9cM //bey1WiCuFMVGWTYGufEpytXoMs61quwOQt9ABjHbjAbPLPSbtNk28GpgoiskliCE7/yMgUsogW XecB5BKV5UU0s4tpvc+0hY91UZ59Ojg6FEgSxvunOxqNDYJAB+gECJChicsZUN/KHAG8HQQZexB2 lzvukJDKxA4fFm517zP4029bHpbj4HR3dHuKom4t3XbWOTCC8KucUvIqx69JXn7HaOWCgchqJ/kn iCrVWFCVH/A7HFe7fRQ5YiuayZSSKqMiDP+JJn1fIytH1xUdqWqeUQ0qUZ6B+dQ7XnASfxAynB67 nfhmqA== -----END CERTIFICATE----- Camerfirma Chambers of Commerce Root ==================================== -----BEGIN CERTIFICATE----- MIIEvTCCA6WgAwIBAgIBADANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJFVTEnMCUGA1UEChMe QUMgQ2FtZXJmaXJtYSBTQSBDSUYgQTgyNzQzMjg3MSMwIQYDVQQLExpodHRwOi8vd3d3LmNoYW1i ZXJzaWduLm9yZzEiMCAGA1UEAxMZQ2hhbWJlcnMgb2YgQ29tbWVyY2UgUm9vdDAeFw0wMzA5MzAx NjEzNDNaFw0zNzA5MzAxNjEzNDRaMH8xCzAJBgNVBAYTAkVVMScwJQYDVQQKEx5BQyBDYW1lcmZp cm1hIFNBIENJRiBBODI3NDMyODcxIzAhBgNVBAsTGmh0dHA6Ly93d3cuY2hhbWJlcnNpZ24ub3Jn MSIwIAYDVQQDExlDaGFtYmVycyBvZiBDb21tZXJjZSBSb290MIIBIDANBgkqhkiG9w0BAQEFAAOC AQ0AMIIBCAKCAQEAtzZV5aVdGDDg2olUkfzIx1L4L1DZ77F1c2VHfRtbunXF/KGIJPov7coISjlU xFF6tdpg6jg8gbLL8bvZkSM/SAFwdakFKq0fcfPJVD0dBmpAPrMMhe5cG3nCYsS4No41XQEMIwRH NaqbYE6gZj3LJgqcQKH0XZi/caulAGgq7YN6D6IUtdQis4CwPAxaUWktWBiP7Zme8a7ileb2R6jW DA+wWFjbw2Y3npuRVDM30pQcakjJyfKl2qUMI/cjDpwyVV5xnIQFUZot/eZOKjRa3spAN2cMVCFV d9oKDMyXroDclDZK9D7ONhMeU+SsTjoF7Nuucpw4i9A5O4kKPnf+dQIBA6OCAUQwggFAMBIGA1Ud EwEB/wQIMAYBAf8CAQwwPAYDVR0fBDUwMzAxoC+gLYYraHR0cDovL2NybC5jaGFtYmVyc2lnbi5v cmcvY2hhbWJlcnNyb290LmNybDAdBgNVHQ4EFgQU45T1sU3p26EpW1eLTXYGduHRooowDgYDVR0P AQH/BAQDAgEGMBEGCWCGSAGG+EIBAQQEAwIABzAnBgNVHREEIDAegRxjaGFtYmVyc3Jvb3RAY2hh bWJlcnNpZ24ub3JnMCcGA1UdEgQgMB6BHGNoYW1iZXJzcm9vdEBjaGFtYmVyc2lnbi5vcmcwWAYD VR0gBFEwTzBNBgsrBgEEAYGHLgoDATA+MDwGCCsGAQUFBwIBFjBodHRwOi8vY3BzLmNoYW1iZXJz aWduLm9yZy9jcHMvY2hhbWJlcnNyb290Lmh0bWwwDQYJKoZIhvcNAQEFBQADggEBAAxBl8IahsAi fJ/7kPMa0QOx7xP5IV8EnNrJpY0nbJaHkb5BkAFyk+cefV/2icZdp0AJPaxJRUXcLo0waLIJuvvD L8y6C98/d3tGfToSJI6WjzwFCm/SlCgdbQzALogi1djPHRPH8EjX1wWnz8dHnjs8NMiAT9QUu/wN UPf6s+xCX6ndbcj0dc97wXImsQEcXCz9ek60AcUFV7nnPKoF2YjpB0ZBzu9Bga5Y34OirsrXdx/n ADydb47kMgkdTXg0eDQ8lJsm7U9xxhl6vSAiSFr+S30Dt+dYvsYyTnQeaN2oaFuzPu5ifdmA6Ap1 erfutGWaIZDgqtCYvDi1czyL+Nw= -----END CERTIFICATE----- Camerfirma Global Chambersign Root ================================== -----BEGIN CERTIFICATE----- MIIExTCCA62gAwIBAgIBADANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJFVTEnMCUGA1UEChMe QUMgQ2FtZXJmaXJtYSBTQSBDSUYgQTgyNzQzMjg3MSMwIQYDVQQLExpodHRwOi8vd3d3LmNoYW1i ZXJzaWduLm9yZzEgMB4GA1UEAxMXR2xvYmFsIENoYW1iZXJzaWduIFJvb3QwHhcNMDMwOTMwMTYx NDE4WhcNMzcwOTMwMTYxNDE4WjB9MQswCQYDVQQGEwJFVTEnMCUGA1UEChMeQUMgQ2FtZXJmaXJt YSBTQSBDSUYgQTgyNzQzMjg3MSMwIQYDVQQLExpodHRwOi8vd3d3LmNoYW1iZXJzaWduLm9yZzEg MB4GA1UEAxMXR2xvYmFsIENoYW1iZXJzaWduIFJvb3QwggEgMA0GCSqGSIb3DQEBAQUAA4IBDQAw ggEIAoIBAQCicKLQn0KuWxfH2H3PFIP8T8mhtxOviteePgQKkotgVvq0Mi+ITaFgCPS3CU6gSS9J 1tPfnZdan5QEcOw/Wdm3zGaLmFIoCQLfxS+EjXqXd7/sQJ0lcqu1PzKY+7e3/HKE5TWH+VX6ox8O by4o3Wmg2UIQxvi1RMLQQ3/bvOSiPGpVeAp3qdjqGTK3L/5cPxvusZjsyq16aUXjlg9V9ubtdepl 6DJWk0aJqCWKZQbua795B9Dxt6/tLE2Su8CoX6dnfQTyFQhwrJLWfQTSM/tMtgsL+xrJxI0DqX5c 8lCrEqWhz0hQpe/SyBoT+rB/sYIcd2oPX9wLlY/vQ37mRQklAgEDo4IBUDCCAUwwEgYDVR0TAQH/ BAgwBgEB/wIBDDA/BgNVHR8EODA2MDSgMqAwhi5odHRwOi8vY3JsLmNoYW1iZXJzaWduLm9yZy9j aGFtYmVyc2lnbnJvb3QuY3JsMB0GA1UdDgQWBBRDnDafsJ4wTcbOX60Qq+UDpfqpFDAOBgNVHQ8B Af8EBAMCAQYwEQYJYIZIAYb4QgEBBAQDAgAHMCoGA1UdEQQjMCGBH2NoYW1iZXJzaWducm9vdEBj aGFtYmVyc2lnbi5vcmcwKgYDVR0SBCMwIYEfY2hhbWJlcnNpZ25yb290QGNoYW1iZXJzaWduLm9y ZzBbBgNVHSAEVDBSMFAGCysGAQQBgYcuCgEBMEEwPwYIKwYBBQUHAgEWM2h0dHA6Ly9jcHMuY2hh bWJlcnNpZ24ub3JnL2Nwcy9jaGFtYmVyc2lnbnJvb3QuaHRtbDANBgkqhkiG9w0BAQUFAAOCAQEA PDtwkfkEVCeR4e3t/mh/YV3lQWVPMvEYBZRqHN4fcNs+ezICNLUMbKGKfKX0j//U2K0X1S0E0T9Y gOKBWYi+wONGkyT+kL0mojAt6JcmVzWJdJYY9hXiryQZVgICsroPFOrGimbBhkVVi76SvpykBMdJ PJ7oKXqJ1/6v/2j1pReQvayZzKWGVwlnRtvWFsJG8eSpUPWP0ZIV018+xgBJOm5YstHRJw0lyDL4 IBHNfTIzSJRUTN3cecQwn+uOuFW114hcxWokPbLTBQNRxgfvzBRydD1ucs4YKIxKoHflCStFREes t2d/AYoFWpO+ocH/+OcOZ6RHSXZddZAa9SaP8A== -----END CERTIFICATE----- NetLock Notary (Class A) Root ============================= -----BEGIN CERTIFICATE----- MIIGfTCCBWWgAwIBAgICAQMwDQYJKoZIhvcNAQEEBQAwga8xCzAJBgNVBAYTAkhVMRAwDgYDVQQI EwdIdW5nYXJ5MREwDwYDVQQHEwhCdWRhcGVzdDEnMCUGA1UEChMeTmV0TG9jayBIYWxvemF0Yml6 dG9uc2FnaSBLZnQuMRowGAYDVQQLExFUYW51c2l0dmFueWtpYWRvazE2MDQGA1UEAxMtTmV0TG9j ayBLb3pqZWd5em9pIChDbGFzcyBBKSBUYW51c2l0dmFueWtpYWRvMB4XDTk5MDIyNDIzMTQ0N1oX DTE5MDIxOTIzMTQ0N1owga8xCzAJBgNVBAYTAkhVMRAwDgYDVQQIEwdIdW5nYXJ5MREwDwYDVQQH EwhCdWRhcGVzdDEnMCUGA1UEChMeTmV0TG9jayBIYWxvemF0Yml6dG9uc2FnaSBLZnQuMRowGAYD VQQLExFUYW51c2l0dmFueWtpYWRvazE2MDQGA1UEAxMtTmV0TG9jayBLb3pqZWd5em9pIChDbGFz cyBBKSBUYW51c2l0dmFueWtpYWRvMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvHSM D7tM9DceqQWC2ObhbHDqeLVu0ThEDaiDzl3S1tWBxdRL51uUcCbbO51qTGL3cfNk1mE7PetzozfZ z+qMkjvN9wfcZnSX9EUi3fRc4L9t875lM+QVOr/bmJBVOMTtplVjC7B4BPTjbsE/jvxReB+SnoPC /tmwqcm8WgD/qaiYdPv2LD4VOQ22BFWoDpggQrOxJa1+mm9dU7GrDPzr4PN6s6iz/0b2Y6LYOph7 tqyF/7AlT3Rj5xMHpQqPBffAZG9+pyeAlt7ULoZgx2srXnN7F+eRP2QM2EsiNCubMvJIH5+hCoR6 4sKtlz2O1cH5VqNQ6ca0+pii7pXmKgOM3wIDAQABo4ICnzCCApswDgYDVR0PAQH/BAQDAgAGMBIG A1UdEwEB/wQIMAYBAf8CAQQwEQYJYIZIAYb4QgEBBAQDAgAHMIICYAYJYIZIAYb4QgENBIICURaC Ak1GSUdZRUxFTSEgRXplbiB0YW51c2l0dmFueSBhIE5ldExvY2sgS2Z0LiBBbHRhbGFub3MgU3pv bGdhbHRhdGFzaSBGZWx0ZXRlbGVpYmVuIGxlaXJ0IGVsamFyYXNvayBhbGFwamFuIGtlc3p1bHQu IEEgaGl0ZWxlc2l0ZXMgZm9seWFtYXRhdCBhIE5ldExvY2sgS2Z0LiB0ZXJtZWtmZWxlbG9zc2Vn LWJpenRvc2l0YXNhIHZlZGkuIEEgZGlnaXRhbGlzIGFsYWlyYXMgZWxmb2dhZGFzYW5hayBmZWx0 ZXRlbGUgYXogZWxvaXJ0IGVsbGVub3J6ZXNpIGVsamFyYXMgbWVndGV0ZWxlLiBBeiBlbGphcmFz IGxlaXJhc2EgbWVndGFsYWxoYXRvIGEgTmV0TG9jayBLZnQuIEludGVybmV0IGhvbmxhcGphbiBh IGh0dHBzOi8vd3d3Lm5ldGxvY2submV0L2RvY3MgY2ltZW4gdmFneSBrZXJoZXRvIGF6IGVsbGVu b3J6ZXNAbmV0bG9jay5uZXQgZS1tYWlsIGNpbWVuLiBJTVBPUlRBTlQhIFRoZSBpc3N1YW5jZSBh bmQgdGhlIHVzZSBvZiB0aGlzIGNlcnRpZmljYXRlIGlzIHN1YmplY3QgdG8gdGhlIE5ldExvY2sg Q1BTIGF2YWlsYWJsZSBhdCBodHRwczovL3d3dy5uZXRsb2NrLm5ldC9kb2NzIG9yIGJ5IGUtbWFp bCBhdCBjcHNAbmV0bG9jay5uZXQuMA0GCSqGSIb3DQEBBAUAA4IBAQBIJEb3ulZv+sgoA0BO5TE5 ayZrU3/b39/zcT0mwBQOxmd7I6gMc90Bu8bKbjc5VdXHjFYgDigKDtIqpLBJUsY4B/6+CgmM0ZjP ytoUMaFP0jn8DxEsQ8Pdq5PHVT5HfBgaANzze9jyf1JsIPQLX2lS9O74silg6+NJMSEN1rUQQeJB CWziGppWS3cC9qCbmieH6FUpccKQn0V4GuEVZD3QDtigdp+uxdAu6tYPVuxkf1qbFFgBJ34TUMdr KuZoPL9coAob4Q566eKAw+np9v1sEZ7Q5SgnK1QyQhSCdeZK8CtmdWOMovsEPoMOmzbwGOQmIMOM 8CgHrTwXZoi1/baI -----END CERTIFICATE----- NetLock Business (Class B) Root =============================== -----BEGIN CERTIFICATE----- MIIFSzCCBLSgAwIBAgIBaTANBgkqhkiG9w0BAQQFADCBmTELMAkGA1UEBhMCSFUxETAPBgNVBAcT CEJ1ZGFwZXN0MScwJQYDVQQKEx5OZXRMb2NrIEhhbG96YXRiaXp0b25zYWdpIEtmdC4xGjAYBgNV BAsTEVRhbnVzaXR2YW55a2lhZG9rMTIwMAYDVQQDEylOZXRMb2NrIFV6bGV0aSAoQ2xhc3MgQikg VGFudXNpdHZhbnlraWFkbzAeFw05OTAyMjUxNDEwMjJaFw0xOTAyMjAxNDEwMjJaMIGZMQswCQYD VQQGEwJIVTERMA8GA1UEBxMIQnVkYXBlc3QxJzAlBgNVBAoTHk5ldExvY2sgSGFsb3phdGJpenRv bnNhZ2kgS2Z0LjEaMBgGA1UECxMRVGFudXNpdHZhbnlraWFkb2sxMjAwBgNVBAMTKU5ldExvY2sg VXpsZXRpIChDbGFzcyBCKSBUYW51c2l0dmFueWtpYWRvMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB iQKBgQCx6gTsIKAjwo84YM/HRrPVG/77uZmeBNwcf4xKgZjupNTKihe5In+DCnVMm8Bp2GQ5o+2S o/1bXHQawEfKOml2mrriRBf8TKPV/riXiK+IA4kfpPIEPsgHC+b5sy96YhQJRhTKZPWLgLViqNhr 1nGTLbO/CVRY7QbrqHvcQ7GhaQIDAQABo4ICnzCCApswEgYDVR0TAQH/BAgwBgEB/wIBBDAOBgNV HQ8BAf8EBAMCAAYwEQYJYIZIAYb4QgEBBAQDAgAHMIICYAYJYIZIAYb4QgENBIICURaCAk1GSUdZ RUxFTSEgRXplbiB0YW51c2l0dmFueSBhIE5ldExvY2sgS2Z0LiBBbHRhbGFub3MgU3pvbGdhbHRh dGFzaSBGZWx0ZXRlbGVpYmVuIGxlaXJ0IGVsamFyYXNvayBhbGFwamFuIGtlc3p1bHQuIEEgaGl0 ZWxlc2l0ZXMgZm9seWFtYXRhdCBhIE5ldExvY2sgS2Z0LiB0ZXJtZWtmZWxlbG9zc2VnLWJpenRv c2l0YXNhIHZlZGkuIEEgZGlnaXRhbGlzIGFsYWlyYXMgZWxmb2dhZGFzYW5hayBmZWx0ZXRlbGUg YXogZWxvaXJ0IGVsbGVub3J6ZXNpIGVsamFyYXMgbWVndGV0ZWxlLiBBeiBlbGphcmFzIGxlaXJh c2EgbWVndGFsYWxoYXRvIGEgTmV0TG9jayBLZnQuIEludGVybmV0IGhvbmxhcGphbiBhIGh0dHBz Oi8vd3d3Lm5ldGxvY2submV0L2RvY3MgY2ltZW4gdmFneSBrZXJoZXRvIGF6IGVsbGVub3J6ZXNA bmV0bG9jay5uZXQgZS1tYWlsIGNpbWVuLiBJTVBPUlRBTlQhIFRoZSBpc3N1YW5jZSBhbmQgdGhl IHVzZSBvZiB0aGlzIGNlcnRpZmljYXRlIGlzIHN1YmplY3QgdG8gdGhlIE5ldExvY2sgQ1BTIGF2 YWlsYWJsZSBhdCBodHRwczovL3d3dy5uZXRsb2NrLm5ldC9kb2NzIG9yIGJ5IGUtbWFpbCBhdCBj cHNAbmV0bG9jay5uZXQuMA0GCSqGSIb3DQEBBAUAA4GBAATbrowXr/gOkDFOzT4JwG06sPgzTEdM 43WIEJessDgVkcYplswhwG08pXTP2IKlOcNl40JwuyKQ433bNXbhoLXan3BukxowOR0w2y7jfLKR stE3Kfq51hdcR0/jHTjrn9V7lagonhVK0dHQKwCXoOKSNitjrFgBazMpUIaD8QFI -----END CERTIFICATE----- NetLock Express (Class C) Root ============================== -----BEGIN CERTIFICATE----- MIIFTzCCBLigAwIBAgIBaDANBgkqhkiG9w0BAQQFADCBmzELMAkGA1UEBhMCSFUxETAPBgNVBAcT CEJ1ZGFwZXN0MScwJQYDVQQKEx5OZXRMb2NrIEhhbG96YXRiaXp0b25zYWdpIEtmdC4xGjAYBgNV BAsTEVRhbnVzaXR2YW55a2lhZG9rMTQwMgYDVQQDEytOZXRMb2NrIEV4cHJlc3N6IChDbGFzcyBD KSBUYW51c2l0dmFueWtpYWRvMB4XDTk5MDIyNTE0MDgxMVoXDTE5MDIyMDE0MDgxMVowgZsxCzAJ BgNVBAYTAkhVMREwDwYDVQQHEwhCdWRhcGVzdDEnMCUGA1UEChMeTmV0TG9jayBIYWxvemF0Yml6 dG9uc2FnaSBLZnQuMRowGAYDVQQLExFUYW51c2l0dmFueWtpYWRvazE0MDIGA1UEAxMrTmV0TG9j ayBFeHByZXNzeiAoQ2xhc3MgQykgVGFudXNpdHZhbnlraWFkbzCBnzANBgkqhkiG9w0BAQEFAAOB jQAwgYkCgYEA6+ywbGGKIyWvYCDj2Z/8kwvbXY2wobNAOoLO/XXgeDIDhlqGlZHtU/qdQPzm6N3Z W3oDvV3zOwzDUXmbrVWg6dADEK8KuhRC2VImESLH0iDMgqSaqf64gXadarfSNnU+sYYJ9m5tfk63 euyucYT2BDMIJTLrdKwWRMbkQJMdf60CAwEAAaOCAp8wggKbMBIGA1UdEwEB/wQIMAYBAf8CAQQw DgYDVR0PAQH/BAQDAgAGMBEGCWCGSAGG+EIBAQQEAwIABzCCAmAGCWCGSAGG+EIBDQSCAlEWggJN RklHWUVMRU0hIEV6ZW4gdGFudXNpdHZhbnkgYSBOZXRMb2NrIEtmdC4gQWx0YWxhbm9zIFN6b2xn YWx0YXRhc2kgRmVsdGV0ZWxlaWJlbiBsZWlydCBlbGphcmFzb2sgYWxhcGphbiBrZXN6dWx0LiBB IGhpdGVsZXNpdGVzIGZvbHlhbWF0YXQgYSBOZXRMb2NrIEtmdC4gdGVybWVrZmVsZWxvc3NlZy1i aXp0b3NpdGFzYSB2ZWRpLiBBIGRpZ2l0YWxpcyBhbGFpcmFzIGVsZm9nYWRhc2FuYWsgZmVsdGV0 ZWxlIGF6IGVsb2lydCBlbGxlbm9yemVzaSBlbGphcmFzIG1lZ3RldGVsZS4gQXogZWxqYXJhcyBs ZWlyYXNhIG1lZ3RhbGFsaGF0byBhIE5ldExvY2sgS2Z0LiBJbnRlcm5ldCBob25sYXBqYW4gYSBo dHRwczovL3d3dy5uZXRsb2NrLm5ldC9kb2NzIGNpbWVuIHZhZ3kga2VyaGV0byBheiBlbGxlbm9y emVzQG5ldGxvY2submV0IGUtbWFpbCBjaW1lbi4gSU1QT1JUQU5UISBUaGUgaXNzdWFuY2UgYW5k IHRoZSB1c2Ugb2YgdGhpcyBjZXJ0aWZpY2F0ZSBpcyBzdWJqZWN0IHRvIHRoZSBOZXRMb2NrIENQ UyBhdmFpbGFibGUgYXQgaHR0cHM6Ly93d3cubmV0bG9jay5uZXQvZG9jcyBvciBieSBlLW1haWwg YXQgY3BzQG5ldGxvY2submV0LjANBgkqhkiG9w0BAQQFAAOBgQAQrX/XDDKACtiG8XmYta3UzbM2 xJZIwVzNmtkFLp++UOv0JhQQLdRmF/iewSf98e3ke0ugbLWrmldwpu2gpO0u9f38vf5NNwgMvOOW gyL1SRt/Syu0VMGAfJlOHdCM7tCs5ZL6dVb+ZKATj7i4Fp1hBWeAyNDYpQcCNJgEjTME1A== -----END CERTIFICATE----- XRamp Global CA Root ==================== -----BEGIN CERTIFICATE----- MIIEMDCCAxigAwIBAgIQUJRs7Bjq1ZxN1ZfvdY+grTANBgkqhkiG9w0BAQUFADCBgjELMAkGA1UE BhMCVVMxHjAcBgNVBAsTFXd3dy54cmFtcHNlY3VyaXR5LmNvbTEkMCIGA1UEChMbWFJhbXAgU2Vj dXJpdHkgU2VydmljZXMgSW5jMS0wKwYDVQQDEyRYUmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBB dXRob3JpdHkwHhcNMDQxMTAxMTcxNDA0WhcNMzUwMTAxMDUzNzE5WjCBgjELMAkGA1UEBhMCVVMx HjAcBgNVBAsTFXd3dy54cmFtcHNlY3VyaXR5LmNvbTEkMCIGA1UEChMbWFJhbXAgU2VjdXJpdHkg U2VydmljZXMgSW5jMS0wKwYDVQQDEyRYUmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBBdXRob3Jp dHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCYJB69FbS638eMpSe2OAtp87ZOqCwu IR1cRN8hXX4jdP5efrRKt6atH67gBhbim1vZZ3RrXYCPKZ2GG9mcDZhtdhAoWORlsH9KmHmf4MMx foArtYzAQDsRhtDLooY2YKTVMIJt2W7QDxIEM5dfT2Fa8OT5kavnHTu86M/0ay00fOJIYRyO82FE zG+gSqmUsE3a56k0enI4qEHMPJQRfevIpoy3hsvKMzvZPTeL+3o+hiznc9cKV6xkmxnr9A8ECIqs AxcZZPRaJSKNNCyy9mgdEm3Tih4U2sSPpuIjhdV6Db1q4Ons7Be7QhtnqiXtRYMh/MHJfNViPvry xS3T/dRlAgMBAAGjgZ8wgZwwEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0PBAQDAgGGMA8GA1Ud EwEB/wQFMAMBAf8wHQYDVR0OBBYEFMZPoj0GY4QJnM5i5ASsjVy16bYbMDYGA1UdHwQvMC0wK6Ap oCeGJWh0dHA6Ly9jcmwueHJhbXBzZWN1cml0eS5jb20vWEdDQS5jcmwwEAYJKwYBBAGCNxUBBAMC AQEwDQYJKoZIhvcNAQEFBQADggEBAJEVOQMBG2f7Shz5CmBbodpNl2L5JFMn14JkTpAuw0kbK5rc /Kh4ZzXxHfARvbdI4xD2Dd8/0sm2qlWkSLoC295ZLhVbO50WfUfXN+pfTXYSNrsf16GBBEYgoyxt qZ4Bfj8pzgCT3/3JknOJiWSe5yvkHJEs0rnOfc5vMZnT5r7SHpDwCRR5XCOrTdLaIR9NmXmd4c8n nxCbHIgNsIpkQTG4DmyQJKSbXHGPurt+HBvbaoAPIbzp26a3QPSyi6mx5O+aGtA9aZnuqCij4Tyz 8LIRnM98QObd50N9otg6tamN8jSZxNQQ4Qb9CYQQO+7ETPTsJ3xCwnR8gooJybQDJbw= -----END CERTIFICATE----- Go Daddy Class 2 CA =================== -----BEGIN CERTIFICATE----- MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMY VGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRp ZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3MDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkG A1UEBhMCVVMxITAfBgNVBAoTGFRoZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28g RGFkZHkgQ2xhc3MgMiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQAD ggENADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCAPVYYYwhv 2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6wwdhFJ2+qN1j3hybX2C32 qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXiEqITLdiOr18SPaAIBQi2XKVlOARFmR6j YGB0xUGlcmIbYsUfb18aQr4CUWWoriMYavx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmY vLEHZ6IVDd2gWMZEewo+YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0O BBYEFNLEsNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h/t2o atTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMu MTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwG A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wim PQoZ+YeAEW5p5JYXMP80kWNyOO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKt I3lpjbi2Tc7PTMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ HmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mERdEr/VxqHD3VI Ls9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5CufReYNnyicsbkqWletNw+vHX/b vZ8= -----END CERTIFICATE----- Starfield Class 2 CA ==================== -----BEGIN CERTIFICATE----- MIIEDzCCAvegAwIBAgIBADANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzElMCMGA1UEChMc U3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMpU3RhcmZpZWxkIENsYXNzIDIg Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQwNjI5MTczOTE2WhcNMzQwNjI5MTczOTE2WjBo MQswCQYDVQQGEwJVUzElMCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAG A1UECxMpU3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEgMA0GCSqG SIb3DQEBAQUAA4IBDQAwggEIAoIBAQC3Msj+6XGmBIWtDBFk385N78gDGIc/oav7PKaf8MOh2tTY bitTkPskpD6E8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN+lq2cwQlZut3f+dZxkqZ JRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0X9tDkYI22WY8sbi5gv2cOj4QyDvvBmVm epsZGD3/cVE8MC5fvj13c7JdBmzDI1aaK4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSN F4Azbl5KXZnJHoe0nRrA1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HF MIHCMB0GA1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fRzt0f hvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0YXJmaWVsZCBUZWNo bm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBDbGFzcyAyIENlcnRpZmljYXRpb24g QXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGs afPzWdqbAYcaT1epoXkJKtv3L7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLM PUxA2IGvd56Deruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl xy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynpVSJYACPq4xJD KVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEYWQPJIrSPnNVeKtelttQKbfi3 QBFGmh95DmK/D5fs4C8fF5Q= -----END CERTIFICATE----- StartCom Certification Authority ================================ -----BEGIN CERTIFICATE----- MIIHyTCCBbGgAwIBAgIBATANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJJTDEWMBQGA1UEChMN U3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmlu ZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDYwOTE3MTk0 NjM2WhcNMzYwOTE3MTk0NjM2WjB9MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRk LjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMg U3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw ggIKAoICAQDBiNsJvGxGfHiflXu1M5DycmLWwTYgIiRezul38kMKogZkpMyONvg45iPwbm2xPN1y o4UcodM9tDMr0y+v/uqwQVlntsQGfQqedIXWeUyAN3rfOQVSWff0G0ZDpNKFhdLDcfN1YjS6LIp/ Ho/u7TTQEceWzVI9ujPW3U3eCztKS5/CJi/6tRYccjV3yjxd5srhJosaNnZcAdt0FCX+7bWgiA/d eMotHweXMAEtcnn6RtYTKqi5pquDSR3l8u/d5AGOGAqPY1MWhWKpDhk6zLVmpsJrdAfkK+F2PrRt 2PZE4XNiHzvEvqBTViVsUQn3qqvKv3b9bZvzndu/PWa8DFaqr5hIlTpL36dYUNk4dalb6kMMAv+Z 6+hsTXBbKWWc3apdzK8BMewM69KN6Oqce+Zu9ydmDBpI125C4z/eIT574Q1w+2OqqGwaVLRcJXrJ osmLFqa7LH4XXgVNWG4SHQHuEhANxjJ/GP/89PrNbpHoNkm+Gkhpi8KWTRoSsmkXwQqQ1vp5Iki/ untp+HDH+no32NgN0nZPV/+Qt+OR0t3vwmC3Zzrd/qqc8NSLf3Iizsafl7b4r4qgEKjZ+xjGtrVc UjyJthkqcwEKDwOzEmDyei+B26Nu/yYwl/WL3YlXtq09s68rxbd2AvCl1iuahhQqcvbjM4xdCUsT 37uMdBNSSwIDAQABo4ICUjCCAk4wDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAa4wHQYDVR0OBBYE FE4L7xqkQFulF2mHMMo0aEPQQa7yMGQGA1UdHwRdMFswLKAqoCiGJmh0dHA6Ly9jZXJ0LnN0YXJ0 Y29tLm9yZy9zZnNjYS1jcmwuY3JsMCugKaAnhiVodHRwOi8vY3JsLnN0YXJ0Y29tLm9yZy9zZnNj YS1jcmwuY3JsMIIBXQYDVR0gBIIBVDCCAVAwggFMBgsrBgEEAYG1NwEBATCCATswLwYIKwYBBQUH AgEWI2h0dHA6Ly9jZXJ0LnN0YXJ0Y29tLm9yZy9wb2xpY3kucGRmMDUGCCsGAQUFBwIBFilodHRw Oi8vY2VydC5zdGFydGNvbS5vcmcvaW50ZXJtZWRpYXRlLnBkZjCB0AYIKwYBBQUHAgIwgcMwJxYg U3RhcnQgQ29tbWVyY2lhbCAoU3RhcnRDb20pIEx0ZC4wAwIBARqBl0xpbWl0ZWQgTGlhYmlsaXR5 LCByZWFkIHRoZSBzZWN0aW9uICpMZWdhbCBMaW1pdGF0aW9ucyogb2YgdGhlIFN0YXJ0Q29tIENl cnRpZmljYXRpb24gQXV0aG9yaXR5IFBvbGljeSBhdmFpbGFibGUgYXQgaHR0cDovL2NlcnQuc3Rh cnRjb20ub3JnL3BvbGljeS5wZGYwEQYJYIZIAYb4QgEBBAQDAgAHMDgGCWCGSAGG+EIBDQQrFilT dGFydENvbSBGcmVlIFNTTCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTANBgkqhkiG9w0BAQUFAAOC AgEAFmyZ9GYMNPXQhV59CuzaEE44HF7fpiUFS5Eyweg78T3dRAlbB0mKKctmArexmvclmAk8jhvh 3TaHK0u7aNM5Zj2gJsfyOZEdUauCe37Vzlrk4gNXcGmXCPleWKYK34wGmkUWFjgKXlf2Ysd6AgXm vB618p70qSmD+LIU424oh0TDkBreOKk8rENNZEXO3SipXPJzewT4F+irsfMuXGRuczE6Eri8sxHk fY+BUZo7jYn0TZNmezwD7dOaHZrzZVD1oNB1ny+v8OqCQ5j4aZyJecRDjkZy42Q2Eq/3JR44iZB3 fsNrarnDy0RLrHiQi+fHLB5LEUTINFInzQpdn4XBidUaePKVEFMy3YCEZnXZtWgo+2EuvoSoOMCZ EoalHmdkrQYuL6lwhceWD3yJZfWOQ1QOq92lgDmUYMA0yZZwLKMS9R9Ie70cfmu3nZD0Ijuu+Pwq yvqCUqDvr0tVk+vBtfAii6w0TiYiBKGHLHVKt+V9E9e4DGTANtLJL4YSjCMJwRuCO3NJo2pXh5Tl 1njFmUNj403gdy3hZZlyaQQaRwnmDwFWJPsfvw55qVguucQJAX6Vum0ABj6y6koQOdjQK/W/7HW/ lwLFCRsI3FU34oH7N4RDYiDK51ZLZer+bMEkkyShNOsF/5oirpt9P/FlUQqmMGqz9IgcgA38coro g14= -----END CERTIFICATE----- Taiwan GRCA =========== -----BEGIN CERTIFICATE----- MIIFcjCCA1qgAwIBAgIQH51ZWtcvwgZEpYAIaeNe9jANBgkqhkiG9w0BAQUFADA/MQswCQYDVQQG EwJUVzEwMC4GA1UECgwnR292ZXJubWVudCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4X DTAyMTIwNTEzMjMzM1oXDTMyMTIwNTEzMjMzM1owPzELMAkGA1UEBhMCVFcxMDAuBgNVBAoMJ0dv dmVybm1lbnQgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCAiIwDQYJKoZIhvcNAQEBBQAD ggIPADCCAgoCggIBAJoluOzMonWoe/fOW1mKydGGEghU7Jzy50b2iPN86aXfTEc2pBsBHH8eV4qN w8XRIePaJD9IK/ufLqGU5ywck9G/GwGHU5nOp/UKIXZ3/6m3xnOUT0b3EEk3+qhZSV1qgQdW8or5 BtD3cCJNtLdBuTK4sfCxw5w/cP1T3YGq2GN49thTbqGsaoQkclSGxtKyyhwOeYHWtXBiCAEuTk8O 1RGvqa/lmr/czIdtJuTJV6L7lvnM4T9TjGxMfptTCAtsF/tnyMKtsc2AtJfcdgEWFelq16TheEfO htX7MfP6Mb40qij7cEwdScevLJ1tZqa2jWR+tSBqnTuBto9AAGdLiYa4zGX+FVPpBMHWXx1E1wov J5pGfaENda1UhhXcSTvxls4Pm6Dso3pdvtUqdULle96ltqqvKKyskKw4t9VoNSZ63Pc78/1Fm9G7 Q3hub/FCVGqY8A2tl+lSXunVanLeavcbYBT0peS2cWeqH+riTcFCQP5nRhc4L0c/cZyu5SHKYS1t B6iEfC3uUSXxY5Ce/eFXiGvviiNtsea9P63RPZYLhY3Naye7twWb7LuRqQoHEgKXTiCQ8P8NHuJB O9NAOueNXdpm5AKwB1KYXA6OM5zCppX7VRluTI6uSw+9wThNXo+EHWbNxWCWtFJaBYmOlXqYwZE8 lSOyDvR5tMl8wUohAgMBAAGjajBoMB0GA1UdDgQWBBTMzO/MKWCkO7GStjz6MmKPrCUVOzAMBgNV HRMEBTADAQH/MDkGBGcqBwAEMTAvMC0CAQAwCQYFKw4DAhoFADAHBgVnKgMAAAQUA5vwIhP/lSg2 09yewDL7MTqKUWUwDQYJKoZIhvcNAQEFBQADggIBAECASvomyc5eMN1PhnR2WPWus4MzeKR6dBcZ TulStbngCnRiqmjKeKBMmo4sIy7VahIkv9Ro04rQ2JyftB8M3jh+Vzj8jeJPXgyfqzvS/3WXy6Tj Zwj/5cAWtUgBfen5Cv8b5Wppv3ghqMKnI6mGq3ZW6A4M9hPdKmaKZEk9GhiHkASfQlK3T8v+R0F2 Ne//AHY2RTKbxkaFXeIksB7jSJaYV0eUVXoPQbFEJPPB/hprv4j9wabak2BegUqZIJxIZhm1AHlU D7gsL0u8qV1bYH+Mh6XgUmMqvtg7hUAV/h62ZT/FS9p+tXo1KaMuephgIqP0fSdOLeq0dDzpD6Qz DxARvBMB1uUO07+1EqLhRSPAzAhuYbeJq4PjJB7mXQfnHyA+z2fI56wwbSdLaG5LKlwCCDTb+Hbk Z6MmnD+iMsJKxYEYMRBWqoTvLQr/uB930r+lWKBi5NdLkXWNiYCYfm3LU05er/ayl4WXudpVBrkk 7tfGOB5jGxI7leFYrPLfhNVfmS8NVVvmONsuP3LpSIXLuykTjx44VbnzssQwmSNOXfJIoRIM3BKQ CZBUkQM8R+XVyWXgt0t97EfTsws+rZ7QdAAO671RrcDeLMDDav7v3Aun+kbfYNucpllQdSNpc5Oy +fwC00fmcc4QAu4njIT/rEUNE1yDMuAlpYYsfPQS -----END CERTIFICATE----- Swisscom Root CA 1 ================== -----BEGIN CERTIFICATE----- MIIF2TCCA8GgAwIBAgIQXAuFXAvnWUHfV8w/f52oNjANBgkqhkiG9w0BAQUFADBkMQswCQYDVQQG EwJjaDERMA8GA1UEChMIU3dpc3Njb20xJTAjBgNVBAsTHERpZ2l0YWwgQ2VydGlmaWNhdGUgU2Vy dmljZXMxGzAZBgNVBAMTElN3aXNzY29tIFJvb3QgQ0EgMTAeFw0wNTA4MTgxMjA2MjBaFw0yNTA4 MTgyMjA2MjBaMGQxCzAJBgNVBAYTAmNoMREwDwYDVQQKEwhTd2lzc2NvbTElMCMGA1UECxMcRGln aXRhbCBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczEbMBkGA1UEAxMSU3dpc3Njb20gUm9vdCBDQSAxMIIC IjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA0LmwqAzZuz8h+BvVM5OAFmUgdbI9m2BtRsiM MW8Xw/qabFbtPMWRV8PNq5ZJkCoZSx6jbVfd8StiKHVFXqrWW/oLJdihFvkcxC7mlSpnzNApbjyF NDhhSbEAn9Y6cV9Nbc5fuankiX9qUvrKm/LcqfmdmUc/TilftKaNXXsLmREDA/7n29uj/x2lzZAe AR81sH8A25Bvxn570e56eqeqDFdvpG3FEzuwpdntMhy0XmeLVNxzh+XTF3xmUHJd1BpYwdnP2IkC b6dJtDZd0KTeByy2dbcokdaXvij1mB7qWybJvbCXc9qukSbraMH5ORXWZ0sKbU/Lz7DkQnGMU3nn 7uHbHaBuHYwadzVcFh4rUx80i9Fs/PJnB3r1re3WmquhsUvhzDdf/X/NTa64H5xD+SpYVUNFvJbN cA78yeNmuk6NO4HLFWR7uZToXTNShXEuT46iBhFRyePLoW4xCGQMwtI89Tbo19AOeCMgkckkKmUp WyL3Ic6DXqTz3kvTaI9GdVyDCW4pa8RwjPWd1yAv/0bSKzjCL3UcPX7ape8eYIVpQtPM+GP+HkM5 haa2Y0EQs3MevNP6yn0WR+Kn1dCjigoIlmJWbjTb2QK5MHXjBNLnj8KwEUAKrNVxAmKLMb7dxiNY MUJDLXT5xp6mig/p/r+D5kNXJLrvRjSq1xIBOO0CAwEAAaOBhjCBgzAOBgNVHQ8BAf8EBAMCAYYw HQYDVR0hBBYwFDASBgdghXQBUwABBgdghXQBUwABMBIGA1UdEwEB/wQIMAYBAf8CAQcwHwYDVR0j BBgwFoAUAyUv3m+CATpcLNwroWm1Z9SM0/0wHQYDVR0OBBYEFAMlL95vggE6XCzcK6FptWfUjNP9 MA0GCSqGSIb3DQEBBQUAA4ICAQA1EMvspgQNDQ/NwNurqPKIlwzfky9NfEBWMXrrpA9gzXrzvsMn jgM+pN0S734edAY8PzHyHHuRMSG08NBsl9Tpl7IkVh5WwzW9iAUPWxAaZOHHgjD5Mq2eUCzneAXQ MbFamIp1TpBcahQq4FJHgmDmHtqBsfsUC1rxn9KVuj7QG9YVHaO+htXbD8BJZLsuUBlL0iT43R4H VtA4oJVwIHaM190e3p9xxCPvgxNcoyQVTSlAPGrEqdi3pkSlDfTgnXceQHAm/NrZNuR55LU/vJtl vrsRls/bxig5OgjOR1tTWsWZ/l2p3e9M1MalrQLmjAcSHm8D0W+go/MpvRLHUKKwf4ipmXeascCl OS5cfGniLLDqN2qk4Vrh9VDlg++luyqI54zb/W1elxmofmZ1a3Hqv7HHb6D0jqTsNFFbjCYDcKF3 1QESVwA12yPeDooomf2xEG9L/zgtYE4snOtnta1J7ksfrK/7DZBaZmBwXarNeNQk7shBoJMBkpxq nvy5JMWzFYJ+vq6VK+uxwNrjAWALXmmshFZhvnEX/h0TD/7Gh0Xp/jKgGg0TpJRVcaUWi7rKibCy x/yP2FS1k2Kdzs9Z+z0YzirLNRWCXf9UIltxUvu3yf5gmwBBZPCqKuy2QkPOiWaByIufOVQDJdMW NY6E0F/6MBr1mmz0DlP5OlvRHA== -----END CERTIFICATE----- DigiCert Assured ID Root CA =========================== -----BEGIN CERTIFICATE----- MIIDtzCCAp+gAwIBAgIQDOfg5RfYRv6P5WD8G/AwOTANBgkqhkiG9w0BAQUFADBlMQswCQYDVQQG EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQw IgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwHhcNMDYxMTEwMDAwMDAwWhcNMzEx MTEwMDAwMDAwWjBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQL ExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0Ew ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtDhXO5EOAXLGH87dg+XESpa7cJpSIqvTO 9SA5KFhgDPiA2qkVlTJhPLWxKISKityfCgyDF3qPkKyK53lTXDGEKvYPmDI2dsze3Tyoou9q+yHy UmHfnyDXH+Kx2f4YZNISW1/5WBg1vEfNoTb5a3/UsDg+wRvDjDPZ2C8Y/igPs6eD1sNuRMBhNZYW /lmci3Zt1/GiSw0r/wty2p5g0I6QNcZ4VYcgoc/lbQrISXwxmDNsIumH0DJaoroTghHtORedmTpy oeb6pNnVFzF1roV9Iq4/AUaG9ih5yLHa5FcXxH4cDrC0kqZWs72yl+2qp/C3xag/lRbQ/6GW6whf GHdPAgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRF 66Kv9JLLgjEtUYunpyGd823IDzAfBgNVHSMEGDAWgBRF66Kv9JLLgjEtUYunpyGd823IDzANBgkq hkiG9w0BAQUFAAOCAQEAog683+Lt8ONyc3pklL/3cmbYMuRCdWKuh+vy1dneVrOfzM4UKLkNl2Bc EkxY5NM9g0lFWJc1aRqoR+pWxnmrEthngYTffwk8lOa4JiwgvT2zKIn3X/8i4peEH+ll74fg38Fn SbNd67IJKusm7Xi+fT8r87cmNW1fiQG2SVufAQWbqz0lwcy2f8Lxb4bG+mRo64EtlOtCt/qMHt1i 8b5QZ7dsvfPxH2sMNgcWfzd8qVttevESRmCD1ycEvkvOl77DZypoEd+A5wwzZr8TDRRu838fYxAe +o0bJW1sj6W3YQGx0qMmoRBxna3iw/nDmVG3KwcIzi7mULKn+gpFL6Lw8g== -----END CERTIFICATE----- DigiCert Global Root CA ======================= -----BEGIN CERTIFICATE----- MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBhMQswCQYDVQQG EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSAw HgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBDQTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAw MDAwMDBaMGExCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3 dy5kaWdpY2VydC5jb20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkq hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsBCSDMAZOn TjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97nh6Vfe63SKMI2tavegw5 BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt43C/dxC//AH2hdmoRBBYMql1GNXRor5H 4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7PT19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y 7vrTC0LUq7dBMtoM1O/4gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQAB o2MwYTAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbRTLtm 8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUwDQYJKoZIhvcNAQEF BQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/EsrhMAtudXH/vTBH1jLuG2cenTnmCmr EbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIt tep3Sp+dWOIrWcBAI+0tKIJFPnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886 UAb3LujEV0lsYSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4= -----END CERTIFICATE----- DigiCert High Assurance EV Root CA ================================== -----BEGIN CERTIFICATE----- MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBsMQswCQYDVQQG EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSsw KQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5jZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAw MFoXDTMxMTExMDAwMDAwMFowbDELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZ MBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFu Y2UgRVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm+9S75S0t Mqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTWPNt0OKRKzE0lgvdKpVMS OO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEMxChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3 MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFBIk5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQ NAQTXKFx01p8VdteZOE3hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUe h10aUAsgEsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMB Af8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaAFLE+w2kD+L9HAdSY JhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3NecnzyIZgYIVyHbIUf4KmeqvxgydkAQ V8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6zeM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFp myPInngiK3BD41VHMWEZ71jFhS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkK mNEVX58Svnw2Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep+OkuE6N36B9K -----END CERTIFICATE----- Certplus Class 2 Primary CA =========================== -----BEGIN CERTIFICATE----- MIIDkjCCAnqgAwIBAgIRAIW9S/PY2uNp9pTXX8OlRCMwDQYJKoZIhvcNAQEFBQAwPTELMAkGA1UE BhMCRlIxETAPBgNVBAoTCENlcnRwbHVzMRswGQYDVQQDExJDbGFzcyAyIFByaW1hcnkgQ0EwHhcN OTkwNzA3MTcwNTAwWhcNMTkwNzA2MjM1OTU5WjA9MQswCQYDVQQGEwJGUjERMA8GA1UEChMIQ2Vy dHBsdXMxGzAZBgNVBAMTEkNsYXNzIDIgUHJpbWFyeSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEP ADCCAQoCggEBANxQltAS+DXSCHh6tlJw/W/uz7kRy1134ezpfgSN1sxvc0NXYKwzCkTsA18cgCSR 5aiRVhKC9+Ar9NuuYS6JEI1rbLqzAr3VNsVINyPi8Fo3UjMXEuLRYE2+L0ER4/YXJQyLkcAbmXuZ Vg2v7tK8R1fjeUl7NIknJITesezpWE7+Tt9avkGtrAjFGA7v0lPubNCdEgETjdyAYveVqUSISnFO YFWe2yMZeVYHDD9jC1yw4r5+FfyUM1hBOHTE4Y+L3yasH7WLO7dDWWuwJKZtkIvEcupdM5i3y95e e++U8Rs+yskhwcWYAqqi9lt3m/V+llU0HGdpwPFC40es/CgcZlUCAwEAAaOBjDCBiTAPBgNVHRME CDAGAQH/AgEKMAsGA1UdDwQEAwIBBjAdBgNVHQ4EFgQU43Mt38sOKAze3bOkynm4jrvoMIkwEQYJ YIZIAYb4QgEBBAQDAgEGMDcGA1UdHwQwMC4wLKAqoCiGJmh0dHA6Ly93d3cuY2VydHBsdXMuY29t L0NSTC9jbGFzczIuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQCnVM+IRBnL39R/AN9WM2K191EBkOvD P9GIROkkXe/nFL0gt5o8AP5tn9uQ3Nf0YtaLcF3n5QRIqWh8yfFC82x/xXp8HVGIutIKPidd3i1R TtMTZGnkLuPT55sJmabglZvOGtd/vjzOUrMRFcEPF80Du5wlFbqidon8BvEY0JNLDnyCt6X09l/+ 7UCmnYR0ObncHoUW2ikbhiMAybuJfm6AiB4vFLQDJKgybwOaRywwvlbGp0ICcBvqQNi6BQNwB6SW //1IMwrh3KWBkJtN3X3n57LNXMhqlfil9o3EXXgIvnsG1knPGTZQIy4I5p4FTUcY1Rbpsda2ENW7 l7+ijrRU -----END CERTIFICATE----- DST Root CA X3 ============== -----BEGIN CERTIFICATE----- MIIDSjCCAjKgAwIBAgIQRK+wgNajJ7qJMDmGLvhAazANBgkqhkiG9w0BAQUFADA/MSQwIgYDVQQK ExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMTDkRTVCBSb290IENBIFgzMB4X DTAwMDkzMDIxMTIxOVoXDTIxMDkzMDE0MDExNVowPzEkMCIGA1UEChMbRGlnaXRhbCBTaWduYXR1 cmUgVHJ1c3QgQ28uMRcwFQYDVQQDEw5EU1QgUm9vdCBDQSBYMzCCASIwDQYJKoZIhvcNAQEBBQAD ggEPADCCAQoCggEBAN+v6ZdQCINXtMxiZfaQguzH0yxrMMpb7NnDfcdAwRgUi+DoM3ZJKuM/IUmT rE4Orz5Iy2Xu/NMhD2XSKtkyj4zl93ewEnu1lcCJo6m67XMuegwGMoOifooUMM0RoOEqOLl5CjH9 UL2AZd+3UWODyOKIYepLYYHsUmu5ouJLGiifSKOeDNoJjj4XLh7dIN9bxiqKqy69cK3FCxolkHRy xXtqqzTWMIn/5WgTe1QLyNau7Fqckh49ZLOMxt+/yUFw7BZy1SbsOFU5Q9D8/RhcQPGX69Wam40d utolucbY38EVAjqr2m7xPi71XAicPNaDaeQQmxkqtilX4+U9m5/wAl0CAwEAAaNCMEAwDwYDVR0T AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMSnsaR7LHH62+FLkHX/xBVghYkQ MA0GCSqGSIb3DQEBBQUAA4IBAQCjGiybFwBcqR7uKGY3Or+Dxz9LwwmglSBd49lZRNI+DT69ikug dB/OEIKcdBodfpga3csTS7MgROSR6cz8faXbauX+5v3gTt23ADq1cEmv8uXrAvHRAosZy5Q6XkjE GB5YGV8eAlrwDPGxrancWYaLbumR9YbK+rlmM6pZW87ipxZzR8srzJmwN0jP41ZL9c8PDHIyh8bw RLtTcm1D9SZImlJnt1ir/md2cXjbDaJWFBM5JDGFoqgCWjBH4d1QB7wCCZAA62RjYJsWvIjJEubS fZGL+T0yjWW06XyxV3bqxbYoOb8VZRzI9neWagqNdwvYkQsEjgfbKbYK7p2CNTUQ -----END CERTIFICATE----- DST ACES CA X6 ============== -----BEGIN CERTIFICATE----- MIIECTCCAvGgAwIBAgIQDV6ZCtadt3js2AdWO4YV2TANBgkqhkiG9w0BAQUFADBbMQswCQYDVQQG EwJVUzEgMB4GA1UEChMXRGlnaXRhbCBTaWduYXR1cmUgVHJ1c3QxETAPBgNVBAsTCERTVCBBQ0VT MRcwFQYDVQQDEw5EU1QgQUNFUyBDQSBYNjAeFw0wMzExMjAyMTE5NThaFw0xNzExMjAyMTE5NTha MFsxCzAJBgNVBAYTAlVTMSAwHgYDVQQKExdEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdDERMA8GA1UE CxMIRFNUIEFDRVMxFzAVBgNVBAMTDkRTVCBBQ0VTIENBIFg2MIIBIjANBgkqhkiG9w0BAQEFAAOC AQ8AMIIBCgKCAQEAuT31LMmU3HWKlV1j6IR3dma5WZFcRt2SPp/5DgO0PWGSvSMmtWPuktKe1jzI DZBfZIGxqAgNTNj50wUoUrQBJcWVHAx+PhCEdc/BGZFjz+iokYi5Q1K7gLFViYsx+tC3dr5BPTCa pCIlF3PoHuLTrCq9Wzgh1SpL11V94zpVvddtawJXa+ZHfAjIgrrep4c9oW24MFbCswKBXy314pow GCi4ZtPLAZZv6opFVdbgnf9nKxcCpk4aahELfrd755jWjHZvwTvbUJN+5dCOHze4vbrGn2zpfDPy MjwmR/onJALJfh1biEITajV8fTXpLmaRcpPVMibEdPVTo7NdmvYJywIDAQABo4HIMIHFMA8GA1Ud EwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgHGMB8GA1UdEQQYMBaBFHBraS1vcHNAdHJ1c3Rkc3Qu Y29tMGIGA1UdIARbMFkwVwYKYIZIAWUDAgEBATBJMEcGCCsGAQUFBwIBFjtodHRwOi8vd3d3LnRy dXN0ZHN0LmNvbS9jZXJ0aWZpY2F0ZXMvcG9saWN5L0FDRVMtaW5kZXguaHRtbDAdBgNVHQ4EFgQU CXIGThhDD+XWzMNqizF7eI+og7gwDQYJKoZIhvcNAQEFBQADggEBAKPYjtay284F5zLNAdMEA+V2 5FYrnJmQ6AgwbN99Pe7lv7UkQIRJ4dEorsTCOlMwiPH1d25Ryvr/ma8kXxug/fKshMrfqfBfBC6t Fr8hlxCBPeP/h40y3JTlR4peahPJlJU90u7INJXQgNStMgiAVDzgvVJT11J8smk/f3rPanTK+gQq nExaBqXpIK1FZg9p8d2/6eMyi/rgwYZNcjwu2JN4Cir42NInPRmJX1p7ijvMDNpRrscL9yuwNwXs vFcj4jjSm2jzVhKIT0J8uDHEtdvkyCE06UgRNe76x5JXxZ805Mf29w4LTJxoeHtxMcfrHuBnQfO3 oKfN5XozNmr6mis= -----END CERTIFICATE----- TURKTRUST Certificate Services Provider Root 1 ============================================== -----BEGIN CERTIFICATE----- MIID+zCCAuOgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBtzE/MD0GA1UEAww2VMOcUktUUlVTVCBF bGVrdHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMQswCQYDVQQGDAJUUjEP MA0GA1UEBwwGQU5LQVJBMVYwVAYDVQQKDE0oYykgMjAwNSBUw5xSS1RSVVNUIEJpbGdpIMSwbGV0 acWfaW0gdmUgQmlsacWfaW0gR8O8dmVubGnEn2kgSGl6bWV0bGVyaSBBLsWeLjAeFw0wNTA1MTMx MDI3MTdaFw0xNTAzMjIxMDI3MTdaMIG3MT8wPQYDVQQDDDZUw5xSS1RSVVNUIEVsZWt0cm9uaWsg U2VydGlmaWthIEhpem1ldCBTYcSfbGF5xLFjxLFzxLExCzAJBgNVBAYMAlRSMQ8wDQYDVQQHDAZB TktBUkExVjBUBgNVBAoMTShjKSAyMDA1IFTDnFJLVFJVU1QgQmlsZ2kgxLBsZXRpxZ9pbSB2ZSBC aWxpxZ9pbSBHw7x2ZW5sacSfaSBIaXptZXRsZXJpIEEuxZ4uMIIBIjANBgkqhkiG9w0BAQEFAAOC AQ8AMIIBCgKCAQEAylIF1mMD2Bxf3dJ7XfIMYGFbazt0K3gNfUW9InTojAPBxhEqPZW8qZSwu5GX yGl8hMW0kWxsE2qkVa2kheiVfrMArwDCBRj1cJ02i67L5BuBf5OI+2pVu32Fks66WJ/bMsW9Xe8i Si9BB35JYbOG7E6mQW6EvAPs9TscyB/C7qju6hJKjRTP8wrgUDn5CDX4EVmt5yLqS8oUBt5CurKZ 8y1UiBAG6uEaPj1nH/vO+3yC6BFdSsG5FOpU2WabfIl9BJpiyelSPJ6c79L1JuTm5Rh8i27fbMx4 W09ysstcP4wFjdFMjK2Sx+F4f2VsSQZQLJ4ywtdKxnWKWU51b0dewQIDAQABoxAwDjAMBgNVHRME BTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQAV9VX/N5aAWSGk/KEVTCD21F/aAyT8z5Aa9CEKmu46 sWrv7/hg0Uw2ZkUd82YCdAR7kjCo3gp2D++Vbr3JN+YaDayJSFvMgzbC9UZcWYJWtNX+I7TYVBxE q8Sn5RTOPEFhfEPmzcSBCYsk+1Ql1haolgxnB2+zUEfjHCQo3SqYpGH+2+oSN7wBGjSFvW5P55Fy B0SFHljKVETd96y5y4khctuPwGkplyqjrhgjlxxBKot8KsF8kOipKMDTkcatKIdAaLX/7KfS0zgY nNN9aV3wxqUeJBujR/xpB2jn5Jq07Q+hh4cCzofSSE7hvP/L8XKSRGQDJereW26fyfJOrN3H -----END CERTIFICATE----- TURKTRUST Certificate Services Provider Root 2 ============================================== -----BEGIN CERTIFICATE----- MIIEPDCCAySgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBvjE/MD0GA1UEAww2VMOcUktUUlVTVCBF bGVrdHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMQswCQYDVQQGEwJUUjEP MA0GA1UEBwwGQW5rYXJhMV0wWwYDVQQKDFRUw5xSS1RSVVNUIEJpbGdpIMSwbGV0acWfaW0gdmUg QmlsacWfaW0gR8O8dmVubGnEn2kgSGl6bWV0bGVyaSBBLsWeLiAoYykgS2FzxLFtIDIwMDUwHhcN MDUxMTA3MTAwNzU3WhcNMTUwOTE2MTAwNzU3WjCBvjE/MD0GA1UEAww2VMOcUktUUlVTVCBFbGVr dHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMQswCQYDVQQGEwJUUjEPMA0G A1UEBwwGQW5rYXJhMV0wWwYDVQQKDFRUw5xSS1RSVVNUIEJpbGdpIMSwbGV0acWfaW0gdmUgQmls acWfaW0gR8O8dmVubGnEn2kgSGl6bWV0bGVyaSBBLsWeLiAoYykgS2FzxLFtIDIwMDUwggEiMA0G CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCpNn7DkUNMwxmYCMjHWHtPFoylzkkBH3MOrHUTpvqe LCDe2JAOCtFp0if7qnefJ1Il4std2NiDUBd9irWCPwSOtNXwSadktx4uXyCcUHVPr+G1QRT0mJKI x+XlZEdhR3n9wFHxwZnn3M5q+6+1ATDcRhzviuyV79z/rxAc653YsKpqhRgNF8k+v/Gb0AmJQv2g QrSdiVFVKc8bcLyEVK3BEx+Y9C52YItdP5qtygy/p1Zbj3e41Z55SZI/4PGXJHpsmxcPbe9TmJEr 5A++WXkHeLuXlfSfadRYhwqp48y2WBmfJiGxxFmNskF1wK1pzpwACPI2/z7woQ8arBT9pmAPAgMB AAGjQzBBMB0GA1UdDgQWBBTZN7NOBf3Zz58SFq62iS/rJTqIHDAPBgNVHQ8BAf8EBQMDBwYAMA8G A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAHJglrfJ3NgpXiOFX7KzLXb7iNcX/ntt Rbj2hWyfIvwqECLsqrkw9qtY1jkQMZkpAL2JZkH7dN6RwRgLn7Vhy506vvWolKMiVW4XSf/SKfE4 Jl3vpao6+XF75tpYHdN0wgH6PmlYX63LaL4ULptswLbcoCb6dxriJNoaN+BnrdFzgw2lGh1uEpJ+ hGIAF728JRhX8tepb1mIvDS3LoV4nZbcFMMsilKbloxSZj2GFotHuFEJjOp9zYhys2AzsfAKRO8P 9Qk3iCQOLGsgOqL6EfJANZxEaGM7rDNvY7wsu/LSy3Z9fYjYHcgFHW68lKlmjHdxx/qR+i9Rnuk5 UrbnBEI= -----END CERTIFICATE----- SwissSign Gold CA - G2 ====================== -----BEGIN CERTIFICATE----- MIIFujCCA6KgAwIBAgIJALtAHEP1Xk+wMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNVBAYTAkNIMRUw EwYDVQQKEwxTd2lzc1NpZ24gQUcxHzAdBgNVBAMTFlN3aXNzU2lnbiBHb2xkIENBIC0gRzIwHhcN MDYxMDI1MDgzMDM1WhcNMzYxMDI1MDgzMDM1WjBFMQswCQYDVQQGEwJDSDEVMBMGA1UEChMMU3dp c3NTaWduIEFHMR8wHQYDVQQDExZTd2lzc1NpZ24gR29sZCBDQSAtIEcyMIICIjANBgkqhkiG9w0B AQEFAAOCAg8AMIICCgKCAgEAr+TufoskDhJuqVAtFkQ7kpJcyrhdhJJCEyq8ZVeCQD5XJM1QiyUq t2/876LQwB8CJEoTlo8jE+YoWACjR8cGp4QjK7u9lit/VcyLwVcfDmJlD909Vopz2q5+bbqBHH5C jCA12UNNhPqE21Is8w4ndwtrvxEvcnifLtg+5hg3Wipy+dpikJKVyh+c6bM8K8vzARO/Ws/BtQpg vd21mWRTuKCWs2/iJneRjOBiEAKfNA+k1ZIzUd6+jbqEemA8atufK+ze3gE/bk3lUIbLtK/tREDF ylqM2tIrfKjuvqblCqoOpd8FUrdVxyJdMmqXl2MT28nbeTZ7hTpKxVKJ+STnnXepgv9VHKVxaSvR AiTysybUa9oEVeXBCsdtMDeQKuSeFDNeFhdVxVu1yzSJkvGdJo+hB9TGsnhQ2wwMC3wLjEHXuend jIj3o02yMszYF9rNt85mndT9Xv+9lz4pded+p2JYryU0pUHHPbwNUMoDAw8IWh+Vc3hiv69yFGkO peUDDniOJihC8AcLYiAQZzlG+qkDzAQ4embvIIO1jEpWjpEA/I5cgt6IoMPiaG59je883WX0XaxR 7ySArqpWl2/5rX3aYT+YdzylkbYcjCbaZaIJbcHiVOO5ykxMgI93e2CaHt+28kgeDrpOVG2Y4OGi GqJ3UM/EY5LsRxmd6+ZrzsECAwEAAaOBrDCBqTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUw AwEB/zAdBgNVHQ4EFgQUWyV7lqRlUX64OfPAeGZe6Drn8O4wHwYDVR0jBBgwFoAUWyV7lqRlUX64 OfPAeGZe6Drn8O4wRgYDVR0gBD8wPTA7BglghXQBWQECAQEwLjAsBggrBgEFBQcCARYgaHR0cDov L3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIBACe645R88a7A3hfm 5djV9VSwg/S7zV4Fe0+fdWavPOhWfvxyeDgD2StiGwC5+OlgzczOUYrHUDFu4Up+GC9pWbY9ZIEr 44OE5iKHjn3g7gKZYbge9LgriBIWhMIxkziWMaa5O1M/wySTVltpkuzFwbs4AOPsF6m43Md8AYOf Mke6UiI0HTJ6CVanfCU2qT1L2sCCbwq7EsiHSycR+R4tx5M/nttfJmtS2S6K8RTGRI0Vqbe/vd6m Gu6uLftIdxf+u+yvGPUqUfA5hJeVbG4bwyvEdGB5JbAKJ9/fXtI5z0V9QkvfsywexcZdylU6oJxp mo/a77KwPJ+HbBIrZXAVUjEaJM9vMSNQH4xPjyPDdEFjHFWoFN0+4FFQz/EbMFYOkrCChdiDyyJk vC24JdVUorgG6q2SpCSgwYa1ShNqR88uC1aVVMvOmttqtKay20EIhid392qgQmwLOM7XdVAyksLf KzAiSNDVQTglXaTpXZ/GlHXQRf0wl0OPkKsKx4ZzYEppLd6leNcG2mqeSz53OiATIgHQv2ieY2Br NU0LbbqhPcCT4H8js1WtciVORvnSFu+wZMEBnunKoGqYDs/YYPIvSbjkQuE4NRb0yG5P94FW6Lqj viOvrv1vA+ACOzB2+httQc8Bsem4yWb02ybzOqR08kkkW8mw0FfB+j564ZfJ -----END CERTIFICATE----- SwissSign Silver CA - G2 ======================== -----BEGIN CERTIFICATE----- MIIFvTCCA6WgAwIBAgIITxvUL1S7L0swDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCQ0gxFTAT BgNVBAoTDFN3aXNzU2lnbiBBRzEhMB8GA1UEAxMYU3dpc3NTaWduIFNpbHZlciBDQSAtIEcyMB4X DTA2MTAyNTA4MzI0NloXDTM2MTAyNTA4MzI0NlowRzELMAkGA1UEBhMCQ0gxFTATBgNVBAoTDFN3 aXNzU2lnbiBBRzEhMB8GA1UEAxMYU3dpc3NTaWduIFNpbHZlciBDQSAtIEcyMIICIjANBgkqhkiG 9w0BAQEFAAOCAg8AMIICCgKCAgEAxPGHf9N4Mfc4yfjDmUO8x/e8N+dOcbpLj6VzHVxumK4DV644 N0MvFz0fyM5oEMF4rhkDKxD6LHmD9ui5aLlV8gREpzn5/ASLHvGiTSf5YXu6t+WiE7brYT7QbNHm +/pe7R20nqA1W6GSy/BJkv6FCgU+5tkL4k+73JU3/JHpMjUi0R86TieFnbAVlDLaYQ1HTWBCrpJH 6INaUFjpiou5XaHc3ZlKHzZnu0jkg7Y360g6rw9njxcH6ATK72oxh9TAtvmUcXtnZLi2kUpCe2Uu MGoM9ZDulebyzYLs2aFK7PayS+VFheZteJMELpyCbTapxDFkH4aDCyr0NQp4yVXPQbBH6TCfmb5h qAaEuSh6XzjZG6k4sIN/c8HDO0gqgg8hm7jMqDXDhBuDsz6+pJVpATqJAHgE2cn0mRmrVn5bi4Y5 FZGkECwJMoBgs5PAKrYYC51+jUnyEEp/+dVGLxmSo5mnJqy7jDzmDrxHB9xzUfFwZC8I+bRHHTBs ROopN4WSaGa8gzj+ezku01DwH/teYLappvonQfGbGHLy9YR0SslnxFSuSGTfjNFusB3hB48IHpmc celM2KX3RxIfdNFRnobzwqIjQAtz20um53MGjMGg6cFZrEb65i/4z3GcRm25xBWNOHkDRUjvxF3X CO6HOSKGsg0PWEP3calILv3q1h8CAwEAAaOBrDCBqTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/ BAUwAwEB/zAdBgNVHQ4EFgQUF6DNweRBtjpbO8tFnb0cwpj6hlgwHwYDVR0jBBgwFoAUF6DNweRB tjpbO8tFnb0cwpj6hlgwRgYDVR0gBD8wPTA7BglghXQBWQEDAQEwLjAsBggrBgEFBQcCARYgaHR0 cDovL3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIBAHPGgeAn0i0P 4JUw4ppBf1AsX19iYamGamkYDHRJ1l2E6kFSGG9YrVBWIGrGvShpWJHckRE1qTodvBqlYJ7YH39F kWnZfrt4csEGDyrOj4VwYaygzQu4OSlWhDJOhrs9xCrZ1x9y7v5RoSJBsXECYxqCsGKrXlcSH9/L 3XWgwF15kIwb4FDm3jH+mHtwX6WQ2K34ArZv02DdQEsixT2tOnqfGhpHkXkzuoLcMmkDlm4fS/Bx /uNncqCxv1yL5PqZIseEuRuNI5c/7SXgz2W79WEE790eslpBIlqhn10s6FvJbakMDHiqYMZWjwFa DGi8aRl5xB9+lwW/xekkUV7U1UtT7dkjWjYDZaPBA61BMPNGG4WQr2W11bHkFlt4dR2Xem1ZqSqP e97Dh4kQmUlzeMg9vVE1dCrV8X5pGyq7O70luJpaPXJhkGaH7gzWTdQRdAtq/gsD/KNVV4n+Ssuu WxcFyPKNIzFTONItaj+CuY0IavdeQXRuwxF+B6wpYJE/OMpXEA29MC/HpeZBoNquBYeaoKRlbEwJ DIm6uNO5wJOKMPqN5ZprFQFOZ6raYlY+hAhm0sQ2fac+EPyI4NSA5QC9qvNOBqN6avlicuMJT+ub DgEj8Z+7fNzcbBGXJbLytGMU0gYqZ4yD9c7qB9iaah7s5Aq7KkzrCWA5zspi2C5u -----END CERTIFICATE----- GeoTrust Primary Certification Authority ======================================== -----BEGIN CERTIFICATE----- MIIDfDCCAmSgAwIBAgIQGKy1av1pthU6Y2yv2vrEoTANBgkqhkiG9w0BAQUFADBYMQswCQYDVQQG EwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjExMC8GA1UEAxMoR2VvVHJ1c3QgUHJpbWFyeSBD ZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjExMjcwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMFgx CzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTEwLwYDVQQDEyhHZW9UcnVzdCBQ cmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB CgKCAQEAvrgVe//UfH1nrYNke8hCUy3f9oQIIGHWAVlqnEQRr+92/ZV+zmEwu3qDXwK9AWbK7hWN b6EwnL2hhZ6UOvNWiAAxz9juapYC2e0DjPt1befquFUWBRaa9OBesYjAZIVcFU2Ix7e64HXprQU9 nceJSOC7KMgD4TCTZF5SwFlwIjVXiIrxlQqD17wxcwE07e9GceBrAqg1cmuXm2bgyxx5X9gaBGge RwLmnWDiNpcB3841kt++Z8dtd1k7j53WkBWUvEI0EME5+bEnPn7WinXFsq+W06Lem+SYvn3h6YGt tm/81w7a4DSwDRp35+MImO9Y+pyEtzavwt+s0vQQBnBxNQIDAQABo0IwQDAPBgNVHRMBAf8EBTAD AQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQULNVQQZcVi/CPNmFbSvtr2ZnJM5IwDQYJKoZI hvcNAQEFBQADggEBAFpwfyzdtzRP9YZRqSa+S7iq8XEN3GHHoOo0Hnp3DwQ16CePbJC/kRYkRj5K Ts4rFtULUh38H2eiAkUxT87z+gOneZ1TatnaYzr4gNfTmeGl4b7UVXGYNTq+k+qurUKykG/g/CFN NWMziUnWm07Kx+dOCQD32sfvmWKZd7aVIl6KoKv0uHiYyjgZmclynnjNS6yvGaBzEi38wkG6gZHa Floxt/m0cYASSJlyc1pZU8FjUjPtp8nSOQJw+uCxQmYpqptR7TBUIhRf2asdweSU8Pj1K/fqynhG 1riR/aYNKxoUAT6A8EKglQdebc3MS6RFjasS6LPeWuWgfOgPIh1a6Vk= -----END CERTIFICATE----- thawte Primary Root CA ====================== -----BEGIN CERTIFICATE----- MIIEIDCCAwigAwIBAgIQNE7VVyDV7exJ9C/ON9srbTANBgkqhkiG9w0BAQUFADCBqTELMAkGA1UE BhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2 aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIwMDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhv cml6ZWQgdXNlIG9ubHkxHzAdBgNVBAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwHhcNMDYxMTE3 MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCBqTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwg SW5jLjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMv KGMpIDIwMDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxHzAdBgNVBAMT FnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCs oPD7gFnUnMekz52hWXMJEEUMDSxuaPFsW0hoSVk3/AszGcJ3f8wQLZU0HObrTQmnHNK4yZc2AreJ 1CRfBsDMRJSUjQJib+ta3RGNKJpchJAQeg29dGYvajig4tVUROsdB58Hum/u6f1OCyn1PoSgAfGc q/gcfomk6KHYcWUNo1F77rzSImANuVud37r8UVsLr5iy6S7pBOhih94ryNdOwUxkHt3Ph1i6Sk/K aAcdHJ1KxtUvkcx8cXIcxcBn6zL9yZJclNqFwJu/U30rCfSMnZEfl2pSy94JNqR32HuHUETVPm4p afs5SSYeCaWAe0At6+gnhcn+Yf1+5nyXHdWdAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYD VR0PAQH/BAQDAgEGMB0GA1UdDgQWBBR7W0XPr87Lev0xkhpqtvNG61dIUDANBgkqhkiG9w0BAQUF AAOCAQEAeRHAS7ORtvzw6WfUDW5FvlXok9LOAz/t2iWwHVfLHjp2oEzsUHboZHIMpKnxuIvW1oeE uzLlQRHAd9mzYJ3rG9XRbkREqaYB7FViHXe4XI5ISXycO1cRrK1zN44veFyQaEfZYGDm/Ac9IiAX xPcW6cTYcvnIc3zfFi8VqT79aie2oetaupgf1eNNZAqdE8hhuvU5HIe6uL17In/2/qxAeeWsEG89 jxt5dovEN7MhGITlNgDrYyCZuen+MwS7QcjBAvlEYyCegc5C09Y/LHbTY5xZ3Y+m4Q6gLkH3LpVH z7z9M/P2C2F+fpErgUfCJzDupxBdN49cOSvkBPB7jVaMaA== -----END CERTIFICATE----- VeriSign Class 3 Public Primary Certification Authority - G5 ============================================================ -----BEGIN CERTIFICATE----- MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCByjELMAkGA1UE BhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBO ZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVk IHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRp ZmljYXRpb24gQXV0aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCB yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2ln biBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2lnbiwgSW5jLiAtIEZvciBh dXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmlt YXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw ggEKAoIBAQCvJAgIKXo1nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKz j/i5Vbext0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIzSdhD Y2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQGBO+QueQA5N06tRn/ Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+rCpSx4/VBEnkjWNHiDxpg8v+R70r fk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/ BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2Uv Z2lmMCEwHzAHBgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKvMzEzMA0GCSqG SIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzEp6B4Eq1iDkVwZMXnl2YtmAl+ X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKE KQsTb47bDN0lAtukixlE0kF6BWlKWE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiC Km0oHw0LxOXnGiYZ4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vE ZV8NhnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq -----END CERTIFICATE----- SecureTrust CA ============== -----BEGIN CERTIFICATE----- MIIDuDCCAqCgAwIBAgIQDPCOXAgWpa1Cf/DrJxhZ0DANBgkqhkiG9w0BAQUFADBIMQswCQYDVQQG EwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24xFzAVBgNVBAMTDlNlY3VyZVRy dXN0IENBMB4XDTA2MTEwNzE5MzExOFoXDTI5MTIzMTE5NDA1NVowSDELMAkGA1UEBhMCVVMxIDAe BgNVBAoTF1NlY3VyZVRydXN0IENvcnBvcmF0aW9uMRcwFQYDVQQDEw5TZWN1cmVUcnVzdCBDQTCC ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKukgeWVzfX2FI7CT8rU4niVWJxB4Q2ZQCQX OZEzZum+4YOvYlyJ0fwkW2Gz4BERQRwdbvC4u/jep4G6pkjGnx29vo6pQT64lO0pGtSO0gMdA+9t DWccV9cGrcrI9f4Or2YlSASWC12juhbDCE/RRvgUXPLIXgGZbf2IzIaowW8xQmxSPmjL8xk037uH GFaAJsTQ3MBv396gwpEWoGQRS0S8Hvbn+mPeZqx2pHGj7DaUaHp3pLHnDi+BeuK1cobvomuL8A/b 01k/unK8RCSc43Oz969XL0Imnal0ugBS8kvNU3xHCzaFDmapCJcWNFfBZveA4+1wVMeT4C4oFVmH ursCAwEAAaOBnTCBmjATBgkrBgEEAYI3FAIEBh4EAEMAQTALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/ BAUwAwEB/zAdBgNVHQ4EFgQUQjK2FvoE/f5dS3rD/fdMQB1aQ68wNAYDVR0fBC0wKzApoCegJYYj aHR0cDovL2NybC5zZWN1cmV0cnVzdC5jb20vU1RDQS5jcmwwEAYJKwYBBAGCNxUBBAMCAQAwDQYJ KoZIhvcNAQEFBQADggEBADDtT0rhWDpSclu1pqNlGKa7UTt36Z3q059c4EVlew3KW+JwULKUBRSu SceNQQcSc5R+DCMh/bwQf2AQWnL1mA6s7Ll/3XpvXdMc9P+IBWlCqQVxyLesJugutIxq/3HcuLHf mbx8IVQr5Fiiu1cprp6poxkmD5kuCLDv/WnPmRoJjeOnnyvJNjR7JLN4TJUXpAYmHrZkUjZfYGfZ nMUFdAvnZyPSCPyI6a6Lf+Ew9Dd+/cYy2i2eRDAwbO4H3tI0/NL/QPZL9GZGBlSm8jIKYyYwa5vR 3ItHuuG51WLQoqD0ZwV4KWMabwTW+MZMo5qxN7SN5ShLHZ4swrhovO0C7jE= -----END CERTIFICATE----- Secure Global CA ================ -----BEGIN CERTIFICATE----- MIIDvDCCAqSgAwIBAgIQB1YipOjUiolN9BPI8PjqpTANBgkqhkiG9w0BAQUFADBKMQswCQYDVQQG EwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24xGTAXBgNVBAMTEFNlY3VyZSBH bG9iYWwgQ0EwHhcNMDYxMTA3MTk0MjI4WhcNMjkxMjMxMTk1MjA2WjBKMQswCQYDVQQGEwJVUzEg MB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24xGTAXBgNVBAMTEFNlY3VyZSBHbG9iYWwg Q0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvNS7YrGxVaQZx5RNoJLNP2MwhR/jx YDiJiQPpvepeRlMJ3Fz1Wuj3RSoC6zFh1ykzTM7HfAo3fg+6MpjhHZevj8fcyTiW89sa/FHtaMbQ bqR8JNGuQsiWUGMu4P51/pinX0kuleM5M2SOHqRfkNJnPLLZ/kG5VacJjnIFHovdRIWCQtBJwB1g 8NEXLJXr9qXBkqPFwqcIYA1gBBCWeZ4WNOaptvolRTnIHmX5k/Wq8VLcmZg9pYYaDDUz+kulBAYV HDGA76oYa8J719rO+TMg1fW9ajMtgQT7sFzUnKPiXB3jqUJ1XnvUd+85VLrJChgbEplJL4hL/VBi 0XPnj3pDAgMBAAGjgZ0wgZowEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0PBAQDAgGGMA8GA1Ud EwEB/wQFMAMBAf8wHQYDVR0OBBYEFK9EBMJBfkiD2045AuzshHrmzsmkMDQGA1UdHwQtMCswKaAn oCWGI2h0dHA6Ly9jcmwuc2VjdXJldHJ1c3QuY29tL1NHQ0EuY3JsMBAGCSsGAQQBgjcVAQQDAgEA MA0GCSqGSIb3DQEBBQUAA4IBAQBjGghAfaReUw132HquHw0LURYD7xh8yOOvaliTFGCRsoTciE6+ OYo68+aCiV0BN7OrJKQVDpI1WkpEXk5X+nXOH0jOZvQ8QCaSmGwb7iRGDBezUqXbpZGRzzfTb+cn CDpOGR86p1hcF895P4vkp9MmI50mD1hp/Ed+stCNi5O/KU9DaXR2Z0vPB4zmAve14bRDtUstFJ/5 3CYNv6ZHdAbYiNE6KTCEztI5gGIbqMdXSbxqVVFnFUq+NQfk1XWYN3kwFNspnWzFacxHVaIw98xc f8LDmBxrThaA63p4ZUWiABqvDA1VZDRIuJK58bRQKfJPIx/abKwfROHdI3hRW8cW -----END CERTIFICATE----- COMODO Certification Authority ============================== -----BEGIN CERTIFICATE----- MIIEHTCCAwWgAwIBAgIQToEtioJl4AsC7j41AkblPTANBgkqhkiG9w0BAQUFADCBgTELMAkGA1UE BhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgG A1UEChMRQ09NT0RPIENBIExpbWl0ZWQxJzAlBgNVBAMTHkNPTU9ETyBDZXJ0aWZpY2F0aW9uIEF1 dGhvcml0eTAeFw0wNjEyMDEwMDAwMDBaFw0yOTEyMzEyMzU5NTlaMIGBMQswCQYDVQQGEwJHQjEb MBkGA1UECBMSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQKExFD T01PRE8gQ0EgTGltaXRlZDEnMCUGA1UEAxMeQ09NT0RPIENlcnRpZmljYXRpb24gQXV0aG9yaXR5 MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0ECLi3LjkRv3UcEbVASY06m/weaKXTuH +7uIzg3jLz8GlvCiKVCZrts7oVewdFFxze1CkU1B/qnI2GqGd0S7WWaXUF601CxwRM/aN5VCaTww xHGzUvAhTaHYujl8HJ6jJJ3ygxaYqhZ8Q5sVW7euNJH+1GImGEaaP+vB+fGQV+useg2L23IwambV 4EajcNxo2f8ESIl33rXp+2dtQem8Ob0y2WIC8bGoPW43nOIv4tOiJovGuFVDiOEjPqXSJDlqR6sA 1KGzqSX+DT+nHbrTUcELpNqsOO9VUCQFZUaTNE8tja3G1CEZ0o7KBWFxB3NH5YoZEr0ETc5OnKVI rLsm9wIDAQABo4GOMIGLMB0GA1UdDgQWBBQLWOWLxkwVN6RAqTCpIb5HNlpW/zAOBgNVHQ8BAf8E BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zBJBgNVHR8EQjBAMD6gPKA6hjhodHRwOi8vY3JsLmNvbW9k b2NhLmNvbS9DT01PRE9DZXJ0aWZpY2F0aW9uQXV0aG9yaXR5LmNybDANBgkqhkiG9w0BAQUFAAOC AQEAPpiem/Yb6dc5t3iuHXIYSdOH5EOC6z/JqvWote9VfCFSZfnVDeFs9D6Mk3ORLgLETgdxb8CP OGEIqB6BCsAvIC9Bi5HcSEW88cbeunZrM8gALTFGTO3nnc+IlP8zwFboJIYmuNg4ON8qa90SzMc/ RxdMosIGlgnW2/4/PEZB31jiVg88O8EckzXZOFKs7sjsLjBOlDW0JB9LeGna8gI4zJVSk/BwJVmc IGfE7vmLV2H0knZ9P4SNVbfo5azV8fUZVqZa+5Acr5Pr5RzUZ5ddBA6+C4OmF4O5MBKgxTMVBbkN +8cFduPYSo38NBejxiEovjBFMR7HeL5YYTisO+IBZQ== -----END CERTIFICATE----- Network Solutions Certificate Authority ======================================= -----BEGIN CERTIFICATE----- MIID5jCCAs6gAwIBAgIQV8szb8JcFuZHFhfjkDFo4DANBgkqhkiG9w0BAQUFADBiMQswCQYDVQQG EwJVUzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMuMTAwLgYDVQQDEydOZXR3b3Jr IFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcNMDYxMjAxMDAwMDAwWhcNMjkxMjMx MjM1OTU5WjBiMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMu MTAwLgYDVQQDEydOZXR3b3JrIFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0G CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDkvH6SMG3G2I4rC7xGzuAnlt7e+foS0zwzc7MEL7xx jOWftiJgPl9dzgn/ggwbmlFQGiaJ3dVhXRncEg8tCqJDXRfQNJIg6nPPOCwGJgl6cvf6UDL4wpPT aaIjzkGxzOTVHzbRijr4jGPiFFlp7Q3Tf2vouAPlT2rlmGNpSAW+Lv8ztumXWWn4Zxmuk2GWRBXT crA/vGp97Eh/jcOrqnErU2lBUzS1sLnFBgrEsEX1QV1uiUV7PTsmjHTC5dLRfbIR1PtYMiKagMnc /Qzpf14Dl847ABSHJ3A4qY5usyd2mFHgBeMhqxrVhSI8KbWaFsWAqPS7azCPL0YCorEMIuDTAgMB AAGjgZcwgZQwHQYDVR0OBBYEFCEwyfsA106Y2oeqKtCnLrFAMadMMA4GA1UdDwEB/wQEAwIBBjAP BgNVHRMBAf8EBTADAQH/MFIGA1UdHwRLMEkwR6BFoEOGQWh0dHA6Ly9jcmwubmV0c29sc3NsLmNv bS9OZXR3b3JrU29sdXRpb25zQ2VydGlmaWNhdGVBdXRob3JpdHkuY3JsMA0GCSqGSIb3DQEBBQUA A4IBAQC7rkvnt1frf6ott3NHhWrB5KUd5Oc86fRZZXe1eltajSU24HqXLjjAV2CDmAaDn7l2em5Q 4LqILPxFzBiwmZVRDuwduIj/h1AcgsLj4DKAv6ALR8jDMe+ZZzKATxcheQxpXN5eNK4CtSbqUN9/ GGUsyfJj4akH/nxxH2szJGoeBfcFaMBqEssuXmHLrijTfsK0ZpEmXzwuJF/LWA/rKOyvEZbz3Htv wKeI8lN3s2Berq4o2jUsbzRF0ybh3uxbTydrFny9RAQYgrOJeRcQcT16ohZO9QHNpGxlaKFJdlxD ydi8NmdspZS11My5vWo1ViHe2MPr+8ukYEywVaCge1ey -----END CERTIFICATE----- WellsSecure Public Root Certificate Authority ============================================= -----BEGIN CERTIFICATE----- MIIEvTCCA6WgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBhTELMAkGA1UEBhMCVVMxIDAeBgNVBAoM F1dlbGxzIEZhcmdvIFdlbGxzU2VjdXJlMRwwGgYDVQQLDBNXZWxscyBGYXJnbyBCYW5rIE5BMTYw NAYDVQQDDC1XZWxsc1NlY3VyZSBQdWJsaWMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcN MDcxMjEzMTcwNzU0WhcNMjIxMjE0MDAwNzU0WjCBhTELMAkGA1UEBhMCVVMxIDAeBgNVBAoMF1dl bGxzIEZhcmdvIFdlbGxzU2VjdXJlMRwwGgYDVQQLDBNXZWxscyBGYXJnbyBCYW5rIE5BMTYwNAYD VQQDDC1XZWxsc1NlY3VyZSBQdWJsaWMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0G CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDub7S9eeKPCCGeOARBJe+rWxxTkqxtnt3CxC5FlAM1 iGd0V+PfjLindo8796jE2yljDpFoNoqXjopxaAkH5OjUDk/41itMpBb570OYj7OeUt9tkTmPOL13 i0Nj67eT/DBMHAGTthP796EfvyXhdDcsHqRePGj4S78NuR4uNuip5Kf4D8uCdXw1LSLWwr8L87T8 bJVhHlfXBIEyg1J55oNjz7fLY4sR4r1e6/aN7ZVyKLSsEmLpSjPmgzKuBXWVvYSV2ypcm44uDLiB K0HmOFafSZtsdvqKXfcBeYF8wYNABf5x/Qw/zE5gCQ5lRxAvAcAFP4/4s0HvWkJ+We/SlwxlAgMB AAGjggE0MIIBMDAPBgNVHRMBAf8EBTADAQH/MDkGA1UdHwQyMDAwLqAsoCqGKGh0dHA6Ly9jcmwu cGtpLndlbGxzZmFyZ28uY29tL3dzcHJjYS5jcmwwDgYDVR0PAQH/BAQDAgHGMB0GA1UdDgQWBBQm lRkQ2eihl5H/3BnZtQQ+0nMKajCBsgYDVR0jBIGqMIGngBQmlRkQ2eihl5H/3BnZtQQ+0nMKaqGB i6SBiDCBhTELMAkGA1UEBhMCVVMxIDAeBgNVBAoMF1dlbGxzIEZhcmdvIFdlbGxzU2VjdXJlMRww GgYDVQQLDBNXZWxscyBGYXJnbyBCYW5rIE5BMTYwNAYDVQQDDC1XZWxsc1NlY3VyZSBQdWJsaWMg Um9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHmCAQEwDQYJKoZIhvcNAQEFBQADggEBALkVsUSRzCPI K0134/iaeycNzXK7mQDKfGYZUMbVmO2rvwNa5U3lHshPcZeG1eMd/ZDJPHV3V3p9+N701NX3leZ0 bh08rnyd2wIDBSxxSyU+B+NemvVmFymIGjifz6pBA4SXa5M4esowRBskRDPQ5NHcKDj0E0M1NSlj qHyita04pO2t/caaH/+Xc/77szWnk4bGdpEA5qxRFsQnMlzbc9qlk1eOPm01JghZ1edE13YgY+es E2fDbbFwRnzVlhE9iW9dqKHrjQrawx0zbKPqZxmamX9LPYNRKh3KL4YMon4QLSvUFpULB6ouFJJJ tylv2G0xffX8oRAHh84vWdw+WNs= -----END CERTIFICATE----- COMODO ECC Certification Authority ================================== -----BEGIN CERTIFICATE----- MIICiTCCAg+gAwIBAgIQH0evqmIAcFBUTAGem2OZKjAKBggqhkjOPQQDAzCBhTELMAkGA1UEBhMC R0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UE ChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBB dXRob3JpdHkwHhcNMDgwMzA2MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0Ix GzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR Q09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRo b3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQDR3svdcmCFYX7deSRFtSrYpn1PlILBs5BAH+X 4QokPB0BBO490o0JlwzgdeT6+3eKKvUDYEs2ixYjFq0JcfRK9ChQtP6IHG4/bC8vCVlbpVsLM5ni wz2J+Wos77LTBumjQjBAMB0GA1UdDgQWBBR1cacZSBm8nZ3qQUfflMRId5nTeTAOBgNVHQ8BAf8E BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjEA7wNbeqy3eApyt4jf/7VG FAkK+qDmfQjGGoe9GKhzvSbKYAydzpmfz1wPMOG+FDHqAjAU9JM8SaczepBGR7NjfRObTrdvGDeA U/7dIOA1mjbRxwG55tzd8/8dLDoWV9mSOdY= -----END CERTIFICATE----- IGC/A ===== -----BEGIN CERTIFICATE----- MIIEAjCCAuqgAwIBAgIFORFFEJQwDQYJKoZIhvcNAQEFBQAwgYUxCzAJBgNVBAYTAkZSMQ8wDQYD VQQIEwZGcmFuY2UxDjAMBgNVBAcTBVBhcmlzMRAwDgYDVQQKEwdQTS9TR0ROMQ4wDAYDVQQLEwVE Q1NTSTEOMAwGA1UEAxMFSUdDL0ExIzAhBgkqhkiG9w0BCQEWFGlnY2FAc2dkbi5wbS5nb3V2LmZy MB4XDTAyMTIxMzE0MjkyM1oXDTIwMTAxNzE0MjkyMlowgYUxCzAJBgNVBAYTAkZSMQ8wDQYDVQQI EwZGcmFuY2UxDjAMBgNVBAcTBVBhcmlzMRAwDgYDVQQKEwdQTS9TR0ROMQ4wDAYDVQQLEwVEQ1NT STEOMAwGA1UEAxMFSUdDL0ExIzAhBgkqhkiG9w0BCQEWFGlnY2FAc2dkbi5wbS5nb3V2LmZyMIIB IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsh/R0GLFMzvABIaIs9z4iPf930Pfeo2aSVz2 TqrMHLmh6yeJ8kbpO0px1R2OLc/mratjUMdUC24SyZA2xtgv2pGqaMVy/hcKshd+ebUyiHDKcMCW So7kVc0dJ5S/znIq7Fz5cyD+vfcuiWe4u0dzEvfRNWk68gq5rv9GQkaiv6GFGvm/5P9JhfejcIYy HF2fYPepraX/z9E0+X1bF8bc1g4oa8Ld8fUzaJ1O/Id8NhLWo4DoQw1VYZTqZDdH6nfK0LJYBcNd frGoRpAxVs5wKpayMLh35nnAvSk7/ZR3TL0gzUEl4C7HG7vupARB0l2tEmqKm0f7yd1GQOGdPDPQ tQIDAQABo3cwdTAPBgNVHRMBAf8EBTADAQH/MAsGA1UdDwQEAwIBRjAVBgNVHSAEDjAMMAoGCCqB egF5AQEBMB0GA1UdDgQWBBSjBS8YYFDCiQrdKyFP/45OqDAxNjAfBgNVHSMEGDAWgBSjBS8YYFDC iQrdKyFP/45OqDAxNjANBgkqhkiG9w0BAQUFAAOCAQEABdwm2Pp3FURo/C9mOnTgXeQp/wYHE4RK q89toB9RlPhJy3Q2FLwV3duJL92PoF189RLrn544pEfMs5bZvpwlqwN+Mw+VgQ39FuCIvjfwbF3Q MZsyK10XZZOYYLxuj7GoPB7ZHPOpJkL5ZB3C55L29B5aqhlSXa/oovdgoPaN8In1buAKBQGVyYsg Crpa/JosPL3Dt8ldeCUFP1YUmwza+zpI/pdpXsoQhvdOlgQITeywvl3cO45Pwf2aNjSaTFR+FwNI lQgRHAdvhQh+XU3Endv7rs6y0bO4g2wdsrN58dhwmX7wEwLOXt1R0982gaEbeC9xs/FZTEYYKKuF 0mBWWg== -----END CERTIFICATE----- Security Communication EV RootCA1 ================================= -----BEGIN CERTIFICATE----- MIIDfTCCAmWgAwIBAgIBADANBgkqhkiG9w0BAQUFADBgMQswCQYDVQQGEwJKUDElMCMGA1UEChMc U0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEqMCgGA1UECxMhU2VjdXJpdHkgQ29tbXVuaWNh dGlvbiBFViBSb290Q0ExMB4XDTA3MDYwNjAyMTIzMloXDTM3MDYwNjAyMTIzMlowYDELMAkGA1UE BhMCSlAxJTAjBgNVBAoTHFNFQ09NIFRydXN0IFN5c3RlbXMgQ08uLExURC4xKjAoBgNVBAsTIVNl Y3VyaXR5IENvbW11bmljYXRpb24gRVYgUm9vdENBMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC AQoCggEBALx/7FebJOD+nLpCeamIivqA4PUHKUPqjgo0No0c+qe1OXj/l3X3L+SqawSERMqm4miO /VVQYg+kcQ7OBzgtQoVQrTyWb4vVog7P3kmJPdZkLjjlHmy1V4qe70gOzXppFodEtZDkBp2uoQSX WHnvIEqCa4wiv+wfD+mEce3xDuS4GBPMVjZd0ZoeUWs5bmB2iDQL87PRsJ3KYeJkHcFGB7hj3R4z ZbOOCVVSPbW9/wfrrWFVGCypaZhKqkDFMxRldAD5kd6vA0jFQFTcD4SQaCDFkpbcLuUCRarAX1T4 bepJz11sS6/vmsJWXMY1VkJqMF/Cq/biPT+zyRGPMUzXn0kCAwEAAaNCMEAwHQYDVR0OBBYEFDVK 9U2vP9eCOKyrcWUXdYydVZPmMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqG SIb3DQEBBQUAA4IBAQCoh+ns+EBnXcPBZsdAS5f8hxOQWsTvoMpfi7ent/HWtWS3irO4G8za+6xm iEHO6Pzk2x6Ipu0nUBsCMCRGef4Eh3CXQHPRwMFXGZpppSeZq51ihPZRwSzJIxXYKLerJRO1RuGG Av8mjMSIkh1W/hln8lXkgKNrnKt34VFxDSDbEJrbvXZ5B3eZKK2aXtqxT0QsNY6llsf9g/BYxnnW mHyojf6GPgcWkuF75x3sM3Z+Qi5KhfmRiWiEA4Glm5q+4zfFVKtWOxgtQaQM+ELbmaDgcm+7XeEW T1MKZPlO9L9OVL14bIjqv5wTJMJwaaJ/D8g8rQjJsJhAoyrniIPtd490 -----END CERTIFICATE----- OISTE WISeKey Global Root GA CA =============================== -----BEGIN CERTIFICATE----- MIID8TCCAtmgAwIBAgIQQT1yx/RrH4FDffHSKFTfmjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UE BhMCQ0gxEDAOBgNVBAoTB1dJU2VLZXkxGzAZBgNVBAsTEkNvcHlyaWdodCAoYykgMjAwNTEiMCAG A1UECxMZT0lTVEUgRm91bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBH bG9iYWwgUm9vdCBHQSBDQTAeFw0wNTEyMTExNjAzNDRaFw0zNzEyMTExNjA5NTFaMIGKMQswCQYD VQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEbMBkGA1UECxMSQ29weXJpZ2h0IChjKSAyMDA1MSIw IAYDVQQLExlPSVNURSBGb3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5 IEdsb2JhbCBSb290IEdBIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy0+zAJs9 Nt350UlqaxBJH+zYK7LG+DKBKUOVTJoZIyEVRd7jyBxRVVuuk+g3/ytr6dTqvirdqFEr12bDYVxg Asj1znJ7O7jyTmUIms2kahnBAbtzptf2w93NvKSLtZlhuAGio9RN1AU9ka34tAhxZK9w8RxrfvbD d50kc3vkDIzh2TbhmYsFmQvtRTEJysIA2/dyoJaqlYfQjse2YXMNdmaM3Bu0Y6Kff5MTMPGhJ9vZ /yxViJGg4E8HsChWjBgbl0SOid3gF27nKu+POQoxhILYQBRJLnpB5Kf+42TMwVlxSywhp1t94B3R LoGbw9ho972WG6xwsRYUC9tguSYBBQIDAQABo1EwTzALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUw AwEB/zAdBgNVHQ4EFgQUswN+rja8sHnR3JQmthG+IbJphpQwEAYJKwYBBAGCNxUBBAMCAQAwDQYJ KoZIhvcNAQEFBQADggEBAEuh/wuHbrP5wUOxSPMowB0uyQlB+pQAHKSkq0lPjz0e701vvbyk9vIm MMkQyh2I+3QZH4VFvbBsUfk2ftv1TDI6QU9bR8/oCy22xBmddMVHxjtqD6wU2zz0c5ypBd8A3HR4 +vg1YFkCExh8vPtNsCBtQ7tgMHpnM1zFmdH4LTlSc/uMqpclXHLZCB6rTjzjgTGfA6b7wP4piFXa hNVQA7bihKOmNqoROgHhGEvWRGizPflTdISzRpFGlgC3gCy24eMQ4tui5yiPAZZiFj4A4xylNoEY okxSdsARo27mHbrjWr42U8U+dY+GaSlYU7Wcu2+fXMUY7N0v4ZjJ/L7fCg0= -----END CERTIFICATE----- Microsec e-Szigno Root CA ========================= -----BEGIN CERTIFICATE----- MIIHqDCCBpCgAwIBAgIRAMy4579OKRr9otxmpRwsDxEwDQYJKoZIhvcNAQEFBQAwcjELMAkGA1UE BhMCSFUxETAPBgNVBAcTCEJ1ZGFwZXN0MRYwFAYDVQQKEw1NaWNyb3NlYyBMdGQuMRQwEgYDVQQL EwtlLVN6aWdubyBDQTEiMCAGA1UEAxMZTWljcm9zZWMgZS1Temlnbm8gUm9vdCBDQTAeFw0wNTA0 MDYxMjI4NDRaFw0xNzA0MDYxMjI4NDRaMHIxCzAJBgNVBAYTAkhVMREwDwYDVQQHEwhCdWRhcGVz dDEWMBQGA1UEChMNTWljcm9zZWMgTHRkLjEUMBIGA1UECxMLZS1Temlnbm8gQ0ExIjAgBgNVBAMT GU1pY3Jvc2VjIGUtU3ppZ25vIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB AQDtyADVgXvNOABHzNuEwSFpLHSQDCHZU4ftPkNEU6+r+ICbPHiN1I2uuO/TEdyB5s87lozWbxXG d36hL+BfkrYn13aaHUM86tnsL+4582pnS4uCzyL4ZVX+LMsvfUh6PXX5qqAnu3jCBspRwn5mS6/N oqdNAoI/gqyFxuEPkEeZlApxcpMqyabAvjxWTHOSJ/FrtfX9/DAFYJLG65Z+AZHCabEeHXtTRbjc QR/Ji3HWVBTji1R4P770Yjtb9aPs1ZJ04nQw7wHb4dSrmZsqa/i9phyGI0Jf7Enemotb9HI6QMVJ PqW+jqpx62z69Rrkav17fVVA71hu5tnVvCSrwe+3AgMBAAGjggQ3MIIEMzBnBggrBgEFBQcBAQRb MFkwKAYIKwYBBQUHMAGGHGh0dHBzOi8vcmNhLmUtc3ppZ25vLmh1L29jc3AwLQYIKwYBBQUHMAKG IWh0dHA6Ly93d3cuZS1zemlnbm8uaHUvUm9vdENBLmNydDAPBgNVHRMBAf8EBTADAQH/MIIBcwYD VR0gBIIBajCCAWYwggFiBgwrBgEEAYGoGAIBAQEwggFQMCgGCCsGAQUFBwIBFhxodHRwOi8vd3d3 LmUtc3ppZ25vLmh1L1NaU1ovMIIBIgYIKwYBBQUHAgIwggEUHoIBEABBACAAdABhAG4A+gBzAO0A dAB2AOEAbgB5ACAA6QByAHQAZQBsAG0AZQB6AOkAcwDpAGgAZQB6ACAA6QBzACAAZQBsAGYAbwBn AGEAZADhAHMA4QBoAG8AegAgAGEAIABTAHoAbwBsAGcA4QBsAHQAYQB0APMAIABTAHoAbwBsAGcA 4QBsAHQAYQB0AOEAcwBpACAAUwB6AGEAYgDhAGwAeQB6AGEAdABhACAAcwB6AGUAcgBpAG4AdAAg AGsAZQBsAGwAIABlAGwAagDhAHIAbgBpADoAIABoAHQAdABwADoALwAvAHcAdwB3AC4AZQAtAHMA egBpAGcAbgBvAC4AaAB1AC8AUwBaAFMAWgAvMIHIBgNVHR8EgcAwgb0wgbqggbeggbSGIWh0dHA6 Ly93d3cuZS1zemlnbm8uaHUvUm9vdENBLmNybIaBjmxkYXA6Ly9sZGFwLmUtc3ppZ25vLmh1L0NO PU1pY3Jvc2VjJTIwZS1Temlnbm8lMjBSb290JTIwQ0EsT1U9ZS1Temlnbm8lMjBDQSxPPU1pY3Jv c2VjJTIwTHRkLixMPUJ1ZGFwZXN0LEM9SFU/Y2VydGlmaWNhdGVSZXZvY2F0aW9uTGlzdDtiaW5h cnkwDgYDVR0PAQH/BAQDAgEGMIGWBgNVHREEgY4wgYuBEGluZm9AZS1zemlnbm8uaHWkdzB1MSMw IQYDVQQDDBpNaWNyb3NlYyBlLVN6aWduw7MgUm9vdCBDQTEWMBQGA1UECwwNZS1TemlnbsOzIEhT WjEWMBQGA1UEChMNTWljcm9zZWMgS2Z0LjERMA8GA1UEBxMIQnVkYXBlc3QxCzAJBgNVBAYTAkhV MIGsBgNVHSMEgaQwgaGAFMegSXUWYYTbMUuE0vE3QJDvTtz3oXakdDByMQswCQYDVQQGEwJIVTER MA8GA1UEBxMIQnVkYXBlc3QxFjAUBgNVBAoTDU1pY3Jvc2VjIEx0ZC4xFDASBgNVBAsTC2UtU3pp Z25vIENBMSIwIAYDVQQDExlNaWNyb3NlYyBlLVN6aWdubyBSb290IENBghEAzLjnv04pGv2i3Gal HCwPETAdBgNVHQ4EFgQUx6BJdRZhhNsxS4TS8TdAkO9O3PcwDQYJKoZIhvcNAQEFBQADggEBANMT nGZjWS7KXHAM/IO8VbH0jgdsZifOwTsgqRy7RlRw7lrMoHfqaEQn6/Ip3Xep1fvj1KcExJW4C+FE aGAHQzAxQmHl7tnlJNUb3+FKG6qfx1/4ehHqE5MAyopYse7tDk2016g2JnzgOsHVV4Lxdbb9iV/a 86g4nzUGCM4ilb7N1fy+W955a9x6qWVmvrElWl/tftOsRm1M9DKHtCAE4Gx4sHfRhUZLphK3dehK yVZs15KrnfVJONJPU+NVkBHbmJbGSfI+9J8b4PeI3CVimUTYc78/MPMMNz7UwiiAc7EBt51alhQB S6kRnSlqLtBdgcDPsiBDxwPgN05dCtxZICU= -----END CERTIFICATE----- Certigna ======== -----BEGIN CERTIFICATE----- MIIDqDCCApCgAwIBAgIJAP7c4wEPyUj/MA0GCSqGSIb3DQEBBQUAMDQxCzAJBgNVBAYTAkZSMRIw EAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hMB4XDTA3MDYyOTE1MTMwNVoXDTI3 MDYyOTE1MTMwNVowNDELMAkGA1UEBhMCRlIxEjAQBgNVBAoMCURoaW15b3RpczERMA8GA1UEAwwI Q2VydGlnbmEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDIaPHJ1tazNHUmgh7stL7q XOEm7RFHYeGifBZ4QCHkYJ5ayGPhxLGWkv8YbWkj4Sti993iNi+RB7lIzw7sebYs5zRLcAglozyH GxnygQcPOJAZ0xH+hrTy0V4eHpbNgGzOOzGTtvKg0KmVEn2lmsxryIRWijOp5yIVUxbwzBfsV1/p ogqYCd7jX5xv3EjjhQsVWqa6n6xI4wmy9/Qy3l40vhx4XUJbzg4ij02Q130yGLMLLGq/jj8UEYkg DncUtT2UCIf3JR7VsmAA7G8qKCVuKj4YYxclPz5EIBb2JsglrgVKtOdjLPOMFlN+XPsRGgjBRmKf Irjxwo1p3Po6WAbfAgMBAAGjgbwwgbkwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUGu3+QTmQ tCRZvgHyUtVF9lo53BEwZAYDVR0jBF0wW4AUGu3+QTmQtCRZvgHyUtVF9lo53BGhOKQ2MDQxCzAJ BgNVBAYTAkZSMRIwEAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hggkA/tzjAQ/J SP8wDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIBAQQEAwIABzANBgkqhkiG9w0BAQUFAAOCAQEA hQMeknH2Qq/ho2Ge6/PAD/Kl1NqV5ta+aDY9fm4fTIrv0Q8hbV6lUmPOEvjvKtpv6zf+EwLHyzs+ ImvaYS5/1HI93TDhHkxAGYwP15zRgzB7mFncfca5DClMoTOi62c6ZYTTluLtdkVwj7Ur3vkj1klu PBS1xp81HlDQwY9qcEQCYsuuHWhBp6pX6FOqB9IG9tUUBguRA3UsbHK1YZWaDYu5Def131TN3ubY 1gkIl2PlwS6wt0QmwCbAr1UwnjvVNioZBPRcHv/PLLf/0P2HQBHVESO7SMAhqaQoLf0V+LBOK/Qw WyH8EZE0vkHve52Xdf+XlcCWWC/qu0bXu+TZLg== -----END CERTIFICATE----- AC Ra\xC3\xADz Certic\xC3\xA1mara S.A. ====================================== -----BEGIN CERTIFICATE----- MIIGZjCCBE6gAwIBAgIPB35Sk3vgFeNX8GmMy+wMMA0GCSqGSIb3DQEBBQUAMHsxCzAJBgNVBAYT AkNPMUcwRQYDVQQKDD5Tb2NpZWRhZCBDYW1lcmFsIGRlIENlcnRpZmljYWNpw7NuIERpZ2l0YWwg LSBDZXJ0aWPDoW1hcmEgUy5BLjEjMCEGA1UEAwwaQUMgUmHDrXogQ2VydGljw6FtYXJhIFMuQS4w HhcNMDYxMTI3MjA0NjI5WhcNMzAwNDAyMjE0MjAyWjB7MQswCQYDVQQGEwJDTzFHMEUGA1UECgw+ U29jaWVkYWQgQ2FtZXJhbCBkZSBDZXJ0aWZpY2FjacOzbiBEaWdpdGFsIC0gQ2VydGljw6FtYXJh IFMuQS4xIzAhBgNVBAMMGkFDIFJhw616IENlcnRpY8OhbWFyYSBTLkEuMIICIjANBgkqhkiG9w0B AQEFAAOCAg8AMIICCgKCAgEAq2uJo1PMSCMI+8PPUZYILrgIem08kBeGqentLhM0R7LQcNzJPNCN yu5LF6vQhbCnIwTLqKL85XXbQMpiiY9QngE9JlsYhBzLfDe3fezTf3MZsGqy2IiKLUV0qPezuMDU 2s0iiXRNWhU5cxh0T7XrmafBHoi0wpOQY5fzp6cSsgkiBzPZkc0OnB8OIMfuuzONj8LSWKdf/WU3 4ojC2I+GdV75LaeHM/J4Ny+LvB2GNzmxlPLYvEqcgxhaBvzz1NS6jBUJJfD5to0EfhcSM2tXSExP 2yYe68yQ54v5aHxwD6Mq0Do43zeX4lvegGHTgNiRg0JaTASJaBE8rF9ogEHMYELODVoqDA+bMMCm 8Ibbq0nXl21Ii/kDwFJnmxL3wvIumGVC2daa49AZMQyth9VXAnow6IYm+48jilSH5L887uvDdUhf HjlvgWJsxS3EF1QZtzeNnDeRyPYL1epjb4OsOMLzP96a++EjYfDIJss2yKHzMI+ko6Kh3VOz3vCa Mh+DkXkwwakfU5tTohVTP92dsxA7SH2JD/ztA/X7JWR1DhcZDY8AFmd5ekD8LVkH2ZD6mq093ICK 5lw1omdMEWux+IBkAC1vImHFrEsm5VoQgpukg3s0956JkSCXjrdCx2bD0Omk1vUgjcTDlaxECp1b czwmPS9KvqfJpxAe+59QafMCAwEAAaOB5jCB4zAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQE AwIBBjAdBgNVHQ4EFgQU0QnQ6dfOeXRU+Tows/RtLAMDG2gwgaAGA1UdIASBmDCBlTCBkgYEVR0g ADCBiTArBggrBgEFBQcCARYfaHR0cDovL3d3dy5jZXJ0aWNhbWFyYS5jb20vZHBjLzBaBggrBgEF BQcCAjBOGkxMaW1pdGFjaW9uZXMgZGUgZ2FyYW507WFzIGRlIGVzdGUgY2VydGlmaWNhZG8gc2Ug cHVlZGVuIGVuY29udHJhciBlbiBsYSBEUEMuMA0GCSqGSIb3DQEBBQUAA4ICAQBclLW4RZFNjmEf AygPU3zmpFmps4p6xbD/CHwso3EcIRNnoZUSQDWDg4902zNc8El2CoFS3UnUmjIz75uny3XlesuX EpBcunvFm9+7OSPI/5jOCk0iAUgHforA1SBClETvv3eiiWdIG0ADBaGJ7M9i4z0ldma/Jre7Ir5v /zlXdLp6yQGVwZVR6Kss+LGGIOk/yzVb0hfpKv6DExdA7ohiZVvVO2Dpezy4ydV/NgIlqmjCMRW3 MGXrfx1IebHPOeJCgBbT9ZMj/EyXyVo3bHwi2ErN0o42gzmRkBDI8ck1fj+404HGIGQatlDCIaR4 3NAvO2STdPCWkPHv+wlaNECW8DYSwaN0jJN+Qd53i+yG2dIPPy3RzECiiWZIHiCznCNZc6lEc7wk eZBWN7PGKX6jD/EpOe9+XCgycDWs2rjIdWb8m0w5R44bb5tNAlQiM+9hup4phO9OSzNHdpdqy35f /RWmnkJDW2ZaiogN9xa5P1FlK2Zqi9E4UqLWRhH6/JocdJ6PlwsCT2TG9WjTSy3/pDceiz+/RL5h RqGEPQgnTIEgd4kI6mdAXmwIUV80WoyWaM3X94nCHNMyAK9Sy9NgWyo6R35rMDOhYil/SrnhLecU Iw4OGEfhefwVVdCx/CVxY3UzHCMrr1zZ7Ud3YA47Dx7SwNxkBYn8eNZcLCZDqQ== -----END CERTIFICATE----- TC TrustCenter Class 2 CA II ============================ -----BEGIN CERTIFICATE----- MIIEqjCCA5KgAwIBAgIOLmoAAQACH9dSISwRXDswDQYJKoZIhvcNAQEFBQAwdjELMAkGA1UEBhMC REUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxIjAgBgNVBAsTGVRDIFRydXN0Q2VudGVy IENsYXNzIDIgQ0ExJTAjBgNVBAMTHFRDIFRydXN0Q2VudGVyIENsYXNzIDIgQ0EgSUkwHhcNMDYw MTEyMTQzODQzWhcNMjUxMjMxMjI1OTU5WjB2MQswCQYDVQQGEwJERTEcMBoGA1UEChMTVEMgVHJ1 c3RDZW50ZXIgR21iSDEiMCAGA1UECxMZVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMiBDQTElMCMGA1UE AxMcVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMiBDQSBJSTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC AQoCggEBAKuAh5uO8MN8h9foJIIRszzdQ2Lu+MNF2ujhoF/RKrLqk2jftMjWQ+nEdVl//OEd+DFw IxuInie5e/060smp6RQvkL4DUsFJzfb95AhmC1eKokKguNV/aVyQMrKXDcpK3EY+AlWJU+MaWss2 xgdW94zPEfRMuzBwBJWl9jmM/XOBCH2JXjIeIqkiRUuwZi4wzJ9l/fzLganx4Duvo4bRierERXlQ Xa7pIXSSTYtZgo+U4+lK8edJsBTj9WLL1XK9H7nSn6DNqPoByNkN39r8R52zyFTfSUrxIan+GE7u SNQZu+995OKdy1u2bv/jzVrndIIFuoAlOMvkaZ6vQaoahPUCAwEAAaOCATQwggEwMA8GA1UdEwEB /wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTjq1RMgKHbVkO3kUrL84J6E1wIqzCB 7QYDVR0fBIHlMIHiMIHfoIHcoIHZhjVodHRwOi8vd3d3LnRydXN0Y2VudGVyLmRlL2NybC92Mi90 Y19jbGFzc18yX2NhX0lJLmNybIaBn2xkYXA6Ly93d3cudHJ1c3RjZW50ZXIuZGUvQ049VEMlMjBU cnVzdENlbnRlciUyMENsYXNzJTIwMiUyMENBJTIwSUksTz1UQyUyMFRydXN0Q2VudGVyJTIwR21i SCxPVT1yb290Y2VydHMsREM9dHJ1c3RjZW50ZXIsREM9ZGU/Y2VydGlmaWNhdGVSZXZvY2F0aW9u TGlzdD9iYXNlPzANBgkqhkiG9w0BAQUFAAOCAQEAjNfffu4bgBCzg/XbEeprS6iSGNn3Bzn1LL4G dXpoUxUc6krtXvwjshOg0wn/9vYua0Fxec3ibf2uWWuFHbhOIprtZjluS5TmVfwLG4t3wVMTZonZ KNaL80VKY7f9ewthXbhtvsPcW3nS7Yblok2+XnR8au0WOB9/WIFaGusyiC2y8zl3gK9etmF1Kdsj TYjKUCjLhdLTEKJZbtOTVAB6okaVhgWcqRmY5TFyDADiZ9lA4CQze28suVyrZZ0srHbqNZn1l7kP JOzHdiEoZa5X6AeIdUpWoNIFOqTmjZKILPPy4cHGYdtBxceb9w4aUUXCYWvcZCcXjFq32nQozZfk vQ== -----END CERTIFICATE----- TC TrustCenter Class 3 CA II ============================ -----BEGIN CERTIFICATE----- MIIEqjCCA5KgAwIBAgIOSkcAAQAC5aBd1j8AUb8wDQYJKoZIhvcNAQEFBQAwdjELMAkGA1UEBhMC REUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxIjAgBgNVBAsTGVRDIFRydXN0Q2VudGVy IENsYXNzIDMgQ0ExJTAjBgNVBAMTHFRDIFRydXN0Q2VudGVyIENsYXNzIDMgQ0EgSUkwHhcNMDYw MTEyMTQ0MTU3WhcNMjUxMjMxMjI1OTU5WjB2MQswCQYDVQQGEwJERTEcMBoGA1UEChMTVEMgVHJ1 c3RDZW50ZXIgR21iSDEiMCAGA1UECxMZVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMyBDQTElMCMGA1UE AxMcVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMyBDQSBJSTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC AQoCggEBALTgu1G7OVyLBMVMeRwjhjEQY0NVJz/GRcekPewJDRoeIMJWHt4bNwcwIi9v8Qbxq63W yKthoy9DxLCyLfzDlml7forkzMA5EpBCYMnMNWju2l+QVl/NHE1bWEnrDgFPZPosPIlY2C8u4rBo 6SI7dYnWRBpl8huXJh0obazovVkdKyT21oQDZogkAHhg8fir/gKya/si+zXmFtGt9i4S5Po1auUZ uV3bOx4a+9P/FRQI2AlqukWdFHlgfa9Aigdzs5OW03Q0jTo3Kd5c7PXuLjHCINy+8U9/I1LZW+Jk 2ZyqBwi1Rb3R0DHBq1SfqdLDYmAD8bs5SpJKPQq5ncWg/jcCAwEAAaOCATQwggEwMA8GA1UdEwEB /wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTUovyfs8PYA9NXXAek0CSnwPIA1DCB 7QYDVR0fBIHlMIHiMIHfoIHcoIHZhjVodHRwOi8vd3d3LnRydXN0Y2VudGVyLmRlL2NybC92Mi90 Y19jbGFzc18zX2NhX0lJLmNybIaBn2xkYXA6Ly93d3cudHJ1c3RjZW50ZXIuZGUvQ049VEMlMjBU cnVzdENlbnRlciUyMENsYXNzJTIwMyUyMENBJTIwSUksTz1UQyUyMFRydXN0Q2VudGVyJTIwR21i SCxPVT1yb290Y2VydHMsREM9dHJ1c3RjZW50ZXIsREM9ZGU/Y2VydGlmaWNhdGVSZXZvY2F0aW9u TGlzdD9iYXNlPzANBgkqhkiG9w0BAQUFAAOCAQEANmDkcPcGIEPZIxpC8vijsrlNirTzwppVMXzE O2eatN9NDoqTSheLG43KieHPOh6sHfGcMrSOWXaiQYUlN6AT0PV8TtXqluJucsG7Kv5sbviRmEb8 yRtXW+rIGjs/sFGYPAfaLFkB2otE6OF0/ado3VS6g0bsyEa1+K+XwDsJHI/OcpY9M1ZwvJbL2NV9 IJqDnxrcOfHFcqMRA/07QlIp2+gB95tejNaNhk4Z+rwcvsUhpYeeeC422wlxo3I0+GzjBgnyXlal 092Y+tTmBvTwtiBjS+opvaqCZh77gaqnN60TGOaSw4HBM7uIHqHn4rS9MWwOUT1v+5ZWgOI2F9Hc 5A== -----END CERTIFICATE----- TC TrustCenter Universal CA I ============================= -----BEGIN CERTIFICATE----- MIID3TCCAsWgAwIBAgIOHaIAAQAC7LdggHiNtgYwDQYJKoZIhvcNAQEFBQAweTELMAkGA1UEBhMC REUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxJDAiBgNVBAsTG1RDIFRydXN0Q2VudGVy IFVuaXZlcnNhbCBDQTEmMCQGA1UEAxMdVEMgVHJ1c3RDZW50ZXIgVW5pdmVyc2FsIENBIEkwHhcN MDYwMzIyMTU1NDI4WhcNMjUxMjMxMjI1OTU5WjB5MQswCQYDVQQGEwJERTEcMBoGA1UEChMTVEMg VHJ1c3RDZW50ZXIgR21iSDEkMCIGA1UECxMbVEMgVHJ1c3RDZW50ZXIgVW5pdmVyc2FsIENBMSYw JAYDVQQDEx1UQyBUcnVzdENlbnRlciBVbml2ZXJzYWwgQ0EgSTCCASIwDQYJKoZIhvcNAQEBBQAD ggEPADCCAQoCggEBAKR3I5ZEr5D0MacQ9CaHnPM42Q9e3s9B6DGtxnSRJJZ4Hgmgm5qVSkr1YnwC qMqs+1oEdjneX/H5s7/zA1hV0qq34wQi0fiU2iIIAI3TfCZdzHd55yx4Oagmcw6iXSVphU9VDprv xrlE4Vc93x9UIuVvZaozhDrzznq+VZeujRIPFDPiUHDDSYcTvFHe15gSWu86gzOSBnWLknwSaHtw ag+1m7Z3W0hZneTvWq3zwZ7U10VOylY0Ibw+F1tvdwxIAUMpsN0/lm7mlaoMwCC2/T42J5zjXM9O gdwZu5GQfezmlwQek8wiSdeXhrYTCjxDI3d+8NzmzSQfO4ObNDqDNOMCAwEAAaNjMGEwHwYDVR0j BBgwFoAUkqR1LKSevoFE63n8isWVpesQdXMwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC AYYwHQYDVR0OBBYEFJKkdSyknr6BROt5/IrFlaXrEHVzMA0GCSqGSIb3DQEBBQUAA4IBAQAo0uCG 1eb4e/CX3CJrO5UUVg8RMKWaTzqwOuAGy2X17caXJ/4l8lfmXpWMPmRgFVp/Lw0BxbFg/UU1z/Cy vwbZ71q+s2IhtNerNXxTPqYn8aEt2hojnczd7Dwtnic0XQ/CNnm8yUpiLe1r2X1BQ3y2qsrtYbE3 ghUJGooWMNjsydZHcnhLEEYUjl8Or+zHL6sQ17bxbuyGssLoDZJz3KL0Dzq/YSMQiZxIQG5wALPT ujdEWBF6AmqI8Dc08BnprNRlc/ZpjGSUOnmFKbAWKwyCPwacx/0QK54PLLae4xW/2TYcuiUaUj0a 7CIMHOCkoj3w6DnPgcB77V0fb8XQC9eY -----END CERTIFICATE----- Deutsche Telekom Root CA 2 ========================== -----BEGIN CERTIFICATE----- MIIDnzCCAoegAwIBAgIBJjANBgkqhkiG9w0BAQUFADBxMQswCQYDVQQGEwJERTEcMBoGA1UEChMT RGV1dHNjaGUgVGVsZWtvbSBBRzEfMB0GA1UECxMWVC1UZWxlU2VjIFRydXN0IENlbnRlcjEjMCEG A1UEAxMaRGV1dHNjaGUgVGVsZWtvbSBSb290IENBIDIwHhcNOTkwNzA5MTIxMTAwWhcNMTkwNzA5 MjM1OTAwWjBxMQswCQYDVQQGEwJERTEcMBoGA1UEChMTRGV1dHNjaGUgVGVsZWtvbSBBRzEfMB0G A1UECxMWVC1UZWxlU2VjIFRydXN0IENlbnRlcjEjMCEGA1UEAxMaRGV1dHNjaGUgVGVsZWtvbSBS b290IENBIDIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCrC6M14IspFLEUha88EOQ5 bzVdSq7d6mGNlUn0b2SjGmBmpKlAIoTZ1KXleJMOaAGtuU1cOs7TuKhCQN/Po7qCWWqSG6wcmtoI KyUn+WkjR/Hg6yx6m/UTAtB+NHzCnjwAWav12gz1MjwrrFDa1sPeg5TKqAyZMg4ISFZbavva4VhY AUlfckE8FQYBjl2tqriTtM2e66foai1SNNs671x1Udrb8zH57nGYMsRUFUQM+ZtV7a3fGAigo4aK Se5TBY8ZTNXeWHmb0mocQqvF1afPaA+W5OFhmHZhyJF81j4A4pFQh+GdCuatl9Idxjp9y7zaAzTV jlsB9WoHtxa2bkp/AgMBAAGjQjBAMB0GA1UdDgQWBBQxw3kbuvVT1xfgiXotF2wKsyudMzAPBgNV HRMECDAGAQH/AgEFMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAlGRZrTlk5ynr E/5aw4sTV8gEJPB0d8Bg42f76Ymmg7+Wgnxu1MM9756AbrsptJh6sTtU6zkXR34ajgv8HzFZMQSy zhfzLMdiNlXiItiJVbSYSKpk+tYcNthEeFpaIzpXl/V6ME+un2pMSyuOoAPjPuCp1NJ70rOo4nI8 rZ7/gFnkm0W09juwzTkZmDLl6iFhkOQxIY40sfcvNUqFENrnijchvllj4PKFiDFT1FQUhXB59C4G dyd1Lx+4ivn+xbrYNuSD7Odlt79jWvNGr4GUN9RBjNYj1h7P9WgbRGOiWrqnNVmh5XAFmw4jV5mU Cm26OWMohpLzGITY+9HPBVZkVw== -----END CERTIFICATE----- ComSign Secured CA ================== -----BEGIN CERTIFICATE----- MIIDqzCCApOgAwIBAgIRAMcoRwmzuGxFjB36JPU2TukwDQYJKoZIhvcNAQEFBQAwPDEbMBkGA1UE AxMSQ29tU2lnbiBTZWN1cmVkIENBMRAwDgYDVQQKEwdDb21TaWduMQswCQYDVQQGEwJJTDAeFw0w NDAzMjQxMTM3MjBaFw0yOTAzMTYxNTA0NTZaMDwxGzAZBgNVBAMTEkNvbVNpZ24gU2VjdXJlZCBD QTEQMA4GA1UEChMHQ29tU2lnbjELMAkGA1UEBhMCSUwwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw ggEKAoIBAQDGtWhfHZQVw6QIVS3joFd67+l0Kru5fFdJGhFeTymHDEjWaueP1H5XJLkGieQcPOqs 49ohgHMhCu95mGwfCP+hUH3ymBvJVG8+pSjsIQQPRbsHPaHA+iqYHU4Gk/v1iDurX8sWv+bznkqH 7Rnqwp9D5PGBpX8QTz7RSmKtUxvLg/8HZaWSLWapW7ha9B20IZFKF3ueMv5WJDmyVIRD9YTC2LxB kMyd1mja6YJQqTtoz7VdApRgFrFD2UNd3V2Hbuq7s8lr9gOUCXDeFhF6K+h2j0kQmHe5Y1yLM5d1 9guMsqtb3nQgJT/j8xH5h2iGNXHDHYwt6+UarA9z1YJZQIDTAgMBAAGjgacwgaQwDAYDVR0TBAUw AwEB/zBEBgNVHR8EPTA7MDmgN6A1hjNodHRwOi8vZmVkaXIuY29tc2lnbi5jby5pbC9jcmwvQ29t U2lnblNlY3VyZWRDQS5jcmwwDgYDVR0PAQH/BAQDAgGGMB8GA1UdIwQYMBaAFMFL7XC29z58ADsA j8c+DkWfHl3sMB0GA1UdDgQWBBTBS+1wtvc+fAA7AI/HPg5Fnx5d7DANBgkqhkiG9w0BAQUFAAOC AQEAFs/ukhNQq3sUnjO2QiBq1BW9Cav8cujvR3qQrFHBZE7piL1DRYHjZiM/EoZNGeQFsOY3wo3a BijJD4mkU6l1P7CW+6tMM1X5eCZGbxs2mPtCdsGCuY7e+0X5YxtiOzkGynd6qDwJz2w2PQ8KRUtp FhpFfTMDZflScZAmlaxMDPWLkz/MdXSFmLr/YnpNH4n+rr2UAJm/EaXc4HnFFgt9AmEd6oX5AhVP 51qJThRv4zdLhfXBPGHg/QVBspJ/wx2g0K5SZGBrGMYmnNj1ZOQ2GmKfig8+/21OGVZOIJFsnzQz OjRXUDpvgV4GxvU+fE6OK85lBi5d0ipTdF7Tbieejw== -----END CERTIFICATE----- Cybertrust Global Root ====================== -----BEGIN CERTIFICATE----- MIIDoTCCAomgAwIBAgILBAAAAAABD4WqLUgwDQYJKoZIhvcNAQEFBQAwOzEYMBYGA1UEChMPQ3li ZXJ0cnVzdCwgSW5jMR8wHQYDVQQDExZDeWJlcnRydXN0IEdsb2JhbCBSb290MB4XDTA2MTIxNTA4 MDAwMFoXDTIxMTIxNTA4MDAwMFowOzEYMBYGA1UEChMPQ3liZXJ0cnVzdCwgSW5jMR8wHQYDVQQD ExZDeWJlcnRydXN0IEdsb2JhbCBSb290MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA +Mi8vRRQZhP/8NN57CPytxrHjoXxEnOmGaoQ25yiZXRadz5RfVb23CO21O1fWLE3TdVJDm71aofW 0ozSJ8bi/zafmGWgE07GKmSb1ZASzxQG9Dvj1Ci+6A74q05IlG2OlTEQXO2iLb3VOm2yHLtgwEZL AfVJrn5GitB0jaEMAs7u/OePuGtm839EAL9mJRQr3RAwHQeWP032a7iPt3sMpTjr3kfb1V05/Iin 89cqdPHoWqI7n1C6poxFNcJQZZXcY4Lv3b93TZxiyWNzFtApD0mpSPCzqrdsxacwOUBdrsTiXSZT 8M4cIwhhqJQZugRiQOwfOHB3EgZxpzAYXSUnpQIDAQABo4GlMIGiMA4GA1UdDwEB/wQEAwIBBjAP BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBS2CHsNesysIEyGVjJez6tuhS1wVzA/BgNVHR8EODA2 MDSgMqAwhi5odHRwOi8vd3d3Mi5wdWJsaWMtdHJ1c3QuY29tL2NybC9jdC9jdHJvb3QuY3JsMB8G A1UdIwQYMBaAFLYIew16zKwgTIZWMl7Pq26FLXBXMA0GCSqGSIb3DQEBBQUAA4IBAQBW7wojoFRO lZfJ+InaRcHUowAl9B8Tq7ejhVhpwjCt2BWKLePJzYFa+HMjWqd8BfP9IjsO0QbE2zZMcwSO5bAi 5MXzLqXZI+O4Tkogp24CJJ8iYGd7ix1yCcUxXOl5n4BHPa2hCwcUPUf/A2kaDAtE52Mlp3+yybh2 hO0j9n0Hq0V+09+zv+mKts2oomcrUtW3ZfA5TGOgkXmTUg9U3YO7n9GPp1Nzw8v/MOx8BLjYRB+T X3EJIrduPuocA06dGiBh+4E37F78CkWr1+cXVdCg6mCbpvbjjFspwgZgFJ0tl0ypkxWdYcQBX0jW WL1WMRJOEcgh4LMRkWXbtKaIOM5V -----END CERTIFICATE----- ePKI Root Certification Authority ================================= -----BEGIN CERTIFICATE----- MIIFsDCCA5igAwIBAgIQFci9ZUdcr7iXAF7kBtK8nTANBgkqhkiG9w0BAQUFADBeMQswCQYDVQQG EwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0ZC4xKjAoBgNVBAsMIWVQS0kg Um9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNDEyMjAwMjMxMjdaFw0zNDEyMjAwMjMx MjdaMF4xCzAJBgNVBAYTAlRXMSMwIQYDVQQKDBpDaHVuZ2h3YSBUZWxlY29tIENvLiwgTHRkLjEq MCgGA1UECwwhZVBLSSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0B AQEFAAOCAg8AMIICCgKCAgEA4SUP7o3biDN1Z82tH306Tm2d0y8U82N0ywEhajfqhFAHSyZbCUNs IZ5qyNUD9WBpj8zwIuQf5/dqIjG3LBXy4P4AakP/h2XGtRrBp0xtInAhijHyl3SJCRImHJ7K2RKi lTza6We/CKBk49ZCt0Xvl/T29de1ShUCWH2YWEtgvM3XDZoTM1PRYfl61dd4s5oz9wCGzh1NlDiv qOx4UXCKXBCDUSH3ET00hl7lSM2XgYI1TBnsZfZrxQWh7kcT1rMhJ5QQCtkkO7q+RBNGMD+XPNjX 12ruOzjjK9SXDrkb5wdJfzcq+Xd4z1TtW0ado4AOkUPB1ltfFLqfpo0kR0BZv3I4sjZsN/+Z0V0O WQqraffAsgRFelQArr5T9rXn4fg8ozHSqf4hUmTFpmfwdQcGlBSBVcYn5AGPF8Fqcde+S/uUWH1+ ETOxQvdibBjWzwloPn9s9h6PYq2lY9sJpx8iQkEeb5mKPtf5P0B6ebClAZLSnT0IFaUQAS2zMnao lQ2zepr7BxB4EW/hj8e6DyUadCrlHJhBmd8hh+iVBmoKs2pHdmX2Os+PYhcZewoozRrSgx4hxyy/ vv9haLdnG7t4TY3OZ+XkwY63I2binZB1NJipNiuKmpS5nezMirH4JYlcWrYvjB9teSSnUmjDhDXi Zo1jDiVN1Rmy5nk3pyKdVDECAwEAAaNqMGgwHQYDVR0OBBYEFB4M97Zn8uGSJglFwFU5Lnc/Qkqi MAwGA1UdEwQFMAMBAf8wOQYEZyoHAAQxMC8wLQIBADAJBgUrDgMCGgUAMAcGBWcqAwAABBRFsMLH ClZ87lt4DJX5GFPBphzYEDANBgkqhkiG9w0BAQUFAAOCAgEACbODU1kBPpVJufGBuvl2ICO1J2B0 1GqZNF5sAFPZn/KmsSQHRGoqxqWOeBLoR9lYGxMqXnmbnwoqZ6YlPwZpVnPDimZI+ymBV3QGypzq KOg4ZyYr8dW1P2WT+DZdjo2NQCCHGervJ8A9tDkPJXtoUHRVnAxZfVo9QZQlUgjgRywVMRnVvwdV xrsStZf0X4OFunHB2WyBEXYKCrC/gpf36j36+uwtqSiUO1bd0lEursC9CBWMd1I0ltabrNMdjmEP NXubrjlpC2JgQCA2j6/7Nu4tCEoduL+bXPjqpRugc6bY+G7gMwRfaKonh+3ZwZCc7b3jajWvY9+r GNm65ulK6lCKD2GTHuItGeIwlDWSXQ62B68ZgI9HkFFLLk3dheLSClIKF5r8GrBQAuUBo2M3IUxE xJtRmREOc5wGj1QupyheRDmHVi03vYVElOEMSyycw5KFNGHLD7ibSkNS/jQ6fbjpKdx2qcgw+BRx gMYeNkh0IkFch4LoGHGLQYlE535YW6i4jRPpp2zDR+2zGp1iro2C6pSe3VkQw63d4k3jMdXH7Ojy sP6SHhYKGvzZ8/gntsm+HbRsZJB/9OTEW9c3rkIO3aQab3yIVMUWbuF6aC74Or8NpDyJO3inTmOD BCEIZ43ygknQW/2xzQ+DhNQ+IIX3Sj0rnP0qCglN6oH4EZw= -----END CERTIFICATE----- T\xc3\x9c\x42\xC4\xB0TAK UEKAE K\xC3\xB6k Sertifika Hizmet Sa\xC4\x9Flay\xc4\xb1\x63\xc4\xb1s\xc4\xb1 - S\xC3\xBCr\xC3\xBCm 3 ============================================================================================================================= -----BEGIN CERTIFICATE----- MIIFFzCCA/+gAwIBAgIBETANBgkqhkiG9w0BAQUFADCCASsxCzAJBgNVBAYTAlRSMRgwFgYDVQQH DA9HZWJ6ZSAtIEtvY2FlbGkxRzBFBgNVBAoMPlTDvHJraXllIEJpbGltc2VsIHZlIFRla25vbG9q aWsgQXJhxZ90xLFybWEgS3VydW11IC0gVMOcQsSwVEFLMUgwRgYDVQQLDD9VbHVzYWwgRWxla3Ry b25payB2ZSBLcmlwdG9sb2ppIEFyYcWfdMSxcm1hIEVuc3RpdMO8c8O8IC0gVUVLQUUxIzAhBgNV BAsMGkthbXUgU2VydGlmaWthc3lvbiBNZXJrZXppMUowSAYDVQQDDEFUw5xCxLBUQUsgVUVLQUUg S8O2ayBTZXJ0aWZpa2EgSGl6bWV0IFNhxJ9sYXnEsWPEsXPEsSAtIFPDvHLDvG0gMzAeFw0wNzA4 MjQxMTM3MDdaFw0xNzA4MjExMTM3MDdaMIIBKzELMAkGA1UEBhMCVFIxGDAWBgNVBAcMD0dlYnpl IC0gS29jYWVsaTFHMEUGA1UECgw+VMO8cmtpeWUgQmlsaW1zZWwgdmUgVGVrbm9sb2ppayBBcmHF n3TEsXJtYSBLdXJ1bXUgLSBUw5xCxLBUQUsxSDBGBgNVBAsMP1VsdXNhbCBFbGVrdHJvbmlrIHZl IEtyaXB0b2xvamkgQXJhxZ90xLFybWEgRW5zdGl0w7xzw7wgLSBVRUtBRTEjMCEGA1UECwwaS2Ft dSBTZXJ0aWZpa2FzeW9uIE1lcmtlemkxSjBIBgNVBAMMQVTDnELEsFRBSyBVRUtBRSBLw7ZrIFNl cnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxIC0gU8O8csO8bSAzMIIBIjANBgkqhkiG9w0B AQEFAAOCAQ8AMIIBCgKCAQEAim1L/xCIOsP2fpTo6iBkcK4hgb46ezzb8R1Sf1n68yJMlaCQvEhO Eav7t7WNeoMojCZG2E6VQIdhn8WebYGHV2yKO7Rm6sxA/OOqbLLLAdsyv9Lrhc+hDVXDWzhXcLh1 xnnRFDDtG1hba+818qEhTsXOfJlfbLm4IpNQp81McGq+agV/E5wrHur+R84EpW+sky58K5+eeROR 6Oqeyjh1jmKwlZMq5d/pXpduIF9fhHpEORlAHLpVK/swsoHvhOPc7Jg4OQOFCKlUAwUp8MmPi+oL hmUZEdPpCSPeaJMDyTYcIW7OjGbxmTDY17PDHfiBLqi9ggtm/oLL4eAagsNAgQIDAQABo0IwQDAd BgNVHQ4EFgQUvYiHyY/2pAoLquvF/pEjnatKijIwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF MAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAB18+kmPNOm3JpIWmgV050vQbTlswyb2zrgxvMTfvCr4 N5EY3ATIZJkrGG2AA1nJrvhY0D7twyOfaTyGOBye79oneNGEN3GKPEs5z35FBtYt2IpNeBLWrcLT y9LQQfMmNkqblWwM7uXRQydmwYj3erMgbOqwaSvHIOgMA8RBBZniP+Rr+KCGgceExh/VS4ESshYh LBOhgLJeDEoTniDYYkCrkOpkSi+sDQESeUWoL4cZaMjihccwsnX5OD+ywJO0a+IDRM5noN+J1q2M dqMTw5RhK2vZbMEHCiIHhWyFJEapvj+LeISCfiQMnf2BN+MlqO02TpUsyZyQ2uypQjyttgI= -----END CERTIFICATE----- Buypass Class 2 CA 1 ==================== -----BEGIN CERTIFICATE----- MIIDUzCCAjugAwIBAgIBATANBgkqhkiG9w0BAQUFADBLMQswCQYDVQQGEwJOTzEdMBsGA1UECgwU QnV5cGFzcyBBUy05ODMxNjMzMjcxHTAbBgNVBAMMFEJ1eXBhc3MgQ2xhc3MgMiBDQSAxMB4XDTA2 MTAxMzEwMjUwOVoXDTE2MTAxMzEwMjUwOVowSzELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBh c3MgQVMtOTgzMTYzMzI3MR0wGwYDVQQDDBRCdXlwYXNzIENsYXNzIDIgQ0EgMTCCASIwDQYJKoZI hvcNAQEBBQADggEPADCCAQoCggEBAIs8B0XY9t/mx8q6jUPFR42wWsE425KEHK8T1A9vNkYgxC7M cXA0ojTTNy7Y3Tp3L8DrKehc0rWpkTSHIln+zNvnma+WwajHQN2lFYxuyHyXA8vmIPLXl18xoS83 0r7uvqmtqEyeIWZDO6i88wmjONVZJMHCR3axiFyCO7srpgTXjAePzdVBHfCuuCkslFJgNJQ72uA4 0Z0zPhX0kzLFANq1KWYOOngPIVJfAuWSeyXTkh4vFZ2B5J2O6O+JzhRMVB0cgRJNcKi+EAUXfh/R uFdV7c27UsKwHnjCTTZoy1YmwVLBvXb3WNVyfh9EdrsAiR0WnVE1703CVu9r4Iw7DekCAwEAAaNC MEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUP42aWYv8e3uco684sDntkHGA1sgwDgYDVR0P AQH/BAQDAgEGMA0GCSqGSIb3DQEBBQUAA4IBAQAVGn4TirnoB6NLJzKyQJHyIdFkhb5jatLPgcIV 1Xp+DCmsNx4cfHZSldq1fyOhKXdlyTKdqC5Wq2B2zha0jX94wNWZUYN/Xtm+DKhQ7SLHrQVMdvvt 7h5HZPb3J31cKA9FxVxiXqaakZG3Uxcu3K1gnZZkOb1naLKuBctN518fV4bVIJwo+28TOPX2EZL2 fZleHwzoq0QkKXJAPTZSr4xYkHPB7GEseaHsh7U/2k3ZIQAw3pDaDtMaSKk+hQsUi4y8QZ5q9w5w wDX3OaJdZtB7WZ+oRxKaJyOkLY4ng5IgodcVf/EuGO70SH8vf/GhGLWhC5SgYiAynB321O+/TIho -----END CERTIFICATE----- Buypass Class 3 CA 1 ==================== -----BEGIN CERTIFICATE----- MIIDUzCCAjugAwIBAgIBAjANBgkqhkiG9w0BAQUFADBLMQswCQYDVQQGEwJOTzEdMBsGA1UECgwU QnV5cGFzcyBBUy05ODMxNjMzMjcxHTAbBgNVBAMMFEJ1eXBhc3MgQ2xhc3MgMyBDQSAxMB4XDTA1 MDUwOTE0MTMwM1oXDTE1MDUwOTE0MTMwM1owSzELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBh c3MgQVMtOTgzMTYzMzI3MR0wGwYDVQQDDBRCdXlwYXNzIENsYXNzIDMgQ0EgMTCCASIwDQYJKoZI hvcNAQEBBQADggEPADCCAQoCggEBAKSO13TZKWTeXx+HgJHqTjnmGcZEC4DVC69TB4sSveZn8AKx ifZgisRbsELRwCGoy+Gb72RRtqfPFfV0gGgEkKBYouZ0plNTVUhjP5JW3SROjvi6K//zNIqeKNc0 n6wv1g/xpC+9UrJJhW05NfBEMJNGJPO251P7vGGvqaMU+8IXF4Rs4HyI+MkcVyzwPX6UvCWThOia AJpFBUJXgPROztmuOfbIUxAMZTpHe2DC1vqRycZxbL2RhzyRhkmr8w+gbCZ2Xhysm3HljbybIR6c 1jh+JIAVMYKWsUnTYjdbiAwKYjT+p0h+mbEwi5A3lRyoH6UsjfRVyNvdWQrCrXig9IsCAwEAAaNC MEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUOBTmyPCppAP0Tj4io1vy1uCtQHQwDgYDVR0P AQH/BAQDAgEGMA0GCSqGSIb3DQEBBQUAA4IBAQABZ6OMySU9E2NdFm/soT4JXJEVKirZgCFPBdy7 pYmrEzMqnji3jG8CcmPHc3ceCQa6Oyh7pEfJYWsICCD8igWKH7y6xsL+z27sEzNxZy5p+qksP2bA EllNC1QCkoS72xLvg3BweMhT+t/Gxv/ciC8HwEmdMldg0/L2mSlf56oBzKwzqBwKu5HEA6BvtjT5 htOzdlSY9EqBs1OdTUDs5XcTRa9bqh/YL0yCe/4qxFi7T/ye/QNlGioOw6UgFpRreaaiErS7GqQj el/wroQk5PMr+4okoyeYZdowdXb8GZHo2+ubPzK/QJcHJrrM85SFSnonk8+QQtS4Wxam58tAA915 -----END CERTIFICATE----- EBG Elektronik Sertifika Hizmet Sa\xC4\x9Flay\xc4\xb1\x63\xc4\xb1s\xc4\xb1 ========================================================================== -----BEGIN CERTIFICATE----- MIIF5zCCA8+gAwIBAgIITK9zQhyOdAIwDQYJKoZIhvcNAQEFBQAwgYAxODA2BgNVBAMML0VCRyBF bGVrdHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMTcwNQYDVQQKDC5FQkcg QmlsacWfaW0gVGVrbm9sb2ppbGVyaSB2ZSBIaXptZXRsZXJpIEEuxZ4uMQswCQYDVQQGEwJUUjAe Fw0wNjA4MTcwMDIxMDlaFw0xNjA4MTQwMDMxMDlaMIGAMTgwNgYDVQQDDC9FQkcgRWxla3Ryb25p ayBTZXJ0aWZpa2EgSGl6bWV0IFNhxJ9sYXnEsWPEsXPEsTE3MDUGA1UECgwuRUJHIEJpbGnFn2lt IFRla25vbG9qaWxlcmkgdmUgSGl6bWV0bGVyaSBBLsWeLjELMAkGA1UEBhMCVFIwggIiMA0GCSqG SIb3DQEBAQUAA4ICDwAwggIKAoICAQDuoIRh0DpqZhAy2DE4f6en5f2h4fuXd7hxlugTlkaDT7by X3JWbhNgpQGR4lvFzVcfd2NR/y8927k/qqk153nQ9dAktiHq6yOU/im/+4mRDGSaBUorzAzu8T2b gmmkTPiab+ci2hC6X5L8GCcKqKpE+i4stPtGmggDg3KriORqcsnlZR9uKg+ds+g75AxuetpX/dfr eYteIAbTdgtsApWjluTLdlHRKJ2hGvxEok3MenaoDT2/F08iiFD9rrbskFBKW5+VQarKD7JK/oCZ TqNGFav4c0JqwmZ2sQomFd2TkuzbqV9UIlKRcF0T6kjsbgNs2d1s/OsNA/+mgxKb8amTD8UmTDGy Y5lhcucqZJnSuOl14nypqZoaqsNW2xCaPINStnuWt6yHd6i58mcLlEOzrz5z+kI2sSXFCjEmN1Zn uqMLfdb3ic1nobc6HmZP9qBVFCVMLDMNpkGMvQQxahByCp0OLna9XvNRiYuoP1Vzv9s6xiQFlpJI qkuNKgPlV5EQ9GooFW5Hd4RcUXSfGenmHmMWOeMRFeNYGkS9y8RsZteEBt8w9DeiQyJ50hBs37vm ExH8nYQKE3vwO9D8owrXieqWfo1IhR5kX9tUoqzVegJ5a9KK8GfaZXINFHDk6Y54jzJ0fFfy1tb0 Nokb+Clsi7n2l9GkLqq+CxnCRelwXQIDAJ3Zo2MwYTAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB /wQEAwIBBjAdBgNVHQ4EFgQU587GT/wWZ5b6SqMHwQSny2re2kcwHwYDVR0jBBgwFoAU587GT/wW Z5b6SqMHwQSny2re2kcwDQYJKoZIhvcNAQEFBQADggIBAJuYml2+8ygjdsZs93/mQJ7ANtyVDR2t FcU22NU57/IeIl6zgrRdu0waypIN30ckHrMk2pGI6YNw3ZPX6bqz3xZaPt7gyPvT/Wwp+BVGoGgm zJNSroIBk5DKd8pNSe/iWtkqvTDOTLKBtjDOWU/aWR1qeqRFsIImgYZ29fUQALjuswnoT4cCB64k XPBfrAowzIpAoHMEwfuJJPaaHFy3PApnNgUIMbOv2AFoKuB4j3TeuFGkjGwgPaL7s9QJ/XvCgKqT bCmYIai7FvOpEl90tYeY8pUm3zTvilORiF0alKM/fCL414i6poyWqD1SNGKfAB5UVUJnxk1Gj7sU RT0KlhaOEKGXmdXTMIXM3rRyt7yKPBgpaP3ccQfuJDlq+u2lrDgv+R4QDgZxGhBM/nV+/x5XOULK 1+EVoVZVWRvRo68R2E7DpSvvkL/A7IITW43WciyTTo9qKd+FPNMN4KIYEsxVL0e3p5sC/kH2iExt 2qkBR4NkJ2IQgtYSe14DHzSpyZH+r11thie3I6p1GMog57AP14kOpmciY/SDQSsGS7tY1dHXt7kQ Y9iJSrSq3RZj9W6+YKH47ejWkE8axsWgKdOnIaj1Wjz3x0miIZpKlVIglnKaZsv30oZDfCK+lvm9 AahH3eU7QPl1K5srRmSGjR70j/sHd9DqSaIcjVIUpgqT -----END CERTIFICATE----- certSIGN ROOT CA ================ -----BEGIN CERTIFICATE----- MIIDODCCAiCgAwIBAgIGIAYFFnACMA0GCSqGSIb3DQEBBQUAMDsxCzAJBgNVBAYTAlJPMREwDwYD VQQKEwhjZXJ0U0lHTjEZMBcGA1UECxMQY2VydFNJR04gUk9PVCBDQTAeFw0wNjA3MDQxNzIwMDRa Fw0zMTA3MDQxNzIwMDRaMDsxCzAJBgNVBAYTAlJPMREwDwYDVQQKEwhjZXJ0U0lHTjEZMBcGA1UE CxMQY2VydFNJR04gUk9PVCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALczuX7I JUqOtdu0KBuqV5Do0SLTZLrTk+jUrIZhQGpgV2hUhE28alQCBf/fm5oqrl0Hj0rDKH/v+yv6efHH rfAQUySQi2bJqIirr1qjAOm+ukbuW3N7LBeCgV5iLKECZbO9xSsAfsT8AzNXDe3i+s5dRdY4zTW2 ssHQnIFKquSyAVwdj1+ZxLGt24gh65AIgoDzMKND5pCCrlUoSe1b16kQOA7+j0xbm0bqQfWwCHTD 0IgztnzXdN/chNFDDnU5oSVAKOp4yw4sLjmdjItuFhwvJoIQ4uNllAoEwF73XVv4EOLQunpL+943 AAAaWyjj0pxzPjKHmKHJUS/X3qwzs08CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8B Af8EBAMCAcYwHQYDVR0OBBYEFOCMm9slSbPxfIbWskKHC9BroNnkMA0GCSqGSIb3DQEBBQUAA4IB AQA+0hyJLjX8+HXd5n9liPRyTMks1zJO890ZeUe9jjtbkw9QSSQTaxQGcu8J06Gh40CEyecYMnQ8 SG4Pn0vU9x7Tk4ZkVJdjclDVVc/6IJMCopvDI5NOFlV2oHB5bc0hH88vLbwZ44gx+FkagQnIl6Z0 x2DEW8xXjrJ1/RsCCdtZb3KTafcxQdaIOL+Hsr0Wefmq5L6IJd1hJyMctTEHBDa0GpC9oHRxUIlt vBTjD4au8as+x6AJzKNI0eDbZOeStc+vckNwi/nDhDwTqn6Sm1dTk/pwwpEOMfmbZ13pljheX7Nz TogVZ96edhBiIL5VaZVDADlN9u6wWk5JRFRYX0KD -----END CERTIFICATE----- CNNIC ROOT ========== -----BEGIN CERTIFICATE----- MIIDVTCCAj2gAwIBAgIESTMAATANBgkqhkiG9w0BAQUFADAyMQswCQYDVQQGEwJDTjEOMAwGA1UE ChMFQ05OSUMxEzARBgNVBAMTCkNOTklDIFJPT1QwHhcNMDcwNDE2MDcwOTE0WhcNMjcwNDE2MDcw OTE0WjAyMQswCQYDVQQGEwJDTjEOMAwGA1UEChMFQ05OSUMxEzARBgNVBAMTCkNOTklDIFJPT1Qw ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDTNfc/c3et6FtzF8LRb+1VvG7q6KR5smzD o+/hn7E7SIX1mlwhIhAsxYLO2uOabjfhhyzcuQxauohV3/2q2x8x6gHx3zkBwRP9SFIhxFXf2tiz VHa6dLG3fdfA6PZZxU3Iva0fFNrfWEQlMhkqx35+jq44sDB7R3IJMfAw28Mbdim7aXZOV/kbZKKT VrdvmW7bCgScEeOAH8tjlBAKqeFkgjH5jCftppkA9nCTGPihNIaj3XrCGHn2emU1z5DrvTOTn1Or czvmmzQgLx3vqR1jGqCA2wMv+SYahtKNu6m+UjqHZ0gNv7Sg2Ca+I19zN38m5pIEo3/PIKe38zrK y5nLAgMBAAGjczBxMBEGCWCGSAGG+EIBAQQEAwIABzAfBgNVHSMEGDAWgBRl8jGtKvf33VKWCscC wQ7vptU7ETAPBgNVHRMBAf8EBTADAQH/MAsGA1UdDwQEAwIB/jAdBgNVHQ4EFgQUZfIxrSr3991S lgrHAsEO76bVOxEwDQYJKoZIhvcNAQEFBQADggEBAEs17szkrr/Dbq2flTtLP1se31cpolnKOOK5 Gv+e5m4y3R6u6jW39ZORTtpC4cMXYFDy0VwmuYK36m3knITnA3kXr5g9lNvHugDnuL8BV8F3RTIM O/G0HAiw/VGgod2aHRM2mm23xzy54cXZF/qD1T0VoDy7HgviyJA/qIYM/PmLXoXLT1tLYhFHxUV8 BS9BsZ4QaRuZluBVeftOhpm4lNqGOGqTo+fLbuXf6iFViZx9fX+Y9QCJ7uOEwFyWtcVG6kbghVW2 G8kS1sHNzYDzAgE8yGnLRUhj2JTQ7IUOO04RZfSCjKY9ri4ilAnIXOo8gV0WKgOXFlUJ24pBgp5m mxE= -----END CERTIFICATE----- ApplicationCA - Japanese Government =================================== -----BEGIN CERTIFICATE----- MIIDoDCCAoigAwIBAgIBMTANBgkqhkiG9w0BAQUFADBDMQswCQYDVQQGEwJKUDEcMBoGA1UEChMT SmFwYW5lc2UgR292ZXJubWVudDEWMBQGA1UECxMNQXBwbGljYXRpb25DQTAeFw0wNzEyMTIxNTAw MDBaFw0xNzEyMTIxNTAwMDBaMEMxCzAJBgNVBAYTAkpQMRwwGgYDVQQKExNKYXBhbmVzZSBHb3Zl cm5tZW50MRYwFAYDVQQLEw1BcHBsaWNhdGlvbkNBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB CgKCAQEAp23gdE6Hj6UG3mii24aZS2QNcfAKBZuOquHMLtJqO8F6tJdhjYq+xpqcBrSGUeQ3DnR4 fl+Kf5Sk10cI/VBaVuRorChzoHvpfxiSQE8tnfWuREhzNgaeZCw7NCPbXCbkcXmP1G55IrmTwcrN wVbtiGrXoDkhBFcsovW8R0FPXjQilbUfKW1eSvNNcr5BViCH/OlQR9cwFO5cjFW6WY2H/CPek9AE jP3vbb3QesmlOmpyM8ZKDQUXKi17safY1vC+9D/qDihtQWEjdnjDuGWk81quzMKq2edY3rZ+nYVu nyoKb58DKTCXKB28t89UKU5RMfkntigm/qJj5kEW8DOYRwIDAQABo4GeMIGbMB0GA1UdDgQWBBRU WssmP3HMlEYNllPqa0jQk/5CdTAOBgNVHQ8BAf8EBAMCAQYwWQYDVR0RBFIwUKROMEwxCzAJBgNV BAYTAkpQMRgwFgYDVQQKDA/ml6XmnKzlm73mlL/lupwxIzAhBgNVBAsMGuOCouODl+ODquOCseOD vOOCt+ODp+ODs0NBMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADlqRHZ3ODrs o2dGD/mLBqj7apAxzn7s2tGJfHrrLgy9mTLnsCTWw//1sogJhyzjVOGjprIIC8CFqMjSnHH2HZ9g /DgzE+Ge3Atf2hZQKXsvcJEPmbo0NI2VdMV+eKlmXb3KIXdCEKxmJj3ekav9FfBv7WxfEPjzFvYD io+nEhEMy/0/ecGc/WLuo89UDNErXxc+4z6/wCs+CZv+iKZ+tJIX/COUgb1up8WMwusRRdv4QcmW dupwX3kSa+SjB1oF7ydJzyGfikwJcGapJsErEU4z0g781mzSDjJkaP+tBXhfAx2o45CsJOAPQKdL rosot4LKGAfmt1t06SAZf7IbiVQ= -----END CERTIFICATE----- GeoTrust Primary Certification Authority - G3 ============================================= -----BEGIN CERTIFICATE----- MIID/jCCAuagAwIBAgIQFaxulBmyeUtB9iepwxgPHzANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UE BhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsTMChjKSAyMDA4IEdlb1RydXN0 IEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTE2MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFy eSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEczMB4XDTA4MDQwMjAwMDAwMFoXDTM3MTIwMTIz NTk1OVowgZgxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAo YykgMjAwOCBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0BgNVBAMT LUdlb1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzCCASIwDQYJKoZI hvcNAQEBBQADggEPADCCAQoCggEBANziXmJYHTNXOTIz+uvLh4yn1ErdBojqZI4xmKU4kB6Yzy5j K/BGvESyiaHAKAxJcCGVn2TAppMSAmUmhsalifD614SgcK9PGpc/BkTVyetyEH3kMSj7HGHmKAdE c5IiaacDiGydY8hS2pgn5whMcD60yRLBxWeDXTPzAxHsatBT4tG6NmCUgLthY2xbF37fQJQeqw3C IShwiP/WJmxsYAQlTlV+fe+/lEjetx3dcI0FX4ilm/LC7urRQEFtYjgdVgbFA0dRIBn8exALDmKu dlW/X3e+PkkBUz2YJQN2JFodtNuJ6nnltrM7P7pMKEF/BqxqjsHQ9gUdfeZChuOl1UcCAwEAAaNC MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMR5yo6hTgMdHNxr 2zFblD4/MH8tMA0GCSqGSIb3DQEBCwUAA4IBAQAtxRPPVoB7eni9n64smefv2t+UXglpp+duaIy9 cr5HqQ6XErhK8WTTOd8lNNTBzU6B8A8ExCSzNJbGpqow32hhc9f5joWJ7w5elShKKiePEI4ufIbE Ap7aDHdlDkQNkv39sxY2+hENHYwOB4lqKVb3cvTdFZx3NWZXqxNT2I7BQMXXExZacse3aQHEerGD AWh9jUGhlBjBJVz88P6DAod8DQ3PLghcSkANPuyBYeYk28rgDi0Hsj5W3I31QYUHSJsMC8tJP33s t/3LjWeJGqvtux6jAAgIFyqCXDFdRootD4abdNlF+9RAsXqqaC2Gspki4cErx5z481+oghLrGREt -----END CERTIFICATE----- thawte Primary Root CA - G2 =========================== -----BEGIN CERTIFICATE----- MIICiDCCAg2gAwIBAgIQNfwmXNmET8k9Jj1Xm67XVjAKBggqhkjOPQQDAzCBhDELMAkGA1UEBhMC VVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjE4MDYGA1UECxMvKGMpIDIwMDcgdGhhd3RlLCBJbmMu IC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxJDAiBgNVBAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3Qg Q0EgLSBHMjAeFw0wNzExMDUwMDAwMDBaFw0zODAxMTgyMzU5NTlaMIGEMQswCQYDVQQGEwJVUzEV MBMGA1UEChMMdGhhd3RlLCBJbmMuMTgwNgYDVQQLEy8oYykgMjAwNyB0aGF3dGUsIEluYy4gLSBG b3IgYXV0aG9yaXplZCB1c2Ugb25seTEkMCIGA1UEAxMbdGhhd3RlIFByaW1hcnkgUm9vdCBDQSAt IEcyMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEotWcgnuVnfFSeIf+iha/BebfowJPDQfGAFG6DAJS LSKkQjnE/o/qycG+1E3/n3qe4rF8mq2nhglzh9HnmuN6papu+7qzcMBniKI11KOasf2twu8x+qi5 8/sIxpHR+ymVo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQU mtgAMADna3+FGO6Lts6KDPgR4bswCgYIKoZIzj0EAwMDaQAwZgIxAN344FdHW6fmCsO99YCKlzUN G4k8VIZ3KMqh9HneteY4sPBlcIx/AlTCv//YoT7ZzwIxAMSNlPzcU9LcnXgWHxUzI1NS41oxXZ3K rr0TKUQNJ1uo52icEvdYPy5yAlejj6EULg== -----END CERTIFICATE----- thawte Primary Root CA - G3 =========================== -----BEGIN CERTIFICATE----- MIIEKjCCAxKgAwIBAgIQYAGXt0an6rS0mtZLL/eQ+zANBgkqhkiG9w0BAQsFADCBrjELMAkGA1UE BhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2 aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIwMDggdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhv cml6ZWQgdXNlIG9ubHkxJDAiBgNVBAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EgLSBHMzAeFw0w ODA0MDIwMDAwMDBaFw0zNzEyMDEyMzU5NTlaMIGuMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhh d3RlLCBJbmMuMSgwJgYDVQQLEx9DZXJ0aWZpY2F0aW9uIFNlcnZpY2VzIERpdmlzaW9uMTgwNgYD VQQLEy8oYykgMjAwOCB0aGF3dGUsIEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTEkMCIG A1UEAxMbdGhhd3RlIFByaW1hcnkgUm9vdCBDQSAtIEczMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A MIIBCgKCAQEAsr8nLPvb2FvdeHsbnndmgcs+vHyu86YnmjSjaDFxODNi5PNxZnmxqWWjpYvVj2At P0LMqmsywCPLLEHd5N/8YZzic7IilRFDGF/Eth9XbAoFWCLINkw6fKXRz4aviKdEAhN0cXMKQlkC +BsUa0Lfb1+6a4KinVvnSr0eAXLbS3ToO39/fR8EtCab4LRarEc9VbjXsCZSKAExQGbY2SS99irY 7CFJXJv2eul/VTV+lmuNk5Mny5K76qxAwJ/C+IDPXfRa3M50hqY+bAtTyr2SzhkGcuYMXDhpxwTW vGzOW/b3aJzcJRVIiKHpqfiYnODz1TEoYRFsZ5aNOZnLwkUkOQIDAQABo0IwQDAPBgNVHRMBAf8E BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUrWyqlGCc7eT/+j4KdCtjA/e2Wb8wDQYJ KoZIhvcNAQELBQADggEBABpA2JVlrAmSicY59BDlqQ5mU1143vokkbvnRFHfxhY0Cu9qRFHqKweK A3rD6z8KLFIWoCtDuSWQP3CpMyVtRRooOyfPqsMpQhvfO0zAMzRbQYi/aytlryjvsvXDqmbOe1bu t8jLZ8HJnBoYuMTDSQPxYA5QzUbF83d597YV4Djbxy8ooAw/dyZ02SUS2jHaGh7cKUGRIjxpp7sC 8rZcJwOJ9Abqm+RyguOhCcHpABnTPtRwa7pxpqpYrvS76Wy274fMm7v/OeZWYdMKp8RcTGB7BXcm er/YB1IsYvdwY9k5vG8cwnncdimvzsUsZAReiDZuMdRAGmI0Nj81Aa6sY6A= -----END CERTIFICATE----- GeoTrust Primary Certification Authority - G2 ============================================= -----BEGIN CERTIFICATE----- MIICrjCCAjWgAwIBAgIQPLL0SAoA4v7rJDteYD7DazAKBggqhkjOPQQDAzCBmDELMAkGA1UEBhMC VVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsTMChjKSAyMDA3IEdlb1RydXN0IElu Yy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTE2MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFyeSBD ZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMB4XDTA3MTEwNTAwMDAwMFoXDTM4MDExODIzNTk1 OVowgZgxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAoYykg MjAwNyBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0BgNVBAMTLUdl b1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMjB2MBAGByqGSM49AgEG BSuBBAAiA2IABBWx6P0DFUPlrOuHNxFi79KDNlJ9RVcLSo17VDs6bl8VAsBQps8lL33KSLjHUGMc KiEIfJo22Av+0SbFWDEwKCXzXV2juLaltJLtbCyf691DiaI8S0iRHVDsJt/WYC69IaNCMEAwDwYD VR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFBVfNVdRVfslsq0DafwBo/q+ EVXVMAoGCCqGSM49BAMDA2cAMGQCMGSWWaboCd6LuvpaiIjwH5HTRqjySkwCY/tsXzjbLkGTqQ7m ndwxHLKgpxgceeHHNgIwOlavmnRs9vuD4DPTCF+hnMJbn0bWtsuRBmOiBuczrD6ogRLQy7rQkgu2 npaqBA+K -----END CERTIFICATE----- VeriSign Universal Root Certification Authority =============================================== -----BEGIN CERTIFICATE----- MIIEuTCCA6GgAwIBAgIQQBrEZCGzEyEDDrvkEhrFHTANBgkqhkiG9w0BAQsFADCBvTELMAkGA1UE BhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBO ZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwOCBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVk IHVzZSBvbmx5MTgwNgYDVQQDEy9WZXJpU2lnbiBVbml2ZXJzYWwgUm9vdCBDZXJ0aWZpY2F0aW9u IEF1dGhvcml0eTAeFw0wODA0MDIwMDAwMDBaFw0zNzEyMDEyMzU5NTlaMIG9MQswCQYDVQQGEwJV UzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv cmsxOjA4BgNVBAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl IG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNhbCBSb290IENlcnRpZmljYXRpb24gQXV0 aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx2E3XrEBNNti1xWb/1hajCMj 1mCOkdeQmIN65lgZOIzF9uVkhbSicfvtvbnazU0AtMgtc6XHaXGVHzk8skQHnOgO+k1KxCHfKWGP MiJhgsWHH26MfF8WIFFE0XBPV+rjHOPMee5Y2A7Cs0WTwCznmhcrewA3ekEzeOEz4vMQGn+HLL72 9fdC4uW/h2KJXwBL38Xd5HVEMkE6HnFuacsLdUYI0crSK5XQz/u5QGtkjFdN/BMReYTtXlT2NJ8I AfMQJQYXStrxHXpma5hgZqTZ79IugvHw7wnqRMkVauIDbjPTrJ9VAMf2CGqUuV/c4DPxhGD5WycR tPwW8rtWaoAljQIDAQABo4GyMIGvMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMG0G CCsGAQUFBwEMBGEwX6FdoFswWTBXMFUWCWltYWdlL2dpZjAhMB8wBwYFKw4DAhoEFI/l0xqGrI2O a8PPgGrUSBgsexkuMCUWI2h0dHA6Ly9sb2dvLnZlcmlzaWduLmNvbS92c2xvZ28uZ2lmMB0GA1Ud DgQWBBS2d/ppSEefUxLVwuoHMnYH0ZcHGTANBgkqhkiG9w0BAQsFAAOCAQEASvj4sAPmLGd75JR3 Y8xuTPl9Dg3cyLk1uXBPY/ok+myDjEedO2Pzmvl2MpWRsXe8rJq+seQxIcaBlVZaDrHC1LGmWazx Y8u4TB1ZkErvkBYoH1quEPuBUDgMbMzxPcP1Y+Oz4yHJJDnp/RVmRvQbEdBNc6N9Rvk97ahfYtTx P/jgdFcrGJ2BtMQo2pSXpXDrrB2+BxHw1dvd5Yzw1TKwg+ZX4o+/vqGqvz0dtdQ46tewXDpPaj+P wGZsY6rp2aQW9IHRlRQOfc2VNNnSj3BzgXucfr2YYdhFh5iQxeuGMMY1v/D/w1WIg0vvBZIGcfK4 mJO37M2CYfE45k+XmCpajQ== -----END CERTIFICATE----- VeriSign Class 3 Public Primary Certification Authority - G4 ============================================================ -----BEGIN CERTIFICATE----- MIIDhDCCAwqgAwIBAgIQL4D+I4wOIg9IZxIokYesszAKBggqhkjOPQQDAzCByjELMAkGA1UEBhMC VVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3 b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVz ZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmlj YXRpb24gQXV0aG9yaXR5IC0gRzQwHhcNMDcxMTA1MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCByjEL MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBU cnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRo b3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5 IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzQwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAASnVnp8 Utpkmw4tXNherJI9/gHmGUo9FANL+mAnINmDiWn6VMaaGF5VKmTeBvaNSjutEDxlPZCIBIngMGGz rl0Bp3vefLK+ymVhAIau2o970ImtTR1ZmkGxvEeA3J5iw/mjgbIwga8wDwYDVR0TAQH/BAUwAwEB /zAOBgNVHQ8BAf8EBAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEw HzAHBgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVyaXNpZ24u Y29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFLMWkf3upm7ktS5Jj4d4gYDs5bG1MAoGCCqGSM49BAMD A2gAMGUCMGYhDBgmYFo4e1ZC4Kf8NoRRkSAsdk1DPcQdhCPQrNZ8NQbOzWm9kA3bbEhCHQ6qQgIx AJw9SDkjOVgaFRJZap7v1VmyHVIsmXHNxynfGyphe3HR3vPA5Q06Sqotp9iGKt0uEA== -----END CERTIFICATE----- NetLock Arany (Class Gold) Főtanúsítvány ============================================ -----BEGIN CERTIFICATE----- MIIEFTCCAv2gAwIBAgIGSUEs5AAQMA0GCSqGSIb3DQEBCwUAMIGnMQswCQYDVQQGEwJIVTERMA8G A1UEBwwIQnVkYXBlc3QxFTATBgNVBAoMDE5ldExvY2sgS2Z0LjE3MDUGA1UECwwuVGFuw7pzw610 dsOhbnlraWFkw7NrIChDZXJ0aWZpY2F0aW9uIFNlcnZpY2VzKTE1MDMGA1UEAwwsTmV0TG9jayBB cmFueSAoQ2xhc3MgR29sZCkgRsWRdGFuw7pzw610dsOhbnkwHhcNMDgxMjExMTUwODIxWhcNMjgx MjA2MTUwODIxWjCBpzELMAkGA1UEBhMCSFUxETAPBgNVBAcMCEJ1ZGFwZXN0MRUwEwYDVQQKDAxO ZXRMb2NrIEtmdC4xNzA1BgNVBAsMLlRhbsO6c8OtdHbDoW55a2lhZMOzayAoQ2VydGlmaWNhdGlv biBTZXJ2aWNlcykxNTAzBgNVBAMMLE5ldExvY2sgQXJhbnkgKENsYXNzIEdvbGQpIEbFkXRhbsO6 c8OtdHbDoW55MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxCRec75LbRTDofTjl5Bu 0jBFHjzuZ9lk4BqKf8owyoPjIMHj9DrTlF8afFttvzBPhCf2nx9JvMaZCpDyD/V/Q4Q3Y1GLeqVw /HpYzY6b7cNGbIRwXdrzAZAj/E4wqX7hJ2Pn7WQ8oLjJM2P+FpD/sLj916jAwJRDC7bVWaaeVtAk H3B5r9s5VA1lddkVQZQBr17s9o3x/61k/iCa11zr/qYfCGSji3ZVrR47KGAuhyXoqq8fxmRGILdw fzzeSNuWU7c5d+Qa4scWhHaXWy+7GRWF+GmF9ZmnqfI0p6m2pgP8b4Y9VHx2BJtr+UBdADTHLpl1 neWIA6pN+APSQnbAGwIDAKiLo0UwQzASBgNVHRMBAf8ECDAGAQH/AgEEMA4GA1UdDwEB/wQEAwIB BjAdBgNVHQ4EFgQUzPpnk/C2uNClwB7zU/2MU9+D15YwDQYJKoZIhvcNAQELBQADggEBAKt/7hwW qZw8UQCgwBEIBaeZ5m8BiFRhbvG5GK1Krf6BQCOUL/t1fC8oS2IkgYIL9WHxHG64YTjrgfpioTta YtOUZcTh5m2C+C8lcLIhJsFyUR+MLMOEkMNaj7rP9KdlpeuY0fsFskZ1FSNqb4VjMIDw1Z4fKRzC bLBQWV2QWzuoDTDPv31/zvGdg73JRm4gpvlhUbohL3u+pRVjodSVh/GeufOJ8z2FuLjbvrW5Kfna NwUASZQDhETnv0Mxz3WLJdH0pmT1kvarBes96aULNmLazAZfNou2XjG4Kvte9nHfRCaexOYNkbQu dZWAUWpLMKawYqGT8ZvYzsRjdT9ZR7E= -----END CERTIFICATE----- Staat der Nederlanden Root CA - G2 ================================== -----BEGIN CERTIFICATE----- MIIFyjCCA7KgAwIBAgIEAJiWjDANBgkqhkiG9w0BAQsFADBaMQswCQYDVQQGEwJOTDEeMBwGA1UE CgwVU3RhYXQgZGVyIE5lZGVybGFuZGVuMSswKQYDVQQDDCJTdGFhdCBkZXIgTmVkZXJsYW5kZW4g Um9vdCBDQSAtIEcyMB4XDTA4MDMyNjExMTgxN1oXDTIwMDMyNTExMDMxMFowWjELMAkGA1UEBhMC TkwxHjAcBgNVBAoMFVN0YWF0IGRlciBOZWRlcmxhbmRlbjErMCkGA1UEAwwiU3RhYXQgZGVyIE5l ZGVybGFuZGVuIFJvb3QgQ0EgLSBHMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMVZ 5291qj5LnLW4rJ4L5PnZyqtdj7U5EILXr1HgO+EASGrP2uEGQxGZqhQlEq0i6ABtQ8SpuOUfiUtn vWFI7/3S4GCI5bkYYCjDdyutsDeqN95kWSpGV+RLufg3fNU254DBtvPUZ5uW6M7XxgpT0GtJlvOj CwV3SPcl5XCsMBQgJeN/dVrlSPhOewMHBPqCYYdu8DvEpMfQ9XQ+pV0aCPKbJdL2rAQmPlU6Yiil e7Iwr/g3wtG61jj99O9JMDeZJiFIhQGp5Rbn3JBV3w/oOM2ZNyFPXfUib2rFEhZgF1XyZWampzCR OME4HYYEhLoaJXhena/MUGDWE4dS7WMfbWV9whUYdMrhfmQpjHLYFhN9C0lK8SgbIHRrxT3dsKpI CT0ugpTNGmXZK4iambwYfp/ufWZ8Pr2UuIHOzZgweMFvZ9C+X+Bo7d7iscksWXiSqt8rYGPy5V65 48r6f1CGPqI0GAwJaCgRHOThuVw+R7oyPxjMW4T182t0xHJ04eOLoEq9jWYv6q012iDTiIJh8BIi trzQ1aTsr1SIJSQ8p22xcik/Plemf1WvbibG/ufMQFxRRIEKeN5KzlW/HdXZt1bv8Hb/C3m1r737 qWmRRpdogBQ2HbN/uymYNqUg+oJgYjOk7Na6B6duxc8UpufWkjTYgfX8HV2qXB72o007uPc5AgMB AAGjgZcwgZQwDwYDVR0TAQH/BAUwAwEB/zBSBgNVHSAESzBJMEcGBFUdIAAwPzA9BggrBgEFBQcC ARYxaHR0cDovL3d3dy5wa2lvdmVyaGVpZC5ubC9wb2xpY2llcy9yb290LXBvbGljeS1HMjAOBgNV HQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJFoMocVHYnitfGsNig0jQt8YojrMA0GCSqGSIb3DQEBCwUA A4ICAQCoQUpnKpKBglBu4dfYszk78wIVCVBR7y29JHuIhjv5tLySCZa59sCrI2AGeYwRTlHSeYAz +51IvuxBQ4EffkdAHOV6CMqqi3WtFMTC6GY8ggen5ieCWxjmD27ZUD6KQhgpxrRW/FYQoAUXvQwj f/ST7ZwaUb7dRUG/kSS0H4zpX897IZmflZ85OkYcbPnNe5yQzSipx6lVu6xiNGI1E0sUOlWDuYaN kqbG9AclVMwWVxJKgnjIFNkXgiYtXSAfea7+1HAWFpWD2DU5/1JddRwWxRNVz0fMdWVSSt7wsKfk CpYL+63C4iWEst3kvX5ZbJvw8NjnyvLplzh+ib7M+zkXYT9y2zqR2GUBGR2tUKRXCnxLvJxxcypF URmFzI79R6d0lR2o0a9OF7FpJsKqeFdbxU2n5Z4FF5TKsl+gSRiNNOkmbEgeqmiSBeGCc1qb3Adb CG19ndeNIdn8FCCqwkXfP+cAslHkwvgFuXkajDTznlvkN1trSt8sV4pAWja63XVECDdCcAz+3F4h oKOKwJCcaNpQ5kUQR3i2TtJlycM33+FCY7BXN0Ute4qcvwXqZVUz9zkQxSgqIXobisQk+T8VyJoV IPVVYpbtbZNQvOSqeK3Zywplh6ZmwcSBo3c6WB4L7oOLnR7SUqTMHW+wmG2UMbX4cQrcufx9MmDm 66+KAQ== -----END CERTIFICATE----- CA Disig ======== -----BEGIN CERTIFICATE----- MIIEDzCCAvegAwIBAgIBATANBgkqhkiG9w0BAQUFADBKMQswCQYDVQQGEwJTSzETMBEGA1UEBxMK QnJhdGlzbGF2YTETMBEGA1UEChMKRGlzaWcgYS5zLjERMA8GA1UEAxMIQ0EgRGlzaWcwHhcNMDYw MzIyMDEzOTM0WhcNMTYwMzIyMDEzOTM0WjBKMQswCQYDVQQGEwJTSzETMBEGA1UEBxMKQnJhdGlz bGF2YTETMBEGA1UEChMKRGlzaWcgYS5zLjERMA8GA1UEAxMIQ0EgRGlzaWcwggEiMA0GCSqGSIb3 DQEBAQUAA4IBDwAwggEKAoIBAQCS9jHBfYj9mQGp2HvycXXxMcbzdWb6UShGhJd4NLxs/LxFWYgm GErENx+hSkS943EE9UQX4j/8SFhvXJ56CbpRNyIjZkMhsDxkovhqFQ4/61HhVKndBpnXmjxUizkD Pw/Fzsbrg3ICqB9x8y34dQjbYkzo+s7552oftms1grrijxaSfQUMbEYDXcDtab86wYqg6I7ZuUUo hwjstMoVvoLdtUSLLa2GDGhibYVW8qwUYzrG0ZmsNHhWS8+2rT+MitcE5eN4TPWGqvWP+j1scaMt ymfraHtuM6kMgiioTGohQBUgDCZbg8KpFhXAJIJdKxatymP2dACw30PEEGBWZ2NFAgMBAAGjgf8w gfwwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUjbJJaJ1yCCW5wCf1UJNWSEZx+Y8wDgYDVR0P AQH/BAQDAgEGMDYGA1UdEQQvMC2BE2Nhb3BlcmF0b3JAZGlzaWcuc2uGFmh0dHA6Ly93d3cuZGlz aWcuc2svY2EwZgYDVR0fBF8wXTAtoCugKYYnaHR0cDovL3d3dy5kaXNpZy5zay9jYS9jcmwvY2Ff ZGlzaWcuY3JsMCygKqAohiZodHRwOi8vY2EuZGlzaWcuc2svY2EvY3JsL2NhX2Rpc2lnLmNybDAa BgNVHSAEEzARMA8GDSuBHpGT5goAAAABAQEwDQYJKoZIhvcNAQEFBQADggEBAF00dGFMrzvY/59t WDYcPQuBDRIrRhCA/ec8J9B6yKm2fnQwM6M6int0wHl5QpNt/7EpFIKrIYwvF/k/Ji/1WcbvgAa3 mkkp7M5+cTxqEEHA9tOasnxakZzArFvITV734VP/Q3f8nktnbNfzg9Gg4H8l37iYC5oyOGwwoPP/ CBUz91BKez6jPiCp3C9WgArtQVCwyfTssuMmRAAOb54GvCKWU3BlxFAKRmukLyeBEicTXxChds6K ezfqwzlhA5WYOudsiCUI/HloDYd9Yvi0X/vF2Ey9WLw/Q1vUHgFNPGO+I++MzVpQuGhU+QqZMxEA 4Z7CRneC9VkGjCFMhwnN5ag= -----END CERTIFICATE----- Juur-SK ======= -----BEGIN CERTIFICATE----- MIIE5jCCA86gAwIBAgIEO45L/DANBgkqhkiG9w0BAQUFADBdMRgwFgYJKoZIhvcNAQkBFglwa2lA c2suZWUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKExlBUyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMRAw DgYDVQQDEwdKdXVyLVNLMB4XDTAxMDgzMDE0MjMwMVoXDTE2MDgyNjE0MjMwMVowXTEYMBYGCSqG SIb3DQEJARYJcGtpQHNrLmVlMQswCQYDVQQGEwJFRTEiMCAGA1UEChMZQVMgU2VydGlmaXRzZWVy aW1pc2tlc2t1czEQMA4GA1UEAxMHSnV1ci1TSzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC ggEBAIFxNj4zB9bjMI0TfncyRsvPGbJgMUaXhvSYRqTCZUXP00B841oiqBB4M8yIsdOBSvZiF3tf TQou0M+LI+5PAk676w7KvRhj6IAcjeEcjT3g/1tf6mTll+g/mX8MCgkzABpTpyHhOEvWgxutr2TC +Rx6jGZITWYfGAriPrsfB2WThbkasLnE+w0R9vXW+RvHLCu3GFH+4Hv2qEivbDtPL+/40UceJlfw UR0zlv/vWT3aTdEVNMfqPxZIe5EcgEMPPbgFPtGzlc3Yyg/CQ2fbt5PgIoIuvvVoKIO5wTtpeyDa Tpxt4brNj3pssAki14sL2xzVWiZbDcDq5WDQn/413z8CAwEAAaOCAawwggGoMA8GA1UdEwEB/wQF MAMBAf8wggEWBgNVHSAEggENMIIBCTCCAQUGCisGAQQBzh8BAQEwgfYwgdAGCCsGAQUFBwICMIHD HoHAAFMAZQBlACAAcwBlAHIAdABpAGYAaQBrAGEAYQB0ACAAbwBuACAAdgDkAGwAagBhAHMAdABh AHQAdQBkACAAQQBTAC0AaQBzACAAUwBlAHIAdABpAGYAaQB0AHMAZQBlAHIAaQBtAGkAcwBrAGUA cwBrAHUAcwAgAGEAbABhAG0ALQBTAEsAIABzAGUAcgB0AGkAZgBpAGsAYQBhAHQAaQBkAGUAIABr AGkAbgBuAGkAdABhAG0AaQBzAGUAawBzMCEGCCsGAQUFBwIBFhVodHRwOi8vd3d3LnNrLmVlL2Nw cy8wKwYDVR0fBCQwIjAgoB6gHIYaaHR0cDovL3d3dy5zay5lZS9qdXVyL2NybC8wHQYDVR0OBBYE FASqekej5ImvGs8KQKcYP2/v6X2+MB8GA1UdIwQYMBaAFASqekej5ImvGs8KQKcYP2/v6X2+MA4G A1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQUFAAOCAQEAe8EYlFOiCfP+JmeaUOTDBS8rNXiRTHyo ERF5TElZrMj3hWVcRrs7EKACr81Ptcw2Kuxd/u+gkcm2k298gFTsxwhwDY77guwqYHhpNjbRxZyL abVAyJRld/JXIWY7zoVAtjNjGr95HvxcHdMdkxuLDF2FvZkwMhgJkVLpfKG6/2SSmuz+Ne6ML678 IIbsSt4beDI3poHSna9aEhbKmVv8b20OxaAehsmR0FyYgl9jDIpaq9iVpszLita/ZEuOyoqysOkh Mp6qqIWYNIE5ITuoOlIyPfZrN4YGWhWY3PARZv40ILcD9EEQfTmEeZZyY7aWAuVrua0ZTbvGRNs2 yyqcjg== -----END CERTIFICATE----- Hongkong Post Root CA 1 ======================= -----BEGIN CERTIFICATE----- MIIDMDCCAhigAwIBAgICA+gwDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCSEsxFjAUBgNVBAoT DUhvbmdrb25nIFBvc3QxIDAeBgNVBAMTF0hvbmdrb25nIFBvc3QgUm9vdCBDQSAxMB4XDTAzMDUx NTA1MTMxNFoXDTIzMDUxNTA0NTIyOVowRzELMAkGA1UEBhMCSEsxFjAUBgNVBAoTDUhvbmdrb25n IFBvc3QxIDAeBgNVBAMTF0hvbmdrb25nIFBvc3QgUm9vdCBDQSAxMIIBIjANBgkqhkiG9w0BAQEF AAOCAQ8AMIIBCgKCAQEArP84tulmAknjorThkPlAj3n54r15/gK97iSSHSL22oVyaf7XPwnU3ZG1 ApzQjVrhVcNQhrkpJsLj2aDxaQMoIIBFIi1WpztUlVYiWR8o3x8gPW2iNr4joLFutbEnPzlTCeqr auh0ssJlXI6/fMN4hM2eFvz1Lk8gKgifd/PFHsSaUmYeSF7jEAaPIpjhZY4bXSNmO7ilMlHIhqqh qZ5/dpTCpmy3QfDVyAY45tQM4vM7TG1QjMSDJ8EThFk9nnV0ttgCXjqQesBCNnLsak3c78QA3xMY V18meMjWCnl3v/evt3a5pQuEF10Q6m/hq5URX208o1xNg1vysxmKgIsLhwIDAQABoyYwJDASBgNV HRMBAf8ECDAGAQH/AgEDMA4GA1UdDwEB/wQEAwIBxjANBgkqhkiG9w0BAQUFAAOCAQEADkbVPK7i h9legYsCmEEIjEy82tvuJxuC52pF7BaLT4Wg87JwvVqWuspube5Gi27nKi6Wsxkz67SfqLI37pio l7Yutmcn1KZJ/RyTZXaeQi/cImyaT/JaFTmxcdcrUehtHJjA2Sr0oYJ71clBoiMBdDhViw+5Lmei IAQ32pwL0xch4I+XeTRvhEgCIDMb5jREn5Fw9IBehEPCKdJsEhTkYY2sEJCehFC78JZvRZ+K88ps T/oROhUVRsPNH4NbLUES7VBnQRM9IauUiqpOfMGx+6fWtScvl6tu4B3i0RwsH0Ti/L6RoZz71ilT c4afU9hDDl3WY4JxHYB0yvbiAmvZWg== -----END CERTIFICATE----- SecureSign RootCA11 =================== -----BEGIN CERTIFICATE----- MIIDbTCCAlWgAwIBAgIBATANBgkqhkiG9w0BAQUFADBYMQswCQYDVQQGEwJKUDErMCkGA1UEChMi SmFwYW4gQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcywgSW5jLjEcMBoGA1UEAxMTU2VjdXJlU2lnbiBS b290Q0ExMTAeFw0wOTA0MDgwNDU2NDdaFw0yOTA0MDgwNDU2NDdaMFgxCzAJBgNVBAYTAkpQMSsw KQYDVQQKEyJKYXBhbiBDZXJ0aWZpY2F0aW9uIFNlcnZpY2VzLCBJbmMuMRwwGgYDVQQDExNTZWN1 cmVTaWduIFJvb3RDQTExMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA/XeqpRyQBTvL TJszi1oURaTnkBbR31fSIRCkF/3frNYfp+TbfPfs37gD2pRY/V1yfIw/XwFndBWW4wI8h9uuywGO wvNmxoVF9ALGOrVisq/6nL+k5tSAMJjzDbaTj6nU2DbysPyKyiyhFTOVMdrAG/LuYpmGYz+/3ZMq g6h2uRMft85OQoWPIucuGvKVCbIFtUROd6EgvanyTgp9UK31BQ1FT0Zx/Sg+U/sE2C3XZR1KG/rP O7AxmjVuyIsG0wCR8pQIZUyxNAYAeoni8McDWc/V1uinMrPmmECGxc0nEovMe863ETxiYAcjPitA bpSACW22s293bzUIUPsCh8U+iQIDAQABo0IwQDAdBgNVHQ4EFgQUW/hNT7KlhtQ60vFjmqC+CfZX t94wDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAKCh OBZmLqdWHyGcBvod7bkixTgm2E5P7KN/ed5GIaGHd48HCJqypMWvDzKYC3xmKbabfSVSSUOrTC4r bnpwrxYO4wJs+0LmGJ1F2FXI6Dvd5+H0LgscNFxsWEr7jIhQX5Ucv+2rIrVls4W6ng+4reV6G4pQ Oh29Dbx7VFALuUKvVaAYga1lme++5Jy/xIWrQbJUb9wlze144o4MjQlJ3WN7WmmWAiGovVJZ6X01 y8hSyn+B/tlr0/cR7SXf+Of5pPpyl4RTDaXQMhhRdlkUbA/r7F+AjHVDg8OFmP9Mni0N5HeDk061 lgeLKBObjBmNQSdJQO7e5iNEOdyhIta6A/I= -----END CERTIFICATE----- ACEDICOM Root ============= -----BEGIN CERTIFICATE----- MIIFtTCCA52gAwIBAgIIYY3HhjsBggUwDQYJKoZIhvcNAQEFBQAwRDEWMBQGA1UEAwwNQUNFRElD T00gUm9vdDEMMAoGA1UECwwDUEtJMQ8wDQYDVQQKDAZFRElDT00xCzAJBgNVBAYTAkVTMB4XDTA4 MDQxODE2MjQyMloXDTI4MDQxMzE2MjQyMlowRDEWMBQGA1UEAwwNQUNFRElDT00gUm9vdDEMMAoG A1UECwwDUEtJMQ8wDQYDVQQKDAZFRElDT00xCzAJBgNVBAYTAkVTMIICIjANBgkqhkiG9w0BAQEF AAOCAg8AMIICCgKCAgEA/5KV4WgGdrQsyFhIyv2AVClVYyT/kGWbEHV7w2rbYgIB8hiGtXxaOLHk WLn709gtn70yN78sFW2+tfQh0hOR2QetAQXW8713zl9CgQr5auODAKgrLlUTY4HKRxx7XBZXehuD YAQ6PmXDzQHe3qTWDLqO3tkE7hdWIpuPY/1NFgu3e3eM+SW10W2ZEi5PGrjm6gSSrj0RuVFCPYew MYWveVqc/udOXpJPQ/yrOq2lEiZmueIM15jO1FillUAKt0SdE3QrwqXrIhWYENiLxQSfHY9g5QYb m8+5eaA9oiM/Qj9r+hwDezCNzmzAv+YbX79nuIQZ1RXve8uQNjFiybwCq0Zfm/4aaJQ0PZCOrfbk HQl/Sog4P75n/TSW9R28MHTLOO7VbKvU/PQAtwBbhTIWdjPp2KOZnQUAqhbm84F9b32qhm2tFXTT xKJxqvQUfecyuB+81fFOvW8XAjnXDpVCOscAPukmYxHqC9FK/xidstd7LzrZlvvoHpKuE1XI2Sf2 3EgbsCTBheN3nZqk8wwRHQ3ItBTutYJXCb8gWH8vIiPYcMt5bMlL8qkqyPyHK9caUPgn6C9D4zq9 2Fdx/c6mUlv53U3t5fZvie27k5x2IXXwkkwp9y+cAS7+UEaeZAwUswdbxcJzbPEHXEUkFDWug/Fq TYl6+rPYLWbwNof1K1MCAwEAAaOBqjCBpzAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFKaz 4SsrSbbXc6GqlPUB53NlTKxQMA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUprPhKytJttdzoaqU 9QHnc2VMrFAwRAYDVR0gBD0wOzA5BgRVHSAAMDEwLwYIKwYBBQUHAgEWI2h0dHA6Ly9hY2VkaWNv bS5lZGljb21ncm91cC5jb20vZG9jMA0GCSqGSIb3DQEBBQUAA4ICAQDOLAtSUWImfQwng4/F9tqg aHtPkl7qpHMyEVNEskTLnewPeUKzEKbHDZ3Ltvo/Onzqv4hTGzz3gvoFNTPhNahXwOf9jU8/kzJP eGYDdwdY6ZXIfj7QeQCM8htRM5u8lOk6e25SLTKeI6RF+7YuE7CLGLHdztUdp0J/Vb77W7tH1Pwk zQSulgUV1qzOMPPKC8W64iLgpq0i5ALudBF/TP94HTXa5gI06xgSYXcGCRZj6hitoocf8seACQl1 ThCojz2GuHURwCRiipZ7SkXp7FnFvmuD5uHorLUwHv4FB4D54SMNUI8FmP8sX+g7tq3PgbUhh8oI KiMnMCArz+2UW6yyetLHKKGKC5tNSixthT8Jcjxn4tncB7rrZXtaAWPWkFtPF2Y9fwsZo5NjEFIq nxQWWOLcpfShFosOkYuByptZ+thrkQdlVV9SH686+5DdaaVbnG0OLLb6zqylfDJKZ0DcMDQj3dcE I2bw/FWAp/tmGYI1Z2JwOV5vx+qQQEQIHriy1tvuWacNGHk0vFQYXlPKNFHtRQrmjseCNj6nOGOp MCwXEGCSn1WHElkQwg9naRHMTh5+Spqtr0CodaxWkHS4oJyleW/c6RrIaQXpuvoDs3zk4E7Czp3o tkYNbn5XOmeUwssfnHdKZ05phkOTOPu220+DkdRgfks+KzgHVZhepA== -----END CERTIFICATE----- Verisign Class 3 Public Primary Certification Authority ======================================================= -----BEGIN CERTIFICATE----- MIICPDCCAaUCEDyRMcsf9tAbDpq40ES/Er4wDQYJKoZIhvcNAQEFBQAwXzELMAkGA1UEBhMCVVMx FzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAzIFB1YmxpYyBQcmltYXJ5 IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTk2MDEyOTAwMDAwMFoXDTI4MDgwMjIzNTk1OVow XzELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAz IFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGfMA0GCSqGSIb3DQEBAQUA A4GNADCBiQKBgQDJXFme8huKARS0EN8EQNvjV69qRUCPhAwL0TPZ2RHP7gJYHyX3KqhEBarsAx94 f56TuZoAqiN91qyFomNFx3InzPRMxnVx0jnvT0Lwdd8KkMaOIG+YD/isI19wKTakyYbnsZogy1Ol hec9vn2a/iRFM9x2Fe0PonFkTGUugWhFpwIDAQABMA0GCSqGSIb3DQEBBQUAA4GBABByUqkFFBky CEHwxWsKzH4PIRnN5GfcX6kb5sroc50i2JhucwNhkcV8sEVAbkSdjbCxlnRhLQ2pRdKkkirWmnWX bj9T/UWZYB2oK0z5XqcJ2HUw19JlYD1n1khVdWk/kfVIC0dpImmClr7JyDiGSnoscxlIaU5rfGW/ D/xwzoiQ -----END CERTIFICATE----- Microsec e-Szigno Root CA 2009 ============================== -----BEGIN CERTIFICATE----- MIIECjCCAvKgAwIBAgIJAMJ+QwRORz8ZMA0GCSqGSIb3DQEBCwUAMIGCMQswCQYDVQQGEwJIVTER MA8GA1UEBwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jv c2VjIGUtU3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5o dTAeFw0wOTA2MTYxMTMwMThaFw0yOTEyMzAxMTMwMThaMIGCMQswCQYDVQQGEwJIVTERMA8GA1UE BwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUt U3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5odTCCASIw DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOn4j/NjrdqG2KfgQvvPkd6mJviZpWNwrZuuyjNA fW2WbqEORO7hE52UQlKavXWFdCyoDh2Tthi3jCyoz/tccbna7P7ofo/kLx2yqHWH2Leh5TvPmUpG 0IMZfcChEhyVbUr02MelTTMuhTlAdX4UfIASmFDHQWe4oIBhVKZsTh/gnQ4H6cm6M+f+wFUoLAKA pxn1ntxVUwOXewdI/5n7N4okxFnMUBBjjqqpGrCEGob5X7uxUG6k0QrM1XF+H6cbfPVTbiJfyyvm 1HxdrtbCxkzlBQHZ7Vf8wSN5/PrIJIOV87VqUQHQd9bpEqH5GoP7ghu5sJf0dgYzQ0mg/wu1+rUC AwEAAaOBgDB+MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTLD8bf QkPMPcu1SCOhGnqmKrs0aDAfBgNVHSMEGDAWgBTLD8bfQkPMPcu1SCOhGnqmKrs0aDAbBgNVHREE FDASgRBpbmZvQGUtc3ppZ25vLmh1MA0GCSqGSIb3DQEBCwUAA4IBAQDJ0Q5eLtXMs3w+y/w9/w0o lZMEyL/azXm4Q5DwpL7v8u8hmLzU1F0G9u5C7DBsoKqpyvGvivo/C3NqPuouQH4frlRheesuCDfX I/OMn74dseGkddug4lQUsbocKaQY9hK6ohQU4zE1yED/t+AFdlfBHFny+L/k7SViXITwfn4fs775 tyERzAMBVnCnEJIeGzSBHq2cGsMEPO0CYdYeBvNfOofyK/FFh+U9rNHHV4S9a67c2Pm2G2JwCz02 yULyMtd6YebS2z3PyKnJm9zbWETXbzivf3jTo60adbocwTZ8jx5tHMN1Rq41Bab2XD0h7lbwyYIi LXpUq3DDfSJlgnCW -----END CERTIFICATE----- E-Guven Kok Elektronik Sertifika Hizmet Saglayicisi =================================================== -----BEGIN CERTIFICATE----- MIIDtjCCAp6gAwIBAgIQRJmNPMADJ72cdpW56tustTANBgkqhkiG9w0BAQUFADB1MQswCQYDVQQG EwJUUjEoMCYGA1UEChMfRWxla3Ryb25payBCaWxnaSBHdXZlbmxpZ2kgQS5TLjE8MDoGA1UEAxMz ZS1HdXZlbiBLb2sgRWxla3Ryb25payBTZXJ0aWZpa2EgSGl6bWV0IFNhZ2xheWljaXNpMB4XDTA3 MDEwNDExMzI0OFoXDTE3MDEwNDExMzI0OFowdTELMAkGA1UEBhMCVFIxKDAmBgNVBAoTH0VsZWt0 cm9uaWsgQmlsZ2kgR3V2ZW5saWdpIEEuUy4xPDA6BgNVBAMTM2UtR3V2ZW4gS29rIEVsZWt0cm9u aWsgU2VydGlmaWthIEhpem1ldCBTYWdsYXlpY2lzaTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC AQoCggEBAMMSIJ6wXgBljU5Gu4Bc6SwGl9XzcslwuedLZYDBS75+PNdUMZTe1RK6UxYC6lhj71vY 8+0qGqpxSKPcEC1fX+tcS5yWCEIlKBHMilpiAVDV6wlTL/jDj/6z/P2douNffb7tC+Bg62nsM+3Y jfsSSYMAyYuXjDtzKjKzEve5TfL0TW3H5tYmNwjy2f1rXKPlSFxYvEK+A1qBuhw1DADT9SN+cTAI JjjcJRFHLfO6IxClv7wC90Nex/6wN1CZew+TzuZDLMN+DfIcQ2Zgy2ExR4ejT669VmxMvLz4Bcpk 9Ok0oSy1c+HCPujIyTQlCFzz7abHlJ+tiEMl1+E5YP6sOVkCAwEAAaNCMEAwDgYDVR0PAQH/BAQD AgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFJ/uRLOU1fqRTy7ZVZoEVtstxNulMA0GCSqG SIb3DQEBBQUAA4IBAQB/X7lTW2M9dTLn+sR0GstG30ZpHFLPqk/CaOv/gKlR6D1id4k9CnU58W5d F4dvaAXBlGzZXd/aslnLpRCKysw5zZ/rTt5S/wzw9JKp8mxTq5vSR6AfdPebmvEvFZ96ZDAYBzwq D2fK/A+JYZ1lpTzlvBNbCNvj/+27BrtqBrF6T2XGgv0enIu1De5Iu7i9qgi0+6N8y5/NkHZchpZ4 Vwpm+Vganf2XKWDeEaaQHBkc7gGWIjQ0LpH5t8Qn0Xvmv/uARFoW5evg1Ao4vOSR49XrXMGs3xtq fJ7lddK2l4fbzIcrQzqECK+rPNv3PGYxhrCdU3nt+CPeQuMtgvEP5fqX -----END CERTIFICATE----- GlobalSign Root CA - R3 ======================= -----BEGIN CERTIFICATE----- MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4GA1UECxMXR2xv YmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2Jh bFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxT aWduIFJvb3QgQ0EgLSBSMzETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2ln bjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWt iHL8RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsTgHeMCOFJ 0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmmKPZpO/bLyCiR5Z2KYVc3 rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zdQQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjl OCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZXriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2 xmmFghcCAwEAAaNCMEAwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYE FI/wS3+oLkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZURUm7 lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMpjjM5RcOO5LlXbKr8 EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK6fBdRoyV3XpYKBovHd7NADdBj+1E bddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQXmcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18 YIvDQVETI53O9zJrlAGomecsMx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7r kpeDMdmztcpHWD9f -----END CERTIFICATE----- Autoridad de Certificacion Firmaprofesional CIF A62634068 ========================================================= -----BEGIN CERTIFICATE----- MIIGFDCCA/ygAwIBAgIIU+w77vuySF8wDQYJKoZIhvcNAQEFBQAwUTELMAkGA1UEBhMCRVMxQjBA BgNVBAMMOUF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uIEZpcm1hcHJvZmVzaW9uYWwgQ0lGIEE2 MjYzNDA2ODAeFw0wOTA1MjAwODM4MTVaFw0zMDEyMzEwODM4MTVaMFExCzAJBgNVBAYTAkVTMUIw QAYDVQQDDDlBdXRvcmlkYWQgZGUgQ2VydGlmaWNhY2lvbiBGaXJtYXByb2Zlc2lvbmFsIENJRiBB NjI2MzQwNjgwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKlmuO6vj78aI14H9M2uDD Utd9thDIAl6zQyrET2qyyhxdKJp4ERppWVevtSBC5IsP5t9bpgOSL/UR5GLXMnE42QQMcas9UX4P B99jBVzpv5RvwSmCwLTaUbDBPLutN0pcyvFLNg4kq7/DhHf9qFD0sefGL9ItWY16Ck6WaVICqjaY 7Pz6FIMMNx/Jkjd/14Et5cS54D40/mf0PmbR0/RAz15iNA9wBj4gGFrO93IbJWyTdBSTo3OxDqqH ECNZXyAFGUftaI6SEspd/NYrspI8IM/hX68gvqB2f3bl7BqGYTM+53u0P6APjqK5am+5hyZvQWyI plD9amML9ZMWGxmPsu2bm8mQ9QEM3xk9Dz44I8kvjwzRAv4bVdZO0I08r0+k8/6vKtMFnXkIoctX MbScyJCyZ/QYFpM6/EfY0XiWMR+6KwxfXZmtY4laJCB22N/9q06mIqqdXuYnin1oKaPnirjaEbsX LZmdEyRG98Xi2J+Of8ePdG1asuhy9azuJBCtLxTa/y2aRnFHvkLfuwHb9H/TKI8xWVvTyQKmtFLK bpf7Q8UIJm+K9Lv9nyiqDdVF8xM6HdjAeI9BZzwelGSuewvF6NkBiDkal4ZkQdU7hwxu+g/GvUgU vzlN1J5Bto+WHWOWk9mVBngxaJ43BjuAiUVhOSPHG0SjFeUc+JIwuwIDAQABo4HvMIHsMBIGA1Ud EwEB/wQIMAYBAf8CAQEwDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBRlzeurNR4APn7VdMActHNH DhpkLzCBpgYDVR0gBIGeMIGbMIGYBgRVHSAAMIGPMC8GCCsGAQUFBwIBFiNodHRwOi8vd3d3LmZp cm1hcHJvZmVzaW9uYWwuY29tL2NwczBcBggrBgEFBQcCAjBQHk4AUABhAHMAZQBvACAAZABlACAA bABhACAAQgBvAG4AYQBuAG8AdgBhACAANAA3ACAAQgBhAHIAYwBlAGwAbwBuAGEAIAAwADgAMAAx ADcwDQYJKoZIhvcNAQEFBQADggIBABd9oPm03cXF661LJLWhAqvdpYhKsg9VSytXjDvlMd3+xDLx 51tkljYyGOylMnfX40S2wBEqgLk9am58m9Ot/MPWo+ZkKXzR4Tgegiv/J2Wv+xYVxC5xhOW1//qk R71kMrv2JYSiJ0L1ILDCExARzRAVukKQKtJE4ZYm6zFIEv0q2skGz3QeqUvVhyj5eTSSPi5E6PaP T481PyWzOdxjKpBrIF/EUhJOlywqrJ2X3kjyo2bbwtKDlaZmp54lD+kLM5FlClrD2VQS3a/DTg4f Jl4N3LON7NWBcN7STyQF82xO9UxJZo3R/9ILJUFI/lGExkKvgATP0H5kSeTy36LssUzAKh3ntLFl osS88Zj0qnAHY7S42jtM+kAiMFsRpvAFDsYCA0irhpuF3dvd6qJ2gHN99ZwExEWN57kci57q13XR crHedUTnQn3iV2t93Jm8PYMo6oCTjcVMZcFwgbg4/EMxsvYDNEeyrPsiBsse3RdHHF9mudMaotoR saS8I8nkvof/uZS2+F0gStRf571oe2XyFR7SOqkt6dhrJKyXWERHrVkY8SFlcN7ONGCoQPHzPKTD KCOM/iczQ0CgFzzr6juwcqajuUpLXhZI9LK8yIySxZ2frHI2vDSANGupi5LAuBft7HZT9SQBjLMi 6Et8Vcad+qMUu2WFbm5PEn4KPJ2V -----END CERTIFICATE----- Izenpe.com ========== -----BEGIN CERTIFICATE----- MIIF8TCCA9mgAwIBAgIQALC3WhZIX7/hy/WL1xnmfTANBgkqhkiG9w0BAQsFADA4MQswCQYDVQQG EwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6ZW5wZS5jb20wHhcNMDcxMjEz MTMwODI4WhcNMzcxMjEzMDgyNzI1WjA4MQswCQYDVQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMu QS4xEzARBgNVBAMMCkl6ZW5wZS5jb20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDJ 03rKDx6sp4boFmVqscIbRTJxldn+EFvMr+eleQGPicPK8lVx93e+d5TzcqQsRNiekpsUOqHnJJAK ClaOxdgmlOHZSOEtPtoKct2jmRXagaKH9HtuJneJWK3W6wyyQXpzbm3benhB6QiIEn6HLmYRY2xU +zydcsC8Lv/Ct90NduM61/e0aL6i9eOBbsFGb12N4E3GVFWJGjMxCrFXuaOKmMPsOzTFlUFpfnXC PCDFYbpRR6AgkJOhkEvzTnyFRVSa0QUmQbC1TR0zvsQDyCV8wXDbO/QJLVQnSKwv4cSsPsjLkkxT OTcj7NMB+eAJRE1NZMDhDVqHIrytG6P+JrUV86f8hBnp7KGItERphIPzidF0BqnMC9bC3ieFUCbK F7jJeodWLBoBHmy+E60QrLUk9TiRodZL2vG70t5HtfG8gfZZa88ZU+mNFctKy6lvROUbQc/hhqfK 0GqfvEyNBjNaooXlkDWgYlwWTvDjovoDGrQscbNYLN57C9saD+veIR8GdwYDsMnvmfzAuU8Lhij+ 0rnq49qlw0dpEuDb8PYZi+17cNcC1u2HGCgsBCRMd+RIihrGO5rUD8r6ddIBQFqNeb+Lz0vPqhbB leStTIo+F5HUsWLlguWABKQDfo2/2n+iD5dPDNMN+9fR5XJ+HMh3/1uaD7euBUbl8agW7EekFwID AQABo4H2MIHzMIGwBgNVHREEgagwgaWBD2luZm9AaXplbnBlLmNvbaSBkTCBjjFHMEUGA1UECgw+ SVpFTlBFIFMuQS4gLSBDSUYgQTAxMzM3MjYwLVJNZXJjLlZpdG9yaWEtR2FzdGVpeiBUMTA1NSBG NjIgUzgxQzBBBgNVBAkMOkF2ZGEgZGVsIE1lZGl0ZXJyYW5lbyBFdG9yYmlkZWEgMTQgLSAwMTAx MCBWaXRvcmlhLUdhc3RlaXowDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0O BBYEFB0cZQ6o8iV7tJHP5LGx5r1VdGwFMA0GCSqGSIb3DQEBCwUAA4ICAQB4pgwWSp9MiDrAyw6l Fn2fuUhfGI8NYjb2zRlrrKvV9pF9rnHzP7MOeIWblaQnIUdCSnxIOvVFfLMMjlF4rJUT3sb9fbga kEyrkgPH7UIBzg/YsfqikuFgba56awmqxinuaElnMIAkejEWOVt+8Rwu3WwJrfIxwYJOubv5vr8q hT/AQKM6WfxZSzwoJNu0FXWuDYi6LnPAvViH5ULy617uHjAimcs30cQhbIHsvm0m5hzkQiCeR7Cs g1lwLDXWrzY0tM07+DKo7+N4ifuNRSzanLh+QBxh5z6ikixL8s36mLYp//Pye6kfLqCTVyvehQP5 aTfLnnhqBbTFMXiJ7HqnheG5ezzevh55hM6fcA5ZwjUukCox2eRFekGkLhObNA5me0mrZJfQRsN5 nXJQY6aYWwa9SG3YOYNw6DXwBdGqvOPbyALqfP2C2sJbUjWumDqtujWTI6cfSN01RpiyEGjkpTHC ClguGYEQyVB1/OpaFs4R1+7vUIgtYf8/QnMFlEPVjjxOAToZpR9GTnfQXeWBIiGH/pR9hNiTrdZo Q0iy2+tzJOeRf1SktoA+naM8THLCV8Sg1Mw4J87VBp6iSNnpn86CcDaTmjvfliHjWbcM2pE38P1Z WrOZyGlsQyYBNWNgVYkDOnXYukrZVP/u3oDYLdE41V4tC5h9Pmzb/CaIxw== -----END CERTIFICATE----- Chambers of Commerce Root - 2008 ================================ -----BEGIN CERTIFICATE----- MIIHTzCCBTegAwIBAgIJAKPaQn6ksa7aMA0GCSqGSIb3DQEBBQUAMIGuMQswCQYDVQQGEwJFVTFD MEEGA1UEBxM6TWFkcmlkIChzZWUgY3VycmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNv bS9hZGRyZXNzKTESMBAGA1UEBRMJQTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMu QS4xKTAnBgNVBAMTIENoYW1iZXJzIG9mIENvbW1lcmNlIFJvb3QgLSAyMDA4MB4XDTA4MDgwMTEy Mjk1MFoXDTM4MDczMTEyMjk1MFowga4xCzAJBgNVBAYTAkVVMUMwQQYDVQQHEzpNYWRyaWQgKHNl ZSBjdXJyZW50IGFkZHJlc3MgYXQgd3d3LmNhbWVyZmlybWEuY29tL2FkZHJlc3MpMRIwEAYDVQQF EwlBODI3NDMyODcxGzAZBgNVBAoTEkFDIENhbWVyZmlybWEgUy5BLjEpMCcGA1UEAxMgQ2hhbWJl cnMgb2YgQ29tbWVyY2UgUm9vdCAtIDIwMDgwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC AQCvAMtwNyuAWko6bHiUfaN/Gh/2NdW928sNRHI+JrKQUrpjOyhYb6WzbZSm891kDFX29ufyIiKA XuFixrYp4YFs8r/lfTJqVKAyGVn+H4vXPWCGhSRv4xGzdz4gljUha7MI2XAuZPeEklPWDrCQiorj h40G072QDuKZoRuGDtqaCrsLYVAGUvGef3bsyw/QHg3PmTA9HMRFEFis1tPo1+XqxQEHd9ZR5gN/ ikilTWh1uem8nk4ZcfUyS5xtYBkL+8ydddy/Js2Pk3g5eXNeJQ7KXOt3EgfLZEFHcpOrUMPrCXZk NNI5t3YRCQ12RcSprj1qr7V9ZS+UWBDsXHyvfuK2GNnQm05aSd+pZgvMPMZ4fKecHePOjlO+Bd5g D2vlGts/4+EhySnB8esHnFIbAURRPHsl18TlUlRdJQfKFiC4reRB7noI/plvg6aRArBsNlVq5331 lubKgdaX8ZSD6e2wsWsSaR6s+12pxZjptFtYer49okQ6Y1nUCyXeG0+95QGezdIp1Z8XGQpvvwyQ 0wlf2eOKNcx5Wk0ZN5K3xMGtr/R5JJqyAQuxr1yW84Ay+1w9mPGgP0revq+ULtlVmhduYJ1jbLhj ya6BXBg14JC7vjxPNyK5fuvPnnchpj04gftI2jE9K+OJ9dC1vX7gUMQSibMjmhAxhduub+84Mxh2 EQIDAQABo4IBbDCCAWgwEgYDVR0TAQH/BAgwBgEB/wIBDDAdBgNVHQ4EFgQU+SSsD7K1+HnA+mCI G8TZTQKeFxkwgeMGA1UdIwSB2zCB2IAU+SSsD7K1+HnA+mCIG8TZTQKeFxmhgbSkgbEwga4xCzAJ BgNVBAYTAkVVMUMwQQYDVQQHEzpNYWRyaWQgKHNlZSBjdXJyZW50IGFkZHJlc3MgYXQgd3d3LmNh bWVyZmlybWEuY29tL2FkZHJlc3MpMRIwEAYDVQQFEwlBODI3NDMyODcxGzAZBgNVBAoTEkFDIENh bWVyZmlybWEgUy5BLjEpMCcGA1UEAxMgQ2hhbWJlcnMgb2YgQ29tbWVyY2UgUm9vdCAtIDIwMDiC CQCj2kJ+pLGu2jAOBgNVHQ8BAf8EBAMCAQYwPQYDVR0gBDYwNDAyBgRVHSAAMCowKAYIKwYBBQUH AgEWHGh0dHA6Ly9wb2xpY3kuY2FtZXJmaXJtYS5jb20wDQYJKoZIhvcNAQEFBQADggIBAJASryI1 wqM58C7e6bXpeHxIvj99RZJe6dqxGfwWPJ+0W2aeaufDuV2I6A+tzyMP3iU6XsxPpcG1Lawk0lgH 3qLPaYRgM+gQDROpI9CF5Y57pp49chNyM/WqfcZjHwj0/gF/JM8rLFQJ3uIrbZLGOU8W6jx+ekbU RWpGqOt1glanq6B8aBMz9p0w8G8nOSQjKpD9kCk18pPfNKXG9/jvjA9iSnyu0/VU+I22mlaHFoI6 M6taIgj3grrqLuBHmrS1RaMFO9ncLkVAO+rcf+g769HsJtg1pDDFOqxXnrN2pSB7+R5KBWIBpih1 YJeSDW4+TTdDDZIVnBgizVGZoCkaPF+KMjNbMMeJL0eYD6MDxvbxrN8y8NmBGuScvfaAFPDRLLmF 9dijscilIeUcE5fuDr3fKanvNFNb0+RqE4QGtjICxFKuItLcsiFCGtpA8CnJ7AoMXOLQusxI0zcK zBIKinmwPQN/aUv0NCB9szTqjktk9T79syNnFQ0EuPAtwQlRPLJsFfClI9eDdOTlLsn+mCdCxqvG nrDQWzilm1DefhiYtUU79nm06PcaewaD+9CL2rvHvRirCG88gGtAPxkZumWK5r7VXNM21+9AUiRg OGcEMeyP84LG3rlV8zsxkVrctQgVrXYlCg17LofiDKYGvCYQbTed7N14jHyAxfDZd0jQ -----END CERTIFICATE----- Global Chambersign Root - 2008 ============================== -----BEGIN CERTIFICATE----- MIIHSTCCBTGgAwIBAgIJAMnN0+nVfSPOMA0GCSqGSIb3DQEBBQUAMIGsMQswCQYDVQQGEwJFVTFD MEEGA1UEBxM6TWFkcmlkIChzZWUgY3VycmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNv bS9hZGRyZXNzKTESMBAGA1UEBRMJQTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMu QS4xJzAlBgNVBAMTHkdsb2JhbCBDaGFtYmVyc2lnbiBSb290IC0gMjAwODAeFw0wODA4MDExMjMx NDBaFw0zODA3MzExMjMxNDBaMIGsMQswCQYDVQQGEwJFVTFDMEEGA1UEBxM6TWFkcmlkIChzZWUg Y3VycmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNvbS9hZGRyZXNzKTESMBAGA1UEBRMJ QTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMuQS4xJzAlBgNVBAMTHkdsb2JhbCBD aGFtYmVyc2lnbiBSb290IC0gMjAwODCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMDf VtPkOpt2RbQT2//BthmLN0EYlVJH6xedKYiONWwGMi5HYvNJBL99RDaxccy9Wglz1dmFRP+RVyXf XjaOcNFccUMd2drvXNL7G706tcuto8xEpw2uIRU/uXpbknXYpBI4iRmKt4DS4jJvVpyR1ogQC7N0 ZJJ0YPP2zxhPYLIj0Mc7zmFLmY/CDNBAspjcDahOo7kKrmCgrUVSY7pmvWjg+b4aqIG7HkF4ddPB /gBVsIdU6CeQNR1MM62X/JcumIS/LMmjv9GYERTtY/jKmIhYF5ntRQOXfjyGHoiMvvKRhI9lNNgA TH23MRdaKXoKGCQwoze1eqkBfSbW+Q6OWfH9GzO1KTsXO0G2Id3UwD2ln58fQ1DJu7xsepeY7s2M H/ucUa6LcL0nn3HAa6x9kGbo1106DbDVwo3VyJ2dwW3Q0L9R5OP4wzg2rtandeavhENdk5IMagfe Ox2YItaswTXbo6Al/3K1dh3ebeksZixShNBFks4c5eUzHdwHU1SjqoI7mjcv3N2gZOnm3b2u/GSF HTynyQbehP9r6GsaPMWis0L7iwk+XwhSx2LE1AVxv8Rk5Pihg+g+EpuoHtQ2TS9x9o0o9oOpE9Jh wZG7SMA0j0GMS0zbaRL/UJScIINZc+18ofLx/d33SdNDWKBWY8o9PeU1VlnpDsogzCtLkykPAgMB AAGjggFqMIIBZjASBgNVHRMBAf8ECDAGAQH/AgEMMB0GA1UdDgQWBBS5CcqcHtvTbDprru1U8VuT BjUuXjCB4QYDVR0jBIHZMIHWgBS5CcqcHtvTbDprru1U8VuTBjUuXqGBsqSBrzCBrDELMAkGA1UE BhMCRVUxQzBBBgNVBAcTOk1hZHJpZCAoc2VlIGN1cnJlbnQgYWRkcmVzcyBhdCB3d3cuY2FtZXJm aXJtYS5jb20vYWRkcmVzcykxEjAQBgNVBAUTCUE4Mjc0MzI4NzEbMBkGA1UEChMSQUMgQ2FtZXJm aXJtYSBTLkEuMScwJQYDVQQDEx5HbG9iYWwgQ2hhbWJlcnNpZ24gUm9vdCAtIDIwMDiCCQDJzdPp 1X0jzjAOBgNVHQ8BAf8EBAMCAQYwPQYDVR0gBDYwNDAyBgRVHSAAMCowKAYIKwYBBQUHAgEWHGh0 dHA6Ly9wb2xpY3kuY2FtZXJmaXJtYS5jb20wDQYJKoZIhvcNAQEFBQADggIBAICIf3DekijZBZRG /5BXqfEv3xoNa/p8DhxJJHkn2EaqbylZUohwEurdPfWbU1Rv4WCiqAm57OtZfMY18dwY6fFn5a+6 ReAJ3spED8IXDneRRXozX1+WLGiLwUePmJs9wOzL9dWCkoQ10b42OFZyMVtHLaoXpGNR6woBrX/s dZ7LoR/xfxKxueRkf2fWIyr0uDldmOghp+G9PUIadJpwr2hsUF1Jz//7Dl3mLEfXgTpZALVza2Mg 9jFFCDkO9HB+QHBaP9BrQql0PSgvAm11cpUJjUhjxsYjV5KTXjXBjfkK9yydYhz2rXzdpjEetrHH foUm+qRqtdpjMNHvkzeyZi99Bffnt0uYlDXA2TopwZ2yUDMdSqlapskD7+3056huirRXhOukP9Du qqqHW2Pok+JrqNS4cnhrG+055F3Lm6qH1U9OAP7Zap88MQ8oAgF9mOinsKJknnn4SPIVqczmyETr P3iZ8ntxPjzxmKfFGBI/5rsoM0LpRQp8bfKGeS/Fghl9CYl8slR2iK7ewfPM4W7bMdaTrpmg7yVq c5iJWzouE4gev8CSlDQb4ye3ix5vQv/n6TebUB0tovkC7stYWDpxvGjjqsGvHCgfotwjZT+B6q6Z 09gwzxMNTxXJhLynSC34MCN32EZLeW32jO06f2ARePTpm67VVMB0gNELQp/B -----END CERTIFICATE----- Go Daddy Root Certificate Authority - G2 ======================================== -----BEGIN CERTIFICATE----- MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMxEDAOBgNVBAgT B0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoTEUdvRGFkZHkuY29tLCBJbmMu MTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5 MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6 b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8G A1UEAxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZI hvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKDE6bFIEMBO4Tx5oVJnyfq 9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD +qK+ihVqf94Lw7YZFAXK6sOoBJQ7RnwyDfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutd fMh8+7ArU6SSYmlRJQVhGkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMl NAJWJwGRtDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEAAaNC MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFDqahQcQZyi27/a9 BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmXWWcDYfF+OwYxdS2hII5PZYe096ac vNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r 5N9ss4UXnT3ZJE95kTXWXwTrgIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYV N8Gb5DKj7Tjo2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI4uJEvlz36hz1 -----END CERTIFICATE----- Starfield Root Certificate Authority - G2 ========================================= -----BEGIN CERTIFICATE----- MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMxEDAOBgNVBAgT B0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoTHFN0YXJmaWVsZCBUZWNobm9s b2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVsZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0 eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAw DgYDVQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQg VGVjaG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZpY2F0ZSBB dXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL3twQP89o/8ArFv W59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMgnLRJdzIpVv257IzdIvpy3Cdhl+72WoTs bhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNk N3mSwOxGXn/hbVNMYq/NHwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7Nf ZTD4p7dNdloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0HZbU JtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC AQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0GCSqGSIb3DQEBCwUAA4IBAQARWfol TwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjUsHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx 4mcujJUDJi5DnUox9g61DLu34jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUw F5okxBDgBPfg8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1mMpYjn0q7pBZ c2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0 -----END CERTIFICATE----- Starfield Services Root Certificate Authority - G2 ================================================== -----BEGIN CERTIFICATE----- MIID7zCCAtegAwIBAgIBADANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UEBhMCVVMxEDAOBgNVBAgT B0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoTHFN0YXJmaWVsZCBUZWNobm9s b2dpZXMsIEluYy4xOzA5BgNVBAMTMlN0YXJmaWVsZCBTZXJ2aWNlcyBSb290IENlcnRpZmljYXRl IEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgZgxCzAJBgNV BAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxT dGFyZmllbGQgVGVjaG5vbG9naWVzLCBJbmMuMTswOQYDVQQDEzJTdGFyZmllbGQgU2VydmljZXMg Um9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC AQoCggEBANUMOsQq+U7i9b4Zl1+OiFOxHz/Lz58gE20pOsgPfTz3a3Y4Y9k2YKibXlwAgLIvWX/2 h/klQ4bnaRtSmpDhcePYLQ1Ob/bISdm28xpWriu2dBTrz/sm4xq6HZYuajtYlIlHVv8loJNwU4Pa hHQUw2eeBGg6345AWh1KTs9DkTvnVtYAcMtS7nt9rjrnvDH5RfbCYM8TWQIrgMw0R9+53pBlbQLP LJGmpufehRhJfGZOozptqbXuNC66DQO4M99H67FrjSXZm86B0UVGMpZwh94CDklDhbZsc7tk6mFB rMnUVN+HL8cisibMn1lUaJ/8viovxFUcdUBgF4UCVTmLfwUCAwEAAaNCMEAwDwYDVR0TAQH/BAUw AwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJxfAN+qAdcwKziIorhtSpzyEZGDMA0GCSqG SIb3DQEBCwUAA4IBAQBLNqaEd2ndOxmfZyMIbw5hyf2E3F/YNoHN2BtBLZ9g3ccaaNnRbobhiCPP E95Dz+I0swSdHynVv/heyNXBve6SbzJ08pGCL72CQnqtKrcgfU28elUSwhXqvfdqlS5sdJ/PHLTy xQGjhdByPq1zqwubdQxtRbeOlKyWN7Wg0I8VRw7j6IPdj/3vQQF3zCepYoUz8jcI73HPdwbeyBkd iEDPfUYd/x7H4c7/I9vG+o1VTqkC50cRRj70/b17KSa7qWFiNyi2LSr2EIZkyXCn0q23KXB56jza YyWf/Wi3MOxw+3WKt21gZ7IeyLnp2KhvAotnDU0mV3HaIPzBSlCNsSi6 -----END CERTIFICATE----- AffirmTrust Commercial ====================== -----BEGIN CERTIFICATE----- MIIDTDCCAjSgAwIBAgIId3cGJyapsXwwDQYJKoZIhvcNAQELBQAwRDELMAkGA1UEBhMCVVMxFDAS BgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBDb21tZXJjaWFsMB4XDTEw MDEyOTE0MDYwNloXDTMwMTIzMTE0MDYwNlowRDELMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmly bVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBDb21tZXJjaWFsMIIBIjANBgkqhkiG9w0BAQEF AAOCAQ8AMIIBCgKCAQEA9htPZwcroRX1BiLLHwGy43NFBkRJLLtJJRTWzsO3qyxPxkEylFf6Eqdb DuKPHx6GGaeqtS25Xw2Kwq+FNXkyLbscYjfysVtKPcrNcV/pQr6U6Mje+SJIZMblq8Yrba0F8PrV C8+a5fBQpIs7R6UjW3p6+DM/uO+Zl+MgwdYoic+U+7lF7eNAFxHUdPALMeIrJmqbTFeurCA+ukV6 BfO9m2kVrn1OIGPENXY6BwLJN/3HR+7o8XYdcxXyl6S1yHp52UKqK39c/s4mT6NmgTWvRLpUHhww MmWd5jyTXlBOeuM61G7MGvv50jeuJCqrVwMiKA1JdX+3KNp1v47j3A55MQIDAQABo0IwQDAdBgNV HQ4EFgQUnZPGU4teyq8/nx4P5ZmVvCT2lI8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC AQYwDQYJKoZIhvcNAQELBQADggEBAFis9AQOzcAN/wr91LoWXym9e2iZWEnStB03TX8nfUYGXUPG hi4+c7ImfU+TqbbEKpqrIZcUsd6M06uJFdhrJNTxFq7YpFzUf1GO7RgBsZNjvbz4YYCanrHOQnDi qX0GJX0nof5v7LMeJNrjS1UaADs1tDvZ110w/YETifLCBivtZ8SOyUOyXGsViQK8YvxO8rUzqrJv 0wqiUOP2O+guRMLbZjipM1ZI8W0bM40NjD9gN53Tym1+NH4Nn3J2ixufcv1SNUFFApYvHLKac0kh sUlHRUe072o0EclNmsxZt9YCnlpOZbWUrhvfKbAW8b8Angc6F2S1BLUjIZkKlTuXfO8= -----END CERTIFICATE----- AffirmTrust Networking ====================== -----BEGIN CERTIFICATE----- MIIDTDCCAjSgAwIBAgIIfE8EORzUmS0wDQYJKoZIhvcNAQEFBQAwRDELMAkGA1UEBhMCVVMxFDAS BgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBOZXR3b3JraW5nMB4XDTEw MDEyOTE0MDgyNFoXDTMwMTIzMTE0MDgyNFowRDELMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmly bVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBOZXR3b3JraW5nMIIBIjANBgkqhkiG9w0BAQEF AAOCAQ8AMIIBCgKCAQEAtITMMxcua5Rsa2FSoOujz3mUTOWUgJnLVWREZY9nZOIG41w3SfYvm4SE Hi3yYJ0wTsyEheIszx6e/jarM3c1RNg1lho9Nuh6DtjVR6FqaYvZ/Ls6rnla1fTWcbuakCNrmreI dIcMHl+5ni36q1Mr3Lt2PpNMCAiMHqIjHNRqrSK6mQEubWXLviRmVSRLQESxG9fhwoXA3hA/Pe24 /PHxI1Pcv2WXb9n5QHGNfb2V1M6+oF4nI979ptAmDgAp6zxG8D1gvz9Q0twmQVGeFDdCBKNwV6gb h+0t+nvujArjqWaJGctB+d1ENmHP4ndGyH329JKBNv3bNPFyfvMMFr20FQIDAQABo0IwQDAdBgNV HQ4EFgQUBx/S55zawm6iQLSwelAQUHTEyL0wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC AQYwDQYJKoZIhvcNAQEFBQADggEBAIlXshZ6qML91tmbmzTCnLQyFE2npN/svqe++EPbkTfOtDIu UFUaNU52Q3Eg75N3ThVwLofDwR1t3Mu1J9QsVtFSUzpE0nPIxBsFZVpikpzuQY0x2+c06lkh1QF6 12S4ZDnNye2v7UsDSKegmQGA3GWjNq5lWUhPgkvIZfFXHeVZLgo/bNjR9eUJtGxUAArgFU2HdW23 WJZa3W3SAKD0m0i+wzekujbgfIeFlxoVot4uolu9rxj5kFDNcFn4J2dHy8egBzp90SxdbBk6ZrV9 /ZFvgrG+CJPbFEfxojfHRZ48x3evZKiT3/Zpg4Jg8klCNO1aAFSFHBY2kgxc+qatv9s= -----END CERTIFICATE----- AffirmTrust Premium =================== -----BEGIN CERTIFICATE----- MIIFRjCCAy6gAwIBAgIIbYwURrGmCu4wDQYJKoZIhvcNAQEMBQAwQTELMAkGA1UEBhMCVVMxFDAS BgNVBAoMC0FmZmlybVRydXN0MRwwGgYDVQQDDBNBZmZpcm1UcnVzdCBQcmVtaXVtMB4XDTEwMDEy OTE0MTAzNloXDTQwMTIzMTE0MTAzNlowQTELMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRy dXN0MRwwGgYDVQQDDBNBZmZpcm1UcnVzdCBQcmVtaXVtMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A MIICCgKCAgEAxBLfqV/+Qd3d9Z+K4/as4Tx4mrzY8H96oDMq3I0gW64tb+eT2TZwamjPjlGjhVtn BKAQJG9dKILBl1fYSCkTtuG+kU3fhQxTGJoeJKJPj/CihQvL9Cl/0qRY7iZNyaqoe5rZ+jjeRFcV 5fiMyNlI4g0WJx0eyIOFJbe6qlVBzAMiSy2RjYvmia9mx+n/K+k8rNrSs8PhaJyJ+HoAVt70VZVs +7pk3WKL3wt3MutizCaam7uqYoNMtAZ6MMgpv+0GTZe5HMQxK9VfvFMSF5yZVylmd2EhMQcuJUmd GPLu8ytxjLW6OQdJd/zvLpKQBY0tL3d770O/Nbua2Plzpyzy0FfuKE4mX4+QaAkvuPjcBukumj5R p9EixAqnOEhss/n/fauGV+O61oV4d7pD6kh/9ti+I20ev9E2bFhc8e6kGVQa9QPSdubhjL08s9NI S+LI+H+SqHZGnEJlPqQewQcDWkYtuJfzt9WyVSHvutxMAJf7FJUnM7/oQ0dG0giZFmA7mn7S5u04 6uwBHjxIVkkJx0w3AJ6IDsBz4W9m6XJHMD4Q5QsDyZpCAGzFlH5hxIrff4IaC1nEWTJ3s7xgaVY5 /bQGeyzWZDbZvUjthB9+pSKPKrhC9IK31FOQeE4tGv2Bb0TXOwF0lkLgAOIua+rF7nKsu7/+6qqo +Nz2snmKtmcCAwEAAaNCMEAwHQYDVR0OBBYEFJ3AZ6YMItkm9UWrpmVSESfYRaxjMA8GA1UdEwEB /wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBDAUAA4ICAQCzV00QYk465KzquByv MiPIs0laUZx2KI15qldGF9X1Uva3ROgIRL8YhNILgM3FEv0AVQVhh0HctSSePMTYyPtwni94loMg Nt58D2kTiKV1NpgIpsbfrM7jWNa3Pt668+s0QNiigfV4Py/VpfzZotReBA4Xrf5B8OWycvpEgjNC 6C1Y91aMYj+6QrCcDFx+LmUmXFNPALJ4fqENmS2NuB2OosSw/WDQMKSOyARiqcTtNd56l+0OOF6S L5Nwpamcb6d9Ex1+xghIsV5n61EIJenmJWtSKZGc0jlzCFfemQa0W50QBuHCAKi4HEoCChTQwUHK +4w1IX2COPKpVJEZNZOUbWo6xbLQu4mGk+ibyQ86p3q4ofB4Rvr8Ny/lioTz3/4E2aFooC8k4gmV BtWVyuEklut89pMFu+1z6S3RdTnX5yTb2E5fQ4+e0BQ5v1VwSJlXMbSc7kqYA5YwH2AG7hsj/oFg IxpHYoWlzBk0gG+zrBrjn/B7SK3VAdlntqlyk+otZrWyuOQ9PLLvTIzq6we/qzWaVYa8GKa1qF60 g2xraUDTn9zxw2lrueFtCfTxqlB2Cnp9ehehVZZCmTEJ3WARjQUwfuaORtGdFNrHF+QFlozEJLUb zxQHskD4o55BhrwE0GuWyCqANP2/7waj3VjFhT0+j/6eKeC2uAloGRwYQw== -----END CERTIFICATE----- AffirmTrust Premium ECC ======================= -----BEGIN CERTIFICATE----- MIIB/jCCAYWgAwIBAgIIdJclisc/elQwCgYIKoZIzj0EAwMwRTELMAkGA1UEBhMCVVMxFDASBgNV BAoMC0FmZmlybVRydXN0MSAwHgYDVQQDDBdBZmZpcm1UcnVzdCBQcmVtaXVtIEVDQzAeFw0xMDAx MjkxNDIwMjRaFw00MDEyMzExNDIwMjRaMEUxCzAJBgNVBAYTAlVTMRQwEgYDVQQKDAtBZmZpcm1U cnVzdDEgMB4GA1UEAwwXQWZmaXJtVHJ1c3QgUHJlbWl1bSBFQ0MwdjAQBgcqhkjOPQIBBgUrgQQA IgNiAAQNMF4bFZ0D0KF5Nbc6PJJ6yhUczWLznCZcBz3lVPqj1swS6vQUX+iOGasvLkjmrBhDeKzQ N8O9ss0s5kfiGuZjuD0uL3jET9v0D6RoTFVya5UdThhClXjMNzyR4ptlKymjQjBAMB0GA1UdDgQW BBSaryl6wBE1NSZRMADDav5A1a7WPDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAK BggqhkjOPQQDAwNnADBkAjAXCfOHiFBar8jAQr9HX/VsaobgxCd05DhT1wV/GzTjxi+zygk8N53X 57hG8f2h4nECMEJZh0PUUd+60wkyWs6Iflc9nF9Ca/UHLbXwgpP5WW+uZPpY5Yse42O+tYHNbwKM eQ== -----END CERTIFICATE----- Certum Trusted Network CA ========================= -----BEGIN CERTIFICATE----- MIIDuzCCAqOgAwIBAgIDBETAMA0GCSqGSIb3DQEBBQUAMH4xCzAJBgNVBAYTAlBMMSIwIAYDVQQK ExlVbml6ZXRvIFRlY2hub2xvZ2llcyBTLkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlv biBBdXRob3JpdHkxIjAgBgNVBAMTGUNlcnR1bSBUcnVzdGVkIE5ldHdvcmsgQ0EwHhcNMDgxMDIy MTIwNzM3WhcNMjkxMjMxMTIwNzM3WjB+MQswCQYDVQQGEwJQTDEiMCAGA1UEChMZVW5pemV0byBU ZWNobm9sb2dpZXMgUy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRpZmljYXRpb24gQXV0aG9yaXR5 MSIwIAYDVQQDExlDZXJ0dW0gVHJ1c3RlZCBOZXR3b3JrIENBMIIBIjANBgkqhkiG9w0BAQEFAAOC AQ8AMIIBCgKCAQEA4/t9o3K6wvDJFIf1awFO4W5AB7ptJ11/91sts1rHUV+rpDKmYYe2bg+G0jAC l/jXaVehGDldamR5xgFZrDwxSjh80gTSSyjoIF87B6LMTXPb865Px1bVWqeWifrzq2jUI4ZZJ88J J7ysbnKDHDBy3+Ci6dLhdHUZvSqeexVUBBvXQzmtVSjF4hq79MDkrjhJM8x2hZ85RdKknvISjFH4 fOQtf/WsX+sWn7Et0brMkUJ3TCXJkDhv2/DM+44el1k+1WBO5gUo7Ul5E0u6SNsv+XLTOcr+H9g0 cvW0QM8xAcPs3hEtF10fuFDRXhmnad4HMyjKUJX5p1TLVIZQRan5SQIDAQABo0IwQDAPBgNVHRMB Af8EBTADAQH/MB0GA1UdDgQWBBQIds3LB/8k9sXN7buQvOKEN0Z19zAOBgNVHQ8BAf8EBAMCAQYw DQYJKoZIhvcNAQEFBQADggEBAKaorSLOAT2mo/9i0Eidi15ysHhE49wcrwn9I0j6vSrEuVUEtRCj jSfeC4Jj0O7eDDd5QVsisrCaQVymcODU0HfLI9MA4GxWL+FpDQ3Zqr8hgVDZBqWo/5U30Kr+4rP1 mS1FhIrlQgnXdAIv94nYmem8J9RHjboNRhx3zxSkHLmkMcScKHQDNP8zGSal6Q10tz6XxnboJ5aj Zt3hrvJBW8qYVoNzcOSGGtIxQbovvi0TWnZvTuhOgQ4/WwMioBK+ZlgRSssDxLQqKi2WF+A5VLxI 03YnnZotBqbJ7DnSq9ufmgsnAjUpsUCV5/nonFWIGUbWtzT1fs45mtk48VH3Tyw= -----END CERTIFICATE----- Certinomis - Autorité Racine ============================= -----BEGIN CERTIFICATE----- MIIFnDCCA4SgAwIBAgIBATANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJGUjETMBEGA1UEChMK Q2VydGlub21pczEXMBUGA1UECxMOMDAwMiA0MzM5OTg5MDMxJjAkBgNVBAMMHUNlcnRpbm9taXMg LSBBdXRvcml0w6kgUmFjaW5lMB4XDTA4MDkxNzA4Mjg1OVoXDTI4MDkxNzA4Mjg1OVowYzELMAkG A1UEBhMCRlIxEzARBgNVBAoTCkNlcnRpbm9taXMxFzAVBgNVBAsTDjAwMDIgNDMzOTk4OTAzMSYw JAYDVQQDDB1DZXJ0aW5vbWlzIC0gQXV0b3JpdMOpIFJhY2luZTCCAiIwDQYJKoZIhvcNAQEBBQAD ggIPADCCAgoCggIBAJ2Fn4bT46/HsmtuM+Cet0I0VZ35gb5j2CN2DpdUzZlMGvE5x4jYF1AMnmHa wE5V3udauHpOd4cN5bjr+p5eex7Ezyh0x5P1FMYiKAT5kcOrJ3NqDi5N8y4oH3DfVS9O7cdxbwly Lu3VMpfQ8Vh30WC8Tl7bmoT2R2FFK/ZQpn9qcSdIhDWerP5pqZ56XjUl+rSnSTV3lqc2W+HN3yNw 2F1MpQiD8aYkOBOo7C+ooWfHpi2GR+6K/OybDnT0K0kCe5B1jPyZOQE51kqJ5Z52qz6WKDgmi92N jMD2AR5vpTESOH2VwnHu7XSu5DaiQ3XV8QCb4uTXzEIDS3h65X27uK4uIJPT5GHfceF2Z5c/tt9q c1pkIuVC28+BA5PY9OMQ4HL2AHCs8MF6DwV/zzRpRbWT5BnbUhYjBYkOjUjkJW+zeL9i9Qf6lSTC lrLooyPCXQP8w9PlfMl1I9f09bze5N/NgL+RiH2nE7Q5uiy6vdFrzPOlKO1Enn1So2+WLhl+HPNb xxaOu2B9d2ZHVIIAEWBsMsGoOBvrbpgT1u449fCfDu/+MYHB0iSVL1N6aaLwD4ZFjliCK0wi1F6g 530mJ0jfJUaNSih8hp75mxpZuWW/Bd22Ql095gBIgl4g9xGC3srYn+Y3RyYe63j3YcNBZFgCQfna 4NH4+ej9Uji29YnfAgMBAAGjWzBZMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G A1UdDgQWBBQNjLZh2kS40RR9w759XkjwzspqsDAXBgNVHSAEEDAOMAwGCiqBegFWAgIAAQEwDQYJ KoZIhvcNAQEFBQADggIBACQ+YAZ+He86PtvqrxyaLAEL9MW12Ukx9F1BjYkMTv9sov3/4gbIOZ/x WqndIlgVqIrTseYyCYIDbNc/CMf4uboAbbnW/FIyXaR/pDGUu7ZMOH8oMDX/nyNTt7buFHAAQCva R6s0fl6nVjBhK4tDrP22iCj1a7Y+YEq6QpA0Z43q619FVDsXrIvkxmUP7tCMXWY5zjKn2BCXwH40 nJ+U8/aGH88bc62UeYdocMMzpXDn2NU4lG9jeeu/Cg4I58UvD0KgKxRA/yHgBcUn4YQRE7rWhh1B CxMjidPJC+iKunqjo3M3NYB9Ergzd0A4wPpeMNLytqOx1qKVl4GbUu1pTP+A5FPbVFsDbVRfsbjv JL1vnxHDx2TCDyhihWZeGnuyt++uNckZM6i4J9szVb9o4XVIRFb7zdNIu0eJOqxp9YDG5ERQL1TE qkPFMTFYvZbF6nVsmnWxTfj3l/+WFvKXTej28xH5On2KOG4Ey+HTRRWqpdEdnV1j6CTmNhTih60b WfVEm/vXd3wfAXBioSAaosUaKPQhA+4u2cGA6rnZgtZbdsLLO7XSAPCjDuGtbkD326C00EauFddE wk01+dIL8hf2rGbVJLJP0RyZwG71fet0BLj5TXcJ17TPBzAJ8bgAVtkXFhYKK4bfjwEZGuW7gmP/ vgt2Fl43N+bYdJeimUV5 -----END CERTIFICATE----- Root CA Generalitat Valenciana ============================== -----BEGIN CERTIFICATE----- MIIGizCCBXOgAwIBAgIEO0XlaDANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJFUzEfMB0GA1UE ChMWR2VuZXJhbGl0YXQgVmFsZW5jaWFuYTEPMA0GA1UECxMGUEtJR1ZBMScwJQYDVQQDEx5Sb290 IENBIEdlbmVyYWxpdGF0IFZhbGVuY2lhbmEwHhcNMDEwNzA2MTYyMjQ3WhcNMjEwNzAxMTUyMjQ3 WjBoMQswCQYDVQQGEwJFUzEfMB0GA1UEChMWR2VuZXJhbGl0YXQgVmFsZW5jaWFuYTEPMA0GA1UE CxMGUEtJR1ZBMScwJQYDVQQDEx5Sb290IENBIEdlbmVyYWxpdGF0IFZhbGVuY2lhbmEwggEiMA0G CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDGKqtXETcvIorKA3Qdyu0togu8M1JAJke+WmmmO3I2 F0zo37i7L3bhQEZ0ZQKQUgi0/6iMweDHiVYQOTPvaLRfX9ptI6GJXiKjSgbwJ/BXufjpTjJ3Cj9B ZPPrZe52/lSqfR0grvPXdMIKX/UIKFIIzFVd0g/bmoGlu6GzwZTNVOAydTGRGmKy3nXiz0+J2ZGQ D0EbtFpKd71ng+CT516nDOeB0/RSrFOyA8dEJvt55cs0YFAQexvba9dHq198aMpunUEDEO5rmXte JajCq+TA81yc477OMUxkHl6AovWDfgzWyoxVjr7gvkkHD6MkQXpYHYTqWBLI4bft75PelAgxAgMB AAGjggM7MIIDNzAyBggrBgEFBQcBAQQmMCQwIgYIKwYBBQUHMAGGFmh0dHA6Ly9vY3NwLnBraS5n dmEuZXMwEgYDVR0TAQH/BAgwBgEB/wIBAjCCAjQGA1UdIASCAiswggInMIICIwYKKwYBBAG/VQIB ADCCAhMwggHoBggrBgEFBQcCAjCCAdoeggHWAEEAdQB0AG8AcgBpAGQAYQBkACAAZABlACAAQwBl AHIAdABpAGYAaQBjAGEAYwBpAPMAbgAgAFIAYQDtAHoAIABkAGUAIABsAGEAIABHAGUAbgBlAHIA YQBsAGkAdABhAHQAIABWAGEAbABlAG4AYwBpAGEAbgBhAC4ADQAKAEwAYQAgAEQAZQBjAGwAYQBy AGEAYwBpAPMAbgAgAGQAZQAgAFAAcgDhAGMAdABpAGMAYQBzACAAZABlACAAQwBlAHIAdABpAGYA aQBjAGEAYwBpAPMAbgAgAHEAdQBlACAAcgBpAGcAZQAgAGUAbAAgAGYAdQBuAGMAaQBvAG4AYQBt AGkAZQBuAHQAbwAgAGQAZQAgAGwAYQAgAHAAcgBlAHMAZQBuAHQAZQAgAEEAdQB0AG8AcgBpAGQA YQBkACAAZABlACAAQwBlAHIAdABpAGYAaQBjAGEAYwBpAPMAbgAgAHMAZQAgAGUAbgBjAHUAZQBu AHQAcgBhACAAZQBuACAAbABhACAAZABpAHIAZQBjAGMAaQDzAG4AIAB3AGUAYgAgAGgAdAB0AHAA OgAvAC8AdwB3AHcALgBwAGsAaQAuAGcAdgBhAC4AZQBzAC8AYwBwAHMwJQYIKwYBBQUHAgEWGWh0 dHA6Ly93d3cucGtpLmd2YS5lcy9jcHMwHQYDVR0OBBYEFHs100DSHHgZZu90ECjcPk+yeAT8MIGV BgNVHSMEgY0wgYqAFHs100DSHHgZZu90ECjcPk+yeAT8oWykajBoMQswCQYDVQQGEwJFUzEfMB0G A1UEChMWR2VuZXJhbGl0YXQgVmFsZW5jaWFuYTEPMA0GA1UECxMGUEtJR1ZBMScwJQYDVQQDEx5S b290IENBIEdlbmVyYWxpdGF0IFZhbGVuY2lhbmGCBDtF5WgwDQYJKoZIhvcNAQEFBQADggEBACRh TvW1yEICKrNcda3FbcrnlD+laJWIwVTAEGmiEi8YPyVQqHxK6sYJ2fR1xkDar1CdPaUWu20xxsdz Ckj+IHLtb8zog2EWRpABlUt9jppSCS/2bxzkoXHPjCpaF3ODR00PNvsETUlR4hTJZGH71BTg9J63 NI8KJr2XXPR5OkowGcytT6CYirQxlyric21+eLj4iIlPsSKRZEv1UN4D2+XFducTZnV+ZfsBn5OH iJ35Rld8TWCvmHMTI6QgkYH60GFmuH3Rr9ZvHmw96RH9qfmCIoaZM3Fa6hlXPZHNqcCjbgcTpsnt +GijnsNacgmHKNHEc8RzGF9QdRYxn7fofMM= -----END CERTIFICATE----- A-Trust-nQual-03 ================ -----BEGIN CERTIFICATE----- MIIDzzCCAregAwIBAgIDAWweMA0GCSqGSIb3DQEBBQUAMIGNMQswCQYDVQQGEwJBVDFIMEYGA1UE Cgw/QS1UcnVzdCBHZXMuIGYuIFNpY2hlcmhlaXRzc3lzdGVtZSBpbSBlbGVrdHIuIERhdGVudmVy a2VociBHbWJIMRkwFwYDVQQLDBBBLVRydXN0LW5RdWFsLTAzMRkwFwYDVQQDDBBBLVRydXN0LW5R dWFsLTAzMB4XDTA1MDgxNzIyMDAwMFoXDTE1MDgxNzIyMDAwMFowgY0xCzAJBgNVBAYTAkFUMUgw RgYDVQQKDD9BLVRydXN0IEdlcy4gZi4gU2ljaGVyaGVpdHNzeXN0ZW1lIGltIGVsZWt0ci4gRGF0 ZW52ZXJrZWhyIEdtYkgxGTAXBgNVBAsMEEEtVHJ1c3QtblF1YWwtMDMxGTAXBgNVBAMMEEEtVHJ1 c3QtblF1YWwtMDMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtPWFuA/OQO8BBC4SA zewqo51ru27CQoT3URThoKgtUaNR8t4j8DRE/5TrzAUjlUC5B3ilJfYKvUWG6Nm9wASOhURh73+n yfrBJcyFLGM/BWBzSQXgYHiVEEvc+RFZznF/QJuKqiTfC0Li21a8StKlDJu3Qz7dg9MmEALP6iPE SU7l0+m0iKsMrmKS1GWH2WrX9IWf5DMiJaXlyDO6w8dB3F/GaswADm0yqLaHNgBid5seHzTLkDx4 iHQF63n1k3Flyp3HaxgtPVxO59X4PzF9j4fsCiIvI+n+u33J4PTs63zEsMMtYrWacdaxaujs2e3V cuy+VwHOBVWf3tFgiBCzAgMBAAGjNjA0MA8GA1UdEwEB/wQFMAMBAf8wEQYDVR0OBAoECERqlWdV eRFPMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAVdRU0VlIXLOThaq/Yy/kgM40 ozRiPvbY7meIMQQDbwvUB/tOdQ/TLtPAF8fGKOwGDREkDg6lXb+MshOWcdzUzg4NCmgybLlBMRmr sQd7TZjTXLDR8KdCoLXEjq/+8T/0709GAHbrAvv5ndJAlseIOrifEXnzgGWovR/TeIGgUUw3tKZd JXDRZslo+S4RFGjxVJgIrCaSD96JntT6s3kr0qN51OyLrIdTaEJMUVF0HhsnLuP1Hyl0Te2v9+GS mYHovjrHF1D2t8b8m7CKa9aIA5GPBnc6hQLdmNVDeD/GMBWsm2vLV7eJUYs66MmEDNuxUCAKGkq6 ahq97BvIxYSazQ== -----END CERTIFICATE----- TWCA Root Certification Authority ================================= -----BEGIN CERTIFICATE----- MIIDezCCAmOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBfMQswCQYDVQQGEwJUVzESMBAGA1UECgwJ VEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NBIFJvb3QgQ2VydGlmaWNh dGlvbiBBdXRob3JpdHkwHhcNMDgwODI4MDcyNDMzWhcNMzAxMjMxMTU1OTU5WjBfMQswCQYDVQQG EwJUVzESMBAGA1UECgwJVEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NB IFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK AoIBAQCwfnK4pAOU5qfeCTiRShFAh6d8WWQUe7UREN3+v9XAu1bihSX0NXIP+FPQQeFEAcK0HMMx QhZHhTMidrIKbw/lJVBPhYa+v5guEGcevhEFhgWQxFnQfHgQsIBct+HHK3XLfJ+utdGdIzdjp9xC oi2SBBtQwXu4PhvJVgSLL1KbralW6cH/ralYhzC2gfeXRfwZVzsrb+RH9JlF/h3x+JejiB03HFyP 4HYlmlD4oFT/RJB2I9IyxsOrBr/8+7/zrX2SYgJbKdM1o5OaQ2RgXbL6Mv87BK9NQGr5x+PvI/1r y+UPizgN7gr8/g+YnzAx3WxSZfmLgb4i4RxYA7qRG4kHAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIB BjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqOFsmjd6LWvJPelSDGRjjCDWmujANBgkqhkiG 9w0BAQUFAAOCAQEAPNV3PdrfibqHDAhUaiBQkr6wQT25JmSDCi/oQMCXKCeCMErJk/9q56YAf4lC mtYR5VPOL8zy2gXE/uJQxDqGfczafhAJO5I1KlOy/usrBdlsXebQ79NqZp4VKIV66IIArB6nCWlW QtNoURi+VJq/REG6Sb4gumlc7rh3zc5sH62Dlhh9DrUUOYTxKOkto557HnpyWoOzeW/vtPzQCqVY T0bf+215WfKEIlKuD8z7fDvnaspHYcN6+NOSBB+4IIThNlQWx0DeO4pz3N/GCUzf7Nr/1FNCocny Yh0igzyXxfkZYiesZSLX0zzG5Y6yU8xJzrww/nsOM5D77dIUkR8Hrw== -----END CERTIFICATE----- Security Communication RootCA2 ============================== -----BEGIN CERTIFICATE----- MIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDElMCMGA1UEChMc U0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMeU2VjdXJpdHkgQ29tbXVuaWNh dGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoXDTI5MDUyOTA1MDAzOVowXTELMAkGA1UEBhMC SlAxJTAjBgNVBAoTHFNFQ09NIFRydXN0IFN5c3RlbXMgQ08uLExURC4xJzAlBgNVBAsTHlNlY3Vy aXR5IENvbW11bmljYXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB ANAVOVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz335c9S672XewhtUGrzbl+dp++ +T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonCv/Q4EpVMVAX3NuRFg3sUZdbcDE3R 3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQhNBqyjoGADdH5H5XTz+L62e4iKrFvlNV spHEfbmwhRkGeC7bYRr6hfVKkaHnFtWOojnflLhwHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1K EOtOghY6rCcMU/Gt1SSwawNQwS08Ft1ENCcadfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXdlBZh8 QIH4D5csOPEK7DzPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEB CwUAA4IBAQBMOqNErLlFsceTfsgLCkLfZOoc7llsCLqJX2rKSpWeeo8HxdpFcoJxDjrSzG+ntKEj u/Ykn8sX/oymzsLS28yN/HH8AynBbF0zX2S2ZTuJbxh2ePXcokgfGT+Ok+vx+hfuzU7jBBJV1uXk 3fs+BXziHV7Gp7yXT2g69ekuCkO2r1dcYmh8t/2jioSgrGK+KwmHNPBqAbubKVY8/gA3zyNs8U6q tnRGEmyR7jTV7JqR50S+kDFy1UkC9gLl9B/rfNmWVan/7Ir5mUf/NVoCqgTLiluHcSmRvaS0eg29 mvVXIwAHIRc/SjnRBUkLp7Y3gaVdjKozXoEofKd9J+sAro03 -----END CERTIFICATE----- EC-ACC ====== -----BEGIN CERTIFICATE----- MIIFVjCCBD6gAwIBAgIQ7is969Qh3hSoYqwE893EATANBgkqhkiG9w0BAQUFADCB8zELMAkGA1UE BhMCRVMxOzA5BgNVBAoTMkFnZW5jaWEgQ2F0YWxhbmEgZGUgQ2VydGlmaWNhY2lvIChOSUYgUS0w ODAxMTc2LUkpMSgwJgYDVQQLEx9TZXJ2ZWlzIFB1YmxpY3MgZGUgQ2VydGlmaWNhY2lvMTUwMwYD VQQLEyxWZWdldSBodHRwczovL3d3dy5jYXRjZXJ0Lm5ldC92ZXJhcnJlbCAoYykwMzE1MDMGA1UE CxMsSmVyYXJxdWlhIEVudGl0YXRzIGRlIENlcnRpZmljYWNpbyBDYXRhbGFuZXMxDzANBgNVBAMT BkVDLUFDQzAeFw0wMzAxMDcyMzAwMDBaFw0zMTAxMDcyMjU5NTlaMIHzMQswCQYDVQQGEwJFUzE7 MDkGA1UEChMyQWdlbmNpYSBDYXRhbGFuYSBkZSBDZXJ0aWZpY2FjaW8gKE5JRiBRLTA4MDExNzYt SSkxKDAmBgNVBAsTH1NlcnZlaXMgUHVibGljcyBkZSBDZXJ0aWZpY2FjaW8xNTAzBgNVBAsTLFZl Z2V1IGh0dHBzOi8vd3d3LmNhdGNlcnQubmV0L3ZlcmFycmVsIChjKTAzMTUwMwYDVQQLEyxKZXJh cnF1aWEgRW50aXRhdHMgZGUgQ2VydGlmaWNhY2lvIENhdGFsYW5lczEPMA0GA1UEAxMGRUMtQUND MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsyLHT+KXQpWIR4NA9h0X84NzJB5R85iK w5K4/0CQBXCHYMkAqbWUZRkiFRfCQ2xmRJoNBD45b6VLeqpjt4pEndljkYRm4CgPukLjbo73FCeT ae6RDqNfDrHrZqJyTxIThmV6PttPB/SnCWDaOkKZx7J/sxaVHMf5NLWUhdWZXqBIoH7nF2W4onW4 HvPlQn2v7fOKSGRdghST2MDk/7NQcvJ29rNdQlB50JQ+awwAvthrDk4q7D7SzIKiGGUzE3eeml0a E9jD2z3Il3rucO2n5nzbcc8tlGLfbdb1OL4/pYUKGbio2Al1QnDE6u/LDsg0qBIimAy4E5S2S+zw 0JDnJwIDAQABo4HjMIHgMB0GA1UdEQQWMBSBEmVjX2FjY0BjYXRjZXJ0Lm5ldDAPBgNVHRMBAf8E BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUoMOLRKo3pUW/l4Ba0fF4opvpXY0wfwYD VR0gBHgwdjB0BgsrBgEEAfV4AQMBCjBlMCwGCCsGAQUFBwIBFiBodHRwczovL3d3dy5jYXRjZXJ0 Lm5ldC92ZXJhcnJlbDA1BggrBgEFBQcCAjApGidWZWdldSBodHRwczovL3d3dy5jYXRjZXJ0Lm5l dC92ZXJhcnJlbCAwDQYJKoZIhvcNAQEFBQADggEBAKBIW4IB9k1IuDlVNZyAelOZ1Vr/sXE7zDkJ lF7W2u++AVtd0x7Y/X1PzaBB4DSTv8vihpw3kpBWHNzrKQXlxJ7HNd+KDM3FIUPpqojlNcAZQmNa Al6kSBg6hW/cnbw/nZzBh7h6YQjpdwt/cKt63dmXLGQehb+8dJahw3oS7AwaboMMPOhyRp/7SNVe l+axofjk70YllJyJ22k4vuxcDlbHZVHlUIiIv0LVKz3l+bqeLrPK9HOSAgu+TGbrIP65y7WZf+a2 E/rKS03Z7lNGBjvGTq2TWoF+bCpLagVFjPIhpDGQh2xlnJ2lYJU6Un/10asIbvPuW/mIPX64b24D 5EI= -----END CERTIFICATE----- Hellenic Academic and Research Institutions RootCA 2011 ======================================================= -----BEGIN CERTIFICATE----- MIIEMTCCAxmgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBlTELMAkGA1UEBhMCR1IxRDBCBgNVBAoT O0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgQ2VydC4gQXV0aG9y aXR5MUAwPgYDVQQDEzdIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0dXRpb25z IFJvb3RDQSAyMDExMB4XDTExMTIwNjEzNDk1MloXDTMxMTIwMTEzNDk1MlowgZUxCzAJBgNVBAYT AkdSMUQwQgYDVQQKEztIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0dXRpb25z IENlcnQuIEF1dGhvcml0eTFAMD4GA1UEAxM3SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJlc2VhcmNo IEluc3RpdHV0aW9ucyBSb290Q0EgMjAxMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB AKlTAOMupvaO+mDYLZU++CwqVE7NuYRhlFhPjz2L5EPzdYmNUeTDN9KKiE15HrcS3UN4SoqS5tdI 1Q+kOilENbgH9mgdVc04UfCMJDGFr4PJfel3r+0ae50X+bOdOFAPplp5kYCvN66m0zH7tSYJnTxa 71HFK9+WXesyHgLacEnsbgzImjeN9/E2YEsmLIKe0HjzDQ9jpFEw4fkrJxIH2Oq9GGKYsFk3fb7u 8yBRQlqD75O6aRXxYp2fmTmCobd0LovUxQt7L/DICto9eQqakxylKHJzkUOap9FNhYS5qXSPFEDH 3N6sQWRstBmbAmNtJGSPRLIl6s5ddAxjMlyNh+UCAwEAAaOBiTCBhjAPBgNVHRMBAf8EBTADAQH/ MAsGA1UdDwQEAwIBBjAdBgNVHQ4EFgQUppFC/RNhSiOeCKQp5dgTBCPuQSUwRwYDVR0eBEAwPqA8 MAWCAy5ncjAFggMuZXUwBoIELmVkdTAGggQub3JnMAWBAy5ncjAFgQMuZXUwBoEELmVkdTAGgQQu b3JnMA0GCSqGSIb3DQEBBQUAA4IBAQAf73lB4XtuP7KMhjdCSk4cNx6NZrokgclPEg8hwAOXhiVt XdMiKahsog2p6z0GW5k6x8zDmjR/qw7IThzh+uTczQ2+vyT+bOdrwg3IBp5OjWEopmr95fZi6hg8 TqBTnbI6nOulnJEWtk2C4AwFSKls9cz4y51JtPACpf1wA+2KIaWuE4ZJwzNzvoc7dIsXRSZMFpGD /md9zU1jZ/rzAxKWeAaNsWftjj++n08C9bMJL/NMh98qy5V8AcysNnq/onN694/BtZqhFLKPM58N 7yLcZnuEvUUXBj08yrl3NI/K6s8/MT7jiOOASSXIl7WdmplNsDz4SgCbZN2fOUvRJ9e4 -----END CERTIFICATE----- Actalis Authentication Root CA ============================== -----BEGIN CERTIFICATE----- MIIFuzCCA6OgAwIBAgIIVwoRl0LE48wwDQYJKoZIhvcNAQELBQAwazELMAkGA1UEBhMCSVQxDjAM BgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8wMzM1ODUyMDk2NzEnMCUGA1UE AwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290IENBMB4XDTExMDkyMjExMjIwMloXDTMwMDky MjExMjIwMlowazELMAkGA1UEBhMCSVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlz IFMucC5BLi8wMzM1ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290 IENBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAp8bEpSmkLO/lGMWwUKNvUTufClrJ wkg4CsIcoBh/kbWHuUA/3R1oHwiD1S0eiKD4j1aPbZkCkpAW1V8IbInX4ay8IMKx4INRimlNAJZa by/ARH6jDuSRzVju3PvHHkVH3Se5CAGfpiEd9UEtL0z9KK3giq0itFZljoZUj5NDKd45RnijMCO6 zfB9E1fAXdKDa0hMxKufgFpbOr3JpyI/gCczWw63igxdBzcIy2zSekciRDXFzMwujt0q7bd9Zg1f YVEiVRvjRuPjPdA1YprbrxTIW6HMiRvhMCb8oJsfgadHHwTrozmSBp+Z07/T6k9QnBn+locePGX2 oxgkg4YQ51Q+qDp2JE+BIcXjDwL4k5RHILv+1A7TaLndxHqEguNTVHnd25zS8gebLra8Pu2Fbe8l EfKXGkJh90qX6IuxEAf6ZYGyojnP9zz/GPvG8VqLWeICrHuS0E4UT1lF9gxeKF+w6D9Fz8+vm2/7 hNN3WpVvrJSEnu68wEqPSpP4RCHiMUVhUE4Q2OM1fEwZtN4Fv6MGn8i1zeQf1xcGDXqVdFUNaBr8 EBtiZJ1t4JWgw5QHVw0U5r0F+7if5t+L4sbnfpb2U8WANFAoWPASUHEXMLrmeGO89LKtmyuy/uE5 jF66CyCU3nuDuP/jVo23Eek7jPKxwV2dpAtMK9myGPW1n0sCAwEAAaNjMGEwHQYDVR0OBBYEFFLY iDrIn3hm7YnzezhwlMkCAjbQMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUUtiIOsifeGbt ifN7OHCUyQICNtAwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBCwUAA4ICAQALe3KHwGCmSUyI WOYdiPcUZEim2FgKDk8TNd81HdTtBjHIgT5q1d07GjLukD0R0i70jsNjLiNmsGe+b7bAEzlgqqI0 JZN1Ut6nna0Oh4lScWoWPBkdg/iaKWW+9D+a2fDzWochcYBNy+A4mz+7+uAwTc+G02UQGRjRlwKx K3JCaKygvU5a2hi/a5iB0P2avl4VSM0RFbnAKVy06Ij3Pjaut2L9HmLecHgQHEhb2rykOLpn7VU+ Xlff1ANATIGk0k9jpwlCCRT8AKnCgHNPLsBA2RF7SOp6AsDT6ygBJlh0wcBzIm2Tlf05fbsq4/aC 4yyXX04fkZT6/iyj2HYauE2yOE+b+h1IYHkm4vP9qdCa6HCPSXrW5b0KDtst842/6+OkfcvHlXHo 2qN8xcL4dJIEG4aspCJTQLas/kx2z/uUMsA1n3Y/buWQbqCmJqK4LL7RK4X9p2jIugErsWx0Hbhz lefut8cl8ABMALJ+tguLHPPAUJ4lueAI3jZm/zel0btUZCzJJ7VLkn5l/9Mt4blOvH+kQSGQQXem OR/qnuOf0GZvBeyqdn6/axag67XH/JJULysRJyU3eExRarDzzFhdFPFqSBX/wge2sY0PjlxQRrM9 vwGYT7JZVEc+NHt4bVaTLnPqZih4zR0Uv6CPLy64Lo7yFIrM6bV8+2ydDKXhlg== -----END CERTIFICATE----- Trustis FPS Root CA =================== -----BEGIN CERTIFICATE----- MIIDZzCCAk+gAwIBAgIQGx+ttiD5JNM2a/fH8YygWTANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQG EwJHQjEYMBYGA1UEChMPVHJ1c3RpcyBMaW1pdGVkMRwwGgYDVQQLExNUcnVzdGlzIEZQUyBSb290 IENBMB4XDTAzMTIyMzEyMTQwNloXDTI0MDEyMTExMzY1NFowRTELMAkGA1UEBhMCR0IxGDAWBgNV BAoTD1RydXN0aXMgTGltaXRlZDEcMBoGA1UECxMTVHJ1c3RpcyBGUFMgUm9vdCBDQTCCASIwDQYJ KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMVQe547NdDfxIzNjpvto8A2mfRC6qc+gIMPpqdZh8mQ RUN+AOqGeSoDvT03mYlmt+WKVoaTnGhLaASMk5MCPjDSNzoiYYkchU59j9WvezX2fihHiTHcDnlk H5nSW7r+f2C/revnPDgpai/lkQtV/+xvWNUtyd5MZnGPDNcE2gfmHhjjvSkCqPoc4Vu5g6hBSLwa cY3nYuUtsuvffM/bq1rKMfFMIvMFE/eC+XN5DL7XSxzA0RU8k0Fk0ea+IxciAIleH2ulrG6nS4zt o3Lmr2NNL4XSFDWaLk6M6jKYKIahkQlBOrTh4/L68MkKokHdqeMDx4gVOxzUGpTXn2RZEm0CAwEA AaNTMFEwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBS6+nEleYtXQSUhhgtx67JkDoshZzAd BgNVHQ4EFgQUuvpxJXmLV0ElIYYLceuyZA6LIWcwDQYJKoZIhvcNAQEFBQADggEBAH5Y//01GX2c GE+esCu8jowU/yyg2kdbw++BLa8F6nRIW/M+TgfHbcWzk88iNVy2P3UnXwmWzaD+vkAMXBJV+JOC yinpXj9WV4s4NvdFGkwozZ5BuO1WTISkQMi4sKUraXAEasP41BIy+Q7DsdwyhEQsb8tGD+pmQQ9P 8Vilpg0ND2HepZ5dfWWhPBfnqFVO76DH7cZEf1T1o+CP8HxVIo8ptoGj4W1OLBuAZ+ytIJ8MYmHV l/9D7S3B2l0pKoU/rGXuhg8FjZBf3+6f9L/uHfuY5H+QK4R4EA5sSVPvFVtlRkpdr7r7OnIdzfYl iB6XzCGcKQENZetX2fNXlrtIzYE= -----END CERTIFICATE----- StartCom Certification Authority ================================ -----BEGIN CERTIFICATE----- MIIHhzCCBW+gAwIBAgIBLTANBgkqhkiG9w0BAQsFADB9MQswCQYDVQQGEwJJTDEWMBQGA1UEChMN U3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmlu ZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDYwOTE3MTk0 NjM3WhcNMzYwOTE3MTk0NjM2WjB9MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRk LjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMg U3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw ggIKAoICAQDBiNsJvGxGfHiflXu1M5DycmLWwTYgIiRezul38kMKogZkpMyONvg45iPwbm2xPN1y o4UcodM9tDMr0y+v/uqwQVlntsQGfQqedIXWeUyAN3rfOQVSWff0G0ZDpNKFhdLDcfN1YjS6LIp/ Ho/u7TTQEceWzVI9ujPW3U3eCztKS5/CJi/6tRYccjV3yjxd5srhJosaNnZcAdt0FCX+7bWgiA/d eMotHweXMAEtcnn6RtYTKqi5pquDSR3l8u/d5AGOGAqPY1MWhWKpDhk6zLVmpsJrdAfkK+F2PrRt 2PZE4XNiHzvEvqBTViVsUQn3qqvKv3b9bZvzndu/PWa8DFaqr5hIlTpL36dYUNk4dalb6kMMAv+Z 6+hsTXBbKWWc3apdzK8BMewM69KN6Oqce+Zu9ydmDBpI125C4z/eIT574Q1w+2OqqGwaVLRcJXrJ osmLFqa7LH4XXgVNWG4SHQHuEhANxjJ/GP/89PrNbpHoNkm+Gkhpi8KWTRoSsmkXwQqQ1vp5Iki/ untp+HDH+no32NgN0nZPV/+Qt+OR0t3vwmC3Zzrd/qqc8NSLf3Iizsafl7b4r4qgEKjZ+xjGtrVc UjyJthkqcwEKDwOzEmDyei+B26Nu/yYwl/WL3YlXtq09s68rxbd2AvCl1iuahhQqcvbjM4xdCUsT 37uMdBNSSwIDAQABo4ICEDCCAgwwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD VR0OBBYEFE4L7xqkQFulF2mHMMo0aEPQQa7yMB8GA1UdIwQYMBaAFE4L7xqkQFulF2mHMMo0aEPQ Qa7yMIIBWgYDVR0gBIIBUTCCAU0wggFJBgsrBgEEAYG1NwEBATCCATgwLgYIKwYBBQUHAgEWImh0 dHA6Ly93d3cuc3RhcnRzc2wuY29tL3BvbGljeS5wZGYwNAYIKwYBBQUHAgEWKGh0dHA6Ly93d3cu c3RhcnRzc2wuY29tL2ludGVybWVkaWF0ZS5wZGYwgc8GCCsGAQUFBwICMIHCMCcWIFN0YXJ0IENv bW1lcmNpYWwgKFN0YXJ0Q29tKSBMdGQuMAMCAQEagZZMaW1pdGVkIExpYWJpbGl0eSwgcmVhZCB0 aGUgc2VjdGlvbiAqTGVnYWwgTGltaXRhdGlvbnMqIG9mIHRoZSBTdGFydENvbSBDZXJ0aWZpY2F0 aW9uIEF1dGhvcml0eSBQb2xpY3kgYXZhaWxhYmxlIGF0IGh0dHA6Ly93d3cuc3RhcnRzc2wuY29t L3BvbGljeS5wZGYwEQYJYIZIAYb4QgEBBAQDAgAHMDgGCWCGSAGG+EIBDQQrFilTdGFydENvbSBG cmVlIFNTTCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTANBgkqhkiG9w0BAQsFAAOCAgEAjo/n3JR5 fPGFf59Jb2vKXfuM/gTFwWLRfUKKvFO3lANmMD+x5wqnUCBVJX92ehQN6wQOQOY+2IirByeDqXWm N3PH/UvSTa0XQMhGvjt/UfzDtgUx3M2FIk5xt/JxXrAaxrqTi3iSSoX4eA+D/i+tLPfkpLst0OcN Org+zvZ49q5HJMqjNTbOx8aHmNrs++myziebiMMEofYLWWivydsQD032ZGNcpRJvkrKTlMeIFw6T tn5ii5B/q06f/ON1FE8qMt9bDeD1e5MNq6HPh+GlBEXoPBKlCcWw0bdT82AUuoVpaiF8H3VhFyAX e2w7QSlc4axa0c2Mm+tgHRns9+Ww2vl5GKVFP0lDV9LdJNUso/2RjSe15esUBppMeyG7Oq0wBhjA 2MFrLH9ZXF2RsXAiV+uKa0hK1Q8p7MZAwC+ITGgBF3f0JBlPvfrhsiAhS90a2Cl9qrjeVOwhVYBs HvUwyKMQ5bLmKhQxw4UtjJixhlpPiVktucf3HMiKf8CdBUrmQk9io20ppB+Fq9vlgcitKj1MXVuE JnHEhV5xJMqlG2zYYdMa4FTbzrqpMrUi9nNBCV24F10OD5mQ1kfabwo6YigUZ4LZ8dCAWZvLMdib D4x3TrVoivJs9iQOLWxwxXPR3hTQcY+203sC9uO41Alua551hDnmfyWl8kgAwKQB2j8= -----END CERTIFICATE----- StartCom Certification Authority G2 =================================== -----BEGIN CERTIFICATE----- MIIFYzCCA0ugAwIBAgIBOzANBgkqhkiG9w0BAQsFADBTMQswCQYDVQQGEwJJTDEWMBQGA1UEChMN U3RhcnRDb20gTHRkLjEsMCoGA1UEAxMjU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkg RzIwHhcNMTAwMTAxMDEwMDAxWhcNMzkxMjMxMjM1OTAxWjBTMQswCQYDVQQGEwJJTDEWMBQGA1UE ChMNU3RhcnRDb20gTHRkLjEsMCoGA1UEAxMjU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3Jp dHkgRzIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC2iTZbB7cgNr2Cu+EWIAOVeq8O o1XJJZlKxdBWQYeQTSFgpBSHO839sj60ZwNq7eEPS8CRhXBF4EKe3ikj1AENoBB5uNsDvfOpL9HG 4A/LnooUCri99lZi8cVytjIl2bLzvWXFDSxu1ZJvGIsAQRSCb0AgJnooD/Uefyf3lLE3PbfHkffi Aez9lInhzG7TNtYKGXmu1zSCZf98Qru23QumNK9LYP5/Q0kGi4xDuFby2X8hQxfqp0iVAXV16iul Q5XqFYSdCI0mblWbq9zSOdIxHWDirMxWRST1HFSr7obdljKF+ExP6JV2tgXdNiNnvP8V4so75qbs O+wmETRIjfaAKxojAuuKHDp2KntWFhxyKrOq42ClAJ8Em+JvHhRYW6Vsi1g8w7pOOlz34ZYrPu8H vKTlXcxNnw3h3Kq74W4a7I/htkxNeXJdFzULHdfBR9qWJODQcqhaX2YtENwvKhOuJv4KHBnM0D4L nMgJLvlblnpHnOl68wVQdJVznjAJ85eCXuaPOQgeWeU1FEIT/wCc976qUM/iUUjXuG+v+E5+M5iS FGI6dWPPe/regjupuznixL0sAA7IF6wT700ljtizkC+p2il9Ha90OrInwMEePnWjFqmveiJdnxMa z6eg6+OGCtP95paV1yPIN93EfKo2rJgaErHgTuixO/XWb/Ew1wIDAQABo0IwQDAPBgNVHRMBAf8E BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUS8W0QGutHLOlHGVuRjaJhwUMDrYwDQYJ KoZIhvcNAQELBQADggIBAHNXPyzVlTJ+N9uWkusZXn5T50HsEbZH77Xe7XRcxfGOSeD8bpkTzZ+K 2s06Ctg6Wgk/XzTQLwPSZh0avZyQN8gMjgdalEVGKua+etqhqaRpEpKwfTbURIfXUfEpY9Z1zRbk J4kd+MIySP3bmdCPX1R0zKxnNBFi2QwKN4fRoxdIjtIXHfbX/dtl6/2o1PXWT6RbdejF0mCy2wl+ JYt7ulKSnj7oxXehPOBKc2thz4bcQ///If4jXSRK9dNtD2IEBVeC2m6kMyV5Sy5UGYvMLD0w6dEG /+gyRr61M3Z3qAFdlsHB1b6uJcDJHgoJIIihDsnzb02CVAAgp9KP5DlUFy6NHrgbuxu9mk47EDTc nIhT76IxW1hPkWLIwpqazRVdOKnWvvgTtZ8SafJQYqz7Fzf07rh1Z2AQ+4NQ+US1dZxAF7L+/Xld blhYXzD8AK6vM8EOTmy6p6ahfzLbOOCxchcKK5HsamMm7YnUeMx0HgX4a/6ManY5Ka5lIxKVCCIc l85bBu4M4ru8H0ST9tg4RQUh7eStqxK2A6RCLi3ECToDZ2mEmuFZkIoohdVddLHRDiBYmxOlsGOm 7XtH/UVVMKTumtTm4ofvmMkyghEpIrwACjFeLQ/Ajulrso8uBtjRkcfGEvRM/TAXw8HaOFvjqerm obp573PYtlNXLfbQ4ddI -----END CERTIFICATE----- Buypass Class 2 Root CA ======================= -----BEGIN CERTIFICATE----- MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEdMBsGA1UECgwU QnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3MgQ2xhc3MgMiBSb290IENBMB4X DTEwMTAyNjA4MzgwM1oXDTQwMTAyNjA4MzgwM1owTjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1 eXBhc3MgQVMtOTgzMTYzMzI3MSAwHgYDVQQDDBdCdXlwYXNzIENsYXNzIDIgUm9vdCBDQTCCAiIw DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANfHXvfBB9R3+0Mh9PT1aeTuMgHbo4Yf5FkNuud1 g1Lr6hxhFUi7HQfKjK6w3Jad6sNgkoaCKHOcVgb/S2TwDCo3SbXlzwx87vFKu3MwZfPVL4O2fuPn 9Z6rYPnT8Z2SdIrkHJasW4DptfQxh6NR/Md+oW+OU3fUl8FVM5I+GC911K2GScuVr1QGbNgGE41b /+EmGVnAJLqBcXmQRFBoJJRfuLMR8SlBYaNByyM21cHxMlAQTn/0hpPshNOOvEu/XAFOBz3cFIqU CqTqc/sLUegTBxj6DvEr0VQVfTzh97QZQmdiXnfgolXsttlpF9U6r0TtSsWe5HonfOV116rLJeff awrbD02TTqigzXsu8lkBarcNuAeBfos4GzjmCleZPe4h6KP1DBbdi+w0jpwqHAAVF41og9JwnxgI zRFo1clrUs3ERo/ctfPYV3Me6ZQ5BL/T3jjetFPsaRyifsSP5BtwrfKi+fv3FmRmaZ9JUaLiFRhn Bkp/1Wy1TbMz4GHrXb7pmA8y1x1LPC5aAVKRCfLf6o3YBkBjqhHk/sM3nhRSP/TizPJhk9H9Z2vX Uq6/aKtAQ6BXNVN48FP4YUIHZMbXb5tMOA1jrGKvNouicwoN9SG9dKpN6nIDSdvHXx1iY8f93ZHs M+71bbRuMGjeyNYmsHVee7QHIJihdjK4TWxPAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYD VR0OBBYEFMmAd+BikoL1RpzzuvdMw964o605MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsF AAOCAgEAU18h9bqwOlI5LJKwbADJ784g7wbylp7ppHR/ehb8t/W2+xUbP6umwHJdELFx7rxP462s A20ucS6vxOOto70MEae0/0qyexAQH6dXQbLArvQsWdZHEIjzIVEpMMpghq9Gqx3tOluwlN5E40EI osHsHdb9T7bWR9AUC8rmyrV7d35BH16Dx7aMOZawP5aBQW9gkOLo+fsicdl9sz1Gv7SEr5AcD48S aq/v7h56rgJKihcrdv6sVIkkLE8/trKnToyokZf7KcZ7XC25y2a2t6hbElGFtQl+Ynhw/qlqYLYd DnkM/crqJIByw5c/8nerQyIKx+u2DISCLIBrQYoIwOula9+ZEsuK1V6ADJHgJgg2SMX6OBE1/yWD LfJ6v9r9jv6ly0UsH8SIU653DtmadsWOLB2jutXsMq7Aqqz30XpN69QH4kj3Io6wpJ9qzo6ysmD0 oyLQI+uUWnpp3Q+/QFesa1lQ2aOZ4W7+jQF5JyMV3pKdewlNWudLSDBaGOYKbeaP4NK75t98biGC wWg5TbSYWGZizEqQXsP6JwSxeRV0mcy+rSDeJmAc61ZRpqPq5KM/p/9h3PFaTWwyI0PurKju7koS CTxdccK+efrCh2gdC/1cacwG0Jp9VJkqyTkaGa9LKkPzY11aWOIv4x3kqdbQCtCev9eBCfHJxyYN rJgWVqA= -----END CERTIFICATE----- Buypass Class 3 Root CA ======================= -----BEGIN CERTIFICATE----- MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEdMBsGA1UECgwU QnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3MgQ2xhc3MgMyBSb290IENBMB4X DTEwMTAyNjA4Mjg1OFoXDTQwMTAyNjA4Mjg1OFowTjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1 eXBhc3MgQVMtOTgzMTYzMzI3MSAwHgYDVQQDDBdCdXlwYXNzIENsYXNzIDMgUm9vdCBDQTCCAiIw DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKXaCpUWUOOV8l6ddjEGMnqb8RB2uACatVI2zSRH sJ8YZLya9vrVediQYkwiL944PdbgqOkcLNt4EemOaFEVcsfzM4fkoF0LXOBXByow9c3EN3coTRiR 5r/VUv1xLXA+58bEiuPwKAv0dpihi4dVsjoT/Lc+JzeOIuOoTyrvYLs9tznDDgFHmV0ST9tD+leh 7fmdvhFHJlsTmKtdFoqwNxxXnUX/iJY2v7vKB3tvh2PX0DJq1l1sDPGzbjniazEuOQAnFN44wOwZ ZoYS6J1yFhNkUsepNxz9gjDthBgd9K5c/3ATAOux9TN6S9ZV+AWNS2mw9bMoNlwUxFFzTWsL8TQH 2xc519woe2v1n/MuwU8XKhDzzMro6/1rqy6any2CbgTUUgGTLT2G/H783+9CHaZr77kgxve9oKeV /afmiSTYzIw0bOIjL9kSGiG5VZFvC5F5GQytQIgLcOJ60g7YaEi7ghM5EFjp2CoHxhLbWNvSO1UQ RwUVZ2J+GGOmRj8JDlQyXr8NYnon74Do29lLBlo3WiXQCBJ31G8JUJc9yB3D34xFMFbG02SrZvPA Xpacw8Tvw3xrizp5f7NJzz3iiZ+gMEuFuZyUJHmPfWupRWgPK9Dx2hzLabjKSWJtyNBjYt1gD1iq j6G8BaVmos8bdrKEZLFMOVLAMLrwjEsCsLa3AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYD VR0OBBYEFEe4zf/lb+74suwvTg75JbCOPGvDMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsF AAOCAgEAACAjQTUEkMJAYmDv4jVM1z+s4jSQuKFvdvoWFqRINyzpkMLyPPgKn9iB5btb2iUspKdV cSQy9sgL8rxq+JOssgfCX5/bzMiKqr5qb+FJEMwx14C7u8jYog5kV+qi9cKpMRXSIGrs/CIBKM+G uIAeqcwRpTzyFrNHnfzSgCHEy9BHcEGhyoMZCCxt8l13nIoUE9Q2HJLw5QY33KbmkJs4j1xrG0aG Q0JfPgEHU1RdZX33inOhmlRaHylDFCfChQ+1iHsaO5S3HWCntZznKWlXWpuTekMwGwPXYshApqr8 ZORK15FTAaggiG6cX0S5y2CBNOxv033aSF/rtJC8LakcC6wc1aJoIIAE1vyxjy+7SjENSoYc6+I2 KSb12tjE8nVhz36udmNKekBlk4f4HoCMhuWG1o8O/FMsYOgWYRqiPkN7zTlgVGr18okmAWiDSKIz 6MkEkbIRNBE+6tBDGR8Dk5AM/1E9V/RBbuHLoL7ryWPNbczk+DaqaJ3tvV2XcEQNtg413OEMXbug UZTLfhbrES+jkkXITHHZvMmZUldGL1DPvTVp9D0VzgalLA8+9oG6lLvDu79leNKGef9JOxqDDPDe eOzI8k1MGt6CKfjBWtrt7uYnXuhF0J0cUahoq0Tj0Itq4/g7u9xN12TyUb7mqqta6THuBrxzvxNi Cp/HuZc= -----END CERTIFICATE----- T-TeleSec GlobalRoot Class 3 ============================ -----BEGIN CERTIFICATE----- MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoM IlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBU cnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDMwHhcNMDgx MDAxMTAyOTU2WhcNMzMxMDAxMjM1OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lz dGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBD ZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDMwggEiMA0GCSqGSIb3 DQEBAQUAA4IBDwAwggEKAoIBAQC9dZPwYiJvJK7genasfb3ZJNW4t/zN8ELg63iIVl6bmlQdTQyK 9tPPcPRStdiTBONGhnFBSivwKixVA9ZIw+A5OO3yXDw/RLyTPWGrTs0NvvAgJ1gORH8EGoel15YU NpDQSXuhdfsaa3Ox+M6pCSzyU9XDFES4hqX2iys52qMzVNn6chr3IhUciJFrf2blw2qAsCTz34ZF iP0Zf3WHHx+xGwpzJFu5ZeAsVMhg02YXP+HMVDNzkQI6pn97djmiH5a2OK61yJN0HZ65tOVgnS9W 0eDrXltMEnAMbEQgqxHY9Bn20pxSN+f6tsIxO0rUFJmtxxr1XV/6B7h8DR/Wgx6zAgMBAAGjQjBA MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS1A/d2O2GCahKqGFPr AyGUv/7OyjANBgkqhkiG9w0BAQsFAAOCAQEAVj3vlNW92nOyWL6ukK2YJ5f+AbGwUgC4TeQbIXQb fsDuXmkqJa9c1h3a0nnJ85cp4IaH3gRZD/FZ1GSFS5mvJQQeyUapl96Cshtwn5z2r3Ex3XsFpSzT ucpH9sry9uetuUg/vBa3wW306gmv7PO15wWeph6KU1HWk4HMdJP2udqmJQV0eVp+QD6CSyYRMG7h P0HHRwA11fXT91Q+gT3aSWqas+8QPebrb9HIIkfLzM8BMZLZGOMivgkeGj5asuRrDFR6fUNOuIml e9eiPZaGzPImNC1qkp2aGtAw4l1OBLBfiyB+d8E9lYLRRpo7PHi4b6HQDWSieB4pTpPDpFQUWw== -----END CERTIFICATE----- EE Certification Centre Root CA =============================== -----BEGIN CERTIFICATE----- MIIEAzCCAuugAwIBAgIQVID5oHPtPwBMyonY43HmSjANBgkqhkiG9w0BAQUFADB1MQswCQYDVQQG EwJFRTEiMCAGA1UECgwZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czEoMCYGA1UEAwwfRUUgQ2Vy dGlmaWNhdGlvbiBDZW50cmUgUm9vdCBDQTEYMBYGCSqGSIb3DQEJARYJcGtpQHNrLmVlMCIYDzIw MTAxMDMwMTAxMDMwWhgPMjAzMDEyMTcyMzU5NTlaMHUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKDBlB UyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMSgwJgYDVQQDDB9FRSBDZXJ0aWZpY2F0aW9uIENlbnRy ZSBSb290IENBMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWUwggEiMA0GCSqGSIb3DQEBAQUAA4IB DwAwggEKAoIBAQDIIMDs4MVLqwd4lfNE7vsLDP90jmG7sWLqI9iroWUyeuuOF0+W2Ap7kaJjbMeM TC55v6kF/GlclY1i+blw7cNRfdCT5mzrMEvhvH2/UpvObntl8jixwKIy72KyaOBhU8E2lf/slLo2 rpwcpzIP5Xy0xm90/XsY6KxX7QYgSzIwWFv9zajmofxwvI6Sc9uXp3whrj3B9UiHbCe9nyV0gVWw 93X2PaRka9ZP585ArQ/dMtO8ihJTmMmJ+xAdTX7Nfh9WDSFwhfYggx/2uh8Ej+p3iDXE/+pOoYtN P2MbRMNE1CV2yreN1x5KZmTNXMWcg+HCCIia7E6j8T4cLNlsHaFLAgMBAAGjgYowgYcwDwYDVR0T AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFBLyWj7qVhy/zQas8fElyalL1BSZ MEUGA1UdJQQ+MDwGCCsGAQUFBwMCBggrBgEFBQcDAQYIKwYBBQUHAwMGCCsGAQUFBwMEBggrBgEF BQcDCAYIKwYBBQUHAwkwDQYJKoZIhvcNAQEFBQADggEBAHv25MANqhlHt01Xo/6tu7Fq1Q+e2+Rj xY6hUFaTlrg4wCQiZrxTFGGVv9DHKpY5P30osxBAIWrEr7BSdxjhlthWXePdNl4dp1BUoMUq5KqM lIpPnTX/dqQGE5Gion0ARD9V04I8GtVbvFZMIi5GQ4okQC3zErg7cBqklrkar4dBGmoYDQZPxz5u uSlNDUmJEYcyW+ZLBMjkXOZ0c5RdFpgTlf7727FE5TpwrDdr5rMzcijJs1eg9gIWiAYLtqZLICjU 3j2LrTcFU3T+bsy8QxdxXvnFzBqpYe73dgzzcvRyrc9yAjYHR8/vGVCJYMzpJJUPwssd8m92kMfM dcGWxZ0= -----END CERTIFICATE----- TURKTRUST Certificate Services Provider Root 2007 ================================================= -----BEGIN CERTIFICATE----- MIIEPTCCAyWgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBvzE/MD0GA1UEAww2VMOcUktUUlVTVCBF bGVrdHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMQswCQYDVQQGEwJUUjEP MA0GA1UEBwwGQW5rYXJhMV4wXAYDVQQKDFVUw5xSS1RSVVNUIEJpbGdpIMSwbGV0acWfaW0gdmUg QmlsacWfaW0gR8O8dmVubGnEn2kgSGl6bWV0bGVyaSBBLsWeLiAoYykgQXJhbMSxayAyMDA3MB4X DTA3MTIyNTE4MzcxOVoXDTE3MTIyMjE4MzcxOVowgb8xPzA9BgNVBAMMNlTDnFJLVFJVU1QgRWxl a3Ryb25payBTZXJ0aWZpa2EgSGl6bWV0IFNhxJ9sYXnEsWPEsXPEsTELMAkGA1UEBhMCVFIxDzAN BgNVBAcMBkFua2FyYTFeMFwGA1UECgxVVMOcUktUUlVTVCBCaWxnaSDEsGxldGnFn2ltIHZlIEJp bGnFn2ltIEfDvHZlbmxpxJ9pIEhpem1ldGxlcmkgQS7Fni4gKGMpIEFyYWzEsWsgMjAwNzCCASIw DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKu3PgqMyKVYFeaK7yc9SrToJdPNM8Ig3BnuiD9N YvDdE3ePYakqtdTyuTFYKTsvP2qcb3N2Je40IIDu6rfwxArNK4aUyeNgsURSsloptJGXg9i3phQv KUmi8wUG+7RP2qFsmmaf8EMJyupyj+sA1zU511YXRxcw9L6/P8JorzZAwan0qafoEGsIiveGHtya KhUG9qPw9ODHFNRRf8+0222vR5YXm3dx2KdxnSQM9pQ/hTEST7ruToK4uT6PIzdezKKqdfcYbwnT rqdUKDT74eA7YH2gvnmJhsifLfkKS8RQouf9eRbHegsYz85M733WB2+Y8a+xwXrXgTW4qhe04MsC AwEAAaNCMEAwHQYDVR0OBBYEFCnFkKslrxHkYb+j/4hhkeYO/pyBMA4GA1UdDwEB/wQEAwIBBjAP BgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQAQDdr4Ouwo0RSVgrESLFF6QSU2TJ/s Px+EnWVUXKgWAkD6bho3hO9ynYYKVZ1WKKxmLNA6VpM0ByWtCLCPyA8JWcqdmBzlVPi5RX9ql2+I aE1KBiY3iAIOtsbWcpnOa3faYjGkVh+uX4132l32iPwa2Z61gfAyuOOI0JzzaqC5mxRZNTZPz/OO Xl0XrRWV2N2y1RVuAE6zS89mlOTgzbUF2mNXi+WzqtvALhyQRNsaXRik7r4EW5nVcV9VZWRi1aKb BFmGyGJ353yCRWo9F7/snXUMrqNvWtMvmDb08PUZqxFdyKbjKlhqQgnDvZImZjINXQhVdP+MmNAK poRq0Tl9 -----END CERTIFICATE----- D-TRUST Root Class 3 CA 2 2009 ============================== -----BEGIN CERTIFICATE----- MIIEMzCCAxugAwIBAgIDCYPzMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQK DAxELVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTAe Fw0wOTExMDUwODM1NThaFw0yOTExMDUwODM1NThaME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxE LVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTCCASIw DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANOySs96R+91myP6Oi/WUEWJNTrGa9v+2wBoqOAD ER03UAifTUpolDWzU9GUY6cgVq/eUXjsKj3zSEhQPgrfRlWLJ23DEE0NkVJD2IfgXU42tSHKXzlA BF9bfsyjxiupQB7ZNoTWSPOSHjRGICTBpFGOShrvUD9pXRl/RcPHAY9RySPocq60vFYJfxLLHLGv KZAKyVXMD9O0Gu1HNVpK7ZxzBCHQqr0ME7UAyiZsxGsMlFqVlNpQmvH/pStmMaTJOKDfHR+4CS7z p+hnUquVH+BGPtikw8paxTGA6Eian5Rp/hnd2HN8gcqW3o7tszIFZYQ05ub9VxC1X3a/L7AQDcUC AwEAAaOCARowggEWMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFP3aFMSfMN4hvR5COfyrYyNJ 4PGEMA4GA1UdDwEB/wQEAwIBBjCB0wYDVR0fBIHLMIHIMIGAoH6gfIZ6bGRhcDovL2RpcmVjdG9y eS5kLXRydXN0Lm5ldC9DTj1ELVRSVVNUJTIwUm9vdCUyMENsYXNzJTIwMyUyMENBJTIwMiUyMDIw MDksTz1ELVRydXN0JTIwR21iSCxDPURFP2NlcnRpZmljYXRlcmV2b2NhdGlvbmxpc3QwQ6BBoD+G PWh0dHA6Ly93d3cuZC10cnVzdC5uZXQvY3JsL2QtdHJ1c3Rfcm9vdF9jbGFzc18zX2NhXzJfMjAw OS5jcmwwDQYJKoZIhvcNAQELBQADggEBAH+X2zDI36ScfSF6gHDOFBJpiBSVYEQBrLLpME+bUMJm 2H6NMLVwMeniacfzcNsgFYbQDfC+rAF1hM5+n02/t2A7nPPKHeJeaNijnZflQGDSNiH+0LS4F9p0 o3/U37CYAqxva2ssJSRyoWXuJVrl5jLn8t+rSfrzkGkj2wTZ51xY/GXUl77M/C4KzCUqNQT4YJEV dT1B/yMfGchs64JTBKbkTCJNjYy6zltz7GRUUG3RnFX7acM2w4y8PIWmawomDeCTmGCufsYkl4ph X5GOZpIJhzbNi5stPvZR1FDUWSi9g/LMKHtThm3YJohw1+qRzT65ysCQblrGXnRl11z+o+I= -----END CERTIFICATE----- D-TRUST Root Class 3 CA 2 EV 2009 ================================= -----BEGIN CERTIFICATE----- MIIEQzCCAyugAwIBAgIDCYP0MA0GCSqGSIb3DQEBCwUAMFAxCzAJBgNVBAYTAkRFMRUwEwYDVQQK DAxELVRydXN0IEdtYkgxKjAoBgNVBAMMIUQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgRVYgMjAw OTAeFw0wOTExMDUwODUwNDZaFw0yOTExMDUwODUwNDZaMFAxCzAJBgNVBAYTAkRFMRUwEwYDVQQK DAxELVRydXN0IEdtYkgxKjAoBgNVBAMMIUQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgRVYgMjAw OTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJnxhDRwui+3MKCOvXwEz75ivJn9gpfS egpnljgJ9hBOlSJzmY3aFS3nBfwZcyK3jpgAvDw9rKFs+9Z5JUut8Mxk2og+KbgPCdM03TP1YtHh zRnp7hhPTFiu4h7WDFsVWtg6uMQYZB7jM7K1iXdODL/ZlGsTl28So/6ZqQTMFexgaDbtCHu39b+T 7WYxg4zGcTSHThfqr4uRjRxWQa4iN1438h3Z0S0NL2lRp75mpoo6Kr3HGrHhFPC+Oh25z1uxav60 sUYgovseO3Dvk5h9jHOW8sXvhXCtKSb8HgQ+HKDYD8tSg2J87otTlZCpV6LqYQXY+U3EJ/pure35 11H3a6UCAwEAAaOCASQwggEgMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNOUikxiEyoZLsyv cop9NteaHNxnMA4GA1UdDwEB/wQEAwIBBjCB3QYDVR0fBIHVMIHSMIGHoIGEoIGBhn9sZGFwOi8v ZGlyZWN0b3J5LmQtdHJ1c3QubmV0L0NOPUQtVFJVU1QlMjBSb290JTIwQ2xhc3MlMjAzJTIwQ0El MjAyJTIwRVYlMjAyMDA5LE89RC1UcnVzdCUyMEdtYkgsQz1ERT9jZXJ0aWZpY2F0ZXJldm9jYXRp b25saXN0MEagRKBChkBodHRwOi8vd3d3LmQtdHJ1c3QubmV0L2NybC9kLXRydXN0X3Jvb3RfY2xh c3NfM19jYV8yX2V2XzIwMDkuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQA07XtaPKSUiO8aEXUHL7P+ PPoeUSbrh/Yp3uDx1MYkCenBz1UbtDDZzhr+BlGmFaQt77JLvyAoJUnRpjZ3NOhk31KxEcdzes05 nsKtjHEh8lprr988TlWvsoRlFIm5d8sqMb7Po23Pb0iUMkZv53GMoKaEGTcH8gNFCSuGdXzfX2lX ANtu2KZyIktQ1HWYVt+3GP9DQ1CuekR78HlR10M9p9OB0/DJT7naxpeG0ILD5EJt/rDiZE4OJudA NCa1CInXCGNjOCd1HjPqbqjdn5lPdE2BiYBL3ZqXKVwvvoFBuYz/6n1gBp7N1z3TLqMVvKjmJuVv w9y4AyHqnxbxLFS1 -----END CERTIFICATE----- PSCProcert ========== -----BEGIN CERTIFICATE----- MIIJhjCCB26gAwIBAgIBCzANBgkqhkiG9w0BAQsFADCCAR4xPjA8BgNVBAMTNUF1dG9yaWRhZCBk ZSBDZXJ0aWZpY2FjaW9uIFJhaXogZGVsIEVzdGFkbyBWZW5lem9sYW5vMQswCQYDVQQGEwJWRTEQ MA4GA1UEBxMHQ2FyYWNhczEZMBcGA1UECBMQRGlzdHJpdG8gQ2FwaXRhbDE2MDQGA1UEChMtU2lz dGVtYSBOYWNpb25hbCBkZSBDZXJ0aWZpY2FjaW9uIEVsZWN0cm9uaWNhMUMwQQYDVQQLEzpTdXBl cmludGVuZGVuY2lhIGRlIFNlcnZpY2lvcyBkZSBDZXJ0aWZpY2FjaW9uIEVsZWN0cm9uaWNhMSUw IwYJKoZIhvcNAQkBFhZhY3JhaXpAc3VzY2VydGUuZ29iLnZlMB4XDTEwMTIyODE2NTEwMFoXDTIw MTIyNTIzNTk1OVowgdExJjAkBgkqhkiG9w0BCQEWF2NvbnRhY3RvQHByb2NlcnQubmV0LnZlMQ8w DQYDVQQHEwZDaGFjYW8xEDAOBgNVBAgTB01pcmFuZGExKjAoBgNVBAsTIVByb3ZlZWRvciBkZSBD ZXJ0aWZpY2Fkb3MgUFJPQ0VSVDE2MDQGA1UEChMtU2lzdGVtYSBOYWNpb25hbCBkZSBDZXJ0aWZp Y2FjaW9uIEVsZWN0cm9uaWNhMQswCQYDVQQGEwJWRTETMBEGA1UEAxMKUFNDUHJvY2VydDCCAiIw DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANW39KOUM6FGqVVhSQ2oh3NekS1wwQYalNo97BVC wfWMrmoX8Yqt/ICV6oNEolt6Vc5Pp6XVurgfoCfAUFM+jbnADrgV3NZs+J74BCXfgI8Qhd19L3uA 3VcAZCP4bsm+lU/hdezgfl6VzbHvvnpC2Mks0+saGiKLt38GieU89RLAu9MLmV+QfI4tL3czkkoh RqipCKzx9hEC2ZUWno0vluYC3XXCFCpa1sl9JcLB/KpnheLsvtF8PPqv1W7/U0HU9TI4seJfxPmO EO8GqQKJ/+MMbpfg353bIdD0PghpbNjU5Db4g7ayNo+c7zo3Fn2/omnXO1ty0K+qP1xmk6wKImG2 0qCZyFSTXai20b1dCl53lKItwIKOvMoDKjSuc/HUtQy9vmebVOvh+qBa7Dh+PsHMosdEMXXqP+UH 0quhJZb25uSgXTcYOWEAM11G1ADEtMo88aKjPvM6/2kwLkDd9p+cJsmWN63nOaK/6mnbVSKVUyqU td+tFjiBdWbjxywbk5yqjKPK2Ww8F22c3HxT4CAnQzb5EuE8XL1mv6JpIzi4mWCZDlZTOpx+FIyw Bm/xhnaQr/2v/pDGj59/i5IjnOcVdo/Vi5QTcmn7K2FjiO/mpF7moxdqWEfLcU8UC17IAggmosvp r2uKGcfLFFb14dq12fy/czja+eevbqQ34gcnAgMBAAGjggMXMIIDEzASBgNVHRMBAf8ECDAGAQH/ AgEBMDcGA1UdEgQwMC6CD3N1c2NlcnRlLmdvYi52ZaAbBgVghl4CAqASDBBSSUYtRy0yMDAwNDAz Ni0wMB0GA1UdDgQWBBRBDxk4qpl/Qguk1yeYVKIXTC1RVDCCAVAGA1UdIwSCAUcwggFDgBStuyId xuDSAaj9dlBSk+2YwU2u06GCASakggEiMIIBHjE+MDwGA1UEAxM1QXV0b3JpZGFkIGRlIENlcnRp ZmljYWNpb24gUmFpeiBkZWwgRXN0YWRvIFZlbmV6b2xhbm8xCzAJBgNVBAYTAlZFMRAwDgYDVQQH EwdDYXJhY2FzMRkwFwYDVQQIExBEaXN0cml0byBDYXBpdGFsMTYwNAYDVQQKEy1TaXN0ZW1hIE5h Y2lvbmFsIGRlIENlcnRpZmljYWNpb24gRWxlY3Ryb25pY2ExQzBBBgNVBAsTOlN1cGVyaW50ZW5k ZW5jaWEgZGUgU2VydmljaW9zIGRlIENlcnRpZmljYWNpb24gRWxlY3Ryb25pY2ExJTAjBgkqhkiG 9w0BCQEWFmFjcmFpekBzdXNjZXJ0ZS5nb2IudmWCAQowDgYDVR0PAQH/BAQDAgEGME0GA1UdEQRG MESCDnByb2NlcnQubmV0LnZloBUGBWCGXgIBoAwMClBTQy0wMDAwMDKgGwYFYIZeAgKgEgwQUklG LUotMzE2MzUzNzMtNzB2BgNVHR8EbzBtMEagRKBChkBodHRwOi8vd3d3LnN1c2NlcnRlLmdvYi52 ZS9sY3IvQ0VSVElGSUNBRE8tUkFJWi1TSEEzODRDUkxERVIuY3JsMCOgIaAfhh1sZGFwOi8vYWNy YWl6LnN1c2NlcnRlLmdvYi52ZTA3BggrBgEFBQcBAQQrMCkwJwYIKwYBBQUHMAGGG2h0dHA6Ly9v Y3NwLnN1c2NlcnRlLmdvYi52ZTBBBgNVHSAEOjA4MDYGBmCGXgMBAjAsMCoGCCsGAQUFBwIBFh5o dHRwOi8vd3d3LnN1c2NlcnRlLmdvYi52ZS9kcGMwDQYJKoZIhvcNAQELBQADggIBACtZ6yKZu4Sq T96QxtGGcSOeSwORR3C7wJJg7ODU523G0+1ng3dS1fLld6c2suNUvtm7CpsR72H0xpkzmfWvADmN g7+mvTV+LFwxNG9s2/NkAZiqlCxB3RWGymspThbASfzXg0gTB1GEMVKIu4YXx2sviiCtxQuPcD4q uxtxj7mkoP3YldmvWb8lK5jpY5MvYB7Eqvh39YtsL+1+LrVPQA3uvFd359m21D+VJzog1eWuq2w1 n8GhHVnchIHuTQfiSLaeS5UtQbHh6N5+LwUeaO6/u5BlOsju6rEYNxxik6SgMexxbJHmpHmJWhSn FFAFTKQAVzAswbVhltw+HoSvOULP5dAssSS830DD7X9jSr3hTxJkhpXzsOfIt+FTvZLm8wyWuevo 5pLtp4EJFAv8lXrPj9Y0TzYS3F7RNHXGRoAvlQSMx4bEqCaJqD8Zm4G7UaRKhqsLEQ+xrmNTbSjq 3TNWOByyrYDT13K9mmyZY+gAu0F2BbdbmRiKw7gSXFbPVgx96OLP7bx0R/vu0xdOIk9W/1DzLuY5 poLWccret9W6aAjtmcz9opLLabid+Qqkpj5PkygqYWwHJgD/ll9ohri4zspV4KuxPX+Y1zMOWj3Y eMLEYC/HYvBhkdI4sPaeVdtAgAUSM84dkpvRabP/v/GSCmE1P93+hvS84Bpxs2Km -----END CERTIFICATE----- China Internet Network Information Center EV Certificates Root ============================================================== -----BEGIN CERTIFICATE----- MIID9zCCAt+gAwIBAgIESJ8AATANBgkqhkiG9w0BAQUFADCBijELMAkGA1UEBhMCQ04xMjAwBgNV BAoMKUNoaW5hIEludGVybmV0IE5ldHdvcmsgSW5mb3JtYXRpb24gQ2VudGVyMUcwRQYDVQQDDD5D aGluYSBJbnRlcm5ldCBOZXR3b3JrIEluZm9ybWF0aW9uIENlbnRlciBFViBDZXJ0aWZpY2F0ZXMg Um9vdDAeFw0xMDA4MzEwNzExMjVaFw0zMDA4MzEwNzExMjVaMIGKMQswCQYDVQQGEwJDTjEyMDAG A1UECgwpQ2hpbmEgSW50ZXJuZXQgTmV0d29yayBJbmZvcm1hdGlvbiBDZW50ZXIxRzBFBgNVBAMM PkNoaW5hIEludGVybmV0IE5ldHdvcmsgSW5mb3JtYXRpb24gQ2VudGVyIEVWIENlcnRpZmljYXRl cyBSb290MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAm35z7r07eKpkQ0H1UN+U8i6y jUqORlTSIRLIOTJCBumD1Z9S7eVnAztUwYyZmczpwA//DdmEEbK40ctb3B75aDFk4Zv6dOtouSCV 98YPjUesWgbdYavi7NifFy2cyjw1l1VxzUOFsUcW9SxTgHbP0wBkvUCZ3czY28Sf1hNfQYOL+Q2H klY0bBoQCxfVWhyXWIQ8hBouXJE0bhlffxdpxWXvayHG1VA6v2G5BY3vbzQ6sm8UY78WO5upKv23 KzhmBsUs4qpnHkWnjQRmQvaPK++IIGmPMowUc9orhpFjIpryp9vOiYurXccUwVswah+xt54ugQEC 7c+WXmPbqOY4twIDAQABo2MwYTAfBgNVHSMEGDAWgBR8cks5x8DbYqVPm6oYNJKiyoOCWTAPBgNV HRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUfHJLOcfA22KlT5uqGDSSosqD glkwDQYJKoZIhvcNAQEFBQADggEBACrDx0M3j92tpLIM7twUbY8opJhJywyA6vPtI2Z1fcXTIWd5 0XPFtQO3WKwMVC/GVhMPMdoG52U7HW8228gd+f2ABsqjPWYWqJ1MFn3AlUa1UeTiH9fqBk1jjZaM 7+czV0I664zBechNdn3e9rG3geCg+aF4RhcaVpjwTj2rHO3sOdwHSPdj/gauwqRcalsyiMXHM4Ws ZkJHwlgkmeHlPuV1LI5D1l08eB6olYIpUNHRFrrvwb562bTYzB5MRuF3sTGrvSrIzo9uoV1/A3U0 5K2JRVRevq4opbs/eHnrc7MKDf2+yfdWrPa37S+bISnHOLaVxATywy39FCqQmbkHzJ8= -----END CERTIFICATE----- Swisscom Root CA 2 ================== -----BEGIN CERTIFICATE----- MIIF2TCCA8GgAwIBAgIQHp4o6Ejy5e/DfEoeWhhntjANBgkqhkiG9w0BAQsFADBkMQswCQYDVQQG EwJjaDERMA8GA1UEChMIU3dpc3Njb20xJTAjBgNVBAsTHERpZ2l0YWwgQ2VydGlmaWNhdGUgU2Vy dmljZXMxGzAZBgNVBAMTElN3aXNzY29tIFJvb3QgQ0EgMjAeFw0xMTA2MjQwODM4MTRaFw0zMTA2 MjUwNzM4MTRaMGQxCzAJBgNVBAYTAmNoMREwDwYDVQQKEwhTd2lzc2NvbTElMCMGA1UECxMcRGln aXRhbCBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczEbMBkGA1UEAxMSU3dpc3Njb20gUm9vdCBDQSAyMIIC IjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAlUJOhJ1R5tMJ6HJaI2nbeHCOFvErjw0DzpPM LgAIe6szjPTpQOYXTKueuEcUMncy3SgM3hhLX3af+Dk7/E6J2HzFZ++r0rk0X2s682Q2zsKwzxNo ysjL67XiPS4h3+os1OD5cJZM/2pYmLcX5BtS5X4HAB1f2uY+lQS3aYg5oUFgJWFLlTloYhyxCwWJ wDaCFCE/rtuh/bxvHGCGtlOUSbkrRsVPACu/obvLP+DHVxxX6NZp+MEkUp2IVd3Chy50I9AU/SpH Wrumnf2U5NGKpV+GY3aFy6//SSj8gO1MedK75MDvAe5QQQg1I3ArqRa0jG6F6bYRzzHdUyYb3y1a SgJA/MTAtukxGggo5WDDH8SQjhBiYEQN7Aq+VRhxLKX0srwVYv8c474d2h5Xszx+zYIdkeNL6yxS NLCK/RJOlrDrcH+eOfdmQrGrrFLadkBXeyq96G4DsguAhYidDMfCd7Camlf0uPoTXGiTOmekl9Ab mbeGMktg2M7v0Ax/lZ9vh0+Hio5fCHyqW/xavqGRn1V9TrALacywlKinh/LTSlDcX3KwFnUey7QY Ypqwpzmqm59m2I2mbJYV4+by+PGDYmy7Velhk6M99bFXi08jsJvllGov34zflVEpYKELKeRcVVi3 qPyZ7iVNTA6z00yPhOgpD/0QVAKFyPnlw4vP5w8CAwEAAaOBhjCBgzAOBgNVHQ8BAf8EBAMCAYYw HQYDVR0hBBYwFDASBgdghXQBUwIBBgdghXQBUwIBMBIGA1UdEwEB/wQIMAYBAf8CAQcwHQYDVR0O BBYEFE0mICKJS9PVpAqhb97iEoHF8TwuMB8GA1UdIwQYMBaAFE0mICKJS9PVpAqhb97iEoHF8Twu MA0GCSqGSIb3DQEBCwUAA4ICAQAyCrKkG8t9voJXiblqf/P0wS4RfbgZPnm3qKhyN2abGu2sEzsO v2LwnN+ee6FTSA5BesogpxcbtnjsQJHzQq0Qw1zv/2BZf82Fo4s9SBwlAjxnffUy6S8w5X2lejjQ 82YqZh6NM4OKb3xuqFp1mrjX2lhIREeoTPpMSQpKwhI3qEAMw8jh0FcNlzKVxzqfl9NX+Ave5XLz o9v/tdhZsnPdTSpxsrpJ9csc1fV5yJmz/MFMdOO0vSk3FQQoHt5FRnDsr7p4DooqzgB53MBfGWcs a0vvaGgLQ+OswWIJ76bdZWGgr4RVSJFSHMYlkSrQwSIjYVmvRRGFHQEkNI/Ps/8XciATwoCqISxx OQ7Qj1zB09GOInJGTB2Wrk9xseEFKZZZ9LuedT3PDTcNYtsmjGOpI99nBjx8Oto0QuFmtEYE3saW mA9LSHokMnWRn6z3aOkquVVlzl1h0ydw2Df+n7mvoC5Wt6NlUe07qxS/TFED6F+KBZvuim6c779o +sjaC+NCydAXFJy3SuCvkychVSa1ZC+N8f+mQAWFBVzKBxlcCxMoTFh/wqXvRdpg065lYZ1Tg3TC rvJcwhbtkj6EPnNgiLx29CzP0H1907he0ZESEOnN3col49XtmS++dYFLJPlFRpTJKSFTnCZFqhMX 5OfNeOI5wSsSnqaeG8XmDtkx2Q== -----END CERTIFICATE----- Swisscom Root EV CA 2 ===================== -----BEGIN CERTIFICATE----- MIIF4DCCA8igAwIBAgIRAPL6ZOJ0Y9ON/RAdBB92ylgwDQYJKoZIhvcNAQELBQAwZzELMAkGA1UE BhMCY2gxETAPBgNVBAoTCFN3aXNzY29tMSUwIwYDVQQLExxEaWdpdGFsIENlcnRpZmljYXRlIFNl cnZpY2VzMR4wHAYDVQQDExVTd2lzc2NvbSBSb290IEVWIENBIDIwHhcNMTEwNjI0MDk0NTA4WhcN MzEwNjI1MDg0NTA4WjBnMQswCQYDVQQGEwJjaDERMA8GA1UEChMIU3dpc3Njb20xJTAjBgNVBAsT HERpZ2l0YWwgQ2VydGlmaWNhdGUgU2VydmljZXMxHjAcBgNVBAMTFVN3aXNzY29tIFJvb3QgRVYg Q0EgMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMT3HS9X6lds93BdY7BxUglgRCgz o3pOCvrY6myLURYaVa5UJsTMRQdBTxB5f3HSek4/OE6zAMaVylvNwSqD1ycfMQ4jFrclyxy0uYAy Xhqdk/HoPGAsp15XGVhRXrwsVgu42O+LgrQ8uMIkqBPHoCE2G3pXKSinLr9xJZDzRINpUKTk4Rti GZQJo/PDvO/0vezbE53PnUgJUmfANykRHvvSEaeFGHR55E+FFOtSN+KxRdjMDUN/rhPSays/p8Li qG12W0OfvrSdsyaGOx9/5fLoZigWJdBLlzin5M8J0TbDC77aO0RYjb7xnglrPvMyxyuHxuxenPaH Za0zKcQvidm5y8kDnftslFGXEBuGCxobP/YCfnvUxVFkKJ3106yDgYjTdLRZncHrYTNaRdHLOdAG alNgHa/2+2m8atwBz735j9m9W8E6X47aD0upm50qKGsaCnw8qyIL5XctcfaCNYGu+HuB5ur+rPQa m3Rc6I8k9l2dRsQs0h4rIWqDJ2dVSqTjyDKXZpBy2uPUZC5f46Fq9mDU5zXNysRojddxyNMkM3Ox bPlq4SjbX8Y96L5V5jcb7STZDxmPX2MYWFCBUWVv8p9+agTnNCRxunZLWB4ZvRVgRaoMEkABnRDi xzgHcgplwLa7JSnaFp6LNYth7eVxV4O1PHGf40+/fh6Bn0GXAgMBAAGjgYYwgYMwDgYDVR0PAQH/ BAQDAgGGMB0GA1UdIQQWMBQwEgYHYIV0AVMCAgYHYIV0AVMCAjASBgNVHRMBAf8ECDAGAQH/AgED MB0GA1UdDgQWBBRF2aWBbj2ITY1x0kbBbkUe88SAnTAfBgNVHSMEGDAWgBRF2aWBbj2ITY1x0kbB bkUe88SAnTANBgkqhkiG9w0BAQsFAAOCAgEAlDpzBp9SSzBc1P6xXCX5145v9Ydkn+0UjrgEjihL j6p7jjm02Vj2e6E1CqGdivdj5eu9OYLU43otb98TPLr+flaYC/NUn81ETm484T4VvwYmneTwkLbU wp4wLh/vx3rEUMfqe9pQy3omywC0Wqu1kx+AiYQElY2NfwmTv9SoqORjbdlk5LgpWgi/UOGED1V7 XwgiG/W9mR4U9s70WBCCswo9GcG/W6uqmdjyMb3lOGbcWAXH7WMaLgqXfIeTK7KK4/HsGOV1timH 59yLGn602MnTihdsfSlEvoqq9X46Lmgxk7lq2prg2+kupYTNHAq4Sgj5nPFhJpiTt3tm7JFe3VE/ 23MPrQRYCd0EApUKPtN236YQHoA96M2kZNEzx5LH4k5E4wnJTsJdhw4Snr8PyQUQ3nqjsTzyP6Wq J3mtMX0f/fwZacXduT98zca0wjAefm6S139hdlqP65VNvBFuIXxZN5nQBrz5Bm0yFqXZaajh3DyA HmBR3NdUIR7KYndP+tiPsys6DXhyyWhBWkdKwqPrGtcKqzwyVcgKEZzfdNbwQBUdyLmPtTbFr/gi uMod89a2GQ+fYWVq6nTIfI/DT11lgh/ZDYnadXL77/FHZxOzyNEZiCcmmpl5fx7kLD977vHeTYuW l8PVP3wbI+2ksx0WckNLIOFZfsLorSa/ovc= -----END CERTIFICATE----- CA Disig Root R1 ================ -----BEGIN CERTIFICATE----- MIIFaTCCA1GgAwIBAgIJAMMDmu5QkG4oMA0GCSqGSIb3DQEBBQUAMFIxCzAJBgNVBAYTAlNLMRMw EQYDVQQHEwpCcmF0aXNsYXZhMRMwEQYDVQQKEwpEaXNpZyBhLnMuMRkwFwYDVQQDExBDQSBEaXNp ZyBSb290IFIxMB4XDTEyMDcxOTA5MDY1NloXDTQyMDcxOTA5MDY1NlowUjELMAkGA1UEBhMCU0sx EzARBgNVBAcTCkJyYXRpc2xhdmExEzARBgNVBAoTCkRpc2lnIGEucy4xGTAXBgNVBAMTEENBIERp c2lnIFJvb3QgUjEwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCqw3j33Jijp1pedxiy 3QRkD2P9m5YJgNXoqqXinCaUOuiZc4yd39ffg/N4T0Dhf9Kn0uXKE5Pn7cZ3Xza1lK/oOI7bm+V8 u8yN63Vz4STN5qctGS7Y1oprFOsIYgrY3LMATcMjfF9DCCMyEtztDK3AfQ+lekLZWnDZv6fXARz2 m6uOt0qGeKAeVjGu74IKgEH3G8muqzIm1Cxr7X1r5OJeIgpFy4QxTaz+29FHuvlglzmxZcfe+5nk CiKxLU3lSCZpq+Kq8/v8kiky6bM+TR8noc2OuRf7JT7JbvN32g0S9l3HuzYQ1VTW8+DiR0jm3hTa YVKvJrT1cU/J19IG32PK/yHoWQbgCNWEFVP3Q+V8xaCJmGtzxmjOZd69fwX3se72V6FglcXM6pM6 vpmumwKjrckWtc7dXpl4fho5frLABaTAgqWjR56M6ly2vGfb5ipN0gTco65F97yLnByn1tUD3AjL LhbKXEAz6GfDLuemROoRRRw1ZS0eRWEkG4IupZ0zXWX4Qfkuy5Q/H6MMMSRE7cderVC6xkGbrPAX ZcD4XW9boAo0PO7X6oifmPmvTiT6l7Jkdtqr9O3jw2Dv1fkCyC2fg69naQanMVXVz0tv/wQFx1is XxYb5dKj6zHbHzMVTdDypVP1y+E9Tmgt2BLdqvLmTZtJ5cUoobqwWsagtQIDAQABo0IwQDAPBgNV HRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUiQq0OJMa5qvum5EY+fU8PjXQ 04IwDQYJKoZIhvcNAQEFBQADggIBADKL9p1Kyb4U5YysOMo6CdQbzoaz3evUuii+Eq5FLAR0rBNR xVgYZk2C2tXck8An4b58n1KeElb21Zyp9HWc+jcSjxyT7Ff+Bw+r1RL3D65hXlaASfX8MPWbTx9B LxyE04nH4toCdu0Jz2zBuByDHBb6lM19oMgY0sidbvW9adRtPTXoHqJPYNcHKfyyo6SdbhWSVhlM CrDpfNIZTUJG7L399ldb3Zh+pE3McgODWF3vkzpBemOqfDqo9ayk0d2iLbYq/J8BjuIQscTK5Gfb VSUZP/3oNn6z4eGBrxEWi1CXYBmCAMBrTXO40RMHPuq2MU/wQppt4hF05ZSsjYSVPCGvxdpHyN85 YmLLW1AL14FABZyb7bq2ix4Eb5YgOe2kfSnbSM6C3NQCjR0EMVrHS/BsYVLXtFHCgWzN4funodKS ds+xDzdYpPJScWc/DIh4gInByLUfkmO+p3qKViwaqKactV2zY9ATIKHrkWzQjX2v3wvkF7mGnjix lAxYjOBVqjtjbZqJYLhkKpLGN/R+Q0O3c+gB53+XD9fyexn9GtePyfqFa3qdnom2piiZk4hA9z7N UaPK6u95RyG1/jLix8NRb76AdPCkwzryT+lf3xkK8jsTQ6wxpLPn6/wY1gGp8yqPNg7rtLG8t0zJ a7+h89n07eLw4+1knj0vllJPgFOL -----END CERTIFICATE----- CA Disig Root R2 ================ -----BEGIN CERTIFICATE----- MIIFaTCCA1GgAwIBAgIJAJK4iNuwisFjMA0GCSqGSIb3DQEBCwUAMFIxCzAJBgNVBAYTAlNLMRMw EQYDVQQHEwpCcmF0aXNsYXZhMRMwEQYDVQQKEwpEaXNpZyBhLnMuMRkwFwYDVQQDExBDQSBEaXNp ZyBSb290IFIyMB4XDTEyMDcxOTA5MTUzMFoXDTQyMDcxOTA5MTUzMFowUjELMAkGA1UEBhMCU0sx EzARBgNVBAcTCkJyYXRpc2xhdmExEzARBgNVBAoTCkRpc2lnIGEucy4xGTAXBgNVBAMTEENBIERp c2lnIFJvb3QgUjIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCio8QACdaFXS1tFPbC w3OeNcJxVX6B+6tGUODBfEl45qt5WDza/3wcn9iXAng+a0EE6UG9vgMsRfYvZNSrXaNHPWSb6Wia xswbP7q+sos0Ai6YVRn8jG+qX9pMzk0DIaPY0jSTVpbLTAwAFjxfGs3Ix2ymrdMxp7zo5eFm1tL7 A7RBZckQrg4FY8aAamkw/dLukO8NJ9+flXP04SXabBbeQTg06ov80egEFGEtQX6sx3dOy1FU+16S GBsEWmjGycT6txOgmLcRK7fWV8x8nhfRyyX+hk4kLlYMeE2eARKmK6cBZW58Yh2EhN/qwGu1pSqV g8NTEQxzHQuyRpDRQjrOQG6Vrf/GlK1ul4SOfW+eioANSW1z4nuSHsPzwfPrLgVv2RvPN3YEyLRa 5Beny912H9AZdugsBbPWnDTYltxhh5EF5EQIM8HauQhl1K6yNg3ruji6DOWbnuuNZt2Zz9aJQfYE koopKW1rOhzndX0CcQ7zwOe9yxndnWCywmZgtrEE7snmhrmaZkCo5xHtgUUDi/ZnWejBBhG93c+A Ak9lQHhcR1DIm+YfgXvkRKhbhZri3lrVx/k6RGZL5DJUfORsnLMOPReisjQS1n6yqEm70XooQL6i Fh/f5DcfEXP7kAplQ6INfPgGAVUzfbANuPT1rqVCV3w2EYx7XsQDnYx5nQIDAQABo0IwQDAPBgNV HRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUtZn4r7CU9eMg1gqtzk5WpC5u Qu0wDQYJKoZIhvcNAQELBQADggIBACYGXnDnZTPIgm7ZnBc6G3pmsgH2eDtpXi/q/075KMOYKmFM tCQSin1tERT3nLXK5ryeJ45MGcipvXrA1zYObYVybqjGom32+nNjf7xueQgcnYqfGopTpti72TVV sRHFqQOzVju5hJMiXn7B9hJSi+osZ7z+Nkz1uM/Rs0mSO9MpDpkblvdhuDvEK7Z4bLQjb/D907Je dR+Zlais9trhxTF7+9FGs9K8Z7RiVLoJ92Owk6Ka+elSLotgEqv89WBW7xBci8QaQtyDW2QOy7W8 1k/BfDxujRNt+3vrMNDcTa/F1balTFtxyegxvug4BkihGuLq0t4SOVga/4AOgnXmt8kHbA7v/zjx mHHEt38OFdAlab0inSvtBfZGR6ztwPDUO+Ls7pZbkBNOHlY667DvlruWIxG68kOGdGSVyCh13x01 utI3gzhTODY7z2zp+WsO0PsE6E9312UBeIYMej4hYvF/Y3EMyZ9E26gnonW+boE+18DrG5gPcFw0 sorMwIUY6256s/daoQe/qUKS82Ail+QUoQebTnbAjn39pCXHR+3/H3OszMOl6W8KjptlwlCFtaOg UxLMVYdh84GuEEZhvUQhuMI9dM9+JDX6HAcOmz0iyu8xL4ysEr3vQCj8KWefshNPZiTEUxnpHikV 7+ZtsH8tZ/3zbBt1RqPlShfppNcL -----END CERTIFICATE----- ACCVRAIZ1 ========= -----BEGIN CERTIFICATE----- MIIH0zCCBbugAwIBAgIIXsO3pkN/pOAwDQYJKoZIhvcNAQEFBQAwQjESMBAGA1UEAwwJQUNDVlJB SVoxMRAwDgYDVQQLDAdQS0lBQ0NWMQ0wCwYDVQQKDARBQ0NWMQswCQYDVQQGEwJFUzAeFw0xMTA1 MDUwOTM3MzdaFw0zMDEyMzEwOTM3MzdaMEIxEjAQBgNVBAMMCUFDQ1ZSQUlaMTEQMA4GA1UECwwH UEtJQUNDVjENMAsGA1UECgwEQUNDVjELMAkGA1UEBhMCRVMwggIiMA0GCSqGSIb3DQEBAQUAA4IC DwAwggIKAoICAQCbqau/YUqXry+XZpp0X9DZlv3P4uRm7x8fRzPCRKPfmt4ftVTdFXxpNRFvu8gM jmoYHtiP2Ra8EEg2XPBjs5BaXCQ316PWywlxufEBcoSwfdtNgM3802/J+Nq2DoLSRYWoG2ioPej0 RGy9ocLLA76MPhMAhN9KSMDjIgro6TenGEyxCQ0jVn8ETdkXhBilyNpAlHPrzg5XPAOBOp0KoVdD aaxXbXmQeOW1tDvYvEyNKKGno6e6Ak4l0Squ7a4DIrhrIA8wKFSVf+DuzgpmndFALW4ir50awQUZ 0m/A8p/4e7MCQvtQqR0tkw8jq8bBD5L/0KIV9VMJcRz/RROE5iZe+OCIHAr8Fraocwa48GOEAqDG WuzndN9wrqODJerWx5eHk6fGioozl2A3ED6XPm4pFdahD9GILBKfb6qkxkLrQaLjlUPTAYVtjrs7 8yM2x/474KElB0iryYl0/wiPgL/AlmXz7uxLaL2diMMxs0Dx6M/2OLuc5NF/1OVYm3z61PMOm3WR 5LpSLhl+0fXNWhn8ugb2+1KoS5kE3fj5tItQo05iifCHJPqDQsGH+tUtKSpacXpkatcnYGMN285J 9Y0fkIkyF/hzQ7jSWpOGYdbhdQrqeWZ2iE9x6wQl1gpaepPluUsXQA+xtrn13k/c4LOsOxFwYIRK Q26ZIMApcQrAZQIDAQABo4ICyzCCAscwfQYIKwYBBQUHAQEEcTBvMEwGCCsGAQUFBzAChkBodHRw Oi8vd3d3LmFjY3YuZXMvZmlsZWFkbWluL0FyY2hpdm9zL2NlcnRpZmljYWRvcy9yYWl6YWNjdjEu Y3J0MB8GCCsGAQUFBzABhhNodHRwOi8vb2NzcC5hY2N2LmVzMB0GA1UdDgQWBBTSh7Tj3zcnk1X2 VuqB5TbMjB4/vTAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFNKHtOPfNyeTVfZW6oHlNsyM Hj+9MIIBcwYDVR0gBIIBajCCAWYwggFiBgRVHSAAMIIBWDCCASIGCCsGAQUFBwICMIIBFB6CARAA QQB1AHQAbwByAGkAZABhAGQAIABkAGUAIABDAGUAcgB0AGkAZgBpAGMAYQBjAGkA8wBuACAAUgBh AO0AegAgAGQAZQAgAGwAYQAgAEEAQwBDAFYAIAAoAEEAZwBlAG4AYwBpAGEAIABkAGUAIABUAGUA YwBuAG8AbABvAGcA7QBhACAAeQAgAEMAZQByAHQAaQBmAGkAYwBhAGMAaQDzAG4AIABFAGwAZQBj AHQAcgDzAG4AaQBjAGEALAAgAEMASQBGACAAUQA0ADYAMAAxADEANQA2AEUAKQAuACAAQwBQAFMA IABlAG4AIABoAHQAdABwADoALwAvAHcAdwB3AC4AYQBjAGMAdgAuAGUAczAwBggrBgEFBQcCARYk aHR0cDovL3d3dy5hY2N2LmVzL2xlZ2lzbGFjaW9uX2MuaHRtMFUGA1UdHwROMEwwSqBIoEaGRGh0 dHA6Ly93d3cuYWNjdi5lcy9maWxlYWRtaW4vQXJjaGl2b3MvY2VydGlmaWNhZG9zL3JhaXphY2N2 MV9kZXIuY3JsMA4GA1UdDwEB/wQEAwIBBjAXBgNVHREEEDAOgQxhY2N2QGFjY3YuZXMwDQYJKoZI hvcNAQEFBQADggIBAJcxAp/n/UNnSEQU5CmH7UwoZtCPNdpNYbdKl02125DgBS4OxnnQ8pdpD70E R9m+27Up2pvZrqmZ1dM8MJP1jaGo/AaNRPTKFpV8M9xii6g3+CfYCS0b78gUJyCpZET/LtZ1qmxN YEAZSUNUY9rizLpm5U9EelvZaoErQNV/+QEnWCzI7UiRfD+mAM/EKXMRNt6GGT6d7hmKG9Ww7Y49 nCrADdg9ZuM8Db3VlFzi4qc1GwQA9j9ajepDvV+JHanBsMyZ4k0ACtrJJ1vnE5Bc5PUzolVt3OAJ TS+xJlsndQAJxGJ3KQhfnlmstn6tn1QwIgPBHnFk/vk4CpYY3QIUrCPLBhwepH2NDd4nQeit2hW3 sCPdK6jT2iWH7ehVRE2I9DZ+hJp4rPcOVkkO1jMl1oRQQmwgEh0q1b688nCBpHBgvgW1m54ERL5h I6zppSSMEYCUWqKiuUnSwdzRp+0xESyeGabu4VXhwOrPDYTkF7eifKXeVSUG7szAh1xA2syVP1Xg Nce4hL60Xc16gwFy7ofmXx2utYXGJt/mwZrpHgJHnyqobalbz+xFd3+YJ5oyXSrjhO7FmGYvliAd 3djDJ9ew+f7Zfc3Qn48LFFhRny+Lwzgt3uiP1o2HpPVWQxaZLPSkVrQ0uGE3ycJYgBugl6H8WY3p EfbRD0tVNEYqi4Y7 -----END CERTIFICATE----- TWCA Global Root CA =================== -----BEGIN CERTIFICATE----- MIIFQTCCAymgAwIBAgICDL4wDQYJKoZIhvcNAQELBQAwUTELMAkGA1UEBhMCVFcxEjAQBgNVBAoT CVRBSVdBTi1DQTEQMA4GA1UECxMHUm9vdCBDQTEcMBoGA1UEAxMTVFdDQSBHbG9iYWwgUm9vdCBD QTAeFw0xMjA2MjcwNjI4MzNaFw0zMDEyMzExNTU5NTlaMFExCzAJBgNVBAYTAlRXMRIwEAYDVQQK EwlUQUlXQU4tQ0ExEDAOBgNVBAsTB1Jvb3QgQ0ExHDAaBgNVBAMTE1RXQ0EgR2xvYmFsIFJvb3Qg Q0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCwBdvI64zEbooh745NnHEKH1Jw7W2C nJfF10xORUnLQEK1EjRsGcJ0pDFfhQKX7EMzClPSnIyOt7h52yvVavKOZsTuKwEHktSz0ALfUPZV r2YOy+BHYC8rMjk1Ujoog/h7FsYYuGLWRyWRzvAZEk2tY/XTP3VfKfChMBwqoJimFb3u/Rk28OKR Q4/6ytYQJ0lM793B8YVwm8rqqFpD/G2Gb3PpN0Wp8DbHzIh1HrtsBv+baz4X7GGqcXzGHaL3SekV tTzWoWH1EfcFbx39Eb7QMAfCKbAJTibc46KokWofwpFFiFzlmLhxpRUZyXx1EcxwdE8tmx2RRP1W KKD+u4ZqyPpcC1jcxkt2yKsi2XMPpfRaAok/T54igu6idFMqPVMnaR1sjjIsZAAmY2E2TqNGtz99 sy2sbZCilaLOz9qC5wc0GZbpuCGqKX6mOL6OKUohZnkfs8O1CWfe1tQHRvMq2uYiN2DLgbYPoA/p yJV/v1WRBXrPPRXAb94JlAGD1zQbzECl8LibZ9WYkTunhHiVJqRaCPgrdLQABDzfuBSO6N+pjWxn kjMdwLfS7JLIvgm/LCkFbwJrnu+8vyq8W8BQj0FwcYeyTbcEqYSjMq+u7msXi7Kx/mzhkIyIqJdI zshNy/MGz19qCkKxHh53L46g5pIOBvwFItIm4TFRfTLcDwIDAQABoyMwITAOBgNVHQ8BAf8EBAMC AQYwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAgEAXzSBdu+WHdXltdkCY4QWwa6g cFGn90xHNcgL1yg9iXHZqjNB6hQbbCEAwGxCGX6faVsgQt+i0trEfJdLjbDorMjupWkEmQqSpqsn LhpNgb+E1HAerUf+/UqdM+DyucRFCCEK2mlpc3INvjT+lIutwx4116KD7+U4x6WFH6vPNOw/KP4M 8VeGTslV9xzU2KV9Bnpv1d8Q34FOIWWxtuEXeZVFBs5fzNxGiWNoRI2T9GRwoD2dKAXDOXC4Ynsg /eTb6QihuJ49CcdP+yz4k3ZB3lLg4VfSnQO8d57+nile98FRYB/e2guyLXW3Q0iT5/Z5xoRdgFlg lPx4mI88k1HtQJAH32RjJMtOcQWh15QaiDLxInQirqWm2BJpTGCjAu4r7NRjkgtevi92a6O2JryP A9gK8kxkRr05YuWW6zRjESjMlfGt7+/cgFhI6Uu46mWs6fyAtbXIRfmswZ/ZuepiiI7E8UuDEq3m i4TWnsLrgxifarsbJGAzcMzs9zLzXNl5fe+epP7JI8Mk7hWSsT2RTyaGvWZzJBPqpK5jwa19hAM8 EHiGG3njxPPyBJUgriOCxLM6AGK/5jYk4Ve6xx6QddVfP5VhK8E7zeWzaGHQRiapIVJpLesux+t3 zqY6tQMzT3bR51xUAV3LePTJDL/PEo4XLSNolOer/qmyKwbQBM0= -----END CERTIFICATE----- TeliaSonera Root CA v1 ====================== -----BEGIN CERTIFICATE----- MIIFODCCAyCgAwIBAgIRAJW+FqD3LkbxezmCcvqLzZYwDQYJKoZIhvcNAQEFBQAwNzEUMBIGA1UE CgwLVGVsaWFTb25lcmExHzAdBgNVBAMMFlRlbGlhU29uZXJhIFJvb3QgQ0EgdjEwHhcNMDcxMDE4 MTIwMDUwWhcNMzIxMDE4MTIwMDUwWjA3MRQwEgYDVQQKDAtUZWxpYVNvbmVyYTEfMB0GA1UEAwwW VGVsaWFTb25lcmEgUm9vdCBDQSB2MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMK+ 6yfwIaPzaSZVfp3FVRaRXP3vIb9TgHot0pGMYzHw7CTww6XScnwQbfQ3t+XmfHnqjLWCi65ItqwA 3GV17CpNX8GH9SBlK4GoRz6JI5UwFpB/6FcHSOcZrr9FZ7E3GwYq/t75rH2D+1665I+XZ75Ljo1k B1c4VWk0Nj0TSO9P4tNmHqTPGrdeNjPUtAa9GAH9d4RQAEX1jF3oI7x+/jXh7VB7qTCNGdMJjmhn Xb88lxhTuylixcpecsHHltTbLaC0H2kD7OriUPEMPPCs81Mt8Bz17Ww5OXOAFshSsCPN4D7c3TxH oLs1iuKYaIu+5b9y7tL6pe0S7fyYGKkmdtwoSxAgHNN/Fnct7W+A90m7UwW7XWjH1Mh1Fj+JWov3 F0fUTPHSiXk+TT2YqGHeOh7S+F4D4MHJHIzTjU3TlTazN19jY5szFPAtJmtTfImMMsJu7D0hADnJ oWjiUIMusDor8zagrC/kb2HCUQk5PotTubtn2txTuXZZNp1D5SDgPTJghSJRt8czu90VL6R4pgd7 gUY2BIbdeTXHlSw7sKMXNeVzH7RcWe/a6hBle3rQf5+ztCo3O3CLm1u5K7fsslESl1MpWtTwEhDc TwK7EpIvYtQ/aUN8Ddb8WHUBiJ1YFkveupD/RwGJBmr2X7KQarMCpgKIv7NHfirZ1fpoeDVNAgMB AAGjPzA9MA8GA1UdEwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMB0GA1UdDgQWBBTwj1k4ALP1j5qW DNXr+nuqF+gTEjANBgkqhkiG9w0BAQUFAAOCAgEAvuRcYk4k9AwI//DTDGjkk0kiP0Qnb7tt3oNm zqjMDfz1mgbldxSR651Be5kqhOX//CHBXfDkH1e3damhXwIm/9fH907eT/j3HEbAek9ALCI18Bmx 0GtnLLCo4MBANzX2hFxc469CeP6nyQ1Q6g2EdvZR74NTxnr/DlZJLo961gzmJ1TjTQpgcmLNkQfW pb/ImWvtxBnmq0wROMVvMeJuScg/doAmAyYp4Db29iBT4xdwNBedY2gea+zDTYa4EzAvXUYNR0PV G6pZDrlcjQZIrXSHX8f8MVRBE+LHIQ6e4B4N4cB7Q4WQxYpYxmUKeFfyxiMPAdkgS94P+5KFdSpc c41teyWRyu5FrgZLAMzTsVlQ2jqIOylDRl6XK1TOU2+NSueW+r9xDkKLfP0ooNBIytrEgUy7onOT JsjrDNYmiLbAJM+7vVvrdX3pCI6GMyx5dwlppYn8s3CQh3aP0yK7Qs69cwsgJirQmz1wHiRszYd2 qReWt88NkvuOGKmYSdGe/mBEciG5Ge3C9THxOUiIkCR1VBatzvT4aRRkOfujuLpwQMcnHL/EVlP6 Y2XQ8xwOFvVrhlhNGNTkDY6lnVuR3HYkUD/GKvvZt5y11ubQ2egZixVxSK236thZiNSQvxaz2ems WWFUyBy6ysHK4bkgTI86k4mloMy/0/Z1pHWWbVY= -----END CERTIFICATE----- E-Tugra Certification Authority =============================== -----BEGIN CERTIFICATE----- MIIGSzCCBDOgAwIBAgIIamg+nFGby1MwDQYJKoZIhvcNAQELBQAwgbIxCzAJBgNVBAYTAlRSMQ8w DQYDVQQHDAZBbmthcmExQDA+BgNVBAoMN0UtVHXEn3JhIEVCRyBCaWxpxZ9pbSBUZWtub2xvamls ZXJpIHZlIEhpem1ldGxlcmkgQS7Fni4xJjAkBgNVBAsMHUUtVHVncmEgU2VydGlmaWthc3lvbiBN ZXJrZXppMSgwJgYDVQQDDB9FLVR1Z3JhIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTEzMDMw NTEyMDk0OFoXDTIzMDMwMzEyMDk0OFowgbIxCzAJBgNVBAYTAlRSMQ8wDQYDVQQHDAZBbmthcmEx QDA+BgNVBAoMN0UtVHXEn3JhIEVCRyBCaWxpxZ9pbSBUZWtub2xvamlsZXJpIHZlIEhpem1ldGxl cmkgQS7Fni4xJjAkBgNVBAsMHUUtVHVncmEgU2VydGlmaWthc3lvbiBNZXJrZXppMSgwJgYDVQQD DB9FLVR1Z3JhIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0BAQEFAAOCAg8A MIICCgKCAgEA4vU/kwVRHoViVF56C/UYB4Oufq9899SKa6VjQzm5S/fDxmSJPZQuVIBSOTkHS0vd hQd2h8y/L5VMzH2nPbxHD5hw+IyFHnSOkm0bQNGZDbt1bsipa5rAhDGvykPL6ys06I+XawGb1Q5K CKpbknSFQ9OArqGIW66z6l7LFpp3RMih9lRozt6Plyu6W0ACDGQXwLWTzeHxE2bODHnv0ZEoq1+g ElIwcxmOj+GMB6LDu0rw6h8VqO4lzKRG+Bsi77MOQ7osJLjFLFzUHPhdZL3Dk14opz8n8Y4e0ypQ BaNV2cvnOVPAmJ6MVGKLJrD3fY185MaeZkJVgkfnsliNZvcHfC425lAcP9tDJMW/hkd5s3kc91r0 E+xs+D/iWR+V7kI+ua2oMoVJl0b+SzGPWsutdEcf6ZG33ygEIqDUD13ieU/qbIWGvaimzuT6w+Gz rt48Ue7LE3wBf4QOXVGUnhMMti6lTPk5cDZvlsouDERVxcr6XQKj39ZkjFqzAQqptQpHF//vkUAq jqFGOjGY5RH8zLtJVor8udBhmm9lbObDyz51Sf6Pp+KJxWfXnUYTTjF2OySznhFlhqt/7x3U+Lzn rFpct1pHXFXOVbQicVtbC/DP3KBhZOqp12gKY6fgDT+gr9Oq0n7vUaDmUStVkhUXU8u3Zg5mTPj5 dUyQ5xJwx0UCAwEAAaNjMGEwHQYDVR0OBBYEFC7j27JJ0JxUeVz6Jyr+zE7S6E5UMA8GA1UdEwEB /wQFMAMBAf8wHwYDVR0jBBgwFoAULuPbsknQnFR5XPonKv7MTtLoTlQwDgYDVR0PAQH/BAQDAgEG MA0GCSqGSIb3DQEBCwUAA4ICAQAFNzr0TbdF4kV1JI+2d1LoHNgQk2Xz8lkGpD4eKexd0dCrfOAK kEh47U6YA5n+KGCRHTAduGN8qOY1tfrTYXbm1gdLymmasoR6d5NFFxWfJNCYExL/u6Au/U5Mh/jO XKqYGwXgAEZKgoClM4so3O0409/lPun++1ndYYRP0lSWE2ETPo+Aab6TR7U1Q9Jauz1c77NCR807 VRMGsAnb/WP2OogKmW9+4c4bU2pEZiNRCHu8W1Ki/QY3OEBhj0qWuJA3+GbHeJAAFS6LrVE1Uweo a2iu+U48BybNCAVwzDk/dr2l02cmAYamU9JgO3xDf1WKvJUawSg5TB9D0pH0clmKuVb8P7Sd2nCc dlqMQ1DujjByTd//SffGqWfZbawCEeI6FiWnWAjLb1NBnEg4R2gz0dfHj9R0IdTDBZB6/86WiLEV KV0jq9BgoRJP3vQXzTLlyb/IQ639Lo7xr+L0mPoSHyDYwKcMhcWQ9DstliaxLL5Mq+ux0orJ23gT Dx4JnW2PAJ8C2sH6H3p6CcRK5ogql5+Ji/03X186zjhZhkuvcQu02PJwT58yE+Owp1fl2tpDy4Q0 8ijE6m30Ku/Ba3ba+367hTzSU8JNvnHhRdH9I2cNE3X7z2VnIp2usAnRCf8dNL/+I5c30jn6PQ0G C7TbO6Orb1wdtn7os4I07QZcJA== -----END CERTIFICATE----- T-TeleSec GlobalRoot Class 2 ============================ -----BEGIN CERTIFICATE----- MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoM IlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBU cnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwHhcNMDgx MDAxMTA0MDE0WhcNMzMxMDAxMjM1OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lz dGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBD ZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwggEiMA0GCSqGSIb3 DQEBAQUAA4IBDwAwggEKAoIBAQCqX9obX+hzkeXaXPSi5kfl82hVYAUdAqSzm1nzHoqvNK38DcLZ SBnuaY/JIPwhqgcZ7bBcrGXHX+0CfHt8LRvWurmAwhiCFoT6ZrAIxlQjgeTNuUk/9k9uN0goOA/F vudocP05l03Sx5iRUKrERLMjfTlH6VJi1hKTXrcxlkIF+3anHqP1wvzpesVsqXFP6st4vGCvx970 2cu+fjOlbpSD8DT6IavqjnKgP6TeMFvvhk1qlVtDRKgQFRzlAVfFmPHmBiiRqiDFt1MmUUOyCxGV WOHAD3bZwI18gfNycJ5v/hqO2V81xrJvNHy+SE/iWjnX2J14np+GPgNeGYtEotXHAgMBAAGjQjBA MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS/WSA2AHmgoCJrjNXy YdK4LMuCSjANBgkqhkiG9w0BAQsFAAOCAQEAMQOiYQsfdOhyNsZt+U2e+iKo4YFWz827n+qrkRk4 r6p8FU3ztqONpfSO9kSpp+ghla0+AGIWiPACuvxhI+YzmzB6azZie60EI4RYZeLbK4rnJVM3YlNf vNoBYimipidx5joifsFvHZVwIEoHNN/q/xWA5brXethbdXwFeilHfkCoMRN3zUA7tFFHei4R40cR 3p1m0IvVVGb6g1XqfMIpiRvpb7PO4gWEyS8+eIVibslfwXhjdFjASBgMmTnrpMwatXlajRWc2BQN 9noHV8cigwUtPJslJj0Ys6lDfMjIq2SPDqO/nBudMNva0Bkuqjzx+zOAduTNrRlPBSeOE6Fuwg== -----END CERTIFICATE----- Atos TrustedRoot 2011 ===================== -----BEGIN CERTIFICATE----- MIIDdzCCAl+gAwIBAgIIXDPLYixfszIwDQYJKoZIhvcNAQELBQAwPDEeMBwGA1UEAwwVQXRvcyBU cnVzdGVkUm9vdCAyMDExMQ0wCwYDVQQKDARBdG9zMQswCQYDVQQGEwJERTAeFw0xMTA3MDcxNDU4 MzBaFw0zMDEyMzEyMzU5NTlaMDwxHjAcBgNVBAMMFUF0b3MgVHJ1c3RlZFJvb3QgMjAxMTENMAsG A1UECgwEQXRvczELMAkGA1UEBhMCREUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCV hTuXbyo7LjvPpvMpNb7PGKw+qtn4TaA+Gke5vJrf8v7MPkfoepbCJI419KkM/IL9bcFyYie96mvr 54rMVD6QUM+A1JX76LWC1BTFtqlVJVfbsVD2sGBkWXppzwO3bw2+yj5vdHLqqjAqc2K+SZFhyBH+ DgMq92og3AIVDV4VavzjgsG1xZ1kCWyjWZgHJ8cblithdHFsQ/H3NYkQ4J7sVaE3IqKHBAUsR320 HLliKWYoyrfhk/WklAOZuXCFteZI6o1Q/NnezG8HDt0Lcp2AMBYHlT8oDv3FdU9T1nSatCQujgKR z3bFmx5VdJx4IbHwLfELn8LVlhgf8FQieowHAgMBAAGjfTB7MB0GA1UdDgQWBBSnpQaxLKYJYO7R l+lwrrw7GWzbITAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFKelBrEspglg7tGX6XCuvDsZ bNshMBgGA1UdIAQRMA8wDQYLKwYBBAGwLQMEAQEwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEB CwUAA4IBAQAmdzTblEiGKkGdLD4GkGDEjKwLVLgfuXvTBznk+j57sj1O7Z8jvZfza1zv7v1Apt+h k6EKhqzvINB5Ab149xnYJDE0BAGmuhWawyfc2E8PzBhj/5kPDpFrdRbhIfzYJsdHt6bPWHJxfrrh TZVHO8mvbaG0weyJ9rQPOLXiZNwlz6bb65pcmaHFCN795trV1lpFDMS3wrUU77QR/w4VtfX128a9 61qn8FYiqTxlVMYVqL2Gns2Dlmh6cYGJ4Qvh6hEbaAjMaZ7snkGeRDImeuKHCnE96+RapNLbxc3G 3mB/ufNPRJLvKrcYPqcZ2Qt9sTdBQrC6YB3y/gkRsPCHe6ed -----END CERTIFICATE----- createRequest($method, $url, null, null, $options); if (isset($options['stream'])) { if ($options['stream'] instanceof StreamRequestFactoryInterface) { return $options['stream']->fromRequest($request); } elseif ($options['stream'] == true) { $streamFactory = new PhpStreamRequestFactory(); return $streamFactory->fromRequest($request); } } return $request->send(); } /** * Send a GET request * * @param string $url URL of the request * @param array $options Array of request options * * @return \Guzzle\Http\Message\Response * @see Guzzle::request for a list of available options */ public static function get($url, $options = array()) { return self::request('GET', $url, $options); } /** * Send a HEAD request * * @param string $url URL of the request * @param array $options Array of request options * * @return \Guzzle\Http\Message\Response * @see Guzzle::request for a list of available options */ public static function head($url, $options = array()) { return self::request('HEAD', $url, $options); } /** * Send a DELETE request * * @param string $url URL of the request * @param array $options Array of request options * * @return \Guzzle\Http\Message\Response * @see Guzzle::request for a list of available options */ public static function delete($url, $options = array()) { return self::request('DELETE', $url, $options); } /** * Send a POST request * * @param string $url URL of the request * @param array $options Array of request options * * @return \Guzzle\Http\Message\Response * @see Guzzle::request for a list of available options */ public static function post($url, $options = array()) { return self::request('POST', $url, $options); } /** * Send a PUT request * * @param string $url URL of the request * @param array $options Array of request options * * @return \Guzzle\Http\Message\Response * @see Guzzle::request for a list of available options */ public static function put($url, $options = array()) { return self::request('PUT', $url, $options); } /** * Send a PATCH request * * @param string $url URL of the request * @param array $options Array of request options * * @return \Guzzle\Http\Message\Response * @see Guzzle::request for a list of available options */ public static function patch($url, $options = array()) { return self::request('PATCH', $url, $options); } /** * Send an OPTIONS request * * @param string $url URL of the request * @param array $options Array of request options * * @return \Guzzle\Http\Message\Response * @see Guzzle::request for a list of available options */ public static function options($url, $options = array()) { return self::request('OPTIONS', $url, $options); } } null, 'host' => null, 'path' => null, 'port' => null, 'query' => null, 'user' => null, 'pass' => null, 'fragment' => null); if (false === ($parts = parse_url($url))) { throw new InvalidArgumentException('Was unable to parse malformed url: ' . $url); } $parts += $defaults; // Convert the query string into a QueryString object if ($parts['query'] || 0 !== strlen($parts['query'])) { $parts['query'] = QueryString::fromString($parts['query']); } return new static($parts['scheme'], $parts['host'], $parts['user'], $parts['pass'], $parts['port'], $parts['path'], $parts['query'], $parts['fragment']); } /** * Build a URL from parse_url parts. The generated URL will be a relative URL if a scheme or host are not provided. * * @param array $parts Array of parse_url parts * * @return string */ public static function buildUrl(array $parts) { $url = $scheme = ''; if (isset($parts['scheme'])) { $scheme = $parts['scheme']; $url .= $scheme . ':'; } if (isset($parts['host'])) { $url .= '//'; if (isset($parts['user'])) { $url .= $parts['user']; if (isset($parts['pass'])) { $url .= ':' . $parts['pass']; } $url .= '@'; } $url .= $parts['host']; // Only include the port if it is not the default port of the scheme if (isset($parts['port']) && !(($scheme == 'http' && $parts['port'] == 80) || ($scheme == 'https' && $parts['port'] == 443)) ) { $url .= ':' . $parts['port']; } } // Add the path component if present if (isset($parts['path']) && 0 !== strlen($parts['path'])) { // Always ensure that the path begins with '/' if set and something is before the path if ($url && $parts['path'][0] != '/' && substr($url, -1) != '/') { $url .= '/'; } $url .= $parts['path']; } // Add the query string if present if (isset($parts['query'])) { $url .= '?' . $parts['query']; } // Ensure that # is only added to the url if fragment contains anything. if (isset($parts['fragment'])) { $url .= '#' . $parts['fragment']; } return $url; } /** * Create a new URL from URL parts * * @param string $scheme Scheme of the URL * @param string $host Host of the URL * @param string $username Username of the URL * @param string $password Password of the URL * @param int $port Port of the URL * @param string $path Path of the URL * @param QueryString|array|string $query Query string of the URL * @param string $fragment Fragment of the URL */ public function __construct($scheme, $host, $username = null, $password = null, $port = null, $path = null, QueryString $query = null, $fragment = null) { $this->scheme = $scheme; $this->host = $host; $this->port = $port; $this->username = $username; $this->password = $password; $this->fragment = $fragment; if (!$query) { $this->query = new QueryString(); } else { $this->setQuery($query); } $this->setPath($path); } /** * Clone the URL */ public function __clone() { $this->query = clone $this->query; } /** * Returns the URL as a URL string * * @return string */ public function __toString() { return self::buildUrl($this->getParts()); } /** * Get the parts of the URL as an array * * @return array */ public function getParts() { $query = (string) $this->query; return array( 'scheme' => $this->scheme, 'user' => $this->username, 'pass' => $this->password, 'host' => $this->host, 'port' => $this->port, 'path' => $this->getPath(), 'query' => $query !== '' ? $query : null, 'fragment' => $this->fragment, ); } /** * Set the host of the request. * * @param string $host Host to set (e.g. www.yahoo.com, yahoo.com) * * @return Url */ public function setHost($host) { if (strpos($host, ':') === false) { $this->host = $host; } else { list($host, $port) = explode(':', $host); $this->host = $host; $this->setPort($port); } return $this; } /** * Get the host part of the URL * * @return string */ public function getHost() { return $this->host; } /** * Set the scheme part of the URL (http, https, ftp, etc) * * @param string $scheme Scheme to set * * @return Url */ public function setScheme($scheme) { if ($this->scheme == 'http' && $this->port == 80) { $this->port = null; } elseif ($this->scheme == 'https' && $this->port == 443) { $this->port = null; } $this->scheme = $scheme; return $this; } /** * Get the scheme part of the URL * * @return string */ public function getScheme() { return $this->scheme; } /** * Set the port part of the URL * * @param int $port Port to set * * @return Url */ public function setPort($port) { $this->port = $port; return $this; } /** * Get the port part of the URl. Will return the default port for a given scheme if no port has been set. * * @return int|null */ public function getPort() { if ($this->port) { return $this->port; } elseif ($this->scheme == 'http') { return 80; } elseif ($this->scheme == 'https') { return 443; } return null; } /** * Set the path part of the URL * * @param array|string $path Path string or array of path segments * * @return Url */ public function setPath($path) { static $pathReplace = array(' ' => '%20', '?' => '%3F'); if (is_array($path)) { $path = '/' . implode('/', $path); } $this->path = strtr($path, $pathReplace); return $this; } /** * Normalize the URL so that double slashes and relative paths are removed * * @return Url */ public function normalizePath() { if (!$this->path || $this->path == '/' || $this->path == '*') { return $this; } $results = array(); $segments = $this->getPathSegments(); foreach ($segments as $segment) { if ($segment == '..') { array_pop($results); } elseif ($segment != '.' && $segment != '') { $results[] = $segment; } } // Combine the normalized parts and add the leading slash if needed $this->path = ($this->path[0] == '/' ? '/' : '') . implode('/', $results); // Add the trailing slash if necessary if ($this->path != '/' && end($segments) == '') { $this->path .= '/'; } return $this; } /** * Add a relative path to the currently set path. * * @param string $relativePath Relative path to add * * @return Url */ public function addPath($relativePath) { if ($relativePath != '/' && is_string($relativePath) && strlen($relativePath) > 0) { // Add a leading slash if needed if ($relativePath[0] != '/') { $relativePath = '/' . $relativePath; } $this->setPath(str_replace('//', '/', $this->path . $relativePath)); } return $this; } /** * Get the path part of the URL * * @return string */ public function getPath() { return $this->path; } /** * Get the path segments of the URL as an array * * @return array */ public function getPathSegments() { return array_slice(explode('/', $this->getPath()), 1); } /** * Set the password part of the URL * * @param string $password Password to set * * @return Url */ public function setPassword($password) { $this->password = $password; return $this; } /** * Get the password part of the URL * * @return null|string */ public function getPassword() { return $this->password; } /** * Set the username part of the URL * * @param string $username Username to set * * @return Url */ public function setUsername($username) { $this->username = $username; return $this; } /** * Get the username part of the URl * * @return null|string */ public function getUsername() { return $this->username; } /** * Get the query part of the URL as a QueryString object * * @return QueryString */ public function getQuery() { return $this->query; } /** * Set the query part of the URL * * @param QueryString|string|array $query Query to set * * @return Url */ public function setQuery($query) { if (is_string($query)) { $output = null; parse_str($query, $output); $this->query = new QueryString($output); } elseif (is_array($query)) { $this->query = new QueryString($query); } elseif ($query instanceof QueryString) { $this->query = $query; } return $this; } /** * Get the fragment part of the URL * * @return null|string */ public function getFragment() { return $this->fragment; } /** * Set the fragment part of the URL * * @param string $fragment Fragment to set * * @return Url */ public function setFragment($fragment) { $this->fragment = $fragment; return $this; } /** * Check if this is an absolute URL * * @return bool */ public function isAbsolute() { return $this->scheme && $this->host; } /** * Combine the URL with another URL. Follows the rules specific in RFC 3986 section 5.4. * * @param string $url Relative URL to combine with * @param bool $strictRfc3986 Set to true to use strict RFC 3986 compliance when merging paths. When first * released, Guzzle used an incorrect algorithm for combining relative URL paths. In * order to not break users, we introduced this flag to allow the merging of URLs based * on strict RFC 3986 section 5.4.1. This means that "http://a.com/foo/baz" merged with * "bar" would become "http://a.com/foo/bar". When this value is set to false, it would * become "http://a.com/foo/baz/bar". * @return Url * @throws InvalidArgumentException * @link http://tools.ietf.org/html/rfc3986#section-5.4 */ public function combine($url, $strictRfc3986 = false) { $url = self::factory($url); // Use the more absolute URL as the base URL if (!$this->isAbsolute() && $url->isAbsolute()) { $url = $url->combine($this); } // Passing a URL with a scheme overrides everything if ($buffer = $url->getScheme()) { $this->scheme = $buffer; $this->host = $url->getHost(); $this->port = $url->getPort(); $this->username = $url->getUsername(); $this->password = $url->getPassword(); $this->path = $url->getPath(); $this->query = $url->getQuery(); $this->fragment = $url->getFragment(); return $this; } // Setting a host overrides the entire rest of the URL if ($buffer = $url->getHost()) { $this->host = $buffer; $this->port = $url->getPort(); $this->username = $url->getUsername(); $this->password = $url->getPassword(); $this->path = $url->getPath(); $this->query = $url->getQuery(); $this->fragment = $url->getFragment(); return $this; } $path = $url->getPath(); $query = $url->getQuery(); if (!$path) { if (count($query)) { $this->addQuery($query, $strictRfc3986); } } else { if ($path[0] == '/') { $this->path = $path; } elseif ($strictRfc3986) { $this->path .= '/../' . $path; } else { $this->path .= '/' . $path; } $this->normalizePath(); $this->addQuery($query, $strictRfc3986); } $this->fragment = $url->getFragment(); return $this; } private function addQuery(QueryString $new, $strictRfc386) { if (!$strictRfc386) { $new->merge($this->query); } $this->query = $new; } } array(), 'camel' => array() ); /** @var int Max entries per cache */ protected $maxCacheSize; /** @var InflectorInterface Decorated inflector */ protected $decoratedInflector; /** * @param InflectorInterface $inflector Inflector being decorated * @param int $maxCacheSize Maximum number of cached items to hold per cache */ public function __construct(InflectorInterface $inflector, $maxCacheSize = 500) { $this->decoratedInflector = $inflector; $this->maxCacheSize = $maxCacheSize; } public function snake($word) { if (!isset($this->cache['snake'][$word])) { $this->pruneCache('snake'); $this->cache['snake'][$word] = $this->decoratedInflector->snake($word); } return $this->cache['snake'][$word]; } /** * Converts strings from snake_case to upper CamelCase * * @param string $word Value to convert into upper CamelCase * * @return string */ public function camel($word) { if (!isset($this->cache['camel'][$word])) { $this->pruneCache('camel'); $this->cache['camel'][$word] = $this->decoratedInflector->camel($word); } return $this->cache['camel'][$word]; } /** * Prune one of the named caches by removing 20% of the cache if it is full * * @param string $cache Type of cache to prune */ protected function pruneCache($cache) { if (count($this->cache[$cache]) == $this->maxCacheSize) { $this->cache[$cache] = array_slice($this->cache[$cache], $this->maxCacheSize * 0.2); } } } array(), 'camel' => array() ); /** @var InflectorInterface Decorated inflector */ protected $decoratedInflector; /** * @param InflectorInterface $inflector Inflector being decorated * @param array $snake Hash of pre-computed camel to snake * @param array $camel Hash of pre-computed snake to camel * @param bool $mirror Mirror snake and camel reflections */ public function __construct(InflectorInterface $inflector, array $snake = array(), array $camel = array(), $mirror = false) { if ($mirror) { $camel = array_merge(array_flip($snake), $camel); $snake = array_merge(array_flip($camel), $snake); } $this->decoratedInflector = $inflector; $this->mapping = array( 'snake' => $snake, 'camel' => $camel ); } public function snake($word) { return isset($this->mapping['snake'][$word]) ? $this->mapping['snake'][$word] : $this->decoratedInflector->snake($word); } /** * Converts strings from snake_case to upper CamelCase * * @param string $word Value to convert into upper CamelCase * * @return string */ public function camel($word) { return isset($this->mapping['camel'][$word]) ? $this->mapping['camel'][$word] : $this->decoratedInflector->camel($word); } } getArrayIterator()->append($iterator); } } chunkSize = $chunkSize; } public function rewind() { parent::rewind(); $this->next(); } public function next() { $this->chunk = array(); for ($i = 0; $i < $this->chunkSize && parent::valid(); $i++) { $this->chunk[] = parent::current(); parent::next(); } } public function current() { return $this->chunk; } public function valid() { return (bool) $this->chunk; } } callback = $callback; } public function accept() { return call_user_func($this->callback, $this->current()); } } callback = $callback; } public function current() { return call_user_func($this->callback, parent::current()); } } getInnerIterator(); while ($i instanceof \OuterIterator) { $i = $i->getInnerIterator(); } return call_user_func_array(array($i, $name), $args); } } log; } } logs[] = array('message' => $message, 'priority' => $priority, 'extras' => $extras); } /** * Get logged entries * * @return array */ public function getLogs() { return $this->logs; } /** * Clears logged entries */ public function clearLogs() { $this->logs = array(); } } log = $logObject; } public function log($message, $priority = LOG_INFO, $extras = array()) { call_user_func($this->log, $message, $priority, $extras); } } >>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{curl_stderr}"; const SHORT_FORMAT = '[{ts}] "{method} {resource} {protocol}/{version}" {code}'; /** * @var string Template used to format log messages */ protected $template; /** * @param string $template Log message template */ public function __construct($template = self::DEFAULT_FORMAT) { $this->template = $template ?: self::DEFAULT_FORMAT; } /** * Set the template to use for logging * * @param string $template Log message template * * @return self */ public function setTemplate($template) { $this->template = $template; return $this; } /** * Returns a formatted message * * @param RequestInterface $request Request that was sent * @param Response $response Response that was received * @param CurlHandle $handle Curl handle associated with the message * @param array $customData Associative array of custom template data * * @return string */ public function format( RequestInterface $request, Response $response = null, CurlHandle $handle = null, array $customData = array() ) { $cache = $customData; return preg_replace_callback( '/{\s*([A-Za-z_\-\.0-9]+)\s*}/', function (array $matches) use ($request, $response, $handle, &$cache) { if (array_key_exists($matches[1], $cache)) { return $cache[$matches[1]]; } $result = ''; switch ($matches[1]) { case 'request': $result = (string) $request; break; case 'response': $result = (string) $response; break; case 'req_body': $result = $request instanceof EntityEnclosingRequestInterface ? (string) $request->getBody() : ''; break; case 'res_body': $result = $response ? $response->getBody(true) : ''; break; case 'ts': $result = gmdate('c'); break; case 'method': $result = $request->getMethod(); break; case 'url': $result = (string) $request->getUrl(); break; case 'resource': $result = $request->getResource(); break; case 'protocol': $result = 'HTTP'; break; case 'version': $result = $request->getProtocolVersion(); break; case 'host': $result = $request->getHost(); break; case 'hostname': $result = gethostname(); break; case 'port': $result = $request->getPort(); break; case 'code': $result = $response ? $response->getStatusCode() : ''; break; case 'phrase': $result = $response ? $response->getReasonPhrase() : ''; break; case 'connect_time': $result = $handle && $handle->getInfo(CURLINFO_CONNECT_TIME) ? $handle->getInfo(CURLINFO_CONNECT_TIME) : ($response ? $response->getInfo('connect_time') : ''); break; case 'total_time': $result = $handle && $handle->getInfo(CURLINFO_TOTAL_TIME) ? $handle->getInfo(CURLINFO_TOTAL_TIME) : ($response ? $response->getInfo('total_time') : ''); break; case 'curl_error': $result = $handle ? $handle->getError() : ''; break; case 'curl_code': $result = $handle ? $handle->getErrorNo() : ''; break; case 'curl_stderr': $result = $handle ? $handle->getStderr() : ''; break; default: if (strpos($matches[1], 'req_header_') === 0) { $result = $request->getHeader(substr($matches[1], 11)); } elseif ($response && strpos($matches[1], 'res_header_') === 0) { $result = $response->getHeader(substr($matches[1], 11)); } } $cache[$matches[1]] = $result; return $result; }, $this->template ); } } Logger::DEBUG, LOG_INFO => Logger::INFO, LOG_WARNING => Logger::WARNING, LOG_ERR => Logger::ERROR, LOG_CRIT => Logger::CRITICAL, LOG_ALERT => Logger::ALERT ); public function __construct(Logger $logObject) { $this->log = $logObject; } public function log($message, $priority = LOG_INFO, $extras = array()) { $this->log->addRecord(self::$mapping[$priority], $message, $extras); } } LogLevel::DEBUG, LOG_INFO => LogLevel::INFO, LOG_WARNING => LogLevel::WARNING, LOG_ERR => LogLevel::ERROR, LOG_CRIT => LogLevel::CRITICAL, LOG_ALERT => LogLevel::ALERT ); public function __construct(LoggerInterface $logObject) { $this->log = $logObject; } public function log($message, $priority = LOG_INFO, $extras = array()) { $this->log->log(self::$mapping[$priority], $message, $extras); } } log = $logObject; Version::warn(__CLASS__ . ' is deprecated'); } public function log($message, $priority = LOG_INFO, $extras = array()) { $this->log->log($message, $priority, $extras); } } log = $logObject; } public function log($message, $priority = LOG_INFO, $extras = array()) { $this->log->log($priority, $message, $extras); } } 'Domain', 'path' => 'Path', 'max_age' => 'Max-Age', 'expires' => 'Expires', 'version' => 'Version', 'secure' => 'Secure', 'port' => 'Port', 'discard' => 'Discard', 'comment' => 'Comment', 'comment_url' => 'Comment-Url', 'http_only' => 'HttpOnly' ); public function parseCookie($cookie, $host = null, $path = null, $decode = false) { // Explode the cookie string using a series of semicolons $pieces = array_filter(array_map('trim', explode(';', $cookie))); // The name of the cookie (first kvp) must include an equal sign. if (empty($pieces) || !strpos($pieces[0], '=')) { return false; } // Create the default return array $data = array_merge(array_fill_keys(array_keys(self::$cookieParts), null), array( 'cookies' => array(), 'data' => array(), 'path' => null, 'http_only' => false, 'discard' => false, 'domain' => $host )); $foundNonCookies = 0; // Add the cookie pieces into the parsed data array foreach ($pieces as $part) { $cookieParts = explode('=', $part, 2); $key = trim($cookieParts[0]); if (count($cookieParts) == 1) { // Can be a single value (e.g. secure, httpOnly) $value = true; } else { // Be sure to strip wrapping quotes $value = trim($cookieParts[1], " \n\r\t\0\x0B\""); if ($decode) { $value = urldecode($value); } } // Only check for non-cookies when cookies have been found if (!empty($data['cookies'])) { foreach (self::$cookieParts as $mapValue => $search) { if (!strcasecmp($search, $key)) { $data[$mapValue] = $mapValue == 'port' ? array_map('trim', explode(',', $value)) : $value; $foundNonCookies++; continue 2; } } } // If cookies have not yet been retrieved, or this value was not found in the pieces array, treat it as a // cookie. IF non-cookies have been parsed, then this isn't a cookie, it's cookie data. Cookies then data. $data[$foundNonCookies ? 'data' : 'cookies'][$key] = $value; } // Calculate the expires date if (!$data['expires'] && $data['max_age']) { $data['expires'] = time() + (int) $data['max_age']; } // Check path attribute according RFC6265 http://tools.ietf.org/search/rfc6265#section-5.2.4 // "If the attribute-value is empty or if the first character of the // attribute-value is not %x2F ("/"): // Let cookie-path be the default-path. // Otherwise: // Let cookie-path be the attribute-value." if (!$data['path'] || substr($data['path'], 0, 1) !== '/') { $data['path'] = $this->getDefaultPath($path); } return $data; } /** * Get default cookie path according to RFC 6265 * http://tools.ietf.org/search/rfc6265#section-5.1.4 Paths and Path-Match * * @param string $path Request uri-path * * @return string */ protected function getDefaultPath($path) { // "The user agent MUST use an algorithm equivalent to the following algorithm // to compute the default-path of a cookie:" // "2. If the uri-path is empty or if the first character of the uri-path is not // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. if (empty($path) || substr($path, 0, 1) !== '/') { return '/'; } // "3. If the uri-path contains no more than one %x2F ("/") character, output // %x2F ("/") and skip the remaining step." if ($path === "/") { return $path; } $rightSlashPos = strrpos($path, '/'); if ($rightSlashPos === 0) { return "/"; } // "4. Output the characters of the uri-path from the first character up to, // but not including, the right-most %x2F ("/")." return substr($path, 0, $rightSlashPos); } } $requestUrl, 'scheme' => 'http' ); // Check for the Host header if (isset($parts['headers']['Host'])) { $urlParts['host'] = $parts['headers']['Host']; } elseif (isset($parts['headers']['host'])) { $urlParts['host'] = $parts['headers']['host']; } else { $urlParts['host'] = null; } if (false === strpos($urlParts['host'], ':')) { $urlParts['port'] = ''; } else { $hostParts = explode(':', $urlParts['host']); $urlParts['host'] = trim($hostParts[0]); $urlParts['port'] = (int) trim($hostParts[1]); if ($urlParts['port'] == 443) { $urlParts['scheme'] = 'https'; } } // Check if a query is present $path = $urlParts['path']; $qpos = strpos($path, '?'); if ($qpos) { $urlParts['query'] = substr($path, $qpos + 1); $urlParts['path'] = substr($path, 0, $qpos); } else { $urlParts['query'] = ''; } return $urlParts; } } parseMessage($message); // Parse the protocol and protocol version if (isset($parts['start_line'][2])) { $startParts = explode('/', $parts['start_line'][2]); $protocol = strtoupper($startParts[0]); $version = isset($startParts[1]) ? $startParts[1] : '1.1'; } else { $protocol = 'HTTP'; $version = '1.1'; } $parsed = array( 'method' => strtoupper($parts['start_line'][0]), 'protocol' => $protocol, 'version' => $version, 'headers' => $parts['headers'], 'body' => $parts['body'] ); $parsed['request_url'] = $this->getUrlPartsFromMessage($parts['start_line'][1], $parsed); return $parsed; } public function parseResponse($message) { if (!$message) { return false; } $parts = $this->parseMessage($message); list($protocol, $version) = explode('/', trim($parts['start_line'][0])); return array( 'protocol' => $protocol, 'version' => $version, 'code' => $parts['start_line'][1], 'reason_phrase' => isset($parts['start_line'][2]) ? $parts['start_line'][2] : '', 'headers' => $parts['headers'], 'body' => $parts['body'] ); } /** * Parse a message into parts * * @param string $message Message to parse * * @return array */ protected function parseMessage($message) { $startLine = null; $headers = array(); $body = ''; // Iterate over each line in the message, accounting for line endings $lines = preg_split('/(\\r?\\n)/', $message, -1, PREG_SPLIT_DELIM_CAPTURE); for ($i = 0, $totalLines = count($lines); $i < $totalLines; $i += 2) { $line = $lines[$i]; // If two line breaks were encountered, then this is the end of body if (empty($line)) { if ($i < $totalLines - 1) { $body = implode('', array_slice($lines, $i + 2)); } break; } // Parse message headers if (!$startLine) { $startLine = explode(' ', $line, 3); } elseif (strpos($line, ':')) { $parts = explode(':', $line, 2); $key = trim($parts[0]); $value = isset($parts[1]) ? trim($parts[1]) : ''; if (!isset($headers[$key])) { $headers[$key] = $value; } elseif (!is_array($headers[$key])) { $headers[$key] = array($headers[$key], $value); } else { $headers[$key][] = $value; } } } return array( 'start_line' => $startLine, 'headers' => $headers, 'body' => $body ); } } $parts->requestMethod, 'protocol' => 'HTTP', 'version' => number_format($parts->httpVersion, 1), 'headers' => $parts->headers, 'body' => $parts->body ); $parsed['request_url'] = $this->getUrlPartsFromMessage($parts->requestUrl, $parsed); return $parsed; } public function parseResponse($message) { if (!$message) { return false; } $parts = http_parse_message($message); return array( 'protocol' => 'HTTP', 'version' => number_format($parts->httpVersion, 1), 'code' => $parts->responseCode, 'reason_phrase' => $parts->responseStatus, 'headers' => $parts->headers, 'body' => $parts->body ); } } 'Guzzle\\Parser\\Message\\MessageParser', 'cookie' => 'Guzzle\\Parser\\Cookie\\CookieParser', 'url' => 'Guzzle\\Parser\\Url\\UrlParser', 'uri_template' => 'Guzzle\\Parser\\UriTemplate\\UriTemplate', ); /** * @return self * @codeCoverageIgnore */ public static function getInstance() { if (!self::$instance) { self::$instance = new static; } return self::$instance; } public function __construct() { // Use the PECL URI template parser if available if (extension_loaded('uri_template')) { $this->mapping['uri_template'] = 'Guzzle\\Parser\\UriTemplate\\PeclUriTemplate'; } } /** * Get a parser by name from an instance * * @param string $name Name of the parser to retrieve * * @return mixed|null */ public function getParser($name) { if (!isset($this->instances[$name])) { if (!isset($this->mapping[$name])) { return null; } $class = $this->mapping[$name]; $this->instances[$name] = new $class(); } return $this->instances[$name]; } /** * Register a custom parser by name with the register * * @param string $name Name or handle of the parser to register * @param mixed $parser Instantiated parser to register */ public function registerParser($name, $parser) { $this->instances[$name] = $parser; } } true, '#' => true, '.' => true, '/' => true, ';' => true, '?' => true, '&' => true ); /** @var array Delimiters */ private static $delims = array( ':', '/', '?', '#', '[', ']', '@', '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=' ); /** @var array Percent encoded delimiters */ private static $delimsPct = array( '%3A', '%2F', '%3F', '%23', '%5B', '%5D', '%40', '%21', '%24', '%26', '%27', '%28', '%29', '%2A', '%2B', '%2C', '%3B', '%3D' ); public function expand($template, array $variables) { if ($this->regex == self::DEFAULT_PATTERN && false === strpos($template, '{')) { return $template; } $this->template = $template; $this->variables = $variables; return preg_replace_callback($this->regex, array($this, 'expandMatch'), $this->template); } /** * Set the regex patten used to expand URI templates * * @param string $regexPattern */ public function setRegex($regexPattern) { $this->regex = $regexPattern; } /** * Parse an expression into parts * * @param string $expression Expression to parse * * @return array Returns an associative array of parts */ private function parseExpression($expression) { // Check for URI operators $operator = ''; if (isset(self::$operatorHash[$expression[0]])) { $operator = $expression[0]; $expression = substr($expression, 1); } $values = explode(',', $expression); foreach ($values as &$value) { $value = trim($value); $varspec = array(); $substrPos = strpos($value, ':'); if ($substrPos) { $varspec['value'] = substr($value, 0, $substrPos); $varspec['modifier'] = ':'; $varspec['position'] = (int) substr($value, $substrPos + 1); } elseif (substr($value, -1) == '*') { $varspec['modifier'] = '*'; $varspec['value'] = substr($value, 0, -1); } else { $varspec['value'] = (string) $value; $varspec['modifier'] = ''; } $value = $varspec; } return array( 'operator' => $operator, 'values' => $values ); } /** * Process an expansion * * @param array $matches Matches met in the preg_replace_callback * * @return string Returns the replacement string */ private function expandMatch(array $matches) { static $rfc1738to3986 = array( '+' => '%20', '%7e' => '~' ); $parsed = self::parseExpression($matches[1]); $replacements = array(); $prefix = $parsed['operator']; $joiner = $parsed['operator']; $useQueryString = false; if ($parsed['operator'] == '?') { $joiner = '&'; $useQueryString = true; } elseif ($parsed['operator'] == '&') { $useQueryString = true; } elseif ($parsed['operator'] == '#') { $joiner = ','; } elseif ($parsed['operator'] == ';') { $useQueryString = true; } elseif ($parsed['operator'] == '' || $parsed['operator'] == '+') { $joiner = ','; $prefix = ''; } foreach ($parsed['values'] as $value) { if (!array_key_exists($value['value'], $this->variables) || $this->variables[$value['value']] === null) { continue; } $variable = $this->variables[$value['value']]; $actuallyUseQueryString = $useQueryString; $expanded = ''; if (is_array($variable)) { $isAssoc = $this->isAssoc($variable); $kvp = array(); foreach ($variable as $key => $var) { if ($isAssoc) { $key = rawurlencode($key); $isNestedArray = is_array($var); } else { $isNestedArray = false; } if (!$isNestedArray) { $var = rawurlencode($var); if ($parsed['operator'] == '+' || $parsed['operator'] == '#') { $var = $this->decodeReserved($var); } } if ($value['modifier'] == '*') { if ($isAssoc) { if ($isNestedArray) { // Nested arrays must allow for deeply nested structures $var = strtr(http_build_query(array($key => $var)), $rfc1738to3986); } else { $var = $key . '=' . $var; } } elseif ($key > 0 && $actuallyUseQueryString) { $var = $value['value'] . '=' . $var; } } $kvp[$key] = $var; } if (empty($variable)) { $actuallyUseQueryString = false; } elseif ($value['modifier'] == '*') { $expanded = implode($joiner, $kvp); if ($isAssoc) { // Don't prepend the value name when using the explode modifier with an associative array $actuallyUseQueryString = false; } } else { if ($isAssoc) { // When an associative array is encountered and the explode modifier is not set, then the // result must be a comma separated list of keys followed by their respective values. foreach ($kvp as $k => &$v) { $v = $k . ',' . $v; } } $expanded = implode(',', $kvp); } } else { if ($value['modifier'] == ':') { $variable = substr($variable, 0, $value['position']); } $expanded = rawurlencode($variable); if ($parsed['operator'] == '+' || $parsed['operator'] == '#') { $expanded = $this->decodeReserved($expanded); } } if ($actuallyUseQueryString) { if (!$expanded && $joiner != '&') { $expanded = $value['value']; } else { $expanded = $value['value'] . '=' . $expanded; } } $replacements[] = $expanded; } $ret = implode($joiner, $replacements); if ($ret && $prefix) { return $prefix . $ret; } return $ret; } /** * Determines if an array is associative * * @param array $array Array to check * * @return bool */ private function isAssoc(array $array) { return (bool) count(array_filter(array_keys($array), 'is_string')); } /** * Removes percent encoding on reserved characters (used with + and # modifiers) * * @param string $string String to fix * * @return string */ private function decodeReserved($string) { return str_replace(self::$delimsPct, self::$delims, $string); } } utf8 = $utf8; } public function parseUrl($url) { Version::warn(__CLASS__ . ' is deprecated. Just use parse_url()'); static $defaults = array('scheme' => null, 'host' => null, 'path' => null, 'port' => null, 'query' => null, 'user' => null, 'pass' => null, 'fragment' => null); $parts = parse_url($url); // Need to handle query parsing specially for UTF-8 requirements if ($this->utf8 && isset($parts['query'])) { $queryPos = strpos($url, '?'); if (isset($parts['fragment'])) { $parts['query'] = substr($url, $queryPos + 1, strpos($url, '#') - $queryPos - 1); } else { $parts['query'] = substr($url, $queryPos + 1); } } return $parts + $defaults; } } 'onBeforeSend', 'request.exception' => 'onRequestTimeout', 'request.sent' => 'onRequestSent', 'curl.callback.progress' => 'onCurlProgress' ); } /** * Event used to ensure that progress callback are emitted from the curl handle's request mediator. * * @param Event $event */ public function onBeforeSend(Event $event) { // Ensure that progress callbacks are dispatched $event['request']->getCurlOptions()->set('progress', true); } /** * Event emitted when a curl progress function is called. When the amount of data uploaded == the amount of data to * upload OR any bytes have been downloaded, then time the request out after 1ms because we're done with * transmitting the request, and tell curl not download a body. * * @param Event $event */ public function onCurlProgress(Event $event) { if ($event['handle'] && ($event['downloaded'] || (isset($event['uploaded']) && $event['upload_size'] === $event['uploaded'])) ) { // Timeout after 1ms curl_setopt($event['handle'], CURLOPT_TIMEOUT_MS, 1); // Even if the response is quick, tell curl not to download the body. // - Note that we can only perform this shortcut if the request transmitted a body so as to ensure that the // request method is not converted to a HEAD request before the request was sent via curl. if ($event['uploaded']) { curl_setopt($event['handle'], CURLOPT_NOBODY, true); } } } /** * Event emitted when a curl exception occurs. Ignore the exception and set a mock response. * * @param Event $event */ public function onRequestTimeout(Event $event) { if ($event['exception'] instanceof CurlException) { $event['request']->setResponse(new Response(200, array( 'X-Guzzle-Async' => 'Did not wait for the response' ))); } } /** * Event emitted when a request completes because it took less than 1ms. Add an X-Guzzle-Async header to notify the * caller that there is no body in the message. * * @param Event $event */ public function onRequestSent(Event $event) { // Let the caller know this was meant to be async $event['request']->getResponse()->setHeader('X-Guzzle-Async', 'Did not wait for the response'); } } next = $next; } /** * Get the next backoff strategy in the chain * * @return AbstractBackoffStrategy|null */ public function getNext() { return $this->next; } public function getBackoffPeriod( $retries, RequestInterface $request, Response $response = null, HttpException $e = null ) { $delay = $this->getDelay($retries, $request, $response, $e); if ($delay === false) { // The strategy knows that this must not be retried return false; } elseif ($delay === null) { // If the strategy is deferring a decision and the next strategy will not make a decision then return false return !$this->next || !$this->next->makesDecision() ? false : $this->next->getBackoffPeriod($retries, $request, $response, $e); } elseif ($delay === true) { // if the strategy knows that it must retry but is deferring to the next to determine the delay if (!$this->next) { return 0; } else { $next = $this->next; while ($next->makesDecision() && $next->getNext()) { $next = $next->getNext(); } return !$next->makesDecision() ? $next->getBackoffPeriod($retries, $request, $response, $e) : 0; } } else { return $delay; } } /** * Check if the strategy does filtering and makes decisions on whether or not to retry. * * Strategies that return false will never retry if all of the previous strategies in a chain defer on a backoff * decision. * * @return bool */ abstract public function makesDecision(); /** * Implement the concrete strategy * * @param int $retries Number of retries of the request * @param RequestInterface $request Request that was sent * @param Response $response Response that was received. Note that there may not be a response * @param HttpException $e Exception that was encountered if any * * @return bool|int|null Returns false to not retry or the number of seconds to delay between retries. Return true * or null to defer to the next strategy if available, and if not, return 0. */ abstract protected function getDelay( $retries, RequestInterface $request, Response $response = null, HttpException $e = null ); } errorCodes = array_fill_keys($codes ?: static::$defaultErrorCodes, 1); $this->next = $next; } /** * Get the default failure codes to retry * * @return array */ public static function getDefaultFailureCodes() { return static::$defaultErrorCodes; } public function makesDecision() { return true; } } logger = $logger; $this->formatter = $formatter ?: new MessageFormatter(self::DEFAULT_FORMAT); } public static function getSubscribedEvents() { return array(BackoffPlugin::RETRY_EVENT => 'onRequestRetry'); } /** * Set the template to use for logging * * @param string $template Log message template * * @return self */ public function setTemplate($template) { $this->formatter->setTemplate($template); return $this; } /** * Called when a request is being retried * * @param Event $event Event emitted */ public function onRequestRetry(Event $event) { $this->logger->log($this->formatter->format( $event['request'], $event['response'], $event['handle'], array( 'retries' => $event['retries'], 'delay' => $event['delay'] ) )); } } strategy = $strategy; } /** * Retrieve a basic truncated exponential backoff plugin that will retry HTTP errors and cURL errors * * @param int $maxRetries Maximum number of retries * @param array $httpCodes HTTP response codes to retry * @param array $curlCodes cURL error codes to retry * * @return self */ public static function getExponentialBackoff( $maxRetries = 3, array $httpCodes = null, array $curlCodes = null ) { return new self(new TruncatedBackoffStrategy($maxRetries, new HttpBackoffStrategy($httpCodes, new CurlBackoffStrategy($curlCodes, new ExponentialBackoffStrategy() ) ) )); } public static function getAllEvents() { return array(self::RETRY_EVENT); } public static function getSubscribedEvents() { return array( 'request.sent' => 'onRequestSent', 'request.exception' => 'onRequestSent', CurlMultiInterface::POLLING_REQUEST => 'onRequestPoll' ); } /** * Called when a request has been sent and isn't finished processing * * @param Event $event */ public function onRequestSent(Event $event) { $request = $event['request']; $response = $event['response']; $exception = $event['exception']; $params = $request->getParams(); $retries = (int) $params->get(self::RETRY_PARAM); $delay = $this->strategy->getBackoffPeriod($retries, $request, $response, $exception); if ($delay !== false) { // Calculate how long to wait until the request should be retried $params->set(self::RETRY_PARAM, ++$retries) ->set(self::DELAY_PARAM, microtime(true) + $delay); // Send the request again $request->setState(RequestInterface::STATE_TRANSFER); $this->dispatch(self::RETRY_EVENT, array( 'request' => $request, 'response' => $response, 'handle' => ($exception && $exception instanceof CurlException) ? $exception->getCurlHandle() : null, 'retries' => $retries, 'delay' => $delay )); } } /** * Called when a request is polling in the curl multi object * * @param Event $event */ public function onRequestPoll(Event $event) { $request = $event['request']; $delay = $request->getParams()->get(self::DELAY_PARAM); // If the duration of the delay has passed, retry the request using the pool if (null !== $delay && microtime(true) >= $delay) { // Remove the request from the pool and then add it back again. This is required for cURL to know that we // want to retry sending the easy handle. $request->getParams()->remove(self::DELAY_PARAM); // Rewind the request body if possible if ($request instanceof EntityEnclosingRequestInterface && $request->getBody()) { $request->getBody()->seek(0); } $multi = $event['curl_multi']; $multi->remove($request); $multi->add($request); } } } callback = $callback; $this->decision = (bool) $decision; $this->next = $next; } public function makesDecision() { return $this->decision; } protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null) { return call_user_func($this->callback, $retries, $request, $response, $e); } } delay = $delay; } public function makesDecision() { return false; } protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null) { return $this->delay; } } errorCodes[$e->getErrorNo()]) ? true : null; } } } isSuccessful()) { return false; } else { return isset($this->errorCodes[$response->getStatusCode()]) ? true : null; } } } } step = $step; } public function makesDecision() { return false; } protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null) { return $retries * $this->step; } } errorCodes[$response->getReasonPhrase()]) ? true : null; } } } max = $maxRetries; $this->next = $next; } public function makesDecision() { return true; } protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null) { return $retries < $this->max ? null : false; } } new DefaultCacheStorage($options)); } elseif ($options instanceof CacheStorageInterface) { $options = array('storage' => $options); } elseif ($options) { $options = array('storage' => new DefaultCacheStorage(CacheAdapterFactory::fromCache($options))); } elseif (!class_exists('Doctrine\Common\Cache\ArrayCache')) { // @codeCoverageIgnoreStart throw new InvalidArgumentException('No cache was provided and Doctrine is not installed'); // @codeCoverageIgnoreEnd } } $this->autoPurge = isset($options['auto_purge']) ? $options['auto_purge'] : false; // Add a cache storage if a cache adapter was provided $this->storage = isset($options['storage']) ? $options['storage'] : new DefaultCacheStorage(new DoctrineCacheAdapter(new ArrayCache())); if (!isset($options['can_cache'])) { $this->canCache = new DefaultCanCacheStrategy(); } else { $this->canCache = is_callable($options['can_cache']) ? new CallbackCanCacheStrategy($options['can_cache']) : $options['can_cache']; } // Use the provided revalidation strategy or the default $this->revalidation = isset($options['revalidation']) ? $options['revalidation'] : new DefaultRevalidation($this->storage, $this->canCache); } public static function getSubscribedEvents() { return array( 'request.before_send' => array('onRequestBeforeSend', -255), 'request.sent' => array('onRequestSent', 255), 'request.error' => array('onRequestError', 0), 'request.exception' => array('onRequestException', 0), ); } /** * Check if a response in cache will satisfy the request before sending * * @param Event $event */ public function onRequestBeforeSend(Event $event) { $request = $event['request']; $request->addHeader('Via', sprintf('%s GuzzleCache/%s', $request->getProtocolVersion(), Version::VERSION)); if (!$this->canCache->canCacheRequest($request)) { switch ($request->getMethod()) { case 'PURGE': $this->purge($request); $request->setResponse(new Response(200, array(), 'purged')); break; case 'PUT': case 'POST': case 'DELETE': case 'PATCH': if ($this->autoPurge) { $this->purge($request); } } return; } if ($response = $this->storage->fetch($request)) { $params = $request->getParams(); $params['cache.lookup'] = true; $response->setHeader( 'Age', time() - strtotime($response->getDate() ? : $response->getLastModified() ?: 'now') ); // Validate that the response satisfies the request if ($this->canResponseSatisfyRequest($request, $response)) { if (!isset($params['cache.hit'])) { $params['cache.hit'] = true; } $request->setResponse($response); } } } /** * If possible, store a response in cache after sending * * @param Event $event */ public function onRequestSent(Event $event) { $request = $event['request']; $response = $event['response']; if ($request->getParams()->get('cache.hit') === null && $this->canCache->canCacheRequest($request) && $this->canCache->canCacheResponse($response) ) { $this->storage->cache($request, $response); } $this->addResponseHeaders($request, $response); } /** * If possible, return a cache response on an error * * @param Event $event */ public function onRequestError(Event $event) { $request = $event['request']; if (!$this->canCache->canCacheRequest($request)) { return; } if ($response = $this->storage->fetch($request)) { $response->setHeader( 'Age', time() - strtotime($response->getLastModified() ? : $response->getDate() ?: 'now') ); if ($this->canResponseSatisfyFailedRequest($request, $response)) { $request->getParams()->set('cache.hit', 'error'); $this->addResponseHeaders($request, $response); $event['response'] = $response; $event->stopPropagation(); } } } /** * If possible, set a cache response on a cURL exception * * @param Event $event * * @return null */ public function onRequestException(Event $event) { if (!$event['exception'] instanceof CurlException) { return; } $request = $event['request']; if (!$this->canCache->canCacheRequest($request)) { return; } if ($response = $this->storage->fetch($request)) { $response->setHeader('Age', time() - strtotime($response->getDate() ? : 'now')); if (!$this->canResponseSatisfyFailedRequest($request, $response)) { return; } $request->getParams()->set('cache.hit', 'error'); $request->setResponse($response); $this->addResponseHeaders($request, $response); $event->stopPropagation(); } } /** * Check if a cache response satisfies a request's caching constraints * * @param RequestInterface $request Request to validate * @param Response $response Response to validate * * @return bool */ public function canResponseSatisfyRequest(RequestInterface $request, Response $response) { $responseAge = $response->calculateAge(); $reqc = $request->getHeader('Cache-Control'); $resc = $response->getHeader('Cache-Control'); // Check the request's max-age header against the age of the response if ($reqc && $reqc->hasDirective('max-age') && $responseAge > $reqc->getDirective('max-age')) { return false; } // Check the response's max-age header if ($response->isFresh() === false) { $maxStale = $reqc ? $reqc->getDirective('max-stale') : null; if (null !== $maxStale) { if ($maxStale !== true && $response->getFreshness() < (-1 * $maxStale)) { return false; } } elseif ($resc && $resc->hasDirective('max-age') && $responseAge > $resc->getDirective('max-age') ) { return false; } } if ($this->revalidation->shouldRevalidate($request, $response)) { try { return $this->revalidation->revalidate($request, $response); } catch (CurlException $e) { $request->getParams()->set('cache.hit', 'error'); return $this->canResponseSatisfyFailedRequest($request, $response); } } return true; } /** * Check if a cache response satisfies a failed request's caching constraints * * @param RequestInterface $request Request to validate * @param Response $response Response to validate * * @return bool */ public function canResponseSatisfyFailedRequest(RequestInterface $request, Response $response) { $reqc = $request->getHeader('Cache-Control'); $resc = $response->getHeader('Cache-Control'); $requestStaleIfError = $reqc ? $reqc->getDirective('stale-if-error') : null; $responseStaleIfError = $resc ? $resc->getDirective('stale-if-error') : null; if (!$requestStaleIfError && !$responseStaleIfError) { return false; } if (is_numeric($requestStaleIfError) && $response->getAge() - $response->getMaxAge() > $requestStaleIfError) { return false; } if (is_numeric($responseStaleIfError) && $response->getAge() - $response->getMaxAge() > $responseStaleIfError) { return false; } return true; } /** * Purge all cache entries for a given URL * * @param string $url URL to purge */ public function purge($url) { // BC compatibility with previous version that accepted a Request object $url = $url instanceof RequestInterface ? $url->getUrl() : $url; $this->storage->purge($url); } /** * Add the plugin's headers to a response * * @param RequestInterface $request Request * @param Response $response Response to add headers to */ protected function addResponseHeaders(RequestInterface $request, Response $response) { $params = $request->getParams(); $response->setHeader('Via', sprintf('%s GuzzleCache/%s', $request->getProtocolVersion(), Version::VERSION)); $lookup = ($params['cache.lookup'] === true ? 'HIT' : 'MISS') . ' from GuzzleCache'; if ($header = $response->getHeader('X-Cache-Lookup')) { // Don't add duplicates $values = $header->toArray(); $values[] = $lookup; $response->setHeader('X-Cache-Lookup', array_unique($values)); } else { $response->setHeader('X-Cache-Lookup', $lookup); } if ($params['cache.hit'] === true) { $xcache = 'HIT from GuzzleCache'; } elseif ($params['cache.hit'] == 'error') { $xcache = 'HIT_ERROR from GuzzleCache'; } else { $xcache = 'MISS from GuzzleCache'; } if ($header = $response->getHeader('X-Cache')) { // Don't add duplicates $values = $header->toArray(); $values[] = $xcache; $response->setHeader('X-Cache', array_unique($values)); } else { $response->setHeader('X-Cache', $xcache); } if ($response->isFresh() === false) { $response->addHeader('Warning', sprintf('110 GuzzleCache/%s "Response is stale"', Version::VERSION)); if ($params['cache.hit'] === 'error') { $response->addHeader('Warning', sprintf('111 GuzzleCache/%s "Revalidation failed"', Version::VERSION)); } } } } requestCallback = $requestCallback; $this->responseCallback = $responseCallback; } public function canCacheRequest(RequestInterface $request) { return $this->requestCallback ? call_user_func($this->requestCallback, $request) : parent::canCacheRequest($request); } public function canCacheResponse(Response $response) { return $this->responseCallback ? call_user_func($this->responseCallback, $response) : parent::canCacheResponse($response); } } getParams()->get(self::CACHE_KEY); if (!$key) { $cloned = clone $request; $cloned->removeHeader('Cache-Control'); // Check to see how and if the key should be filtered foreach (explode(';', $request->getParams()->get(self::CACHE_KEY_FILTER)) as $part) { $pieces = array_map('trim', explode('=', $part)); if (isset($pieces[1])) { foreach (array_map('trim', explode(',', $pieces[1])) as $remove) { if ($pieces[0] == 'header') { $cloned->removeHeader($remove); } elseif ($pieces[0] == 'query') { $cloned->getQuery()->remove($remove); } } } } $raw = (string) $cloned; $key = 'GZ' . md5($raw); $request->getParams()->set(self::CACHE_KEY, $key)->set(self::CACHE_KEY_RAW, $raw); } return $key; } } cache = CacheAdapterFactory::fromCache($cache); $this->defaultTtl = $defaultTtl; $this->keyPrefix = $keyPrefix; } public function cache(RequestInterface $request, Response $response) { $currentTime = time(); $ttl = $request->getParams()->get('cache.override_ttl') ?: $response->getMaxAge() ?: $this->defaultTtl; if ($cacheControl = $response->getHeader('Cache-Control')) { $stale = $cacheControl->getDirective('stale-if-error'); $ttl += $stale == true ? $ttl : $stale; } // Determine which manifest key should be used $key = $this->getCacheKey($request); $persistedRequest = $this->persistHeaders($request); $entries = array(); if ($manifest = $this->cache->fetch($key)) { // Determine which cache entries should still be in the cache $vary = $response->getVary(); foreach (unserialize($manifest) as $entry) { // Check if the entry is expired if ($entry[4] < $currentTime) { continue; } $entry[1]['vary'] = isset($entry[1]['vary']) ? $entry[1]['vary'] : ''; if ($vary != $entry[1]['vary'] || !$this->requestsMatch($vary, $entry[0], $persistedRequest)) { $entries[] = $entry; } } } // Persist the response body if needed $bodyDigest = null; if ($response->getBody() && $response->getBody()->getContentLength() > 0) { $bodyDigest = $this->getBodyKey($request->getUrl(), $response->getBody()); $this->cache->save($bodyDigest, (string) $response->getBody(), $ttl); } array_unshift($entries, array( $persistedRequest, $this->persistHeaders($response), $response->getStatusCode(), $bodyDigest, $currentTime + $ttl )); $this->cache->save($key, serialize($entries)); } public function delete(RequestInterface $request) { $key = $this->getCacheKey($request); if ($entries = $this->cache->fetch($key)) { // Delete each cached body foreach (unserialize($entries) as $entry) { if ($entry[3]) { $this->cache->delete($entry[3]); } } $this->cache->delete($key); } } public function purge($url) { foreach (array('GET', 'HEAD', 'POST', 'PUT', 'DELETE') as $method) { $this->delete(new Request($method, $url)); } } public function fetch(RequestInterface $request) { $key = $this->getCacheKey($request); if (!($entries = $this->cache->fetch($key))) { return null; } $match = null; $headers = $this->persistHeaders($request); $entries = unserialize($entries); foreach ($entries as $index => $entry) { if ($this->requestsMatch(isset($entry[1]['vary']) ? $entry[1]['vary'] : '', $headers, $entry[0])) { $match = $entry; break; } } if (!$match) { return null; } // Ensure that the response is not expired $response = null; if ($match[4] < time()) { $response = -1; } else { $response = new Response($match[2], $match[1]); if ($match[3]) { if ($body = $this->cache->fetch($match[3])) { $response->setBody($body); } else { // The response is not valid because the body was somehow deleted $response = -1; } } } if ($response === -1) { // Remove the entry from the metadata and update the cache unset($entries[$index]); if ($entries) { $this->cache->save($key, serialize($entries)); } else { $this->cache->delete($key); } return null; } return $response; } /** * Hash a request URL into a string that returns cache metadata * * @param RequestInterface $request * * @return string */ protected function getCacheKey(RequestInterface $request) { // Allow cache.key_filter to trim down the URL cache key by removing generate query string values (e.g. auth) if ($filter = $request->getParams()->get('cache.key_filter')) { $url = $request->getUrl(true); foreach (explode(',', $filter) as $remove) { $url->getQuery()->remove(trim($remove)); } } else { $url = $request->getUrl(); } return $this->keyPrefix . md5($request->getMethod() . ' ' . $url); } /** * Create a cache key for a response's body * * @param string $url URL of the entry * @param EntityBodyInterface $body Response body * * @return string */ protected function getBodyKey($url, EntityBodyInterface $body) { return $this->keyPrefix . md5($url) . $body->getContentMd5(); } /** * Determines whether two Request HTTP header sets are non-varying * * @param string $vary Response vary header * @param array $r1 HTTP header array * @param array $r2 HTTP header array * * @return bool */ private function requestsMatch($vary, $r1, $r2) { if ($vary) { foreach (explode(',', $vary) as $header) { $key = trim(strtolower($header)); $v1 = isset($r1[$key]) ? $r1[$key] : null; $v2 = isset($r2[$key]) ? $r2[$key] : null; if ($v1 !== $v2) { return false; } } } return true; } /** * Creates an array of cacheable and normalized message headers * * @param MessageInterface $message * * @return array */ private function persistHeaders(MessageInterface $message) { // Headers are excluded from the caching (see RFC 2616:13.5.1) static $noCache = array( 'age' => true, 'connection' => true, 'keep-alive' => true, 'proxy-authenticate' => true, 'proxy-authorization' => true, 'te' => true, 'trailers' => true, 'transfer-encoding' => true, 'upgrade' => true, 'set-cookie' => true, 'set-cookie2' => true ); // Clone the response to not destroy any necessary headers when caching $headers = $message->getHeaders()->getAll(); $headers = array_diff_key($headers, $noCache); // Cast the headers to a string $headers = array_map(function ($h) { return (string) $h; }, $headers); return $headers; } } getMethod() != RequestInterface::GET && $request->getMethod() != RequestInterface::HEAD) { return false; } // Never cache requests when using no-store if ($request->hasHeader('Cache-Control') && $request->getHeader('Cache-Control')->hasDirective('no-store')) { return false; } return true; } public function canCacheResponse(Response $response) { return $response->isSuccessful() && $response->canCache(); } } storage = $cache; $this->canCache = $canCache ?: new DefaultCanCacheStrategy(); } public function revalidate(RequestInterface $request, Response $response) { try { $revalidate = $this->createRevalidationRequest($request, $response); $validateResponse = $revalidate->send(); if ($validateResponse->getStatusCode() == 200) { return $this->handle200Response($request, $validateResponse); } elseif ($validateResponse->getStatusCode() == 304) { return $this->handle304Response($request, $validateResponse, $response); } } catch (BadResponseException $e) { $this->handleBadResponse($e); } // Other exceptions encountered in the revalidation request are ignored // in hopes that sending a request to the origin server will fix it return false; } public function shouldRevalidate(RequestInterface $request, Response $response) { if ($request->getMethod() != RequestInterface::GET) { return false; } $reqCache = $request->getHeader('Cache-Control'); $resCache = $response->getHeader('Cache-Control'); $revalidate = $request->getHeader('Pragma') == 'no-cache' || ($reqCache && ($reqCache->hasDirective('no-cache') || $reqCache->hasDirective('must-revalidate'))) || ($resCache && ($resCache->hasDirective('no-cache') || $resCache->hasDirective('must-revalidate'))); // Use the strong ETag validator if available and the response contains no Cache-Control directive if (!$revalidate && !$resCache && $response->hasHeader('ETag')) { $revalidate = true; } return $revalidate; } /** * Handles a bad response when attempting to revalidate * * @param BadResponseException $e Exception encountered * * @throws BadResponseException */ protected function handleBadResponse(BadResponseException $e) { // 404 errors mean the resource no longer exists, so remove from // cache, and prevent an additional request by throwing the exception if ($e->getResponse()->getStatusCode() == 404) { $this->storage->delete($e->getRequest()); throw $e; } } /** * Creates a request to use for revalidation * * @param RequestInterface $request Request * @param Response $response Response to revalidate * * @return RequestInterface returns a revalidation request */ protected function createRevalidationRequest(RequestInterface $request, Response $response) { $revalidate = clone $request; $revalidate->removeHeader('Pragma')->removeHeader('Cache-Control'); if ($response->getLastModified()) { $revalidate->setHeader('If-Modified-Since', $response->getLastModified()); } if ($response->getEtag()) { $revalidate->setHeader('If-None-Match', $response->getEtag()); } // Remove any cache plugins that might be on the request to prevent infinite recursive revalidations $dispatcher = $revalidate->getEventDispatcher(); foreach ($dispatcher->getListeners() as $eventName => $listeners) { foreach ($listeners as $listener) { if (is_array($listener) && $listener[0] instanceof CachePlugin) { $dispatcher->removeListener($eventName, $listener); } } } return $revalidate; } /** * Handles a 200 response response from revalidating. The server does not support validation, so use this response. * * @param RequestInterface $request Request that was sent * @param Response $validateResponse Response received * * @return bool Returns true if valid, false if invalid */ protected function handle200Response(RequestInterface $request, Response $validateResponse) { $request->setResponse($validateResponse); if ($this->canCache->canCacheResponse($validateResponse)) { $this->storage->cache($request, $validateResponse); } return false; } /** * Handle a 304 response and ensure that it is still valid * * @param RequestInterface $request Request that was sent * @param Response $validateResponse Response received * @param Response $response Original cached response * * @return bool Returns true if valid, false if invalid */ protected function handle304Response(RequestInterface $request, Response $validateResponse, Response $response) { static $replaceHeaders = array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified'); // Make sure that this response has the same ETag if ($validateResponse->getEtag() != $response->getEtag()) { return false; } // Replace cached headers with any of these headers from the // origin server that might be more up to date $modified = false; foreach ($replaceHeaders as $name) { if ($validateResponse->hasHeader($name)) { $modified = true; $response->setHeader($name, $validateResponse->getHeader($name)); } } // Store the updated response in cache if ($modified && $this->canCache->canCacheResponse($response)) { $this->storage->cache($request, $response); } return true; } } '', 'value' => '', 'domain' => '', 'path' => '/', 'expires' => null, 'max_age' => 0, 'comment' => null, 'comment_url' => null, 'port' => array(), 'version' => null, 'secure' => false, 'discard' => false, 'http_only' => false ); $this->data = array_merge($defaults, $data); // Extract the expires value and turn it into a UNIX timestamp if needed if (!$this->getExpires() && $this->getMaxAge()) { // Calculate the expires date $this->setExpires(time() + (int) $this->getMaxAge()); } elseif ($this->getExpires() && !is_numeric($this->getExpires())) { $this->setExpires(strtotime($this->getExpires())); } } /** * Get the cookie as an array * * @return array */ public function toArray() { return $this->data; } /** * Get the cookie name * * @return string */ public function getName() { return $this->data['name']; } /** * Set the cookie name * * @param string $name Cookie name * * @return Cookie */ public function setName($name) { return $this->setData('name', $name); } /** * Get the cookie value * * @return string */ public function getValue() { return $this->data['value']; } /** * Set the cookie value * * @param string $value Cookie value * * @return Cookie */ public function setValue($value) { return $this->setData('value', $value); } /** * Get the domain * * @return string|null */ public function getDomain() { return $this->data['domain']; } /** * Set the domain of the cookie * * @param string $domain * * @return Cookie */ public function setDomain($domain) { return $this->setData('domain', $domain); } /** * Get the path * * @return string */ public function getPath() { return $this->data['path']; } /** * Set the path of the cookie * * @param string $path Path of the cookie * * @return Cookie */ public function setPath($path) { return $this->setData('path', $path); } /** * Maximum lifetime of the cookie in seconds * * @return int|null */ public function getMaxAge() { return $this->data['max_age']; } /** * Set the max-age of the cookie * * @param int $maxAge Max age of the cookie in seconds * * @return Cookie */ public function setMaxAge($maxAge) { return $this->setData('max_age', $maxAge); } /** * The UNIX timestamp when the cookie expires * * @return mixed */ public function getExpires() { return $this->data['expires']; } /** * Set the unix timestamp for which the cookie will expire * * @param int $timestamp Unix timestamp * * @return Cookie */ public function setExpires($timestamp) { return $this->setData('expires', $timestamp); } /** * Version of the cookie specification. RFC 2965 is 1 * * @return mixed */ public function getVersion() { return $this->data['version']; } /** * Set the cookie version * * @param string|int $version Version to set * * @return Cookie */ public function setVersion($version) { return $this->setData('version', $version); } /** * Get whether or not this is a secure cookie * * @return null|bool */ public function getSecure() { return $this->data['secure']; } /** * Set whether or not the cookie is secure * * @param bool $secure Set to true or false if secure * * @return Cookie */ public function setSecure($secure) { return $this->setData('secure', (bool) $secure); } /** * Get whether or not this is a session cookie * * @return null|bool */ public function getDiscard() { return $this->data['discard']; } /** * Set whether or not this is a session cookie * * @param bool $discard Set to true or false if this is a session cookie * * @return Cookie */ public function setDiscard($discard) { return $this->setData('discard', $discard); } /** * Get the comment * * @return string|null */ public function getComment() { return $this->data['comment']; } /** * Set the comment of the cookie * * @param string $comment Cookie comment * * @return Cookie */ public function setComment($comment) { return $this->setData('comment', $comment); } /** * Get the comment URL of the cookie * * @return string|null */ public function getCommentUrl() { return $this->data['comment_url']; } /** * Set the comment URL of the cookie * * @param string $commentUrl Cookie comment URL for more information * * @return Cookie */ public function setCommentUrl($commentUrl) { return $this->setData('comment_url', $commentUrl); } /** * Get an array of acceptable ports this cookie can be used with * * @return array */ public function getPorts() { return $this->data['port']; } /** * Set a list of acceptable ports this cookie can be used with * * @param array $ports Array of acceptable ports * * @return Cookie */ public function setPorts(array $ports) { return $this->setData('port', $ports); } /** * Get whether or not this is an HTTP only cookie * * @return bool */ public function getHttpOnly() { return $this->data['http_only']; } /** * Set whether or not this is an HTTP only cookie * * @param bool $httpOnly Set to true or false if this is HTTP only * * @return Cookie */ public function setHttpOnly($httpOnly) { return $this->setData('http_only', $httpOnly); } /** * Get an array of extra cookie data * * @return array */ public function getAttributes() { return $this->data['data']; } /** * Get a specific data point from the extra cookie data * * @param string $name Name of the data point to retrieve * * @return null|string */ public function getAttribute($name) { return array_key_exists($name, $this->data['data']) ? $this->data['data'][$name] : null; } /** * Set a cookie data attribute * * @param string $name Name of the attribute to set * @param string $value Value to set * * @return Cookie */ public function setAttribute($name, $value) { $this->data['data'][$name] = $value; return $this; } /** * Check if the cookie matches a path value * * @param string $path Path to check against * * @return bool */ public function matchesPath($path) { // RFC6265 http://tools.ietf.org/search/rfc6265#section-5.1.4 // A request-path path-matches a given cookie-path if at least one of // the following conditions holds: // o The cookie-path and the request-path are identical. if ($path == $this->getPath()) { return true; } $pos = stripos($path, $this->getPath()); if ($pos === 0) { // o The cookie-path is a prefix of the request-path, and the last // character of the cookie-path is %x2F ("/"). if (substr($this->getPath(), -1, 1) === "/") { return true; } // o The cookie-path is a prefix of the request-path, and the first // character of the request-path that is not included in the cookie- // path is a %x2F ("/") character. if (substr($path, strlen($this->getPath()), 1) === "/") { return true; } } return false; } /** * Check if the cookie matches a domain value * * @param string $domain Domain to check against * * @return bool */ public function matchesDomain($domain) { // Remove the leading '.' as per spec in RFC 6265: http://tools.ietf.org/html/rfc6265#section-5.2.3 $cookieDomain = ltrim($this->getDomain(), '.'); // Domain not set or exact match. if (!$cookieDomain || !strcasecmp($domain, $cookieDomain)) { return true; } // Matching the subdomain according to RFC 6265: http://tools.ietf.org/html/rfc6265#section-5.1.3 if (filter_var($domain, FILTER_VALIDATE_IP)) { return false; } return (bool) preg_match('/\.' . preg_quote($cookieDomain, '/') . '$/i', $domain); } /** * Check if the cookie is compatible with a specific port * * @param int $port Port to check * * @return bool */ public function matchesPort($port) { return count($this->getPorts()) == 0 || in_array($port, $this->getPorts()); } /** * Check if the cookie is expired * * @return bool */ public function isExpired() { return $this->getExpires() && time() > $this->getExpires(); } /** * Check if the cookie is valid according to RFC 6265 * * @return bool|string Returns true if valid or an error message if invalid */ public function validate() { // Names must not be empty, but can be 0 $name = $this->getName(); if (empty($name) && !is_numeric($name)) { return 'The cookie name must not be empty'; } // Check if any of the invalid characters are present in the cookie name if (strpbrk($name, self::getInvalidCharacters()) !== false) { return 'The cookie name must not contain invalid characters: ' . $name; } // Value must not be empty, but can be 0 $value = $this->getValue(); if (empty($value) && !is_numeric($value)) { return 'The cookie value must not be empty'; } // Domains must not be empty, but can be 0 // A "0" is not a valid internet domain, but may be used as server name in a private network $domain = $this->getDomain(); if (empty($domain) && !is_numeric($domain)) { return 'The cookie domain must not be empty'; } return true; } /** * Set a value and return the cookie object * * @param string $key Key to set * @param string $value Value to set * * @return Cookie */ private function setData($key, $value) { $this->data[$key] = $value; return $this; } } strictMode = $strictMode; } /** * Enable or disable strict mode on the cookie jar * * @param bool $strictMode Set to true to throw exceptions when invalid cookies are added. False to ignore them. * * @return self */ public function setStrictMode($strictMode) { $this->strictMode = $strictMode; } public function remove($domain = null, $path = null, $name = null) { $cookies = $this->all($domain, $path, $name, false, false); $this->cookies = array_filter($this->cookies, function (Cookie $cookie) use ($cookies) { return !in_array($cookie, $cookies, true); }); return $this; } public function removeTemporary() { $this->cookies = array_filter($this->cookies, function (Cookie $cookie) { return !$cookie->getDiscard() && $cookie->getExpires(); }); return $this; } public function removeExpired() { $currentTime = time(); $this->cookies = array_filter($this->cookies, function (Cookie $cookie) use ($currentTime) { return !$cookie->getExpires() || $currentTime < $cookie->getExpires(); }); return $this; } public function all($domain = null, $path = null, $name = null, $skipDiscardable = false, $skipExpired = true) { return array_values(array_filter($this->cookies, function (Cookie $cookie) use ( $domain, $path, $name, $skipDiscardable, $skipExpired ) { return false === (($name && $cookie->getName() != $name) || ($skipExpired && $cookie->isExpired()) || ($skipDiscardable && ($cookie->getDiscard() || !$cookie->getExpires())) || ($path && !$cookie->matchesPath($path)) || ($domain && !$cookie->matchesDomain($domain))); })); } public function add(Cookie $cookie) { // Only allow cookies with set and valid domain, name, value $result = $cookie->validate(); if ($result !== true) { if ($this->strictMode) { throw new InvalidCookieException($result); } else { $this->removeCookieIfEmpty($cookie); return false; } } // Resolve conflicts with previously set cookies foreach ($this->cookies as $i => $c) { // Two cookies are identical, when their path, domain, port and name are identical if ($c->getPath() != $cookie->getPath() || $c->getDomain() != $cookie->getDomain() || $c->getPorts() != $cookie->getPorts() || $c->getName() != $cookie->getName() ) { continue; } // The previously set cookie is a discard cookie and this one is not so allow the new cookie to be set if (!$cookie->getDiscard() && $c->getDiscard()) { unset($this->cookies[$i]); continue; } // If the new cookie's expiration is further into the future, then replace the old cookie if ($cookie->getExpires() > $c->getExpires()) { unset($this->cookies[$i]); continue; } // If the value has changed, we better change it if ($cookie->getValue() !== $c->getValue()) { unset($this->cookies[$i]); continue; } // The cookie exists, so no need to continue return false; } $this->cookies[] = $cookie; return true; } /** * Serializes the cookie cookieJar * * @return string */ public function serialize() { // Only serialize long term cookies and unexpired cookies return json_encode(array_map(function (Cookie $cookie) { return $cookie->toArray(); }, $this->all(null, null, null, true, true))); } /** * Unserializes the cookie cookieJar */ public function unserialize($data) { $data = json_decode($data, true); if (empty($data)) { $this->cookies = array(); } else { $this->cookies = array_map(function (array $cookie) { return new Cookie($cookie); }, $data); } } /** * Returns the total number of stored cookies * * @return int */ public function count() { return count($this->cookies); } /** * Returns an iterator * * @return \ArrayIterator */ public function getIterator() { return new \ArrayIterator($this->cookies); } public function addCookiesFromResponse(Response $response, RequestInterface $request = null) { if ($cookieHeader = $response->getHeader('Set-Cookie')) { $parser = ParserRegistry::getInstance()->getParser('cookie'); foreach ($cookieHeader as $cookie) { if ($parsed = $request ? $parser->parseCookie($cookie, $request->getHost(), $request->getPath()) : $parser->parseCookie($cookie) ) { // Break up cookie v2 into multiple cookies foreach ($parsed['cookies'] as $key => $value) { $row = $parsed; $row['name'] = $key; $row['value'] = $value; unset($row['cookies']); $this->add(new Cookie($row)); } } } } } public function getMatchingCookies(RequestInterface $request) { // Find cookies that match this request $cookies = $this->all($request->getHost(), $request->getPath()); // Remove ineligible cookies foreach ($cookies as $index => $cookie) { if (!$cookie->matchesPort($request->getPort()) || ($cookie->getSecure() && $request->getScheme() != 'https')) { unset($cookies[$index]); } }; return $cookies; } /** * If a cookie already exists and the server asks to set it again with a null value, the * cookie must be deleted. * * @param \Guzzle\Plugin\Cookie\Cookie $cookie */ private function removeCookieIfEmpty(Cookie $cookie) { $cookieValue = $cookie->getValue(); if ($cookieValue === null || $cookieValue === '') { $this->remove($cookie->getDomain(), $cookie->getPath(), $cookie->getName()); } } } filename = $cookieFile; $this->load(); } /** * Saves the file when shutting down */ public function __destruct() { $this->persist(); } /** * Save the contents of the data array to the file * * @throws RuntimeException if the file cannot be found or created */ protected function persist() { if (false === file_put_contents($this->filename, $this->serialize())) { // @codeCoverageIgnoreStart throw new RuntimeException('Unable to open file ' . $this->filename); // @codeCoverageIgnoreEnd } } /** * Load the contents of the json formatted file into the data array and discard any unsaved state */ protected function load() { $json = file_get_contents($this->filename); if (false === $json) { // @codeCoverageIgnoreStart throw new RuntimeException('Unable to open file ' . $this->filename); // @codeCoverageIgnoreEnd } $this->unserialize($json); $this->cookies = $this->cookies ?: array(); } } cookieJar = $cookieJar ?: new ArrayCookieJar(); } public static function getSubscribedEvents() { return array( 'request.before_send' => array('onRequestBeforeSend', 125), 'request.sent' => array('onRequestSent', 125) ); } /** * Get the cookie cookieJar * * @return CookieJarInterface */ public function getCookieJar() { return $this->cookieJar; } /** * Add cookies before a request is sent * * @param Event $event */ public function onRequestBeforeSend(Event $event) { $request = $event['request']; if (!$request->getParams()->get('cookies.disable')) { $request->removeHeader('Cookie'); // Find cookies that match this request foreach ($this->cookieJar->getMatchingCookies($request) as $cookie) { $request->addCookie($cookie->getName(), $cookie->getValue()); } } } /** * Extract cookies from a sent request * * @param Event $event */ public function onRequestSent(Event $event) { $this->cookieJar->addCookiesFromResponse($event['response'], $event['request']); } } getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest'); */ class CurlAuthPlugin implements EventSubscriberInterface { private $username; private $password; private $scheme; /** * @param string $username HTTP basic auth username * @param string $password Password * @param int $scheme Curl auth scheme */ public function __construct($username, $password, $scheme=CURLAUTH_BASIC) { Version::warn(__CLASS__ . " is deprecated. Use \$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest');"); $this->username = $username; $this->password = $password; $this->scheme = $scheme; } public static function getSubscribedEvents() { return array('client.create_request' => array('onRequestCreate', 255)); } /** * Add basic auth * * @param Event $event */ public function onRequestCreate(Event $event) { $event['request']->setAuth($this->username, $this->password, $this->scheme); } } array('onCommandBeforeSend', -1)); } /** * Adds a listener to requests before they sent from a command * * @param Event $event Event emitted */ public function onCommandBeforeSend(Event $event) { $command = $event['command']; if ($operation = $command->getOperation()) { if ($operation->getErrorResponses()) { $request = $command->getRequest(); $request->getEventDispatcher() ->addListener('request.complete', $this->getErrorClosure($request, $command, $operation)); } } } /** * @param RequestInterface $request Request that received an error * @param CommandInterface $command Command that created the request * @param Operation $operation Operation that defines the request and errors * * @return \Closure Returns a closure * @throws ErrorResponseException */ protected function getErrorClosure(RequestInterface $request, CommandInterface $command, Operation $operation) { return function (Event $event) use ($request, $command, $operation) { $response = $event['response']; foreach ($operation->getErrorResponses() as $error) { if (!isset($error['class'])) { continue; } if (isset($error['code']) && $response->getStatusCode() != $error['code']) { continue; } if (isset($error['reason']) && $response->getReasonPhrase() != $error['reason']) { continue; } $className = $error['class']; $errorClassInterface = __NAMESPACE__ . '\\ErrorResponseExceptionInterface'; if (!class_exists($className)) { throw new ErrorResponseException("{$className} does not exist"); } elseif (!(in_array($errorClassInterface, class_implements($className)))) { throw new ErrorResponseException("{$className} must implement {$errorClassInterface}"); } throw $className::fromCommand($command, $response); } }; } } array('onRequestSent', 9999)); } /** * Convert to a string that contains all request and response headers * * @return string */ public function __toString() { $lines = array(); foreach ($this->transactions as $entry) { $response = isset($entry['response']) ? $entry['response'] : ''; $lines[] = '> ' . trim($entry['request']) . "\n\n< " . trim($response) . "\n"; } return implode("\n", $lines); } /** * Add a request to the history * * @param RequestInterface $request Request to add * @param Response $response Response of the request * * @return HistoryPlugin */ public function add(RequestInterface $request, Response $response = null) { if (!$response && $request->getResponse()) { $response = $request->getResponse(); } $this->transactions[] = array('request' => $request, 'response' => $response); if (count($this->transactions) > $this->getlimit()) { array_shift($this->transactions); } return $this; } /** * Set the max number of requests to store * * @param int $limit Limit * * @return HistoryPlugin */ public function setLimit($limit) { $this->limit = (int) $limit; return $this; } /** * Get the request limit * * @return int */ public function getLimit() { return $this->limit; } /** * Get all of the raw transactions in the form of an array of associative arrays containing * 'request' and 'response' keys. * * @return array */ public function getAll() { return $this->transactions; } /** * Get the requests in the history * * @return \ArrayIterator */ public function getIterator() { // Return an iterator just like the old iteration of the HistoryPlugin for BC compatibility (use getAll()) return new \ArrayIterator(array_map(function ($entry) { $entry['request']->getParams()->set('actual_response', $entry['response']); return $entry['request']; }, $this->transactions)); } /** * Get the number of requests in the history * * @return int */ public function count() { return count($this->transactions); } /** * Get the last request sent * * @return RequestInterface */ public function getLastRequest() { $last = end($this->transactions); return $last['request']; } /** * Get the last response in the history * * @return Response|null */ public function getLastResponse() { $last = end($this->transactions); return isset($last['response']) ? $last['response'] : null; } /** * Clears the history * * @return HistoryPlugin */ public function clear() { $this->transactions = array(); return $this; } public function onRequestSent(Event $event) { $this->add($event['request'], $event['response']); } } logAdapter = $logAdapter; $this->formatter = $formatter instanceof MessageFormatter ? $formatter : new MessageFormatter($formatter); $this->wireBodies = $wireBodies; } /** * Get a log plugin that outputs full request, response, and curl error information to stderr * * @param bool $wireBodies Set to false to disable request/response body output when they use are not repeatable * @param resource $stream Stream to write to when logging. Defaults to STDERR when it is available * * @return self */ public static function getDebugPlugin($wireBodies = true, $stream = null) { if ($stream === null) { if (defined('STDERR')) { $stream = STDERR; } else { $stream = fopen('php://output', 'w'); } } return new self(new ClosureLogAdapter(function ($m) use ($stream) { fwrite($stream, $m . PHP_EOL); }), "# Request:\n{request}\n\n# Response:\n{response}\n\n# Errors: {curl_code} {curl_error}", $wireBodies); } public static function getSubscribedEvents() { return array( 'curl.callback.write' => array('onCurlWrite', 255), 'curl.callback.read' => array('onCurlRead', 255), 'request.before_send' => array('onRequestBeforeSend', 255), 'request.sent' => array('onRequestSent', 255) ); } /** * Event triggered when curl data is read from a request * * @param Event $event */ public function onCurlRead(Event $event) { // Stream the request body to the log if the body is not repeatable if ($wire = $event['request']->getParams()->get('request_wire')) { $wire->write($event['read']); } } /** * Event triggered when curl data is written to a response * * @param Event $event */ public function onCurlWrite(Event $event) { // Stream the response body to the log if the body is not repeatable if ($wire = $event['request']->getParams()->get('response_wire')) { $wire->write($event['write']); } } /** * Called before a request is sent * * @param Event $event */ public function onRequestBeforeSend(Event $event) { if ($this->wireBodies) { $request = $event['request']; // Ensure that curl IO events are emitted $request->getCurlOptions()->set('emit_io', true); // We need to make special handling for content wiring and non-repeatable streams. if ($request instanceof EntityEnclosingRequestInterface && $request->getBody() && (!$request->getBody()->isSeekable() || !$request->getBody()->isReadable()) ) { // The body of the request cannot be recalled so logging the body will require us to buffer it $request->getParams()->set('request_wire', EntityBody::factory()); } if (!$request->getResponseBody()->isRepeatable()) { // The body of the response cannot be recalled so logging the body will require us to buffer it $request->getParams()->set('response_wire', EntityBody::factory()); } } } /** * Triggers the actual log write when a request completes * * @param Event $event */ public function onRequestSent(Event $event) { $request = $event['request']; $response = $event['response']; $handle = $event['handle']; if ($wire = $request->getParams()->get('request_wire')) { $request = clone $request; $request->setBody($wire); } if ($wire = $request->getParams()->get('response_wire')) { $response = clone $response; $response->setBody($wire); } // Send the log message to the adapter, adding a category and host $priority = $response && $response->isError() ? LOG_ERR : LOG_DEBUG; $message = $this->formatter->format($request, $response, $handle); $this->logAdapter->log($message, $priority, array( 'request' => $request, 'response' => $response, 'handle' => $handle )); } } contentMd5Param = $contentMd5Param; $this->validateMd5Param = $validateMd5Param; } public static function getSubscribedEvents() { return array('command.before_send' => array('onCommandBeforeSend', -255)); } public function onCommandBeforeSend(Event $event) { $command = $event['command']; $request = $command->getRequest(); // Only add an MD5 is there is a MD5 option on the operation and it has a payload if ($request instanceof EntityEnclosingRequestInterface && $request->getBody() && $command->getOperation()->hasParam($this->contentMd5Param)) { // Check if an MD5 checksum value should be passed along to the request if ($command[$this->contentMd5Param] === true) { if (false !== ($md5 = $request->getBody()->getContentMd5(true, true))) { $request->setHeader('Content-MD5', $md5); } } } // Check if MD5 validation should be used with the response if ($command[$this->validateMd5Param] === true) { $request->addSubscriber(new Md5ValidatorPlugin(true, false)); } } } contentLengthCutoff = $contentLengthCutoff; $this->contentEncoded = $contentEncoded; } public static function getSubscribedEvents() { return array('request.complete' => array('onRequestComplete', 255)); } /** * {@inheritdoc} * @throws UnexpectedValueException */ public function onRequestComplete(Event $event) { $response = $event['response']; if (!$contentMd5 = $response->getContentMd5()) { return; } $contentEncoding = $response->getContentEncoding(); if ($contentEncoding && !$this->contentEncoded) { return false; } // Make sure that the size of the request is under the cutoff size if ($this->contentLengthCutoff) { $size = $response->getContentLength() ?: $response->getBody()->getSize(); if (!$size || $size > $this->contentLengthCutoff) { return; } } if (!$contentEncoding) { $hash = $response->getBody()->getContentMd5(); } elseif ($contentEncoding == 'gzip') { $response->getBody()->compress('zlib.deflate'); $hash = $response->getBody()->getContentMd5(); $response->getBody()->uncompress(); } elseif ($contentEncoding == 'compress') { $response->getBody()->compress('bzip2.compress'); $hash = $response->getBody()->getContentMd5(); $response->getBody()->uncompress(); } else { return; } if ($contentMd5 !== $hash) { throw new UnexpectedValueException( "The response entity body may have been modified over the wire. The Content-MD5 " . "received ({$contentMd5}) did not match the calculated MD5 hash ({$hash})." ); } } } readBodies = $readBodies; $this->temporary = $temporary; if ($items) { foreach ($items as $item) { if ($item instanceof \Exception) { $this->addException($item); } else { $this->addResponse($item); } } } } public static function getSubscribedEvents() { // Use a number lower than the CachePlugin return array('request.before_send' => array('onRequestBeforeSend', -999)); } public static function getAllEvents() { return array('mock.request'); } /** * Get a mock response from a file * * @param string $path File to retrieve a mock response from * * @return Response * @throws InvalidArgumentException if the file is not found */ public static function getMockFile($path) { if (!file_exists($path)) { throw new InvalidArgumentException('Unable to open mock file: ' . $path); } return Response::fromMessage(file_get_contents($path)); } /** * Set whether or not to consume the entity body of a request when a mock * response is used * * @param bool $readBodies Set to true to read and consume entity bodies * * @return self */ public function readBodies($readBodies) { $this->readBodies = $readBodies; return $this; } /** * Returns the number of remaining mock responses * * @return int */ public function count() { return count($this->queue); } /** * Add a response to the end of the queue * * @param string|Response $response Response object or path to response file * * @return MockPlugin * @throws InvalidArgumentException if a string or Response is not passed */ public function addResponse($response) { if (!($response instanceof Response)) { if (!is_string($response)) { throw new InvalidArgumentException('Invalid response'); } $response = self::getMockFile($response); } $this->queue[] = $response; return $this; } /** * Add an exception to the end of the queue * * @param CurlException $e Exception to throw when the request is executed * * @return MockPlugin */ public function addException(CurlException $e) { $this->queue[] = $e; return $this; } /** * Clear the queue * * @return MockPlugin */ public function clearQueue() { $this->queue = array(); return $this; } /** * Returns an array of mock responses remaining in the queue * * @return array */ public function getQueue() { return $this->queue; } /** * Check if this is a temporary plugin * * @return bool */ public function isTemporary() { return $this->temporary; } /** * Get a response from the front of the list and add it to a request * * @param RequestInterface $request Request to mock * * @return self * @throws CurlException When request.send is called and an exception is queued */ public function dequeue(RequestInterface $request) { $this->dispatch('mock.request', array('plugin' => $this, 'request' => $request)); $item = array_shift($this->queue); if ($item instanceof Response) { if ($this->readBodies && $request instanceof EntityEnclosingRequestInterface) { $request->getEventDispatcher()->addListener('request.sent', $f = function (Event $event) use (&$f) { while ($data = $event['request']->getBody()->read(8096)); // Remove the listener after one-time use $event['request']->getEventDispatcher()->removeListener('request.sent', $f); }); } $request->setResponse($item); } elseif ($item instanceof CurlException) { // Emulates exceptions encountered while transferring requests $item->setRequest($request); $state = $request->setState(RequestInterface::STATE_ERROR, array('exception' => $item)); // Only throw if the exception wasn't handled if ($state == RequestInterface::STATE_ERROR) { throw $item; } } return $this; } /** * Clear the array of received requests */ public function flush() { $this->received = array(); } /** * Get an array of requests that were mocked by this plugin * * @return array */ public function getReceivedRequests() { return $this->received; } /** * Called when a request is about to be sent * * @param Event $event * @throws \OutOfBoundsException When queue is empty */ public function onRequestBeforeSend(Event $event) { if (!$this->queue) { throw new \OutOfBoundsException('Mock queue is empty'); } $request = $event['request']; $this->received[] = $request; // Detach the filter from the client so it's a one-time use if ($this->temporary && count($this->queue) == 1 && $request->getClient()) { $request->getClient()->getEventDispatcher()->removeSubscriber($this); } $this->dequeue($request); } } config = Collection::fromConfig($config, array( 'version' => '1.0', 'request_method' => self::REQUEST_METHOD_HEADER, 'consumer_key' => 'anonymous', 'consumer_secret' => 'anonymous', 'signature_method' => 'HMAC-SHA1', 'signature_callback' => function($stringToSign, $key) { return hash_hmac('sha1', $stringToSign, $key, true); } ), array( 'signature_method', 'signature_callback', 'version', 'consumer_key', 'consumer_secret' )); } public static function getSubscribedEvents() { return array( 'request.before_send' => array('onRequestBeforeSend', -1000) ); } /** * Request before-send event handler * * @param Event $event Event received * @return array * @throws \InvalidArgumentException */ public function onRequestBeforeSend(Event $event) { $timestamp = $this->getTimestamp($event); $request = $event['request']; $nonce = $this->generateNonce($request); $authorizationParams = $this->getOauthParams($timestamp, $nonce); $authorizationParams['oauth_signature'] = $this->getSignature($request, $timestamp, $nonce); switch ($this->config['request_method']) { case self::REQUEST_METHOD_HEADER: $request->setHeader( 'Authorization', $this->buildAuthorizationHeader($authorizationParams) ); break; case self::REQUEST_METHOD_QUERY: foreach ($authorizationParams as $key => $value) { $request->getQuery()->set($key, $value); } break; default: throw new \InvalidArgumentException(sprintf( 'Invalid consumer method "%s"', $this->config['request_method'] )); } return $authorizationParams; } /** * Builds the Authorization header for a request * * @param array $authorizationParams Associative array of authorization parameters * * @return string */ private function buildAuthorizationHeader($authorizationParams) { $authorizationString = 'OAuth '; foreach ($authorizationParams as $key => $val) { if ($val) { $authorizationString .= $key . '="' . urlencode($val) . '", '; } } return substr($authorizationString, 0, -2); } /** * Calculate signature for request * * @param RequestInterface $request Request to generate a signature for * @param integer $timestamp Timestamp to use for nonce * @param string $nonce * * @return string */ public function getSignature(RequestInterface $request, $timestamp, $nonce) { $string = $this->getStringToSign($request, $timestamp, $nonce); $key = urlencode($this->config['consumer_secret']) . '&' . urlencode($this->config['token_secret']); return base64_encode(call_user_func($this->config['signature_callback'], $string, $key)); } /** * Calculate string to sign * * @param RequestInterface $request Request to generate a signature for * @param int $timestamp Timestamp to use for nonce * @param string $nonce * * @return string */ public function getStringToSign(RequestInterface $request, $timestamp, $nonce) { $params = $this->getParamsToSign($request, $timestamp, $nonce); // Convert booleans to strings. $params = $this->prepareParameters($params); // Build signing string from combined params $parameterString = clone $request->getQuery(); $parameterString->replace($params); $url = Url::factory($request->getUrl())->setQuery('')->setFragment(null); return strtoupper($request->getMethod()) . '&' . rawurlencode($url) . '&' . rawurlencode((string) $parameterString); } /** * Get the oauth parameters as named by the oauth spec * * @param $timestamp * @param $nonce * @return Collection */ protected function getOauthParams($timestamp, $nonce) { $params = new Collection(array( 'oauth_consumer_key' => $this->config['consumer_key'], 'oauth_nonce' => $nonce, 'oauth_signature_method' => $this->config['signature_method'], 'oauth_timestamp' => $timestamp, )); // Optional parameters should not be set if they have not been set in the config as // the parameter may be considered invalid by the Oauth service. $optionalParams = array( 'callback' => 'oauth_callback', 'token' => 'oauth_token', 'verifier' => 'oauth_verifier', 'version' => 'oauth_version' ); foreach ($optionalParams as $optionName => $oauthName) { if (isset($this->config[$optionName]) == true) { $params[$oauthName] = $this->config[$optionName]; } } return $params; } /** * Get all of the parameters required to sign a request including: * * The oauth params * * The request GET params * * The params passed in the POST body (with a content-type of application/x-www-form-urlencoded) * * @param RequestInterface $request Request to generate a signature for * @param integer $timestamp Timestamp to use for nonce * @param string $nonce * * @return array */ public function getParamsToSign(RequestInterface $request, $timestamp, $nonce) { $params = $this->getOauthParams($timestamp, $nonce); // Add query string parameters $params->merge($request->getQuery()); // Add POST fields to signing string if required if ($this->shouldPostFieldsBeSigned($request)) { $params->merge($request->getPostFields()); } // Sort params $params = $params->toArray(); uksort($params, 'strcmp'); return $params; } /** * Decide whether the post fields should be added to the base string that Oauth signs. * This implementation is correct. Non-conformant APIs may require that this method be * overwritten e.g. the Flickr API incorrectly adds the post fields when the Content-Type * is 'application/x-www-form-urlencoded' * * @param $request * @return bool Whether the post fields should be signed or not */ public function shouldPostFieldsBeSigned($request) { if (!$this->config->get('disable_post_params') && $request instanceof EntityEnclosingRequestInterface && false !== strpos($request->getHeader('Content-Type'), 'application/x-www-form-urlencoded')) { return true; } return false; } /** * Returns a Nonce Based on the unique id and URL. This will allow for multiple requests in parallel with the same * exact timestamp to use separate nonce's. * * @param RequestInterface $request Request to generate a nonce for * * @return string */ public function generateNonce(RequestInterface $request) { return sha1(uniqid('', true) . $request->getUrl()); } /** * Gets timestamp from event or create new timestamp * * @param Event $event Event containing contextual information * * @return int */ public function getTimestamp(Event $event) { return $event['timestamp'] ?: time(); } /** * Convert booleans to strings, removed unset parameters, and sorts the array * * @param array $data Data array * * @return array */ protected function prepareParameters($data) { ksort($data); foreach ($data as $key => &$value) { switch (gettype($value)) { case 'NULL': unset($data[$key]); break; case 'array': $data[$key] = self::prepareParameters($value); break; case 'boolean': $data[$key] = $value ? 'true' : 'false'; break; } } return $data; } } 'JSON_ERROR_NONE - No errors', JSON_ERROR_DEPTH => 'JSON_ERROR_DEPTH - Maximum stack depth exceeded', JSON_ERROR_STATE_MISMATCH => 'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch', JSON_ERROR_CTRL_CHAR => 'JSON_ERROR_CTRL_CHAR - Unexpected control character found', JSON_ERROR_SYNTAX => 'JSON_ERROR_SYNTAX - Syntax error, malformed JSON', JSON_ERROR_UTF8 => 'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded' ); public function load($config, array $options = array()) { // Reset the array of loaded files because this is a new config $this->loadedFiles = array(); if (is_string($config)) { $config = $this->loadFile($config); } elseif (!is_array($config)) { throw new InvalidArgumentException('Unknown type passed to configuration loader: ' . gettype($config)); } else { $this->mergeIncludes($config); } return $this->build($config, $options); } /** * Add an include alias to the loader * * @param string $filename Filename to alias (e.g. _foo) * @param string $alias Actual file to use (e.g. /path/to/foo.json) * * @return self */ public function addAlias($filename, $alias) { $this->aliases[$filename] = $alias; return $this; } /** * Remove an alias from the loader * * @param string $alias Alias to remove * * @return self */ public function removeAlias($alias) { unset($this->aliases[$alias]); return $this; } /** * Perform the parsing of a config file and create the end result * * @param array $config Configuration data * @param array $options Options to use when building * * @return mixed */ protected abstract function build($config, array $options); /** * Load a configuration file (can load JSON or PHP files that return an array when included) * * @param string $filename File to load * * @return array * @throws InvalidArgumentException * @throws RuntimeException when the JSON cannot be parsed */ protected function loadFile($filename) { if (isset($this->aliases[$filename])) { $filename = $this->aliases[$filename]; } switch (pathinfo($filename, PATHINFO_EXTENSION)) { case 'js': case 'json': $level = error_reporting(0); $json = file_get_contents($filename); error_reporting($level); if ($json === false) { $err = error_get_last(); throw new InvalidArgumentException("Unable to open {$filename}: " . $err['message']); } $config = json_decode($json, true); // Throw an exception if there was an error loading the file if ($error = json_last_error()) { $message = isset(self::$jsonErrors[$error]) ? self::$jsonErrors[$error] : 'Unknown error'; throw new RuntimeException("Error loading JSON data from {$filename}: ({$error}) - {$message}"); } break; case 'php': if (!is_readable($filename)) { throw new InvalidArgumentException("Unable to open {$filename} for reading"); } $config = require $filename; if (!is_array($config)) { throw new InvalidArgumentException('PHP files must return an array of configuration data'); } break; default: throw new InvalidArgumentException('Unknown file extension: ' . $filename); } // Keep track of this file being loaded to prevent infinite recursion $this->loadedFiles[$filename] = true; // Merge include files into the configuration array $this->mergeIncludes($config, dirname($filename)); return $config; } /** * Merges in all include files * * @param array $config Config data that contains includes * @param string $basePath Base path to use when a relative path is encountered * * @return array Returns the merged and included data */ protected function mergeIncludes(&$config, $basePath = null) { if (!empty($config['includes'])) { foreach ($config['includes'] as &$path) { // Account for relative paths if ($path[0] != DIRECTORY_SEPARATOR && !isset($this->aliases[$path]) && $basePath) { $path = "{$basePath}/{$path}"; } // Don't load the same files more than once if (!isset($this->loadedFiles[$path])) { $this->loadedFiles[$path] = true; $config = $this->mergeData($this->loadFile($path), $config); } } } } /** * Default implementation for merging two arrays of data (uses array_merge_recursive) * * @param array $a Original data * @param array $b Data to merge into the original and overwrite existing values * * @return array */ protected function mergeData(array $a, array $b) { return array_merge_recursive($a, $b); } } load($config, $globalParameters); } /** * @param array $serviceBuilderConfig Service configuration settings: * - name: Name of the service * - class: Client class to instantiate using a factory method * - params: array of key value pair configuration settings for the builder */ public function __construct(array $serviceBuilderConfig = array()) { $this->builderConfig = $serviceBuilderConfig; } public static function getAllEvents() { return array('service_builder.create_client'); } public function unserialize($serialized) { $this->builderConfig = json_decode($serialized, true); } public function serialize() { return json_encode($this->builderConfig); } /** * Attach a plugin to every client created by the builder * * @param EventSubscriberInterface $plugin Plugin to attach to each client * * @return self */ public function addGlobalPlugin(EventSubscriberInterface $plugin) { $this->plugins[] = $plugin; return $this; } /** * Get data from the service builder without triggering the building of a service * * @param string $name Name of the service to retrieve * * @return array|null */ public function getData($name) { return isset($this->builderConfig[$name]) ? $this->builderConfig[$name] : null; } public function get($name, $throwAway = false) { if (!isset($this->builderConfig[$name])) { // Check to see if arbitrary data is being referenced if (isset($this->clients[$name])) { return $this->clients[$name]; } // Check aliases and return a match if found foreach ($this->builderConfig as $actualName => $config) { if (isset($config['alias']) && $config['alias'] == $name) { return $this->get($actualName, $throwAway); } } throw new ServiceNotFoundException('No service is registered as ' . $name); } if (!$throwAway && isset($this->clients[$name])) { return $this->clients[$name]; } $builder =& $this->builderConfig[$name]; // Convert references to the actual client foreach ($builder['params'] as &$v) { if (is_string($v) && substr($v, 0, 1) == '{' && substr($v, -1) == '}') { $v = $this->get(trim($v, '{} ')); } } // Get the configured parameters and merge in any parameters provided for throw-away clients $config = $builder['params']; if (is_array($throwAway)) { $config = $throwAway + $config; } $client = $builder['class']::factory($config); if (!$throwAway) { $this->clients[$name] = $client; } if ($client instanceof ClientInterface) { foreach ($this->plugins as $plugin) { $client->addSubscriber($plugin); } // Dispatch an event letting listeners know a client was created $this->dispatch('service_builder.create_client', array('client' => $client)); } return $client; } public function set($key, $service) { if (is_array($service) && isset($service['class']) && isset($service['params'])) { $this->builderConfig[$key] = $service; } else { $this->clients[$key] = $service; } return $this; } public function offsetSet($offset, $value) { $this->set($offset, $value); } public function offsetUnset($offset) { unset($this->builderConfig[$offset]); unset($this->clients[$offset]); } public function offsetExists($offset) { return isset($this->builderConfig[$offset]) || isset($this->clients[$offset]); } public function offsetGet($offset) { return $this->get($offset); } } &$service) { $service['params'] = isset($service['params']) ? $service['params'] : array(); // Check if this client builder extends another client if (!empty($service['extends'])) { // Make sure that the service it's extending has been defined if (!isset($services[$service['extends']])) { throw new ServiceNotFoundException( "{$name} is trying to extend a non-existent service: {$service['extends']}" ); } $extended = &$services[$service['extends']]; // Use the correct class attribute if (empty($service['class'])) { $service['class'] = isset($extended['class']) ? $extended['class'] : ''; } if ($extendsParams = isset($extended['params']) ? $extended['params'] : false) { $service['params'] = $service['params'] + $extendsParams; } } // Overwrite default values with global parameter values if (!empty($options)) { $service['params'] = $options + $service['params']; } $service['class'] = isset($service['class']) ? $service['class'] : ''; } return new $class($services); } protected function mergeData(array $a, array $b) { $result = $b + $a; // Merge services using a recursive union of arrays if (isset($a['services']) && $b['services']) { // Get a union of the services of the two arrays $result['services'] = $b['services'] + $a['services']; // Merge each service in using a union of the two arrays foreach ($result['services'] as $name => &$service) { // By default, services completely override a previously defined service unless it extends itself if (isset($a['services'][$name]['extends']) && isset($b['services'][$name]['extends']) && $b['services'][$name]['extends'] == $name ) { $service += $a['services'][$name]; // Use the `extends` attribute of the parent $service['extends'] = $a['services'][$name]['extends']; // Merge parameters using a union if both have parameters if (isset($a['services'][$name]['params'])) { $service['params'] += $a['services'][$name]['params']; } } } } return $result; } } loader = $loader; $this->cache = $cache; } public function load($config, array $options = array()) { if (!is_string($config)) { $key = false; } else { $key = 'loader_' . crc32($config); if ($result = $this->cache->fetch($key)) { return $result; } } $result = $this->loader->load($config, $options); if ($key) { $this->cache->save($key, $result); } return $result; } } getCommand($method, isset($args[0]) ? $args[0] : array())->getResult(); } public function getCommand($name, array $args = array()) { // Add global client options to the command if ($options = $this->getConfig(self::COMMAND_PARAMS)) { $args += $options; } if (!($command = $this->getCommandFactory()->factory($name, $args))) { throw new InvalidArgumentException("Command was not found matching {$name}"); } $command->setClient($this); $this->dispatch('client.command.create', array('client' => $this, 'command' => $command)); return $command; } /** * Set the command factory used to create commands by name * * @param CommandFactoryInterface $factory Command factory * * @return self */ public function setCommandFactory(CommandFactoryInterface $factory) { $this->commandFactory = $factory; return $this; } /** * Set the resource iterator factory associated with the client * * @param ResourceIteratorFactoryInterface $factory Resource iterator factory * * @return self */ public function setResourceIteratorFactory(ResourceIteratorFactoryInterface $factory) { $this->resourceIteratorFactory = $factory; return $this; } public function getIterator($command, array $commandOptions = null, array $iteratorOptions = array()) { if (!($command instanceof CommandInterface)) { $command = $this->getCommand($command, $commandOptions ?: array()); } return $this->getResourceIteratorFactory()->build($command, $iteratorOptions); } public function execute($command) { if ($command instanceof CommandInterface) { $this->send($this->prepareCommand($command)); $this->dispatch('command.after_send', array('command' => $command)); return $command->getResult(); } elseif (is_array($command) || $command instanceof \Traversable) { return $this->executeMultiple($command); } else { throw new InvalidArgumentException('Command must be a command or array of commands'); } } public function setDescription(ServiceDescriptionInterface $service) { $this->serviceDescription = $service; if ($this->getCommandFactory() && $this->getCommandFactory() instanceof CompositeFactory) { $this->commandFactory->add(new Command\Factory\ServiceDescriptionFactory($service)); } // If a baseUrl was set on the description, then update the client if ($baseUrl = $service->getBaseUrl()) { $this->setBaseUrl($baseUrl); } return $this; } public function getDescription() { return $this->serviceDescription; } /** * Set the inflector used with the client * * @param InflectorInterface $inflector Inflection object * * @return self */ public function setInflector(InflectorInterface $inflector) { $this->inflector = $inflector; return $this; } /** * Get the inflector used with the client * * @return self */ public function getInflector() { if (!$this->inflector) { $this->inflector = Inflector::getDefault(); } return $this->inflector; } /** * Prepare a command for sending and get the RequestInterface object created by the command * * @param CommandInterface $command Command to prepare * * @return RequestInterface */ protected function prepareCommand(CommandInterface $command) { // Set the client and prepare the command $request = $command->setClient($this)->prepare(); // Set the state to new if the command was previously executed $request->setState(RequestInterface::STATE_NEW); $this->dispatch('command.before_send', array('command' => $command)); return $request; } /** * Execute multiple commands in parallel * * @param array|Traversable $commands Array of CommandInterface objects to execute * * @return array Returns an array of the executed commands * @throws Exception\CommandTransferException */ protected function executeMultiple($commands) { $requests = array(); $commandRequests = new \SplObjectStorage(); foreach ($commands as $command) { $request = $this->prepareCommand($command); $commandRequests[$request] = $command; $requests[] = $request; } try { $this->send($requests); foreach ($commands as $command) { $this->dispatch('command.after_send', array('command' => $command)); } return $commands; } catch (MultiTransferException $failureException) { // Throw a CommandTransferException using the successful and failed commands $e = CommandTransferException::fromMultiTransferException($failureException); // Remove failed requests from the successful requests array and add to the failures array foreach ($failureException->getFailedRequests() as $request) { if (isset($commandRequests[$request])) { $e->addFailedCommand($commandRequests[$request]); unset($commandRequests[$request]); } } // Always emit the command after_send events for successful commands foreach ($commandRequests as $success) { $e->addSuccessfulCommand($commandRequests[$success]); $this->dispatch('command.after_send', array('command' => $commandRequests[$success])); } throw $e; } } protected function getResourceIteratorFactory() { if (!$this->resourceIteratorFactory) { // Build the default resource iterator factory if one is not set $clientClass = get_class($this); $prefix = substr($clientClass, 0, strrpos($clientClass, '\\')); $this->resourceIteratorFactory = new ResourceIteratorClassFactory(array( "{$prefix}\\Iterator", "{$prefix}\\Model" )); } return $this->resourceIteratorFactory; } /** * Get the command factory associated with the client * * @return CommandFactoryInterface */ protected function getCommandFactory() { if (!$this->commandFactory) { $this->commandFactory = CompositeFactory::getDefaultChain($this); } return $this->commandFactory; } /** * @deprecated * @codeCoverageIgnore */ public function enableMagicMethods($isEnabled) { Version::warn(__METHOD__ . ' is deprecated'); } } operation = $operation ?: $this->createOperation(); foreach ($this->operation->getParams() as $name => $arg) { $currentValue = $this[$name]; $configValue = $arg->getValue($currentValue); // If default or static values are set, then this should always be updated on the config object if ($currentValue !== $configValue) { $this[$name] = $configValue; } } $headers = $this[self::HEADERS_OPTION]; if (!$headers instanceof Collection) { $this[self::HEADERS_OPTION] = new Collection((array) $headers); } // You can set a command.on_complete option in your parameters to set an onComplete callback if ($onComplete = $this['command.on_complete']) { unset($this['command.on_complete']); $this->setOnComplete($onComplete); } // Set the hidden additional parameters if (!$this[self::HIDDEN_PARAMS]) { $this[self::HIDDEN_PARAMS] = array( self::HEADERS_OPTION, self::RESPONSE_PROCESSING, self::HIDDEN_PARAMS, self::REQUEST_OPTIONS ); } $this->init(); } /** * Custom clone behavior */ public function __clone() { $this->request = null; $this->result = null; } /** * Execute the command in the same manner as calling a function * * @return mixed Returns the result of {@see AbstractCommand::execute} */ public function __invoke() { return $this->execute(); } public function getName() { return $this->operation->getName(); } /** * Get the API command information about the command * * @return OperationInterface */ public function getOperation() { return $this->operation; } public function setOnComplete($callable) { if (!is_callable($callable)) { throw new InvalidArgumentException('The onComplete function must be callable'); } $this->onComplete = $callable; return $this; } public function execute() { if (!$this->client) { throw new CommandException('A client must be associated with the command before it can be executed.'); } return $this->client->execute($this); } public function getClient() { return $this->client; } public function setClient(ClientInterface $client) { $this->client = $client; return $this; } public function getRequest() { if (!$this->request) { throw new CommandException('The command must be prepared before retrieving the request'); } return $this->request; } public function getResponse() { if (!$this->isExecuted()) { $this->execute(); } return $this->request->getResponse(); } public function getResult() { if (!$this->isExecuted()) { $this->execute(); } if (null === $this->result) { $this->process(); // Call the onComplete method if one is set if ($this->onComplete) { call_user_func($this->onComplete, $this); } } return $this->result; } public function setResult($result) { $this->result = $result; return $this; } public function isPrepared() { return $this->request !== null; } public function isExecuted() { return $this->request !== null && $this->request->getState() == 'complete'; } public function prepare() { if (!$this->isPrepared()) { if (!$this->client) { throw new CommandException('A client must be associated with the command before it can be prepared.'); } // If no response processing value was specified, then attempt to use the highest level of processing if (!isset($this[self::RESPONSE_PROCESSING])) { $this[self::RESPONSE_PROCESSING] = self::TYPE_MODEL; } // Notify subscribers of the client that the command is being prepared $this->client->dispatch('command.before_prepare', array('command' => $this)); // Fail on missing required arguments, and change parameters via filters $this->validate(); // Delegate to the subclass that implements the build method $this->build(); // Add custom request headers set on the command if ($headers = $this[self::HEADERS_OPTION]) { foreach ($headers as $key => $value) { $this->request->setHeader($key, $value); } } // Add any curl options to the request if ($options = $this[Client::CURL_OPTIONS]) { $this->request->getCurlOptions()->overwriteWith(CurlHandle::parseCurlConfig($options)); } // Set a custom response body if ($responseBody = $this[self::RESPONSE_BODY]) { $this->request->setResponseBody($responseBody); } $this->client->dispatch('command.after_prepare', array('command' => $this)); } return $this->request; } /** * Set the validator used to validate and prepare command parameters and nested JSON schemas. If no validator is * set, then the command will validate using the default {@see SchemaValidator}. * * @param ValidatorInterface $validator Validator used to prepare and validate properties against a JSON schema * * @return self */ public function setValidator(ValidatorInterface $validator) { $this->validator = $validator; return $this; } public function getRequestHeaders() { return $this[self::HEADERS_OPTION]; } /** * Initialize the command (hook that can be implemented in subclasses) */ protected function init() {} /** * Create the request object that will carry out the command */ abstract protected function build(); /** * Hook used to create an operation for concrete commands that are not associated with a service description * * @return OperationInterface */ protected function createOperation() { return new Operation(array('name' => get_class($this))); } /** * Create the result of the command after the request has been completed. * Override this method in subclasses to customize this behavior */ protected function process() { $this->result = $this[self::RESPONSE_PROCESSING] != self::TYPE_RAW ? DefaultResponseParser::getInstance()->parse($this) : $this->request->getResponse(); } /** * Validate and prepare the command based on the schema and rules defined by the command's Operation object * * @throws ValidationException when validation errors occur */ protected function validate() { // Do not perform request validation/transformation if it is disable if ($this[self::DISABLE_VALIDATION]) { return; } $errors = array(); $validator = $this->getValidator(); foreach ($this->operation->getParams() as $name => $schema) { $value = $this[$name]; if (!$validator->validate($schema, $value)) { $errors = array_merge($errors, $validator->getErrors()); } elseif ($value !== $this[$name]) { // Update the config value if it changed and no validation errors were encountered $this->data[$name] = $value; } } // Validate additional parameters $hidden = $this[self::HIDDEN_PARAMS]; if ($properties = $this->operation->getAdditionalParameters()) { foreach ($this->toArray() as $name => $value) { // It's only additional if it isn't defined in the schema if (!$this->operation->hasParam($name) && !in_array($name, $hidden)) { // Always set the name so that error messages are useful $properties->setName($name); if (!$validator->validate($properties, $value)) { $errors = array_merge($errors, $validator->getErrors()); } elseif ($value !== $this[$name]) { $this->data[$name] = $value; } } } } if (!empty($errors)) { $e = new ValidationException('Validation errors: ' . implode("\n", $errors)); $e->setErrors($errors); throw $e; } } /** * Get the validator used to prepare and validate properties. If no validator has been set on the command, then * the default {@see SchemaValidator} will be used. * * @return ValidatorInterface */ protected function getValidator() { if (!$this->validator) { $this->validator = SchemaValidator::getInstance(); } return $this->validator; } /** * Get array of any validation errors * If no validator has been set then return false */ public function getValidationErrors() { if (!$this->validator) { return false; } return $this->validator->getErrors(); } } request = $closure($this, $this->operation); if (!$this->request || !$this->request instanceof RequestInterface) { throw new UnexpectedValueException('Closure command did not return a RequestInterface object'); } } } stopPropagation(); } /** * Get the created object * * @return mixed */ public function getResult() { return $this['result']; } } factory = $factory; } /** * Add a location visitor to the serializer * * @param string $location Location to associate with the visitor * @param RequestVisitorInterface $visitor Visitor to attach * * @return self */ public function addVisitor($location, RequestVisitorInterface $visitor) { $this->factory->addRequestVisitor($location, $visitor); return $this; } public function prepare(CommandInterface $command) { $request = $this->createRequest($command); // Keep an array of visitors found in the operation $foundVisitors = array(); $operation = $command->getOperation(); // Add arguments to the request using the location attribute foreach ($operation->getParams() as $name => $arg) { /** @var $arg \Guzzle\Service\Description\Parameter */ $location = $arg->getLocation(); // Skip 'uri' locations because they've already been processed if ($location && $location != 'uri') { // Instantiate visitors as they are detected in the properties if (!isset($foundVisitors[$location])) { $foundVisitors[$location] = $this->factory->getRequestVisitor($location); } // Ensure that a value has been set for this parameter $value = $command[$name]; if ($value !== null) { // Apply the parameter value with the location visitor $foundVisitors[$location]->visit($command, $request, $arg, $value); } } } // Serialize additional parameters if ($additional = $operation->getAdditionalParameters()) { if ($visitor = $this->prepareAdditionalParameters($operation, $command, $request, $additional)) { $foundVisitors[$additional->getLocation()] = $visitor; } } // Call the after method on each visitor found in the operation foreach ($foundVisitors as $visitor) { $visitor->after($command, $request); } return $request; } /** * Serialize additional parameters * * @param OperationInterface $operation Operation that owns the command * @param CommandInterface $command Command to prepare * @param RequestInterface $request Request to serialize * @param Parameter $additional Additional parameters * * @return null|RequestVisitorInterface */ protected function prepareAdditionalParameters( OperationInterface $operation, CommandInterface $command, RequestInterface $request, Parameter $additional ) { if (!($location = $additional->getLocation())) { return; } $visitor = $this->factory->getRequestVisitor($location); $hidden = $command[$command::HIDDEN_PARAMS]; foreach ($command->toArray() as $key => $value) { // Ignore values that are null or built-in command options if ($value !== null && !in_array($key, $hidden) && !$operation->hasParam($key) ) { $additional->setName($key); $visitor->visit($command, $request, $additional, $value); } } return $visitor; } /** * Create a request for the command and operation * * @param CommandInterface $command Command to create a request for * * @return RequestInterface */ protected function createRequest(CommandInterface $command) { $operation = $command->getOperation(); $client = $command->getClient(); $options = $command[AbstractCommand::REQUEST_OPTIONS] ?: array(); // If the command does not specify a template, then assume the base URL of the client if (!($uri = $operation->getUri())) { return $client->createRequest($operation->getHttpMethod(), $client->getBaseUrl(), null, null, $options); } // Get the path values and use the client config settings $variables = array(); foreach ($operation->getParams() as $name => $arg) { if ($arg->getLocation() == 'uri') { if (isset($command[$name])) { $variables[$name] = $arg->filter($command[$name]); if (!is_array($variables[$name])) { $variables[$name] = (string) $variables[$name]; } } } } return $client->createRequest($operation->getHttpMethod(), array($uri, $variables), null, null, $options); } } getRequest()->getResponse(); // Account for hard coded content-type values specified in service descriptions if ($contentType = $command['command.expects']) { $response->setHeader('Content-Type', $contentType); } else { $contentType = (string) $response->getHeader('Content-Type'); } return $this->handleParsing($command, $response, $contentType); } protected function handleParsing(CommandInterface $command, Response $response, $contentType) { $result = $response; if ($result->getBody()) { if (stripos($contentType, 'json') !== false) { $result = $result->json(); } elseif (stripos($contentType, 'xml') !== false) { $result = $result->xml(); } } return $result; } } client = $client; $this->aliases = $aliases; } public function factory($name, array $args = array()) { if (isset($this->aliases[$name])) { try { return $this->client->getCommand($this->aliases[$name], $args); } catch (InvalidArgumentException $e) { return null; } } } } getDescription()) { $factories[] = new ServiceDescriptionFactory($description); } $factories[] = new ConcreteClassFactory($client); return new self($factories); } /** * @param array $factories Array of command factories */ public function __construct(array $factories = array()) { $this->factories = $factories; } /** * Add a command factory to the chain * * @param FactoryInterface $factory Factory to add * @param string|FactoryInterface $before Insert the new command factory before a command factory class or object * matching a class name. * @return CompositeFactory */ public function add(FactoryInterface $factory, $before = null) { $pos = null; if ($before) { foreach ($this->factories as $i => $f) { if ($before instanceof FactoryInterface) { if ($f === $before) { $pos = $i; break; } } elseif (is_string($before)) { if ($f instanceof $before) { $pos = $i; break; } } } } if ($pos === null) { $this->factories[] = $factory; } else { array_splice($this->factories, $i, 0, array($factory)); } return $this; } /** * Check if the chain contains a specific command factory * * @param FactoryInterface|string $factory Factory to check * * @return bool */ public function has($factory) { return (bool) $this->find($factory); } /** * Remove a specific command factory from the chain * * @param string|FactoryInterface $factory Factory to remove by name or instance * * @return CompositeFactory */ public function remove($factory = null) { if (!($factory instanceof FactoryInterface)) { $factory = $this->find($factory); } $this->factories = array_values(array_filter($this->factories, function($f) use ($factory) { return $f !== $factory; })); return $this; } /** * Get a command factory by class name * * @param string|FactoryInterface $factory Command factory class or instance * * @return null|FactoryInterface */ public function find($factory) { foreach ($this->factories as $f) { if ($factory === $f || (is_string($factory) && $f instanceof $factory)) { return $f; } } } /** * Create a command using the associated command factories * * @param string $name Name of the command * @param array $args Command arguments * * @return CommandInterface */ public function factory($name, array $args = array()) { foreach ($this->factories as $factory) { $command = $factory->factory($name, $args); if ($command) { return $command; } } } public function count() { return count($this->factories); } public function getIterator() { return new \ArrayIterator($this->factories); } } client = $client; $this->inflector = $inflector ?: Inflector::getDefault(); } public function factory($name, array $args = array()) { // Determine the class to instantiate based on the namespace of the current client and the default directory $prefix = $this->client->getConfig('command.prefix'); if (!$prefix) { // The prefix can be specified in a factory method and is cached $prefix = implode('\\', array_slice(explode('\\', get_class($this->client)), 0, -1)) . '\\Command\\'; $this->client->getConfig()->set('command.prefix', $prefix); } $class = $prefix . str_replace(' ', '\\', ucwords(str_replace('.', ' ', $this->inflector->camel($name)))); // Create the concrete command if it exists if (class_exists($class)) { return new $class($args); } } } map = $map; } public function factory($name, array $args = array()) { if (isset($this->map[$name])) { $class = $this->map[$name]; return new $class($args); } } } setServiceDescription($description); $this->inflector = $inflector; } /** * Change the service description used with the factory * * @param ServiceDescriptionInterface $description Service description to use * * @return FactoryInterface */ public function setServiceDescription(ServiceDescriptionInterface $description) { $this->description = $description; return $this; } /** * Returns the service description * * @return ServiceDescriptionInterface */ public function getServiceDescription() { return $this->description; } public function factory($name, array $args = array()) { $command = $this->description->getOperation($name); // If a command wasn't found, then try to uppercase the first letter and try again if (!$command) { $command = $this->description->getOperation(ucfirst($name)); // If an inflector was passed, then attempt to get the command using snake_case inflection if (!$command && $this->inflector) { $command = $this->description->getOperation($this->inflector->snake($name)); } } if ($command) { $class = $command->getClass(); return new $class($args, $command, $this->description); } } } resolveRecursively($value, $param) : $param->filter($value); } /** * Map nested parameters into the location_key based parameters * * @param array $value Value to map * @param Parameter $param Parameter that holds information about the current key * * @return array Returns the mapped array */ protected function resolveRecursively(array $value, Parameter $param) { foreach ($value as $name => &$v) { switch ($param->getType()) { case 'object': if ($subParam = $param->getProperty($name)) { $key = $subParam->getWireName(); $value[$key] = $this->prepareValue($v, $subParam); if ($name != $key) { unset($value[$name]); } } elseif ($param->getAdditionalProperties() instanceof Parameter) { $v = $this->prepareValue($v, $param->getAdditionalProperties()); } break; case 'array': if ($items = $param->getItems()) { $v = $this->prepareValue($v, $items); } break; } } return $param->filter($value); } } filter($value); $entityBody = EntityBody::factory($value); $request->setBody($entityBody); $this->addExpectHeader($request, $entityBody, $param->getData('expect_header')); // Add the Content-Encoding header if one is set on the EntityBody if ($encoding = $entityBody->getContentEncoding()) { $request->setHeader('Content-Encoding', $encoding); } } /** * Add the appropriate expect header to a request * * @param EntityEnclosingRequestInterface $request Request to update * @param EntityBodyInterface $body Entity body of the request * @param string|int $expect Expect header setting */ protected function addExpectHeader(EntityEnclosingRequestInterface $request, EntityBodyInterface $body, $expect) { // Allow the `expect` data parameter to be set to remove the Expect header from the request if ($expect === false) { $request->removeHeader('Expect'); } elseif ($expect !== true) { // Default to using a MB as the point in which to start using the expect header $expect = $expect ?: 1048576; // If the expect_header value is numeric then only add if the size is greater than the cutoff if (is_numeric($expect) && $body->getSize()) { if ($body->getSize() < $expect) { $request->removeHeader('Expect'); } else { $request->setHeader('Expect', '100-Continue'); } } } } } filter($value); if ($param->getType() == 'object' && $param->getAdditionalProperties() instanceof Parameter) { $this->addPrefixedHeaders($request, $param, $value); } else { $request->setHeader($param->getWireName(), $value); } } /** * Add a prefixed array of headers to the request * * @param RequestInterface $request Request to update * @param Parameter $param Parameter object * @param array $value Header array to add * * @throws InvalidArgumentException */ protected function addPrefixedHeaders(RequestInterface $request, Parameter $param, $value) { if (!is_array($value)) { throw new InvalidArgumentException('An array of mapped headers expected, but received a single value'); } $prefix = $param->getSentAs(); foreach ($value as $headerName => $headerValue) { $request->setHeader($prefix . $headerName, $headerValue); } } } data = new \SplObjectStorage(); } /** * Set the Content-Type header to add to the request if JSON is added to the body. This visitor does not add a * Content-Type header unless you specify one here. * * @param string $header Header to set when JSON is added (e.g. application/json) * * @return self */ public function setContentTypeHeader($header = 'application/json') { $this->jsonContentType = $header; return $this; } public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value) { if (isset($this->data[$command])) { $json = $this->data[$command]; } else { $json = array(); } $json[$param->getWireName()] = $this->prepareValue($value, $param); $this->data[$command] = $json; } public function after(CommandInterface $command, RequestInterface $request) { if (isset($this->data[$command])) { // Don't overwrite the Content-Type if one is set if ($this->jsonContentType && !$request->hasHeader('Content-Type')) { $request->setHeader('Content-Type', $this->jsonContentType); } $request->setBody(json_encode($this->data[$command])); unset($this->data[$command]); } } } setPostField($param->getWireName(), $this->prepareValue($value, $param)); } } filter($value); if ($value instanceof PostFileInterface) { $request->addPostFile($value); } else { $request->addPostFile($param->getWireName(), $value); } } } getQuery()->set($param->getWireName(), $this->prepareValue($value, $param)); } } setResponseBody($value); } } data = new \SplObjectStorage(); } /** * Change the content-type header that is added when XML is found * * @param string $header Header to set when XML is found * * @return self */ public function setContentTypeHeader($header) { $this->contentType = $header; return $this; } public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value) { $xml = isset($this->data[$command]) ? $this->data[$command] : $this->createRootElement($param->getParent()); $this->addXml($xml, $param, $value); $this->data[$command] = $xml; } public function after(CommandInterface $command, RequestInterface $request) { $xml = null; // If data was found that needs to be serialized, then do so if (isset($this->data[$command])) { $xml = $this->finishDocument($this->data[$command]); unset($this->data[$command]); } else { // Check if XML should always be sent for the command $operation = $command->getOperation(); if ($operation->getData('xmlAllowEmpty')) { $xmlWriter = $this->createRootElement($operation); $xml = $this->finishDocument($xmlWriter); } } if ($xml) { // Don't overwrite the Content-Type if one is set if ($this->contentType && !$request->hasHeader('Content-Type')) { $request->setHeader('Content-Type', $this->contentType); } $request->setBody($xml); } } /** * Create the root XML element to use with a request * * @param Operation $operation Operation object * * @return \XMLWriter */ protected function createRootElement(Operation $operation) { static $defaultRoot = array('name' => 'Request'); // If no root element was specified, then just wrap the XML in 'Request' $root = $operation->getData('xmlRoot') ?: $defaultRoot; // Allow the XML declaration to be customized with xmlEncoding $encoding = $operation->getData('xmlEncoding'); $xmlWriter = $this->startDocument($encoding); $xmlWriter->startElement($root['name']); // Create the wrapping element with no namespaces if no namespaces were present if (!empty($root['namespaces'])) { // Create the wrapping element with an array of one or more namespaces foreach ((array) $root['namespaces'] as $prefix => $uri) { $nsLabel = 'xmlns'; if (!is_numeric($prefix)) { $nsLabel .= ':'.$prefix; } $xmlWriter->writeAttribute($nsLabel, $uri); } } return $xmlWriter; } /** * Recursively build the XML body * * @param \XMLWriter $xmlWriter XML to modify * @param Parameter $param API Parameter * @param mixed $value Value to add */ protected function addXml(\XMLWriter $xmlWriter, Parameter $param, $value) { if ($value === null) { return; } $value = $param->filter($value); $type = $param->getType(); $name = $param->getWireName(); $prefix = null; $namespace = $param->getData('xmlNamespace'); if (false !== strpos($name, ':')) { list($prefix, $name) = explode(':', $name, 2); } if ($type == 'object' || $type == 'array') { if (!$param->getData('xmlFlattened')) { $xmlWriter->startElementNS(null, $name, $namespace); } if ($param->getType() == 'array') { $this->addXmlArray($xmlWriter, $param, $value); } elseif ($param->getType() == 'object') { $this->addXmlObject($xmlWriter, $param, $value); } if (!$param->getData('xmlFlattened')) { $xmlWriter->endElement(); } return; } if ($param->getData('xmlAttribute')) { $this->writeAttribute($xmlWriter, $prefix, $name, $namespace, $value); } else { $this->writeElement($xmlWriter, $prefix, $name, $namespace, $value); } } /** * Write an attribute with namespace if used * * @param \XMLWriter $xmlWriter XMLWriter instance * @param string $prefix Namespace prefix if any * @param string $name Attribute name * @param string $namespace The uri of the namespace * @param string $value The attribute content */ protected function writeAttribute($xmlWriter, $prefix, $name, $namespace, $value) { if (empty($namespace)) { $xmlWriter->writeAttribute($name, $value); } else { $xmlWriter->writeAttributeNS($prefix, $name, $namespace, $value); } } /** * Write an element with namespace if used * * @param \XMLWriter $xmlWriter XML writer resource * @param string $prefix Namespace prefix if any * @param string $name Element name * @param string $namespace The uri of the namespace * @param string $value The element content */ protected function writeElement(\XMLWriter $xmlWriter, $prefix, $name, $namespace, $value) { $xmlWriter->startElementNS($prefix, $name, $namespace); if (strpbrk($value, '<>&')) { $xmlWriter->writeCData($value); } else { $xmlWriter->writeRaw($value); } $xmlWriter->endElement(); } /** * Create a new xml writer and start a document * * @param string $encoding document encoding * * @return \XMLWriter the writer resource */ protected function startDocument($encoding) { $xmlWriter = new \XMLWriter(); $xmlWriter->openMemory(); $xmlWriter->startDocument('1.0', $encoding); return $xmlWriter; } /** * End the document and return the output * * @param \XMLWriter $xmlWriter * * @return \string the writer resource */ protected function finishDocument($xmlWriter) { $xmlWriter->endDocument(); return $xmlWriter->outputMemory(); } /** * Add an array to the XML */ protected function addXmlArray(\XMLWriter $xmlWriter, Parameter $param, &$value) { if ($items = $param->getItems()) { foreach ($value as $v) { $this->addXml($xmlWriter, $items, $v); } } } /** * Add an object to the XML */ protected function addXmlObject(\XMLWriter $xmlWriter, Parameter $param, &$value) { $noAttributes = array(); // add values which have attributes foreach ($value as $name => $v) { if ($property = $param->getProperty($name)) { if ($property->getData('xmlAttribute')) { $this->addXml($xmlWriter, $property, $v); } else { $noAttributes[] = array('value' => $v, 'property' => $property); } } } // now add values with no attributes foreach ($noAttributes as $element) { $this->addXml($xmlWriter, $element['property'], $element['value']); } } } getName()] = $param->filter($response->getBody()); } } getType() == 'object' && $param->getAdditionalProperties() instanceof Parameter) { $this->processPrefixedHeaders($response, $param, $value); } else { $value[$param->getName()] = $param->filter((string) $response->getHeader($param->getWireName())); } } /** * Process a prefixed header array * * @param Response $response Response that contains the headers * @param Parameter $param Parameter object * @param array $value Value response array to modify */ protected function processPrefixedHeaders(Response $response, Parameter $param, &$value) { // Grab prefixed headers that should be placed into an array with the prefix stripped if ($prefix = $param->getSentAs()) { $container = $param->getName(); $len = strlen($prefix); // Find all matching headers and place them into the containing element foreach ($response->getHeaders()->toArray() as $key => $header) { if (stripos($key, $prefix) === 0) { // Account for multi-value headers $value[$container][substr($key, $len)] = count($header) == 1 ? end($header) : $header; } } } } } getResponse()->json(); } public function visit( CommandInterface $command, Response $response, Parameter $param, &$value, $context = null ) { $name = $param->getName(); $key = $param->getWireName(); if (isset($value[$key])) { $this->recursiveProcess($param, $value[$key]); if ($key != $name) { $value[$name] = $value[$key]; unset($value[$key]); } } } /** * Recursively process a parameter while applying filters * * @param Parameter $param API parameter being validated * @param mixed $value Value to validate and process. The value may change during this process. */ protected function recursiveProcess(Parameter $param, &$value) { if ($value === null) { return; } if (is_array($value)) { $type = $param->getType(); if ($type == 'array') { foreach ($value as &$item) { $this->recursiveProcess($param->getItems(), $item); } } elseif ($type == 'object' && !isset($value[0])) { // On the above line, we ensure that the array is associative and not numerically indexed $knownProperties = array(); if ($properties = $param->getProperties()) { foreach ($properties as $property) { $name = $property->getName(); $key = $property->getWireName(); $knownProperties[$name] = 1; if (isset($value[$key])) { $this->recursiveProcess($property, $value[$key]); if ($key != $name) { $value[$name] = $value[$key]; unset($value[$key]); } } } } // Remove any unknown and potentially unsafe properties if ($param->getAdditionalProperties() === false) { $value = array_intersect_key($value, $knownProperties); } elseif (($additional = $param->getAdditionalProperties()) !== true) { // Validate and filter additional properties foreach ($value as &$v) { $this->recursiveProcess($additional, $v); } } } } $value = $param->filter($value); } } getName()] = $response->getReasonPhrase(); } } getName()] = $response->getStatusCode(); } } getResponse()->xml()), true); } public function visit( CommandInterface $command, Response $response, Parameter $param, &$value, $context = null ) { $sentAs = $param->getWireName(); $name = $param->getName(); if (isset($value[$sentAs])) { $this->recursiveProcess($param, $value[$sentAs]); if ($name != $sentAs) { $value[$name] = $value[$sentAs]; unset($value[$sentAs]); } } } /** * Recursively process a parameter while applying filters * * @param Parameter $param API parameter being processed * @param mixed $value Value to validate and process. The value may change during this process. */ protected function recursiveProcess(Parameter $param, &$value) { $type = $param->getType(); if (!is_array($value)) { if ($type == 'array') { // Cast to an array if the value was a string, but should be an array $this->recursiveProcess($param->getItems(), $value); $value = array($value); } } elseif ($type == 'object') { $this->processObject($param, $value); } elseif ($type == 'array') { $this->processArray($param, $value); } elseif ($type == 'string' && gettype($value) == 'array') { $value = ''; } if ($value !== null) { $value = $param->filter($value); } } /** * Process an array * * @param Parameter $param API parameter being parsed * @param mixed $value Value to process */ protected function processArray(Parameter $param, &$value) { // Convert the node if it was meant to be an array if (!isset($value[0])) { // Collections fo nodes are sometimes wrapped in an additional array. For example: // 12 should become: // array('Items' => array(array('a' => 1), array('a' => 2)) // Some nodes are not wrapped. For example: 12 // should become array('Foo' => array(array('a' => 1), array('a' => 2)) if ($param->getItems() && isset($value[$param->getItems()->getWireName()])) { // Account for the case of a collection wrapping wrapped nodes: Items => Item[] $value = $value[$param->getItems()->getWireName()]; // If the wrapped node only had one value, then make it an array of nodes if (!isset($value[0]) || !is_array($value)) { $value = array($value); } } elseif (!empty($value)) { // Account for repeated nodes that must be an array: Foo => Baz, Foo => Baz, but only if the // value is set and not empty $value = array($value); } } foreach ($value as &$item) { $this->recursiveProcess($param->getItems(), $item); } } /** * Process an object * * @param Parameter $param API parameter being parsed * @param mixed $value Value to process */ protected function processObject(Parameter $param, &$value) { // Ensure that the array is associative and not numerically indexed if (!isset($value[0]) && ($properties = $param->getProperties())) { $knownProperties = array(); foreach ($properties as $property) { $name = $property->getName(); $sentAs = $property->getWireName(); $knownProperties[$name] = 1; if ($property->getData('xmlAttribute')) { $this->processXmlAttribute($property, $value); } elseif (isset($value[$sentAs])) { $this->recursiveProcess($property, $value[$sentAs]); if ($name != $sentAs) { $value[$name] = $value[$sentAs]; unset($value[$sentAs]); } } } // Remove any unknown and potentially unsafe properties if ($param->getAdditionalProperties() === false) { $value = array_intersect_key($value, $knownProperties); } } } /** * Process an XML attribute property * * @param Parameter $property Property to process * @param array $value Value to process and update */ protected function processXmlAttribute(Parameter $property, array &$value) { $sentAs = $property->getWireName(); if (isset($value['@attributes'][$sentAs])) { $value[$property->getName()] = $value['@attributes'][$sentAs]; unset($value['@attributes'][$sentAs]); if (empty($value['@attributes'])) { unset($value['@attributes']); } } } } 'Guzzle\Service\Command\LocationVisitor\Request\BodyVisitor', 'request.header' => 'Guzzle\Service\Command\LocationVisitor\Request\HeaderVisitor', 'request.json' => 'Guzzle\Service\Command\LocationVisitor\Request\JsonVisitor', 'request.postField' => 'Guzzle\Service\Command\LocationVisitor\Request\PostFieldVisitor', 'request.postFile' => 'Guzzle\Service\Command\LocationVisitor\Request\PostFileVisitor', 'request.query' => 'Guzzle\Service\Command\LocationVisitor\Request\QueryVisitor', 'request.response_body' => 'Guzzle\Service\Command\LocationVisitor\Request\ResponseBodyVisitor', 'request.responseBody' => 'Guzzle\Service\Command\LocationVisitor\Request\ResponseBodyVisitor', 'request.xml' => 'Guzzle\Service\Command\LocationVisitor\Request\XmlVisitor', 'response.body' => 'Guzzle\Service\Command\LocationVisitor\Response\BodyVisitor', 'response.header' => 'Guzzle\Service\Command\LocationVisitor\Response\HeaderVisitor', 'response.json' => 'Guzzle\Service\Command\LocationVisitor\Response\JsonVisitor', 'response.reasonPhrase' => 'Guzzle\Service\Command\LocationVisitor\Response\ReasonPhraseVisitor', 'response.statusCode' => 'Guzzle\Service\Command\LocationVisitor\Response\StatusCodeVisitor', 'response.xml' => 'Guzzle\Service\Command\LocationVisitor\Response\XmlVisitor' ); /** @var array Array of mappings of location names to classes */ protected $mappings; /** @var array Cache of instantiated visitors */ protected $cache = array(); /** * @return self * @codeCoverageIgnore */ public static function getInstance() { if (!self::$instance) { self::$instance = new self(); } return self::$instance; } /** * @param array $mappings Array mapping request.name and response.name to location visitor classes. Leave null to * use the default values. */ public function __construct(array $mappings = null) { $this->mappings = $mappings === null ? self::$defaultMappings : $mappings; } /** * Get an instance of a request visitor by location name * * @param string $visitor Visitor name * * @return RequestVisitorInterface */ public function getRequestVisitor($visitor) { return $this->getKey('request.' . $visitor); } /** * Get an instance of a response visitor by location name * * @param string $visitor Visitor name * * @return ResponseVisitorInterface */ public function getResponseVisitor($visitor) { return $this->getKey('response.' . $visitor); } /** * Add a response visitor to the factory by name * * @param string $name Name of the visitor * @param RequestVisitorInterface $visitor Visitor to add * * @return self */ public function addRequestVisitor($name, RequestVisitorInterface $visitor) { $this->cache['request.' . $name] = $visitor; return $this; } /** * Add a response visitor to the factory by name * * @param string $name Name of the visitor * @param ResponseVisitorInterface $visitor Visitor to add * * @return self */ public function addResponseVisitor($name, ResponseVisitorInterface $visitor) { $this->cache['response.' . $name] = $visitor; return $this; } /** * Get a visitor by key value name * * @param string $key Key name to retrieve * * @return mixed * @throws InvalidArgumentException */ private function getKey($key) { if (!isset($this->cache[$key])) { if (!isset($this->mappings[$key])) { list($type, $name) = explode('.', $key); throw new InvalidArgumentException("No {$type} visitor has been mapped for {$name}"); } $this->cache[$key] = new $this->mappings[$key]; } return $this->cache[$key]; } } responseParser = $parser; return $this; } /** * Set the request serializer used with the command * * @param RequestSerializerInterface $serializer Request serializer * * @return self */ public function setRequestSerializer(RequestSerializerInterface $serializer) { $this->requestSerializer = $serializer; return $this; } /** * Get the request serializer used with the command * * @return RequestSerializerInterface */ public function getRequestSerializer() { if (!$this->requestSerializer) { // Use the default request serializer if none was found $this->requestSerializer = DefaultRequestSerializer::getInstance(); } return $this->requestSerializer; } /** * Get the response parser used for the operation * * @return ResponseParserInterface */ public function getResponseParser() { if (!$this->responseParser) { // Use the default response parser if none was found $this->responseParser = OperationResponseParser::getInstance(); } return $this->responseParser; } protected function build() { // Prepare and serialize the request $this->request = $this->getRequestSerializer()->prepare($this); } protected function process() { // Do not process the response if 'command.response_processing' is set to 'raw' $this->result = $this[self::RESPONSE_PROCESSING] == self::TYPE_RAW ? $this->request->getResponse() : $this->getResponseParser()->parse($this); } } factory = $factory; $this->schemaInModels = $schemaInModels; } /** * Add a location visitor to the command * * @param string $location Location to associate with the visitor * @param ResponseVisitorInterface $visitor Visitor to attach * * @return self */ public function addVisitor($location, ResponseVisitorInterface $visitor) { $this->factory->addResponseVisitor($location, $visitor); return $this; } protected function handleParsing(CommandInterface $command, Response $response, $contentType) { $operation = $command->getOperation(); $type = $operation->getResponseType(); $model = null; if ($type == OperationInterface::TYPE_MODEL) { $model = $operation->getServiceDescription()->getModel($operation->getResponseClass()); } elseif ($type == OperationInterface::TYPE_CLASS) { return $this->parseClass($command); } if (!$model) { // Return basic processing if the responseType is not model or the model cannot be found return parent::handleParsing($command, $response, $contentType); } elseif ($command[AbstractCommand::RESPONSE_PROCESSING] != AbstractCommand::TYPE_MODEL) { // Returns a model with no visiting if the command response processing is not model return new Model(parent::handleParsing($command, $response, $contentType)); } else { // Only inject the schema into the model if "schemaInModel" is true return new Model($this->visitResult($model, $command, $response), $this->schemaInModels ? $model : null); } } /** * Parse a class object * * @param CommandInterface $command Command to parse into an object * * @return mixed * @throws ResponseClassException */ protected function parseClass(CommandInterface $command) { // Emit the operation.parse_class event. If a listener injects a 'result' property, then that will be the result $event = new CreateResponseClassEvent(array('command' => $command)); $command->getClient()->getEventDispatcher()->dispatch('command.parse_response', $event); if ($result = $event->getResult()) { return $result; } $className = $command->getOperation()->getResponseClass(); if (!method_exists($className, 'fromCommand')) { throw new ResponseClassException("{$className} must exist and implement a static fromCommand() method"); } return $className::fromCommand($command); } /** * Perform transformations on the result array * * @param Parameter $model Model that defines the structure * @param CommandInterface $command Command that performed the operation * @param Response $response Response received * * @return array Returns the array of result data */ protected function visitResult(Parameter $model, CommandInterface $command, Response $response) { $foundVisitors = $result = $knownProps = array(); $props = $model->getProperties(); foreach ($props as $schema) { if ($location = $schema->getLocation()) { // Trigger the before method on the first found visitor of this type if (!isset($foundVisitors[$location])) { $foundVisitors[$location] = $this->factory->getResponseVisitor($location); $foundVisitors[$location]->before($command, $result); } } } // Visit additional properties when it is an actual schema if (($additional = $model->getAdditionalProperties()) instanceof Parameter) { $this->visitAdditionalProperties($model, $command, $response, $additional, $result, $foundVisitors); } // Apply the parameter value with the location visitor foreach ($props as $schema) { $knownProps[$schema->getName()] = 1; if ($location = $schema->getLocation()) { $foundVisitors[$location]->visit($command, $response, $schema, $result); } } // Remove any unknown and potentially unsafe top-level properties if ($additional === false) { $result = array_intersect_key($result, $knownProps); } // Call the after() method of each found visitor foreach ($foundVisitors as $visitor) { $visitor->after($command); } return $result; } protected function visitAdditionalProperties( Parameter $model, CommandInterface $command, Response $response, Parameter $additional, &$result, array &$foundVisitors ) { // Only visit when a location is specified if ($location = $additional->getLocation()) { if (!isset($foundVisitors[$location])) { $foundVisitors[$location] = $this->factory->getResponseVisitor($location); $foundVisitors[$location]->before($command, $result); } // Only traverse if an array was parsed from the before() visitors if (is_array($result)) { // Find each additional property foreach (array_keys($result) as $key) { // Check if the model actually knows this property. If so, then it is not additional if (!$model->getProperty($key)) { // Set the name to the key so that we can parse it with each visitor $additional->setName($key); $foundVisitors[$location]->visit($command, $response, $additional, $result); } } // Reset the additionalProperties name to null $additional->setName(null); } } } } true, 'httpMethod' => true, 'uri' => true, 'class' => true, 'responseClass' => true, 'responseType' => true, 'responseNotes' => true, 'notes' => true, 'summary' => true, 'documentationUrl' => true, 'deprecated' => true, 'data' => true, 'parameters' => true, 'additionalParameters' => true, 'errorResponses' => true ); /** @var array Parameters */ protected $parameters = array(); /** @var Parameter Additional parameters schema */ protected $additionalParameters; /** @var string Name of the command */ protected $name; /** @var string HTTP method */ protected $httpMethod; /** @var string This is a short summary of what the operation does */ protected $summary; /** @var string A longer text field to explain the behavior of the operation. */ protected $notes; /** @var string Reference URL providing more information about the operation */ protected $documentationUrl; /** @var string HTTP URI of the command */ protected $uri; /** @var string Class of the command object */ protected $class; /** @var string This is what is returned from the method */ protected $responseClass; /** @var string Type information about the response */ protected $responseType; /** @var string Information about the response returned by the operation */ protected $responseNotes; /** @var bool Whether or not the command is deprecated */ protected $deprecated; /** @var array Array of errors that could occur when running the command */ protected $errorResponses; /** @var ServiceDescriptionInterface */ protected $description; /** @var array Extra operation information */ protected $data; /** * Builds an Operation object using an array of configuration data: * - name: (string) Name of the command * - httpMethod: (string) HTTP method of the operation * - uri: (string) URI template that can create a relative or absolute URL * - class: (string) Concrete class that implements this command * - parameters: (array) Associative array of parameters for the command. {@see Parameter} for information. * - summary: (string) This is a short summary of what the operation does * - notes: (string) A longer text field to explain the behavior of the operation. * - documentationUrl: (string) Reference URL providing more information about the operation * - responseClass: (string) This is what is returned from the method. Can be a primitive, PSR-0 compliant * class name, or model. * - responseNotes: (string) Information about the response returned by the operation * - responseType: (string) One of 'primitive', 'class', 'model', or 'documentation'. If not specified, this * value will be automatically inferred based on whether or not there is a model matching the * name, if a matching PSR-0 compliant class name is found, or set to 'primitive' by default. * - deprecated: (bool) Set to true if this is a deprecated command * - errorResponses: (array) Errors that could occur when executing the command. Array of hashes, each with a * 'code' (the HTTP response code), 'phrase' (response reason phrase or description of the * error), and 'class' (a custom exception class that would be thrown if the error is * encountered). * - data: (array) Any extra data that might be used to help build or serialize the operation * - additionalParameters: (null|array) Parameter schema to use when an option is passed to the operation that is * not in the schema * * @param array $config Array of configuration data * @param ServiceDescriptionInterface $description Service description used to resolve models if $ref tags are found */ public function __construct(array $config = array(), ServiceDescriptionInterface $description = null) { $this->description = $description; // Get the intersection of the available properties and properties set on the operation foreach (array_intersect_key($config, self::$properties) as $key => $value) { $this->{$key} = $value; } $this->class = $this->class ?: self::DEFAULT_COMMAND_CLASS; $this->deprecated = (bool) $this->deprecated; $this->errorResponses = $this->errorResponses ?: array(); $this->data = $this->data ?: array(); if (!$this->responseClass) { $this->responseClass = 'array'; $this->responseType = 'primitive'; } elseif ($this->responseType) { // Set the response type to perform validation $this->setResponseType($this->responseType); } else { // A response class was set and no response type was set, so guess what the type is $this->inferResponseType(); } // Parameters need special handling when adding if ($this->parameters) { foreach ($this->parameters as $name => $param) { if ($param instanceof Parameter) { $param->setName($name)->setParent($this); } elseif (is_array($param)) { $param['name'] = $name; $this->addParam(new Parameter($param, $this->description)); } } } if ($this->additionalParameters) { if ($this->additionalParameters instanceof Parameter) { $this->additionalParameters->setParent($this); } elseif (is_array($this->additionalParameters)) { $this->setadditionalParameters(new Parameter($this->additionalParameters, $this->description)); } } } public function toArray() { $result = array(); // Grab valid properties and filter out values that weren't set foreach (array_keys(self::$properties) as $check) { if ($value = $this->{$check}) { $result[$check] = $value; } } // Remove the name property unset($result['name']); // Parameters need to be converted to arrays $result['parameters'] = array(); foreach ($this->parameters as $key => $param) { $result['parameters'][$key] = $param->toArray(); } // Additional parameters need to be cast to an array if ($this->additionalParameters instanceof Parameter) { $result['additionalParameters'] = $this->additionalParameters->toArray(); } return $result; } public function getServiceDescription() { return $this->description; } public function setServiceDescription(ServiceDescriptionInterface $description) { $this->description = $description; return $this; } public function getParams() { return $this->parameters; } public function getParamNames() { return array_keys($this->parameters); } public function hasParam($name) { return isset($this->parameters[$name]); } public function getParam($param) { return isset($this->parameters[$param]) ? $this->parameters[$param] : null; } /** * Add a parameter to the command * * @param Parameter $param Parameter to add * * @return self */ public function addParam(Parameter $param) { $this->parameters[$param->getName()] = $param; $param->setParent($this); return $this; } /** * Remove a parameter from the command * * @param string $name Name of the parameter to remove * * @return self */ public function removeParam($name) { unset($this->parameters[$name]); return $this; } public function getHttpMethod() { return $this->httpMethod; } /** * Set the HTTP method of the command * * @param string $httpMethod Method to set * * @return self */ public function setHttpMethod($httpMethod) { $this->httpMethod = $httpMethod; return $this; } public function getClass() { return $this->class; } /** * Set the concrete class of the command * * @param string $className Concrete class name * * @return self */ public function setClass($className) { $this->class = $className; return $this; } public function getName() { return $this->name; } /** * Set the name of the command * * @param string $name Name of the command * * @return self */ public function setName($name) { $this->name = $name; return $this; } public function getSummary() { return $this->summary; } /** * Set a short summary of what the operation does * * @param string $summary Short summary of the operation * * @return self */ public function setSummary($summary) { $this->summary = $summary; return $this; } public function getNotes() { return $this->notes; } /** * Set a longer text field to explain the behavior of the operation. * * @param string $notes Notes on the operation * * @return self */ public function setNotes($notes) { $this->notes = $notes; return $this; } public function getDocumentationUrl() { return $this->documentationUrl; } /** * Set the URL pointing to additional documentation on the command * * @param string $docUrl Documentation URL * * @return self */ public function setDocumentationUrl($docUrl) { $this->documentationUrl = $docUrl; return $this; } public function getResponseClass() { return $this->responseClass; } /** * Set what is returned from the method. Can be a primitive, class name, or model. For example: 'array', * 'Guzzle\\Foo\\Baz', or 'MyModelName' (to reference a model by ID). * * @param string $responseClass Type of response * * @return self */ public function setResponseClass($responseClass) { $this->responseClass = $responseClass; $this->inferResponseType(); return $this; } public function getResponseType() { return $this->responseType; } /** * Set qualifying information about the responseClass. One of 'primitive', 'class', 'model', or 'documentation' * * @param string $responseType Response type information * * @return self * @throws InvalidArgumentException */ public function setResponseType($responseType) { static $types = array( self::TYPE_PRIMITIVE => true, self::TYPE_CLASS => true, self::TYPE_MODEL => true, self::TYPE_DOCUMENTATION => true ); if (!isset($types[$responseType])) { throw new InvalidArgumentException('responseType must be one of ' . implode(', ', array_keys($types))); } $this->responseType = $responseType; return $this; } public function getResponseNotes() { return $this->responseNotes; } /** * Set notes about the response of the operation * * @param string $notes Response notes * * @return self */ public function setResponseNotes($notes) { $this->responseNotes = $notes; return $this; } public function getDeprecated() { return $this->deprecated; } /** * Set whether or not the command is deprecated * * @param bool $isDeprecated Set to true to mark as deprecated * * @return self */ public function setDeprecated($isDeprecated) { $this->deprecated = $isDeprecated; return $this; } public function getUri() { return $this->uri; } /** * Set the URI template of the command * * @param string $uri URI template to set * * @return self */ public function setUri($uri) { $this->uri = $uri; return $this; } public function getErrorResponses() { return $this->errorResponses; } /** * Add an error to the command * * @param string $code HTTP response code * @param string $reason HTTP response reason phrase or information about the error * @param string $class Exception class associated with the error * * @return self */ public function addErrorResponse($code, $reason, $class) { $this->errorResponses[] = array('code' => $code, 'reason' => $reason, 'class' => $class); return $this; } /** * Set all of the error responses of the operation * * @param array $errorResponses Hash of error name to a hash containing a code, reason, class * * @return self */ public function setErrorResponses(array $errorResponses) { $this->errorResponses = $errorResponses; return $this; } public function getData($name) { return isset($this->data[$name]) ? $this->data[$name] : null; } /** * Set a particular data point on the operation * * @param string $name Name of the data value * @param mixed $value Value to set * * @return self */ public function setData($name, $value) { $this->data[$name] = $value; return $this; } /** * Get the additionalParameters of the operation * * @return Parameter|null */ public function getAdditionalParameters() { return $this->additionalParameters; } /** * Set the additionalParameters of the operation * * @param Parameter|null $parameter Parameter to set * * @return self */ public function setAdditionalParameters($parameter) { if ($this->additionalParameters = $parameter) { $this->additionalParameters->setParent($this); } return $this; } /** * Infer the response type from the responseClass value */ protected function inferResponseType() { static $primitives = array('array' => 1, 'boolean' => 1, 'string' => 1, 'integer' => 1, '' => 1); if (isset($primitives[$this->responseClass])) { $this->responseType = self::TYPE_PRIMITIVE; } elseif ($this->description && $this->description->hasModel($this->responseClass)) { $this->responseType = self::TYPE_MODEL; } else { $this->responseType = self::TYPE_CLASS; } } } getModel($data['$ref'])) { $data = $model->toArray() + $data; } } elseif (isset($data['extends'])) { // If this parameter extends from another parameter then start with the actual data // union in the parent's data (e.g. actual supersedes parent) if ($extends = $description->getModel($data['extends'])) { $data += $extends->toArray(); } } } // Pull configuration data into the parameter foreach ($data as $key => $value) { $this->{$key} = $value; } $this->serviceDescription = $description; $this->required = (bool) $this->required; $this->data = (array) $this->data; if ($this->filters) { $this->setFilters((array) $this->filters); } if ($this->type == 'object' && $this->additionalProperties === null) { $this->additionalProperties = true; } } /** * Convert the object to an array * * @return array */ public function toArray() { static $checks = array('required', 'description', 'static', 'type', 'format', 'instanceOf', 'location', 'sentAs', 'pattern', 'minimum', 'maximum', 'minItems', 'maxItems', 'minLength', 'maxLength', 'data', 'enum', 'filters'); $result = array(); // Anything that is in the `Items` attribute of an array *must* include it's name if available if ($this->parent instanceof self && $this->parent->getType() == 'array' && isset($this->name)) { $result['name'] = $this->name; } foreach ($checks as $c) { if ($value = $this->{$c}) { $result[$c] = $value; } } if ($this->default !== null) { $result['default'] = $this->default; } if ($this->items !== null) { $result['items'] = $this->getItems()->toArray(); } if ($this->additionalProperties !== null) { $result['additionalProperties'] = $this->getAdditionalProperties(); if ($result['additionalProperties'] instanceof self) { $result['additionalProperties'] = $result['additionalProperties']->toArray(); } } if ($this->type == 'object' && $this->properties) { $result['properties'] = array(); foreach ($this->getProperties() as $name => $property) { $result['properties'][$name] = $property->toArray(); } } return $result; } /** * Get the default or static value of the command based on a value * * @param string $value Value that is currently set * * @return mixed Returns the value, a static value if one is present, or a default value */ public function getValue($value) { if ($this->static || ($this->default !== null && $value === null)) { return $this->default; } return $value; } /** * Run a value through the filters OR format attribute associated with the parameter * * @param mixed $value Value to filter * * @return mixed Returns the filtered value */ public function filter($value) { // Formats are applied exclusively and supersed filters if ($this->format) { return SchemaFormatter::format($this->format, $value); } // Convert Boolean values if ($this->type == 'boolean' && !is_bool($value)) { $value = filter_var($value, FILTER_VALIDATE_BOOLEAN); } // Apply filters to the value if ($this->filters) { foreach ($this->filters as $filter) { if (is_array($filter)) { // Convert complex filters that hold value place holders foreach ($filter['args'] as &$data) { if ($data == '@value') { $data = $value; } elseif ($data == '@api') { $data = $this; } } $value = call_user_func_array($filter['method'], $filter['args']); } else { $value = call_user_func($filter, $value); } } } return $value; } /** * Get the name of the parameter * * @return string */ public function getName() { return $this->name; } /** * Get the key of the parameter, where sentAs will supersede name if it is set * * @return string */ public function getWireName() { return $this->sentAs ?: $this->name; } /** * Set the name of the parameter * * @param string $name Name to set * * @return self */ public function setName($name) { $this->name = $name; return $this; } /** * Get the type(s) of the parameter * * @return string|array */ public function getType() { return $this->type; } /** * Set the type(s) of the parameter * * @param string|array $type Type of parameter or array of simple types used in a union * * @return self */ public function setType($type) { $this->type = $type; return $this; } /** * Get if the parameter is required * * @return bool */ public function getRequired() { return $this->required; } /** * Set if the parameter is required * * @param bool $isRequired Whether or not the parameter is required * * @return self */ public function setRequired($isRequired) { $this->required = (bool) $isRequired; return $this; } /** * Get the default value of the parameter * * @return string|null */ public function getDefault() { return $this->default; } /** * Set the default value of the parameter * * @param string|null $default Default value to set * * @return self */ public function setDefault($default) { $this->default = $default; return $this; } /** * Get the description of the parameter * * @return string|null */ public function getDescription() { return $this->description; } /** * Set the description of the parameter * * @param string $description Description * * @return self */ public function setDescription($description) { $this->description = $description; return $this; } /** * Get the minimum acceptable value for an integer * * @return int|null */ public function getMinimum() { return $this->minimum; } /** * Set the minimum acceptable value for an integer * * @param int|null $min Minimum * * @return self */ public function setMinimum($min) { $this->minimum = $min; return $this; } /** * Get the maximum acceptable value for an integer * * @return int|null */ public function getMaximum() { return $this->maximum; } /** * Set the maximum acceptable value for an integer * * @param int $max Maximum * * @return self */ public function setMaximum($max) { $this->maximum = $max; return $this; } /** * Get the minimum allowed length of a string value * * @return int */ public function getMinLength() { return $this->minLength; } /** * Set the minimum allowed length of a string value * * @param int|null $min Minimum * * @return self */ public function setMinLength($min) { $this->minLength = $min; return $this; } /** * Get the maximum allowed length of a string value * * @return int|null */ public function getMaxLength() { return $this->maxLength; } /** * Set the maximum allowed length of a string value * * @param int $max Maximum length * * @return self */ public function setMaxLength($max) { $this->maxLength = $max; return $this; } /** * Get the maximum allowed number of items in an array value * * @return int|null */ public function getMaxItems() { return $this->maxItems; } /** * Set the maximum allowed number of items in an array value * * @param int $max Maximum * * @return self */ public function setMaxItems($max) { $this->maxItems = $max; return $this; } /** * Get the minimum allowed number of items in an array value * * @return int */ public function getMinItems() { return $this->minItems; } /** * Set the minimum allowed number of items in an array value * * @param int|null $min Minimum * * @return self */ public function setMinItems($min) { $this->minItems = $min; return $this; } /** * Get the location of the parameter * * @return string|null */ public function getLocation() { return $this->location; } /** * Set the location of the parameter * * @param string|null $location Location of the parameter * * @return self */ public function setLocation($location) { $this->location = $location; return $this; } /** * Get the sentAs attribute of the parameter that used with locations to sentAs an attribute when it is being * applied to a location. * * @return string|null */ public function getSentAs() { return $this->sentAs; } /** * Set the sentAs attribute * * @param string|null $name Name of the value as it is sent over the wire * * @return self */ public function setSentAs($name) { $this->sentAs = $name; return $this; } /** * Retrieve a known property from the parameter by name or a data property by name. When not specific name value * is specified, all data properties will be returned. * * @param string|null $name Specify a particular property name to retrieve * * @return array|mixed|null */ public function getData($name = null) { if (!$name) { return $this->data; } if (isset($this->data[$name])) { return $this->data[$name]; } elseif (isset($this->{$name})) { return $this->{$name}; } return null; } /** * Set the extra data properties of the parameter or set a specific extra property * * @param string|array|null $nameOrData The name of a specific extra to set or an array of extras to set * @param mixed|null $data When setting a specific extra property, specify the data to set for it * * @return self */ public function setData($nameOrData, $data = null) { if (is_array($nameOrData)) { $this->data = $nameOrData; } else { $this->data[$nameOrData] = $data; } return $this; } /** * Get whether or not the default value can be changed * * @return mixed|null */ public function getStatic() { return $this->static; } /** * Set to true if the default value cannot be changed * * @param bool $static True or false * * @return self */ public function setStatic($static) { $this->static = (bool) $static; return $this; } /** * Get an array of filters used by the parameter * * @return array */ public function getFilters() { return $this->filters ?: array(); } /** * Set the array of filters used by the parameter * * @param array $filters Array of functions to use as filters * * @return self */ public function setFilters(array $filters) { $this->filters = array(); foreach ($filters as $filter) { $this->addFilter($filter); } return $this; } /** * Add a filter to the parameter * * @param string|array $filter Method to filter the value through * * @return self * @throws InvalidArgumentException */ public function addFilter($filter) { if (is_array($filter)) { if (!isset($filter['method'])) { throw new InvalidArgumentException('A [method] value must be specified for each complex filter'); } } if (!$this->filters) { $this->filters = array($filter); } else { $this->filters[] = $filter; } return $this; } /** * Get the parent object (an {@see OperationInterface} or {@see Parameter} * * @return OperationInterface|Parameter|null */ public function getParent() { return $this->parent; } /** * Set the parent object of the parameter * * @param OperationInterface|Parameter|null $parent Parent container of the parameter * * @return self */ public function setParent($parent) { $this->parent = $parent; return $this; } /** * Get the properties of the parameter * * @return array */ public function getProperties() { if (!$this->propertiesCache) { $this->propertiesCache = array(); foreach (array_keys($this->properties) as $name) { $this->propertiesCache[$name] = $this->getProperty($name); } } return $this->propertiesCache; } /** * Get a specific property from the parameter * * @param string $name Name of the property to retrieve * * @return null|Parameter */ public function getProperty($name) { if (!isset($this->properties[$name])) { return null; } if (!($this->properties[$name] instanceof self)) { $this->properties[$name]['name'] = $name; $this->properties[$name] = new static($this->properties[$name], $this->serviceDescription); $this->properties[$name]->setParent($this); } return $this->properties[$name]; } /** * Remove a property from the parameter * * @param string $name Name of the property to remove * * @return self */ public function removeProperty($name) { unset($this->properties[$name]); $this->propertiesCache = null; return $this; } /** * Add a property to the parameter * * @param Parameter $property Properties to set * * @return self */ public function addProperty(Parameter $property) { $this->properties[$property->getName()] = $property; $property->setParent($this); $this->propertiesCache = null; return $this; } /** * Get the additionalProperties value of the parameter * * @return bool|Parameter|null */ public function getAdditionalProperties() { if (is_array($this->additionalProperties)) { $this->additionalProperties = new static($this->additionalProperties, $this->serviceDescription); $this->additionalProperties->setParent($this); } return $this->additionalProperties; } /** * Set the additionalProperties value of the parameter * * @param bool|Parameter|null $additional Boolean to allow any, an Parameter to specify a schema, or false to disallow * * @return self */ public function setAdditionalProperties($additional) { $this->additionalProperties = $additional; return $this; } /** * Set the items data of the parameter * * @param Parameter|null $items Items to set * * @return self */ public function setItems(Parameter $items = null) { if ($this->items = $items) { $this->items->setParent($this); } return $this; } /** * Get the item data of the parameter * * @return Parameter|null */ public function getItems() { if (is_array($this->items)) { $this->items = new static($this->items, $this->serviceDescription); $this->items->setParent($this); } return $this->items; } /** * Get the class that the parameter must implement * * @return null|string */ public function getInstanceOf() { return $this->instanceOf; } /** * Set the class that the parameter must be an instance of * * @param string|null $instanceOf Class or interface name * * @return self */ public function setInstanceOf($instanceOf) { $this->instanceOf = $instanceOf; return $this; } /** * Get the enum of strings that are valid for the parameter * * @return array|null */ public function getEnum() { return $this->enum; } /** * Set the enum of strings that are valid for the parameter * * @param array|null $enum Array of strings or null * * @return self */ public function setEnum(array $enum = null) { $this->enum = $enum; return $this; } /** * Get the regex pattern that must match a value when the value is a string * * @return string */ public function getPattern() { return $this->pattern; } /** * Set the regex pattern that must match a value when the value is a string * * @param string $pattern Regex pattern * * @return self */ public function setPattern($pattern) { $this->pattern = $pattern; return $this; } /** * Get the format attribute of the schema * * @return string */ public function getFormat() { return $this->format; } /** * Set the format attribute of the schema * * @param string $format Format to set (e.g. date, date-time, timestamp, time, date-time-http) * * @return self */ public function setFormat($format) { $this->format = $format; return $this; } } setTimezone(self::getUtcTimeZone())->format($format); } throw new InvalidArgumentException('Date/Time values must be either a string, integer, or DateTime object'); } } castIntegerToStringType = $castIntegerToStringType; } public function validate(Parameter $param, &$value) { $this->errors = array(); $this->recursiveProcess($param, $value); if (empty($this->errors)) { return true; } else { sort($this->errors); return false; } } /** * Get the errors encountered while validating * * @return array */ public function getErrors() { return $this->errors ?: array(); } /** * Recursively validate a parameter * * @param Parameter $param API parameter being validated * @param mixed $value Value to validate and validate. The value may change during this validate. * @param string $path Current validation path (used for error reporting) * @param int $depth Current depth in the validation validate * * @return bool Returns true if valid, or false if invalid */ protected function recursiveProcess(Parameter $param, &$value, $path = '', $depth = 0) { // Update the value by adding default or static values $value = $param->getValue($value); $required = $param->getRequired(); // if the value is null and the parameter is not required or is static, then skip any further recursion if ((null === $value && !$required) || $param->getStatic()) { return true; } $type = $param->getType(); // Attempt to limit the number of times is_array is called by tracking if the value is an array $valueIsArray = is_array($value); // If a name is set then update the path so that validation messages are more helpful if ($name = $param->getName()) { $path .= "[{$name}]"; } if ($type == 'object') { // Objects are either associative arrays, ToArrayInterface, or some other object if ($param->getInstanceOf()) { $instance = $param->getInstanceOf(); if (!($value instanceof $instance)) { $this->errors[] = "{$path} must be an instance of {$instance}"; return false; } } // Determine whether or not this "value" has properties and should be traversed $traverse = $temporaryValue = false; // Convert the value to an array if (!$valueIsArray && $value instanceof ToArrayInterface) { $value = $value->toArray(); } if ($valueIsArray) { // Ensure that the array is associative and not numerically indexed if (isset($value[0])) { $this->errors[] = "{$path} must be an array of properties. Got a numerically indexed array."; return false; } $traverse = true; } elseif ($value === null) { // Attempt to let the contents be built up by default values if possible $value = array(); $temporaryValue = $valueIsArray = $traverse = true; } if ($traverse) { if ($properties = $param->getProperties()) { // if properties were found, the validate each property of the value foreach ($properties as $property) { $name = $property->getName(); if (isset($value[$name])) { $this->recursiveProcess($property, $value[$name], $path, $depth + 1); } else { $current = null; $this->recursiveProcess($property, $current, $path, $depth + 1); // Only set the value if it was populated with something if (null !== $current) { $value[$name] = $current; } } } } $additional = $param->getAdditionalProperties(); if ($additional !== true) { // If additional properties were found, then validate each against the additionalProperties attr. $keys = array_keys($value); // Determine the keys that were specified that were not listed in the properties of the schema $diff = array_diff($keys, array_keys($properties)); if (!empty($diff)) { // Determine which keys are not in the properties if ($additional instanceOf Parameter) { foreach ($diff as $key) { $this->recursiveProcess($additional, $value[$key], "{$path}[{$key}]", $depth); } } else { // if additionalProperties is set to false and there are additionalProperties in the values, then fail foreach ($diff as $prop) { $this->errors[] = sprintf('%s[%s] is not an allowed property', $path, $prop); } } } } // A temporary value will be used to traverse elements that have no corresponding input value. // This allows nested required parameters with default values to bubble up into the input. // Here we check if we used a temp value and nothing bubbled up, then we need to remote the value. if ($temporaryValue && empty($value)) { $value = null; $valueIsArray = false; } } } elseif ($type == 'array' && $valueIsArray && $param->getItems()) { foreach ($value as $i => &$item) { // Validate each item in an array against the items attribute of the schema $this->recursiveProcess($param->getItems(), $item, $path . "[{$i}]", $depth + 1); } } // If the value is required and the type is not null, then there is an error if the value is not set if ($required && $value === null && $type != 'null') { $message = "{$path} is " . ($param->getType() ? ('a required ' . implode(' or ', (array) $param->getType())) : 'required'); if ($param->getDescription()) { $message .= ': ' . $param->getDescription(); } $this->errors[] = $message; return false; } // Validate that the type is correct. If the type is string but an integer was passed, the class can be // instructed to cast the integer to a string to pass validation. This is the default behavior. if ($type && (!$type = $this->determineType($type, $value))) { if ($this->castIntegerToStringType && $param->getType() == 'string' && is_integer($value)) { $value = (string) $value; } else { $this->errors[] = "{$path} must be of type " . implode(' or ', (array) $param->getType()); } } // Perform type specific validation for strings, arrays, and integers if ($type == 'string') { // Strings can have enums which are a list of predefined values if (($enum = $param->getEnum()) && !in_array($value, $enum)) { $this->errors[] = "{$path} must be one of " . implode(' or ', array_map(function ($s) { return '"' . addslashes($s) . '"'; }, $enum)); } // Strings can have a regex pattern that the value must match if (($pattern = $param->getPattern()) && !preg_match($pattern, $value)) { $this->errors[] = "{$path} must match the following regular expression: {$pattern}"; } $strLen = null; if ($min = $param->getMinLength()) { $strLen = strlen($value); if ($strLen < $min) { $this->errors[] = "{$path} length must be greater than or equal to {$min}"; } } if ($max = $param->getMaxLength()) { if (($strLen ?: strlen($value)) > $max) { $this->errors[] = "{$path} length must be less than or equal to {$max}"; } } } elseif ($type == 'array') { $size = null; if ($min = $param->getMinItems()) { $size = count($value); if ($size < $min) { $this->errors[] = "{$path} must contain {$min} or more elements"; } } if ($max = $param->getMaxItems()) { if (($size ?: count($value)) > $max) { $this->errors[] = "{$path} must contain {$max} or fewer elements"; } } } elseif ($type == 'integer' || $type == 'number' || $type == 'numeric') { if (($min = $param->getMinimum()) && $value < $min) { $this->errors[] = "{$path} must be greater than or equal to {$min}"; } if (($max = $param->getMaximum()) && $value > $max) { $this->errors[] = "{$path} must be less than or equal to {$max}"; } } return empty($this->errors); } /** * From the allowable types, determine the type that the variable matches * * @param string $type Parameter type * @param mixed $value Value to determine the type * * @return string|bool Returns the matching type on */ protected function determineType($type, $value) { foreach ((array) $type as $t) { if ($t == 'string' && (is_string($value) || (is_object($value) && method_exists($value, '__toString')))) { return 'string'; } elseif ($t == 'object' && (is_array($value) || is_object($value))) { return 'object'; } elseif ($t == 'array' && is_array($value)) { return 'array'; } elseif ($t == 'integer' && is_integer($value)) { return 'integer'; } elseif ($t == 'boolean' && is_bool($value)) { return 'boolean'; } elseif ($t == 'number' && is_numeric($value)) { return 'number'; } elseif ($t == 'numeric' && is_numeric($value)) { return 'numeric'; } elseif ($t == 'null' && !$value) { return 'null'; } elseif ($t == 'any') { return 'any'; } } return false; } } load($config, $options); } /** * @param array $config Array of configuration data */ public function __construct(array $config = array()) { $this->fromArray($config); } public function serialize() { return json_encode($this->toArray()); } public function unserialize($json) { $this->operations = array(); $this->fromArray(json_decode($json, true)); } public function toArray() { $result = array( 'name' => $this->name, 'apiVersion' => $this->apiVersion, 'baseUrl' => $this->baseUrl, 'description' => $this->description ) + $this->extraData; $result['operations'] = array(); foreach ($this->getOperations() as $name => $operation) { $result['operations'][$operation->getName() ?: $name] = $operation->toArray(); } if (!empty($this->models)) { $result['models'] = array(); foreach ($this->models as $id => $model) { $result['models'][$id] = $model instanceof Parameter ? $model->toArray(): $model; } } return array_filter($result); } public function getBaseUrl() { return $this->baseUrl; } /** * Set the baseUrl of the description * * @param string $baseUrl Base URL of each operation * * @return self */ public function setBaseUrl($baseUrl) { $this->baseUrl = $baseUrl; return $this; } public function getOperations() { foreach (array_keys($this->operations) as $name) { $this->getOperation($name); } return $this->operations; } public function hasOperation($name) { return isset($this->operations[$name]); } public function getOperation($name) { // Lazily retrieve and build operations if (!isset($this->operations[$name])) { return null; } if (!($this->operations[$name] instanceof Operation)) { $this->operations[$name] = new Operation($this->operations[$name], $this); } return $this->operations[$name]; } /** * Add a operation to the service description * * @param OperationInterface $operation Operation to add * * @return self */ public function addOperation(OperationInterface $operation) { $this->operations[$operation->getName()] = $operation->setServiceDescription($this); return $this; } public function getModel($id) { if (!isset($this->models[$id])) { return null; } if (!($this->models[$id] instanceof Parameter)) { $this->models[$id] = new Parameter($this->models[$id] + array('name' => $id), $this); } return $this->models[$id]; } public function getModels() { // Ensure all models are converted into parameter objects foreach (array_keys($this->models) as $id) { $this->getModel($id); } return $this->models; } public function hasModel($id) { return isset($this->models[$id]); } /** * Add a model to the service description * * @param Parameter $model Model to add * * @return self */ public function addModel(Parameter $model) { $this->models[$model->getName()] = $model; return $this; } public function getApiVersion() { return $this->apiVersion; } public function getName() { return $this->name; } public function getDescription() { return $this->description; } public function getData($key) { return isset($this->extraData[$key]) ? $this->extraData[$key] : null; } public function setData($key, $value) { $this->extraData[$key] = $value; return $this; } /** * Initialize the state from an array * * @param array $config Configuration data * @throws InvalidArgumentException */ protected function fromArray(array $config) { // Keep a list of default keys used in service descriptions that is later used to determine extra data keys static $defaultKeys = array('name', 'models', 'apiVersion', 'baseUrl', 'description'); // Pull in the default configuration values foreach ($defaultKeys as $key) { if (isset($config[$key])) { $this->{$key} = $config[$key]; } } // Account for the Swagger name for Guzzle's baseUrl if (isset($config['basePath'])) { $this->baseUrl = $config['basePath']; } // Ensure that the models and operations properties are always arrays $this->models = (array) $this->models; $this->operations = (array) $this->operations; // We want to add operations differently than adding the other properties $defaultKeys[] = 'operations'; // Create operations for each operation if (isset($config['operations'])) { foreach ($config['operations'] as $name => $operation) { if (!($operation instanceof Operation) && !is_array($operation)) { throw new InvalidArgumentException('Invalid operation in service description: ' . gettype($operation)); } $this->operations[$name] = $operation; } } // Get all of the additional properties of the service description and store them in a data array foreach (array_diff(array_keys($config), $defaultKeys) as $key) { $this->extraData[$key] = $config[$key]; } } } $op) { $name = $op['name'] = isset($op['name']) ? $op['name'] : $name; // Extend other operations if (!empty($op['extends'])) { $this->resolveExtension($name, $op, $operations); } $op['parameters'] = isset($op['parameters']) ? $op['parameters'] : array(); $operations[$name] = $op; } } return new ServiceDescription(array( 'apiVersion' => isset($config['apiVersion']) ? $config['apiVersion'] : null, 'baseUrl' => isset($config['baseUrl']) ? $config['baseUrl'] : null, 'description' => isset($config['description']) ? $config['description'] : null, 'operations' => $operations, 'models' => isset($config['models']) ? $config['models'] : null ) + $config); } /** * @param string $name Name of the operation * @param array $op Operation value array * @param array $operations Currently loaded operations * @throws DescriptionBuilderException when extending a non-existent operation */ protected function resolveExtension($name, array &$op, array &$operations) { $resolved = array(); $original = empty($op['parameters']) ? false: $op['parameters']; $hasClass = !empty($op['class']); foreach ((array) $op['extends'] as $extendedCommand) { if (empty($operations[$extendedCommand])) { throw new DescriptionBuilderException("{$name} extends missing operation {$extendedCommand}"); } $toArray = $operations[$extendedCommand]; $resolved = empty($resolved) ? $toArray['parameters'] : array_merge($resolved, $toArray['parameters']); $op = $op + $toArray; if (!$hasClass && isset($toArray['class'])) { $op['class'] = $toArray['class']; } } $op['parameters'] = $original ? array_merge($resolved, $original) : $resolved; } } getMessage(), $e->getCode(), $e->getPrevious()); $ce->setSuccessfulRequests($e->getSuccessfulRequests()); $alreadyAddedExceptions = array(); foreach ($e->getFailedRequests() as $request) { if ($re = $e->getExceptionForFailedRequest($request)) { $alreadyAddedExceptions[] = $re; $ce->addFailedRequestWithException($request, $re); } else { $ce->addFailedRequest($request); } } // Add any exceptions that did not map to a request if (count($alreadyAddedExceptions) < count($e)) { foreach ($e as $ex) { if (!in_array($ex, $alreadyAddedExceptions)) { $ce->add($ex); } } } return $ce; } /** * Get all of the commands in the transfer * * @return array */ public function getAllCommands() { return array_merge($this->successfulCommands, $this->failedCommands); } /** * Add to the array of successful commands * * @param CommandInterface $command Successful command * * @return self */ public function addSuccessfulCommand(CommandInterface $command) { $this->successfulCommands[] = $command; return $this; } /** * Add to the array of failed commands * * @param CommandInterface $command Failed command * * @return self */ public function addFailedCommand(CommandInterface $command) { $this->failedCommands[] = $command; return $this; } /** * Get an array of successful commands * * @return array */ public function getSuccessfulCommands() { return $this->successfulCommands; } /** * Get an array of failed commands * * @return array */ public function getFailedCommands() { return $this->failedCommands; } /** * Get the Exception that caused the given $command to fail * * @param CommandInterface $command Failed command * * @return \Exception|null */ public function getExceptionForFailedCommand(CommandInterface $command) { return $this->getExceptionForFailedRequest($command->getRequest()); } } invalidCommands = $commands; parent::__construct( 'Encountered commands in a batch transfer that use inconsistent clients. The batching ' . 'strategy you use with a command transfer must divide command batches by client.' ); } /** * Get the invalid commands * * @return array */ public function getCommands() { return $this->invalidCommands; } } errors = $errors; } /** * Get any validation errors * * @return array */ public function getErrors() { return $this->errors; } } canBuild($command)) { throw new InvalidArgumentException('Iterator was not found for ' . $command->getName()); } $className = $this->getClassName($command); return new $className($command, $options); } public function canBuild(CommandInterface $command) { return (bool) $this->getClassName($command); } /** * Get the name of the class to instantiate for the command * * @param CommandInterface $command Command that is associated with the iterator * * @return string */ abstract protected function getClassName(CommandInterface $command); } factories = $factories; } public function build(CommandInterface $command, array $options = array()) { if (!($factory = $this->getFactory($command))) { throw new InvalidArgumentException('Iterator was not found for ' . $command->getName()); } return $factory->build($command, $options); } public function canBuild(CommandInterface $command) { return $this->getFactory($command) !== false; } /** * Add a factory to the composite factory * * @param ResourceIteratorFactoryInterface $factory Factory to add * * @return self */ public function addFactory(ResourceIteratorFactoryInterface $factory) { $this->factories[] = $factory; return $this; } /** * Get the factory that matches the command object * * @param CommandInterface $command Command retrieving the iterator for * * @return ResourceIteratorFactoryInterface|bool */ protected function getFactory(CommandInterface $command) { foreach ($this->factories as $factory) { if ($factory->canBuild($command)) { return $factory; } } return false; } } map = $map; } public function getClassName(CommandInterface $command) { $className = $command->getName(); if (isset($this->map[$className])) { return $this->map[$className]; } elseif (isset($this->map['*'])) { // If a wildcard was added, then always use that return $this->map['*']; } return null; } } data = $data; $this->structure = $structure; } /** * Get the structure of the model * * @return Parameter */ public function getStructure() { return $this->structure ?: new Parameter(); } /** * Provides debug information about the model object * * @return string */ public function __toString() { $output = 'Debug output of '; if ($this->structure) { $output .= $this->structure->getName() . ' '; } $output .= 'model'; $output = str_repeat('=', strlen($output)) . "\n" . $output . "\n" . str_repeat('=', strlen($output)) . "\n\n"; $output .= "Model data\n-----------\n\n"; $output .= "This data can be retrieved from the model object using the get() method of the model " . "(e.g. \$model->get(\$key)) or accessing the model like an associative array (e.g. \$model['key']).\n\n"; $lines = array_slice(explode("\n", trim(print_r($this->toArray(), true))), 2, -1); $output .= implode("\n", $lines); if ($this->structure) { $output .= "\n\nModel structure\n---------------\n\n"; $output .= "The following JSON document defines how the model was parsed from an HTTP response into the " . "associative array structure you see above.\n\n"; $output .= ' ' . json_encode($this->structure->toArray()) . "\n\n"; } return $output . "\n"; } } originalCommand = $command; // Parse options from the array of options $this->data = $data; $this->limit = array_key_exists('limit', $data) ? $data['limit'] : 0; $this->pageSize = array_key_exists('page_size', $data) ? $data['page_size'] : false; } /** * Get all of the resources as an array (Warning: this could issue a large number of requests) * * @return array */ public function toArray() { return iterator_to_array($this, false); } public function setLimit($limit) { $this->limit = $limit; $this->resetState(); return $this; } public function setPageSize($pageSize) { $this->pageSize = $pageSize; $this->resetState(); return $this; } /** * Get an option from the iterator * * @param string $key Key of the option to retrieve * * @return mixed|null Returns NULL if not set or the value if set */ public function get($key) { return array_key_exists($key, $this->data) ? $this->data[$key] : null; } /** * Set an option on the iterator * * @param string $key Key of the option to set * @param mixed $value Value to set for the option * * @return ResourceIterator */ public function set($key, $value) { $this->data[$key] = $value; return $this; } public function current() { return $this->resources ? current($this->resources) : false; } public function key() { return max(0, $this->iteratedCount - 1); } public function count() { return $this->retrievedCount; } /** * Get the total number of requests sent * * @return int */ public function getRequestCount() { return $this->requestCount; } /** * Rewind the Iterator to the first element and send the original command */ public function rewind() { // Use the original command $this->command = clone $this->originalCommand; $this->resetState(); $this->next(); } public function valid() { return !$this->invalid && (!$this->resources || $this->current() || $this->nextToken) && (!$this->limit || $this->iteratedCount < $this->limit + 1); } public function next() { $this->iteratedCount++; // Check if a new set of resources needs to be retrieved $sendRequest = false; if (!$this->resources) { $sendRequest = true; } else { // iterate over the internal array $current = next($this->resources); $sendRequest = $current === false && $this->nextToken && (!$this->limit || $this->iteratedCount < $this->limit + 1); } if ($sendRequest) { $this->dispatch('resource_iterator.before_send', array( 'iterator' => $this, 'resources' => $this->resources )); // Get a new command object from the original command $this->command = clone $this->originalCommand; // Send a request and retrieve the newly loaded resources $this->resources = $this->sendRequest(); $this->requestCount++; // If no resources were found, then the last request was not needed // and iteration must stop if (empty($this->resources)) { $this->invalid = true; } else { // Add to the number of retrieved resources $this->retrievedCount += count($this->resources); // Ensure that we rewind to the beginning of the array reset($this->resources); } $this->dispatch('resource_iterator.after_send', array( 'iterator' => $this, 'resources' => $this->resources )); } } /** * Retrieve the NextToken that can be used in other iterators. * * @return string Returns a NextToken */ public function getNextToken() { return $this->nextToken; } /** * Returns the value that should be specified for the page size for a request that will maintain any hard limits, * but still honor the specified pageSize if the number of items retrieved + pageSize < hard limit * * @return int Returns the page size of the next request. */ protected function calculatePageSize() { if ($this->limit && $this->iteratedCount + $this->pageSize > $this->limit) { return 1 + ($this->limit - $this->iteratedCount); } return (int) $this->pageSize; } /** * Reset the internal state of the iterator without triggering a rewind() */ protected function resetState() { $this->iteratedCount = 0; $this->retrievedCount = 0; $this->nextToken = false; $this->resources = null; $this->invalid = false; } /** * Send a request to retrieve the next page of results. Hook for subclasses to implement. * * @return array Returns the newly loaded resources */ abstract protected function sendRequest(); } iterator = $iterator; $this->callback = $callback; Version::warn(__CLASS__ . ' is deprecated'); } /** * Apply the callback to the contents of the resource iterator * * @param int $perBatch The number of records to group per batch transfer * * @return int Returns the number of iterated resources */ public function apply($perBatch = 50) { $this->iterated = $this->batches = $batches = 0; $that = $this; $it = $this->iterator; $callback = $this->callback; $batch = BatchBuilder::factory() ->createBatchesWith(new BatchSizeDivisor($perBatch)) ->transferWith(new BatchClosureTransfer(function (array $batch) use ($that, $callback, &$batches, $it) { $batches++; $that->dispatch('iterator_batch.before_batch', array('iterator' => $it, 'batch' => $batch)); call_user_func_array($callback, array($it, $batch)); $that->dispatch('iterator_batch.after_batch', array('iterator' => $it, 'batch' => $batch)); })) ->autoFlushAt($perBatch) ->build(); $this->dispatch('iterator_batch.created_batch', array('batch' => $batch)); foreach ($this->iterator as $resource) { $this->iterated++; $batch->add($resource); } $batch->flush(); $this->batches = $batches; return $this->iterated; } /** * Get the total number of batches sent * * @return int */ public function getBatchCount() { return $this->batches; } /** * Get the total number of iterated resources * * @return int */ public function getIteratedCount() { return $this->iterated; } } AbcFoo). */ class ResourceIteratorClassFactory extends AbstractResourceIteratorFactory { /** @var array List of namespaces used to look for classes */ protected $namespaces; /** @var InflectorInterface Inflector used to determine class names */ protected $inflector; /** * @param string|array $namespaces List of namespaces for iterator objects * @param InflectorInterface $inflector Inflector used to resolve class names */ public function __construct($namespaces = array(), InflectorInterface $inflector = null) { $this->namespaces = (array) $namespaces; $this->inflector = $inflector ?: Inflector::getDefault(); } /** * Registers a namespace to check for Iterators * * @param string $namespace Namespace which contains Iterator classes * * @return self */ public function registerNamespace($namespace) { array_unshift($this->namespaces, $namespace); return $this; } protected function getClassName(CommandInterface $command) { $iteratorName = $this->inflector->camel($command->getName()) . 'Iterator'; // Determine the name of the class to load foreach ($this->namespaces as $namespace) { $potentialClassName = $namespace . '\\' . $iteratorName; if (class_exists($potentialClassName)) { return $potentialClassName; } } return false; } } contextOptions = stream_context_get_options($context); $this->context = $context; } elseif (is_array($context) || !$context) { $this->contextOptions = $context; $this->createContext($params); } elseif ($context) { throw new InvalidArgumentException('$context must be an array or resource'); } // Dispatch the before send event $request->dispatch('request.before_send', array( 'request' => $request, 'context' => $this->context, 'context_options' => $this->contextOptions )); $this->setUrl($request); $this->addDefaultContextOptions($request); $this->addSslOptions($request); $this->addBodyOptions($request); $this->addProxyOptions($request); // Create the file handle but silence errors return $this->createStream($params) ->setCustomData('request', $request) ->setCustomData('response_headers', $this->getLastResponseHeaders()); } /** * Set an option on the context and the internal options array * * @param string $wrapper Stream wrapper name of http * @param string $name Context name * @param mixed $value Context value * @param bool $overwrite Set to true to overwrite an existing value */ protected function setContextValue($wrapper, $name, $value, $overwrite = false) { if (!isset($this->contextOptions[$wrapper])) { $this->contextOptions[$wrapper] = array($name => $value); } elseif (!$overwrite && isset($this->contextOptions[$wrapper][$name])) { return; } $this->contextOptions[$wrapper][$name] = $value; stream_context_set_option($this->context, $wrapper, $name, $value); } /** * Create a stream context * * @param array $params Parameter array */ protected function createContext(array $params) { $options = $this->contextOptions; $this->context = $this->createResource(function () use ($params, $options) { return stream_context_create($options, $params); }); } /** * Get the last response headers received by the HTTP request * * @return array */ public function getLastResponseHeaders() { return $this->lastResponseHeaders; } /** * Adds the default context options to the stream context options * * @param RequestInterface $request Request */ protected function addDefaultContextOptions(RequestInterface $request) { $this->setContextValue('http', 'method', $request->getMethod()); $headers = $request->getHeaderLines(); // "Connection: close" is required to get streams to work in HTTP 1.1 if (!$request->hasHeader('Connection')) { $headers[] = 'Connection: close'; } $this->setContextValue('http', 'header', $headers); $this->setContextValue('http', 'protocol_version', $request->getProtocolVersion()); $this->setContextValue('http', 'ignore_errors', true); } /** * Set the URL to use with the factory * * @param RequestInterface $request Request that owns the URL */ protected function setUrl(RequestInterface $request) { $this->url = $request->getUrl(true); // Check for basic Auth username if ($request->getUsername()) { $this->url->setUsername($request->getUsername()); } // Check for basic Auth password if ($request->getPassword()) { $this->url->setPassword($request->getPassword()); } } /** * Add SSL options to the stream context * * @param RequestInterface $request Request */ protected function addSslOptions(RequestInterface $request) { if ($request->getCurlOptions()->get(CURLOPT_SSL_VERIFYPEER)) { $this->setContextValue('ssl', 'verify_peer', true, true); if ($cafile = $request->getCurlOptions()->get(CURLOPT_CAINFO)) { $this->setContextValue('ssl', 'cafile', $cafile, true); } } else { $this->setContextValue('ssl', 'verify_peer', false, true); } } /** * Add body (content) specific options to the context options * * @param RequestInterface $request */ protected function addBodyOptions(RequestInterface $request) { // Add the content for the request if needed if (!($request instanceof EntityEnclosingRequestInterface)) { return; } if (count($request->getPostFields())) { $this->setContextValue('http', 'content', (string) $request->getPostFields(), true); } elseif ($request->getBody()) { $this->setContextValue('http', 'content', (string) $request->getBody(), true); } // Always ensure a content-length header is sent if (isset($this->contextOptions['http']['content'])) { $headers = isset($this->contextOptions['http']['header']) ? $this->contextOptions['http']['header'] : array(); $headers[] = 'Content-Length: ' . strlen($this->contextOptions['http']['content']); $this->setContextValue('http', 'header', $headers, true); } } /** * Add proxy parameters to the context if needed * * @param RequestInterface $request Request */ protected function addProxyOptions(RequestInterface $request) { if ($proxy = $request->getCurlOptions()->get(CURLOPT_PROXY)) { $this->setContextValue('http', 'proxy', $proxy); } } /** * Create the stream for the request with the context options * * @param array $params Parameters of the stream * * @return StreamInterface */ protected function createStream(array $params) { $http_response_header = null; $url = $this->url; $context = $this->context; $fp = $this->createResource(function () use ($context, $url, &$http_response_header) { return fopen((string) $url, 'r', false, $context); }); // Determine the class to instantiate $className = isset($params['stream_class']) ? $params['stream_class'] : __NAMESPACE__ . '\\Stream'; /** @var $stream StreamInterface */ $stream = new $className($fp); // Track the response headers of the request if (isset($http_response_header)) { $this->lastResponseHeaders = $http_response_header; $this->processResponseHeaders($stream); } return $stream; } /** * Process response headers * * @param StreamInterface $stream */ protected function processResponseHeaders(StreamInterface $stream) { // Set the size on the stream if it was returned in the response foreach ($this->lastResponseHeaders as $header) { if ((stripos($header, 'Content-Length:')) === 0) { $stream->setSize(trim(substr($header, 15))); } } } /** * Create a resource and check to ensure it was created successfully * * @param callable $callback Closure to invoke that must return a valid resource * * @return resource * @throws RuntimeException on error */ protected function createResource($callback) { // Turn off error reporting while we try to initiate the request $level = error_reporting(0); $resource = call_user_func($callback); error_reporting($level); // If the resource could not be created, then grab the last error and throw an exception if (false === $resource) { $message = 'Error creating resource. '; foreach (error_get_last() as $key => $value) { $message .= "[{$key}] {$value} "; } throw new RuntimeException(trim($message)); } return $resource; } } array( 'r' => true, 'w+' => true, 'r+' => true, 'x+' => true, 'c+' => true, 'rb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true, 'c+b' => true, 'rt' => true, 'w+t' => true, 'r+t' => true, 'x+t' => true, 'c+t' => true, 'a+' => true ), 'write' => array( 'w' => true, 'w+' => true, 'rw' => true, 'r+' => true, 'x+' => true, 'c+' => true, 'wb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true, 'c+b' => true, 'w+t' => true, 'r+t' => true, 'x+t' => true, 'c+t' => true, 'a' => true, 'a+' => true ) ); /** * @param resource $stream Stream resource to wrap * @param int $size Size of the stream in bytes. Only pass if the size cannot be obtained from the stream. * * @throws InvalidArgumentException if the stream is not a stream resource */ public function __construct($stream, $size = null) { $this->setStream($stream, $size); } /** * Closes the stream when the helper is destructed */ public function __destruct() { $this->close(); } public function __toString() { if (!$this->isReadable() || (!$this->isSeekable() && $this->isConsumed())) { return ''; } $originalPos = $this->ftell(); $body = stream_get_contents($this->stream, -1, 0); $this->seek($originalPos); return $body; } public function close() { if (is_resource($this->stream)) { fclose($this->stream); } $this->cache[self::IS_READABLE] = false; $this->cache[self::IS_WRITABLE] = false; } /** * Calculate a hash of a Stream * * @param StreamInterface $stream Stream to calculate the hash for * @param string $algo Hash algorithm (e.g. md5, crc32, etc) * @param bool $rawOutput Whether or not to use raw output * * @return bool|string Returns false on failure or a hash string on success */ public static function getHash(StreamInterface $stream, $algo, $rawOutput = false) { $pos = $stream->ftell(); if (!$stream->seek(0)) { return false; } $ctx = hash_init($algo); while (!$stream->feof()) { hash_update($ctx, $stream->read(8192)); } $out = hash_final($ctx, (bool) $rawOutput); $stream->seek($pos); return $out; } public function getMetaData($key = null) { $meta = stream_get_meta_data($this->stream); return !$key ? $meta : (array_key_exists($key, $meta) ? $meta[$key] : null); } public function getStream() { return $this->stream; } public function setStream($stream, $size = null) { if (!is_resource($stream)) { throw new InvalidArgumentException('Stream must be a resource'); } $this->size = $size; $this->stream = $stream; $this->rebuildCache(); return $this; } public function detachStream() { $this->stream = null; return $this; } public function getWrapper() { return $this->cache[self::WRAPPER_TYPE]; } public function getWrapperData() { return $this->getMetaData('wrapper_data') ?: array(); } public function getStreamType() { return $this->cache[self::STREAM_TYPE]; } public function getUri() { return $this->cache['uri']; } public function getSize() { if ($this->size !== null) { return $this->size; } // If the stream is a file based stream and local, then use fstat clearstatcache(true, $this->cache['uri']); $stats = fstat($this->stream); if (isset($stats['size'])) { $this->size = $stats['size']; return $this->size; } elseif ($this->cache[self::IS_READABLE] && $this->cache[self::SEEKABLE]) { // Only get the size based on the content if the the stream is readable and seekable $pos = $this->ftell(); $this->size = strlen((string) $this); $this->seek($pos); return $this->size; } return false; } public function isReadable() { return $this->cache[self::IS_READABLE]; } public function isRepeatable() { return $this->cache[self::IS_READABLE] && $this->cache[self::SEEKABLE]; } public function isWritable() { return $this->cache[self::IS_WRITABLE]; } public function isConsumed() { return feof($this->stream); } public function feof() { return $this->isConsumed(); } public function isLocal() { return $this->cache[self::IS_LOCAL]; } public function isSeekable() { return $this->cache[self::SEEKABLE]; } public function setSize($size) { $this->size = $size; return $this; } public function seek($offset, $whence = SEEK_SET) { return $this->cache[self::SEEKABLE] ? fseek($this->stream, $offset, $whence) === 0 : false; } public function read($length) { return fread($this->stream, $length); } public function write($string) { // We can't know the size after writing anything $this->size = null; return fwrite($this->stream, $string); } public function ftell() { return ftell($this->stream); } public function rewind() { return $this->seek(0); } public function readLine($maxLength = null) { if (!$this->cache[self::IS_READABLE]) { return false; } else { return $maxLength ? fgets($this->getStream(), $maxLength) : fgets($this->getStream()); } } public function setCustomData($key, $value) { $this->customData[$key] = $value; return $this; } public function getCustomData($key) { return isset($this->customData[$key]) ? $this->customData[$key] : null; } /** * Reprocess stream metadata */ protected function rebuildCache() { $this->cache = stream_get_meta_data($this->stream); $this->cache[self::IS_LOCAL] = stream_is_local($this->stream); $this->cache[self::IS_READABLE] = isset(self::$readWriteHash['read'][$this->cache['mode']]); $this->cache[self::IS_WRITABLE] = isset(self::$readWriteHash['write'][$this->cache['mode']]); } } Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PHP_Timer Copyright (c) 2010-2013, Sebastian Bergmann . All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Sebastian Bergmann nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. . * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Sebastian Bergmann nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package PHP * @subpackage Timer * @author Sebastian Bergmann * @copyright 2010-2013 Sebastian Bergmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://github.com/sebastianbergmann/php-timer * @since File available since Release 1.0.0 */ /** * Utility class for timing. * * @package PHP * @subpackage Timer * @author Sebastian Bergmann * @copyright 2010-2013 Sebastian Bergmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @version Release: @package_version@ * @link http://github.com/sebastianbergmann/php-timer * @since Class available since Release 1.0.0 */ class PHP_Timer { /** * @var array */ private static $times = array( 'hour' => 3600000, 'minute' => 60000, 'second' => 1000 ); /** * @var array */ private static $startTimes = array(); /** * @var float */ public static $requestTime; /** * Starts the timer. */ public static function start() { array_push(self::$startTimes, microtime(TRUE)); } /** * Stops the timer and returns the elapsed time. * * @return float */ public static function stop() { return microtime(TRUE) - array_pop(self::$startTimes); } /** * Formats the elapsed time as a string. * * @param float $time * @return string */ public static function secondsToTimeString($time) { $ms = round($time * 1000); foreach (self::$times as $unit => $value) { if ($ms >= $value) { $time = floor($ms / $value * 100.0) / 100.0; return $time . ' ' . ($time == 1 ? $unit : $unit . 's'); } } return $ms . ' ms'; } /** * Formats the elapsed time since the start of the request as a string. * * @return string */ public static function timeSinceStartOfRequest() { return self::secondsToTimeString(microtime(TRUE) - self::$requestTime); } /** * Returns the resources (time, memory) of the request as a string. * * @return string */ public static function resourceUsage() { return sprintf( 'Time: %s, Memory: %4.2fMb', self::timeSinceStartOfRequest(), memory_get_peak_usage(TRUE) / 1048576 ); } } if (isset($_SERVER['REQUEST_TIME_FLOAT'])) { PHP_Timer::$requestTime = $_SERVER['REQUEST_TIME_FLOAT']; } else { PHP_Timer::$requestTime = microtime(TRUE); } * setKey('abcdefghijklmnop'); * * $size = 10 * 1024; * $plaintext = ''; * for ($i = 0; $i < $size; $i++) { * $plaintext.= 'a'; * } * * echo $aes->decrypt($aes->encrypt($plaintext)); * ?> * * * @category Crypt * @package AES * @author Jim Wigginton * @copyright 2008 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\Crypt; use phpseclib\Crypt\Rijndael; /** * Pure-PHP implementation of AES. * * @package AES * @author Jim Wigginton * @access public */ class AES extends Rijndael { /** * The namespace used by the cipher for its constants. * * @see \phpseclib\Crypt\Base::const_namespace * @var String * @access private */ var $const_namespace = 'AES'; /** * Dummy function * * Since \phpseclib\Crypt\AES extends \phpseclib\Crypt\Rijndael, this function is, technically, available, but it doesn't do anything. * * @see \phpseclib\Crypt\Rijndael::setBlockLength() * @access public * @param Integer $length */ function setBlockLength($length) { return; } /** * Sets the key length * * Valid key lengths are 128, 192, and 256. If the length is less than 128, it will be rounded up to * 128. If the length is greater than 128 and invalid, it will be rounded down to the closest valid amount. * * @see \phpseclib\Crypt\Rijndael:setKeyLength() * @access public * @param Integer $length */ function setKeyLength($length) { switch ($length) { case 160: $length = 192; break; case 224: $length = 256; } parent::setKeyLength($length); } /** * Sets the key. * * Rijndael supports five different key lengths, AES only supports three. * * @see \phpseclib\Crypt\Rijndael:setKey() * @see setKeyLength() * @access public * @param String $key */ function setKey($key) { parent::setKey($key); if (!$this->explicit_key_length) { $length = strlen($key); switch (true) { case $length <= 16: $this->key_size = 16; break; case $length <= 24: $this->key_size = 24; break; default: $this->key_size = 32; } $this->_setupEngine(); } } } * @author Hans-Juergen Petrich * @copyright 2007 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\Crypt; use phpseclib\Crypt\Hash; /** * Base Class for all \phpseclib\Crypt\* cipher classes * * @package Base * @author Jim Wigginton * @author Hans-Juergen Petrich * @access public */ class Base { /**#@+ * @access public * @see \phpseclib\Crypt\Base::encrypt() * @see \phpseclib\Crypt\Base::decrypt() */ /** * Encrypt / decrypt using the Counter mode. * * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode. * * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29 */ const MODE_CTR = -1; /** * Encrypt / decrypt using the Electronic Code Book mode. * * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29 */ const MODE_ECB = 1; /** * Encrypt / decrypt using the Code Book Chaining mode. * * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29 */ const MODE_CBC = 2; /** * Encrypt / decrypt using the Cipher Feedback mode. * * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29 */ const MODE_CFB = 3; /** * Encrypt / decrypt using the Output Feedback mode. * * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29 */ const MODE_OFB = 4; /** * Encrypt / decrypt using streaming mode. * */ const MODE_STREAM = 5; /**#@-*/ /**#@+ * @access private * @see \phpseclib\Crypt\Base::__construct() */ /** * Base value for the internal implementation $engine switch */ const ENGINE_INTERNAL = 1; /** * Base value for the mcrypt implementation $engine switch */ const ENGINE_MCRYPT = 2; /**#@-*/ /** * The Encryption Mode * * @see \phpseclib\Crypt\Base::__construct() * @var Integer * @access private */ var $mode; /** * The Block Length of the block cipher * * @var Integer * @access private */ var $block_size = 16; /** * The Key * * @see \phpseclib\Crypt\Base::setKey() * @var String * @access private */ var $key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; /** * The Initialization Vector * * @see \phpseclib\Crypt\Base::setIV() * @var String * @access private */ var $iv; /** * A "sliding" Initialization Vector * * @see \phpseclib\Crypt\Base::enableContinuousBuffer() * @see \phpseclib\Crypt\Base::_clearBuffers() * @var String * @access private */ var $encryptIV; /** * A "sliding" Initialization Vector * * @see \phpseclib\Crypt\Base::enableContinuousBuffer() * @see \phpseclib\Crypt\Base::_clearBuffers() * @var String * @access private */ var $decryptIV; /** * Continuous Buffer status * * @see \phpseclib\Crypt\Base::enableContinuousBuffer() * @var Boolean * @access private */ var $continuousBuffer = false; /** * Encryption buffer for CTR, OFB and CFB modes * * @see \phpseclib\Crypt\Base::encrypt() * @see \phpseclib\Crypt\Base::_clearBuffers() * @var Array * @access private */ var $enbuffer; /** * Decryption buffer for CTR, OFB and CFB modes * * @see \phpseclib\Crypt\Base::decrypt() * @see \phpseclib\Crypt\Base::_clearBuffers() * @var Array * @access private */ var $debuffer; /** * mcrypt resource for encryption * * The mcrypt resource can be recreated every time something needs to be created or it can be created just once. * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode. * * @see \phpseclib\Crypt\Base::encrypt() * @var Resource * @access private */ var $enmcrypt; /** * mcrypt resource for decryption * * The mcrypt resource can be recreated every time something needs to be created or it can be created just once. * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode. * * @see \phpseclib\Crypt\Base::decrypt() * @var Resource * @access private */ var $demcrypt; /** * Does the enmcrypt resource need to be (re)initialized? * * @see \phpseclib\Crypt\Twofish::setKey() * @see \phpseclib\Crypt\Twofish::setIV() * @var Boolean * @access private */ var $enchanged = true; /** * Does the demcrypt resource need to be (re)initialized? * * @see \phpseclib\Crypt\Twofish::setKey() * @see \phpseclib\Crypt\Twofish::setIV() * @var Boolean * @access private */ var $dechanged = true; /** * mcrypt resource for CFB mode * * mcrypt's CFB mode, in (and only in) buffered context, * is broken, so phpseclib implements the CFB mode by it self, * even when the mcrypt php extension is available. * * In order to do the CFB-mode work (fast) phpseclib * use a separate ECB-mode mcrypt resource. * * @link http://phpseclib.sourceforge.net/cfb-demo.phps * @see \phpseclib\Crypt\Base::encrypt() * @see \phpseclib\Crypt\Base::decrypt() * @see \phpseclib\Crypt\Base::_setupMcrypt() * @var Resource * @access private */ var $ecb; /** * Optimizing value while CFB-encrypting * * Only relevant if $continuousBuffer enabled * and $engine == self::ENGINE_MCRYPT * * It's faster to re-init $enmcrypt if * $buffer bytes > $cfb_init_len than * using the $ecb resource furthermore. * * This value depends of the chosen cipher * and the time it would be needed for it's * initialization [by mcrypt_generic_init()] * which, typically, depends on the complexity * on its internaly Key-expanding algorithm. * * @see \phpseclib\Crypt\Base::encrypt() * @var Integer * @access private */ var $cfb_init_len = 600; /** * Does internal cipher state need to be (re)initialized? * * @see setKey() * @see setIV() * @see disableContinuousBuffer() * @var Boolean * @access private */ var $changed = true; /** * Padding status * * @see \phpseclib\Crypt\Base::enablePadding() * @var Boolean * @access private */ var $padding = true; /** * Is the mode one that is paddable? * * @see \phpseclib\Crypt\Base::__construct() * @var Boolean * @access private */ var $paddable = false; /** * Holds which crypt engine internaly should be use, * which will be determined automatically on __construct() * * Currently available $engines are: * - self::ENGINE_MCRYPT (fast, php-extension: mcrypt, extension_loaded('mcrypt') required) * - self::ENGINE_INTERNAL (slower, pure php-engine, no php-extension required) * * In the pipeline... maybe. But currently not available: * - self::ENGINE_OPENSSL (very fast, php-extension: openssl, extension_loaded('openssl') required) * * If possible, self::ENGINE_MCRYPT will be used for each cipher. * Otherwise self::ENGINE_INTERNAL * * @see \phpseclib\Crypt\Base::encrypt() * @see \phpseclib\Crypt\Base::decrypt() * @var Integer * @access private */ var $engine; /** * The mcrypt specific name of the cipher * * Only used if $engine == self::ENGINE_MCRYPT * * @link http://www.php.net/mcrypt_module_open * @link http://www.php.net/mcrypt_list_algorithms * @see \phpseclib\Crypt\Base::_setupMcrypt() * @var String * @access private */ var $cipher_name_mcrypt; /** * The default password key_size used by setPassword() * * @see \phpseclib\Crypt\Base::setPassword() * @var Integer * @access private */ var $password_key_size = 32; /** * The default salt used by setPassword() * * @see \phpseclib\Crypt\Base::setPassword() * @var String * @access private */ var $password_default_salt = 'phpseclib/salt'; /** * The namespace used by the cipher for its constants. * * ie: AES.php is using CRYPT_AES_MODE_* for its constants * so $const_namespace is AES * * DES.php is using CRYPT_DES_MODE_* for its constants * so $const_namespace is DES... and so on * * All CRYPT_<$const_namespace>_MODE_* are aliases of * the generic CRYPT_MODE_* constants, so both could be used * for each cipher. * * Example: * $aes = new \phpseclib\Crypt\AES(\phpseclib\Crypt\AES::MODE_CFB); // $aes will operate in cfb mode * $aes = new \phpseclib\Crypt\AES(self::MODE_CFB); // identical * * @see \phpseclib\Crypt\Base::__construct() * @var String * @access private */ var $const_namespace; /** * The name of the performance-optimized callback function * * Used by encrypt() / decrypt() * only if $engine == self::ENGINE_INTERNAL * * @see \phpseclib\Crypt\Base::encrypt() * @see \phpseclib\Crypt\Base::decrypt() * @see \phpseclib\Crypt\Base::_setupInlineCrypt() * @see \phpseclib\Crypt\Base::$use_inline_crypt * @var Callback * @access private */ var $inline_crypt; /** * Holds whether performance-optimized $inline_crypt() can/should be used. * * @see \phpseclib\Crypt\Base::encrypt() * @see \phpseclib\Crypt\Base::decrypt() * @see \phpseclib\Crypt\Base::inline_crypt * @var mixed * @access private */ var $use_inline_crypt; /** * Default Constructor. * * Determines whether or not the mcrypt extension should be used. * * $mode could be: * * - self::MODE_ECB * * - self::MODE_CBC * * - self::MODE_CTR * * - self::MODE_CFB * * - self::MODE_OFB * * (or the alias constants of the chosen cipher, for example for AES: CRYPT_AES_MODE_ECB or CRYPT_AES_MODE_CBC ...) * * If not explicitly set, self::MODE_CBC will be used. * * @param optional Integer $mode * @access public */ function __construct($mode = self::MODE_CBC) { $const_crypt_mode = 'CRYPT_' . $this->const_namespace . '_MODE'; // Determining the availibility of mcrypt support for the cipher if (!defined($const_crypt_mode)) { switch (true) { case extension_loaded('mcrypt') && in_array($this->cipher_name_mcrypt, mcrypt_list_algorithms()): define($const_crypt_mode, self::ENGINE_MCRYPT); break; default: define($const_crypt_mode, self::ENGINE_INTERNAL); } } // Determining which internal $engine should be used. // The fastes possible first. switch (true) { case empty($this->cipher_name_mcrypt): // The cipher module has no mcrypt-engine support at all so we force self::ENGINE_INTERNAL $this->engine = self::ENGINE_INTERNAL; break; case constant($const_crypt_mode) == self::ENGINE_MCRYPT: $this->engine = self::ENGINE_MCRYPT; break; default: $this->engine = self::ENGINE_INTERNAL; } // $mode dependent settings switch ($mode) { case self::MODE_ECB: $this->paddable = true; $this->mode = $mode; break; case self::MODE_CTR: case self::MODE_CFB: case self::MODE_OFB: case self::MODE_STREAM: $this->mode = $mode; break; case self::MODE_CBC: default: $this->paddable = true; $this->mode = self::MODE_CBC; } // Determining whether inline crypting can be used by the cipher if ($this->use_inline_crypt !== false && function_exists('create_function')) { $this->use_inline_crypt = true; } } /** * Sets the initialization vector. (optional) * * SetIV is not required when self::MODE_ECB (or ie for AES: \phpseclib\Crypt\AES::MODE_ECB) is being used. If not explicitly set, it'll be assumed * to be all zero's. * * Note: Could, but not must, extend by the child \phpseclib\Crypt\* class * * @access public * @param String $iv */ function setIV($iv) { if ($this->mode == self::MODE_ECB) { return; } $this->iv = $iv; $this->changed = true; } /** * Sets the key. * * The min/max length(s) of the key depends on the cipher which is used. * If the key not fits the length(s) of the cipher it will paded with null bytes * up to the closest valid key length. If the key is more than max length, * we trim the excess bits. * * If the key is not explicitly set, it'll be assumed to be all null bytes. * * Note: Could, but not must, extend by the child \phpseclib\Crypt\* class * * @access public * @param String $key */ function setKey($key) { $this->key = $key; $this->changed = true; } /** * Sets the password. * * Depending on what $method is set to, setPassword()'s (optional) parameters are as follows: * {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2} or pbkdf1: * $hash, $salt, $count, $dkLen * * Where $hash (default = sha1) currently supports the following hashes: see: Crypt/Hash.php * * Note: Could, but not must, extend by the child \phpseclib\Crypt\* class * * @see Crypt/Hash.php * @param String $password * @param optional String $method * @return Boolean * @access public */ function setPassword($password, $method = 'pbkdf2') { $key = ''; switch ($method) { default: // 'pbkdf2' or 'pbkdf1' $func_args = func_get_args(); // Hash function $hash = isset($func_args[2]) ? $func_args[2] : 'sha1'; // WPA and WPA2 use the SSID as the salt $salt = isset($func_args[3]) ? $func_args[3] : $this->password_default_salt; // RFC2898#section-4.2 uses 1,000 iterations by default // WPA and WPA2 use 4,096. $count = isset($func_args[4]) ? $func_args[4] : 1000; // Keylength if (isset($func_args[5])) { $dkLen = $func_args[5]; } else { $dkLen = $method == 'pbkdf1' ? 2 * $this->password_key_size : $this->password_key_size; } switch (true) { case $method == 'pbkdf1': $hashObj = new Hash(); $hashObj->setHash($hash); if ($dkLen > $hashObj->getLength()) { user_error('Derived key too long'); return false; } $t = $password . $salt; for ($i = 0; $i < $count; ++$i) { $t = $hashObj->hash($t); } $key = substr($t, 0, $dkLen); $this->setKey(substr($key, 0, $dkLen >> 1)); $this->setIV(substr($key, $dkLen >> 1)); return true; // Determining if php[>=5.5.0]'s hash_pbkdf2() function avail- and useable case !function_exists('hash_pbkdf2'): case !function_exists('hash_algos'): case !in_array($hash, hash_algos()): $i = 1; while (strlen($key) < $dkLen) { $hmac = new Hash(); $hmac->setHash($hash); $hmac->setKey($password); $f = $u = $hmac->hash($salt . pack('N', $i++)); for ($j = 2; $j <= $count; ++$j) { $u = $hmac->hash($u); $f^= $u; } $key.= $f; } $key = substr($key, 0, $dkLen); break; default: $key = hash_pbkdf2($hash, $password, $salt, $count, $dkLen, true); } } $this->setKey($key); return true; } /** * Encrypts a message. * * $plaintext will be padded with additional bytes such that it's length is a multiple of the block size. Other cipher * implementations may or may not pad in the same manner. Other common approaches to padding and the reasons why it's * necessary are discussed in the following * URL: * * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html} * * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does. * strlen($plaintext) will still need to be a multiple of the block size, however, arbitrary values can be added to make it that * length. * * Note: Could, but not must, extend by the child \phpseclib\Crypt\* class * * @see \phpseclib\Crypt\Base::decrypt() * @access public * @param String $plaintext * @return String $cipertext */ function encrypt($plaintext) { if ($this->engine == self::ENGINE_MCRYPT) { if ($this->changed) { $this->_setupMcrypt(); $this->changed = false; } if ($this->enchanged) { mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV); $this->enchanged = false; } // re: {@link http://phpseclib.sourceforge.net/cfb-demo.phps} // using mcrypt's default handing of CFB the above would output two different things. using phpseclib's // rewritten CFB implementation the above outputs the same thing twice. if ($this->mode == self::MODE_CFB && $this->continuousBuffer) { $block_size = $this->block_size; $iv = &$this->encryptIV; $pos = &$this->enbuffer['pos']; $len = strlen($plaintext); $ciphertext = ''; $i = 0; if ($pos) { $orig_pos = $pos; $max = $block_size - $pos; if ($len >= $max) { $i = $max; $len-= $max; $pos = 0; } else { $i = $len; $pos+= $len; $len = 0; } $ciphertext = substr($iv, $orig_pos) ^ $plaintext; $iv = substr_replace($iv, $ciphertext, $orig_pos, $i); $this->enbuffer['enmcrypt_init'] = true; } if ($len >= $block_size) { if ($this->enbuffer['enmcrypt_init'] === false || $len > $this->cfb_init_len) { if ($this->enbuffer['enmcrypt_init'] === true) { mcrypt_generic_init($this->enmcrypt, $this->key, $iv); $this->enbuffer['enmcrypt_init'] = false; } $ciphertext.= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % $block_size)); $iv = substr($ciphertext, -$block_size); $len%= $block_size; } else { while ($len >= $block_size) { $iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, $block_size); $ciphertext.= $iv; $len-= $block_size; $i+= $block_size; } } } if ($len) { $iv = mcrypt_generic($this->ecb, $iv); $block = $iv ^ substr($plaintext, -$len); $iv = substr_replace($iv, $block, 0, $len); $ciphertext.= $block; $pos = $len; } return $ciphertext; } if ($this->paddable) { $plaintext = $this->_pad($plaintext); } $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext); if (!$this->continuousBuffer) { mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV); } return $ciphertext; } if ($this->changed) { $this->_setup(); $this->changed = false; } if ($this->use_inline_crypt) { $inline = $this->inline_crypt; return $inline('encrypt', $this, $plaintext); } if ($this->paddable) { $plaintext = $this->_pad($plaintext); } $buffer = &$this->enbuffer; $block_size = $this->block_size; $ciphertext = ''; switch ($this->mode) { case self::MODE_ECB: for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { $ciphertext.= $this->_encryptBlock(substr($plaintext, $i, $block_size)); } break; case self::MODE_CBC: $xor = $this->encryptIV; for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { $block = substr($plaintext, $i, $block_size); $block = $this->_encryptBlock($block ^ $xor); $xor = $block; $ciphertext.= $block; } if ($this->continuousBuffer) { $this->encryptIV = $xor; } break; case self::MODE_CTR: $xor = $this->encryptIV; if (strlen($buffer['encrypted'])) { for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { $block = substr($plaintext, $i, $block_size); if (strlen($block) > strlen($buffer['encrypted'])) { $buffer['encrypted'].= $this->_encryptBlock($this->_generateXor($xor, $block_size)); } $key = $this->_stringShift($buffer['encrypted'], $block_size); $ciphertext.= $block ^ $key; } } else { for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { $block = substr($plaintext, $i, $block_size); $key = $this->_encryptBlock($this->_generateXor($xor, $block_size)); $ciphertext.= $block ^ $key; } } if ($this->continuousBuffer) { $this->encryptIV = $xor; if ($start = strlen($plaintext) % $block_size) { $buffer['encrypted'] = substr($key, $start) . $buffer['encrypted']; } } break; case self::MODE_CFB: // cfb loosely routines inspired by openssl's: // {@link http://cvs.openssl.org/fileview?f=openssl/crypto/modes/cfb128.c&v=1.3.2.2.2.1} if ($this->continuousBuffer) { $iv = &$this->encryptIV; $pos = &$buffer['pos']; } else { $iv = $this->encryptIV; $pos = 0; } $len = strlen($plaintext); $i = 0; if ($pos) { $orig_pos = $pos; $max = $block_size - $pos; if ($len >= $max) { $i = $max; $len-= $max; $pos = 0; } else { $i = $len; $pos+= $len; $len = 0; } // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize $ciphertext = substr($iv, $orig_pos) ^ $plaintext; $iv = substr_replace($iv, $ciphertext, $orig_pos, $i); } while ($len >= $block_size) { $iv = $this->_encryptBlock($iv) ^ substr($plaintext, $i, $block_size); $ciphertext.= $iv; $len-= $block_size; $i+= $block_size; } if ($len) { $iv = $this->_encryptBlock($iv); $block = $iv ^ substr($plaintext, $i); $iv = substr_replace($iv, $block, 0, $len); $ciphertext.= $block; $pos = $len; } break; case self::MODE_OFB: $xor = $this->encryptIV; if (strlen($buffer['xor'])) { for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { $block = substr($plaintext, $i, $block_size); if (strlen($block) > strlen($buffer['xor'])) { $xor = $this->_encryptBlock($xor); $buffer['xor'].= $xor; } $key = $this->_stringShift($buffer['xor'], $block_size); $ciphertext.= $block ^ $key; } } else { for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { $xor = $this->_encryptBlock($xor); $ciphertext.= substr($plaintext, $i, $block_size) ^ $xor; } $key = $xor; } if ($this->continuousBuffer) { $this->encryptIV = $xor; if ($start = strlen($plaintext) % $block_size) { $buffer['xor'] = substr($key, $start) . $buffer['xor']; } } break; case self::MODE_STREAM: $ciphertext = $this->_encryptBlock($plaintext); break; } return $ciphertext; } /** * Decrypts a message. * * If strlen($ciphertext) is not a multiple of the block size, null bytes will be added to the end of the string until * it is. * * Note: Could, but not must, extend by the child \phpseclib\Crypt\* class * * @see \phpseclib\Crypt\Base::encrypt() * @access public * @param String $ciphertext * @return String $plaintext */ function decrypt($ciphertext) { if ($this->engine == self::ENGINE_MCRYPT) { $block_size = $this->block_size; if ($this->changed) { $this->_setupMcrypt(); $this->changed = false; } if ($this->dechanged) { mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV); $this->dechanged = false; } if ($this->mode == self::MODE_CFB && $this->continuousBuffer) { $iv = &$this->decryptIV; $pos = &$this->debuffer['pos']; $len = strlen($ciphertext); $plaintext = ''; $i = 0; if ($pos) { $orig_pos = $pos; $max = $block_size - $pos; if ($len >= $max) { $i = $max; $len-= $max; $pos = 0; } else { $i = $len; $pos+= $len; $len = 0; } // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize $plaintext = substr($iv, $orig_pos) ^ $ciphertext; $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i); } if ($len >= $block_size) { $cb = substr($ciphertext, $i, $len - $len % $block_size); $plaintext.= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb; $iv = substr($cb, -$block_size); $len%= $block_size; } if ($len) { $iv = mcrypt_generic($this->ecb, $iv); $plaintext.= $iv ^ substr($ciphertext, -$len); $iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len); $pos = $len; } return $plaintext; } if ($this->paddable) { // we pad with chr(0) since that's what mcrypt_generic does. to quote from {@link http://www.php.net/function.mcrypt-generic}: // "The data is padded with "\0" to make sure the length of the data is n * blocksize." $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($block_size - strlen($ciphertext) % $block_size) % $block_size, chr(0)); } $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext); if (!$this->continuousBuffer) { mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV); } return $this->paddable ? $this->_unpad($plaintext) : $plaintext; } if ($this->changed) { $this->_setup(); $this->changed = false; } if ($this->use_inline_crypt) { $inline = $this->inline_crypt; return $inline('decrypt', $this, $ciphertext); } $block_size = $this->block_size; if ($this->paddable) { // we pad with chr(0) since that's what mcrypt_generic does [...] $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($block_size - strlen($ciphertext) % $block_size) % $block_size, chr(0)); } $buffer = &$this->debuffer; $plaintext = ''; switch ($this->mode) { case self::MODE_ECB: for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) { $plaintext.= $this->_decryptBlock(substr($ciphertext, $i, $block_size)); } break; case self::MODE_CBC: $xor = $this->decryptIV; for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) { $block = substr($ciphertext, $i, $block_size); $plaintext.= $this->_decryptBlock($block) ^ $xor; $xor = $block; } if ($this->continuousBuffer) { $this->decryptIV = $xor; } break; case self::MODE_CTR: $xor = $this->decryptIV; if (strlen($buffer['ciphertext'])) { for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) { $block = substr($ciphertext, $i, $block_size); if (strlen($block) > strlen($buffer['ciphertext'])) { $buffer['ciphertext'].= $this->_encryptBlock($this->_generateXor($xor, $block_size)); } $key = $this->_stringShift($buffer['ciphertext'], $block_size); $plaintext.= $block ^ $key; } } else { for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) { $block = substr($ciphertext, $i, $block_size); $key = $this->_encryptBlock($this->_generateXor($xor, $block_size)); $plaintext.= $block ^ $key; } } if ($this->continuousBuffer) { $this->decryptIV = $xor; if ($start = strlen($ciphertext) % $block_size) { $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext']; } } break; case self::MODE_CFB: if ($this->continuousBuffer) { $iv = &$this->decryptIV; $pos = &$buffer['pos']; } else { $iv = $this->decryptIV; $pos = 0; } $len = strlen($ciphertext); $i = 0; if ($pos) { $orig_pos = $pos; $max = $block_size - $pos; if ($len >= $max) { $i = $max; $len-= $max; $pos = 0; } else { $i = $len; $pos+= $len; $len = 0; } // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize $plaintext = substr($iv, $orig_pos) ^ $ciphertext; $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i); } while ($len >= $block_size) { $iv = $this->_encryptBlock($iv); $cb = substr($ciphertext, $i, $block_size); $plaintext.= $iv ^ $cb; $iv = $cb; $len-= $block_size; $i+= $block_size; } if ($len) { $iv = $this->_encryptBlock($iv); $plaintext.= $iv ^ substr($ciphertext, $i); $iv = substr_replace($iv, substr($ciphertext, $i), 0, $len); $pos = $len; } break; case self::MODE_OFB: $xor = $this->decryptIV; if (strlen($buffer['xor'])) { for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) { $block = substr($ciphertext, $i, $block_size); if (strlen($block) > strlen($buffer['xor'])) { $xor = $this->_encryptBlock($xor); $buffer['xor'].= $xor; } $key = $this->_stringShift($buffer['xor'], $block_size); $plaintext.= $block ^ $key; } } else { for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) { $xor = $this->_encryptBlock($xor); $plaintext.= substr($ciphertext, $i, $block_size) ^ $xor; } $key = $xor; } if ($this->continuousBuffer) { $this->decryptIV = $xor; if ($start = strlen($ciphertext) % $block_size) { $buffer['xor'] = substr($key, $start) . $buffer['xor']; } } break; case self::MODE_STREAM: $plaintext = $this->_decryptBlock($ciphertext); break; } return $this->paddable ? $this->_unpad($plaintext) : $plaintext; } /** * Pad "packets". * * Block ciphers working by encrypting between their specified [$this->]block_size at a time * If you ever need to encrypt or decrypt something that isn't of the proper length, it becomes necessary to * pad the input so that it is of the proper length. * * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH, * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is * transmitted separately) * * @see \phpseclib\Crypt\Base::disablePadding() * @access public */ function enablePadding() { $this->padding = true; } /** * Do not pad packets. * * @see \phpseclib\Crypt\Base::enablePadding() * @access public */ function disablePadding() { $this->padding = false; } /** * Treat consecutive "packets" as if they are a continuous buffer. * * Say you have a 32-byte plaintext $plaintext. Using the default behavior, the two following code snippets * will yield different outputs: * * * echo $rijndael->encrypt(substr($plaintext, 0, 16)); * echo $rijndael->encrypt(substr($plaintext, 16, 16)); * * * echo $rijndael->encrypt($plaintext); * * * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates * another, as demonstrated with the following: * * * $rijndael->encrypt(substr($plaintext, 0, 16)); * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16))); * * * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16))); * * * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different * outputs. The reason is due to the fact that the initialization vector's change after every encryption / * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant. * * Put another way, when the continuous buffer is enabled, the state of the \phpseclib\Crypt\*() object changes after each * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them), * however, they are also less intuitive and more likely to cause you problems. * * Note: Could, but not must, extend by the child \phpseclib\Crypt\* class * * @see \phpseclib\Crypt\Base::disableContinuousBuffer() * @access public */ function enableContinuousBuffer() { if ($this->mode == self::MODE_ECB) { return; } $this->continuousBuffer = true; } /** * Treat consecutive packets as if they are a discontinuous buffer. * * The default behavior. * * Note: Could, but not must, extend by the child \phpseclib\Crypt\* class * * @see \phpseclib\Crypt\Base::enableContinuousBuffer() * @access public */ function disableContinuousBuffer() { if ($this->mode == self::MODE_ECB) { return; } if (!$this->continuousBuffer) { return; } $this->continuousBuffer = false; $this->changed = true; } /** * Encrypts a block * * Note: Must extend by the child \phpseclib\Crypt\* class * * @access private * @param String $in * @return String */ function _encryptBlock($in) { user_error(__METHOD__ . '() must extend by class ' . get_class($this), E_USER_ERROR); } /** * Decrypts a block * * Note: Must extend by the child \phpseclib\Crypt\* class * * @access private * @param String $in * @return String */ function _decryptBlock($in) { user_error(__METHOD__ . '() must extend by class ' . get_class($this), E_USER_ERROR); } /** * Setup the key (expansion) * * Only used if $engine == self::ENGINE_INTERNAL * * Note: Must extend by the child \phpseclib\Crypt\* class * * @see \phpseclib\Crypt\Base::_setup() * @access private */ function _setupKey() { user_error(__METHOD__ . '() must extend by class ' . get_class($this), E_USER_ERROR); } /** * Setup the self::ENGINE_INTERNAL $engine * * (re)init, if necessary, the internal cipher $engine and flush all $buffers * Used (only) if $engine == self::ENGINE_INTERNAL * * _setup() will be called each time if $changed === true * typically this happens when using one or more of following public methods: * * - setKey() * * - setIV() * * - disableContinuousBuffer() * * - First run of encrypt() / decrypt() with no init-settings * * Internally: _setup() is called always before(!) en/decryption. * * Note: Could, but not must, extend by the child \phpseclib\Crypt\* class * * @see setKey() * @see setIV() * @see disableContinuousBuffer() * @access private */ function _setup() { $this->_clearBuffers(); $this->_setupKey(); if ($this->use_inline_crypt) { $this->_setupInlineCrypt(); } } /** * Setup the self::ENGINE_MCRYPT $engine * * (re)init, if necessary, the (ext)mcrypt resources and flush all $buffers * Used (only) if $engine = self::ENGINE_MCRYPT * * _setupMcrypt() will be called each time if $changed === true * typically this happens when using one or more of following public methods: * * - setKey() * * - setIV() * * - disableContinuousBuffer() * * - First run of encrypt() / decrypt() * * * Note: Could, but not must, extend by the child \phpseclib\Crypt\* class * * @see setKey() * @see setIV() * @see disableContinuousBuffer() * @access private */ function _setupMcrypt() { $this->_clearBuffers(); $this->enchanged = $this->dechanged = true; if (!isset($this->enmcrypt)) { static $mcrypt_modes = array( self::MODE_CTR => 'ctr', self::MODE_ECB => MCRYPT_MODE_ECB, self::MODE_CBC => MCRYPT_MODE_CBC, self::MODE_CFB => 'ncfb', self::MODE_OFB => MCRYPT_MODE_NOFB, self::MODE_STREAM => MCRYPT_MODE_STREAM, ); $this->demcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], ''); $this->enmcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], ''); // we need the $ecb mcrypt resource (only) in MODE_CFB with enableContinuousBuffer() // to workaround mcrypt's broken ncfb implementation in buffered mode // see: {@link http://phpseclib.sourceforge.net/cfb-demo.phps} if ($this->mode == self::MODE_CFB) { $this->ecb = mcrypt_module_open($this->cipher_name_mcrypt, '', MCRYPT_MODE_ECB, ''); } } // else should mcrypt_generic_deinit be called? if ($this->mode == self::MODE_CFB) { mcrypt_generic_init($this->ecb, $this->key, str_repeat("\0", $this->block_size)); } } /** * Pads a string * * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize. * $this->block_size - (strlen($text) % $this->block_size) bytes are added, each of which is equal to * chr($this->block_size - (strlen($text) % $this->block_size) * * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless * and padding will, hence forth, be enabled. * * @see \phpseclib\Crypt\Base::_unpad() * @param String $text * @access private * @return String */ function _pad($text) { $length = strlen($text); if (!$this->padding) { if ($length % $this->block_size == 0) { return $text; } else { user_error("The plaintext's length ($length) is not a multiple of the block size ({$this->block_size})"); $this->padding = true; } } $pad = $this->block_size - ($length % $this->block_size); return str_pad($text, $length + $pad, chr($pad)); } /** * Unpads a string. * * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong * and false will be returned. * * @see \phpseclib\Crypt\Base::_pad() * @param String $text * @access private * @return String */ function _unpad($text) { if (!$this->padding) { return $text; } $length = ord($text[strlen($text) - 1]); if (!$length || $length > $this->block_size) { return false; } return substr($text, 0, -$length); } /** * Clears internal buffers * * Clearing/resetting the internal buffers is done everytime * after disableContinuousBuffer() or on cipher $engine (re)init * ie after setKey() or setIV() * * Note: Could, but not must, extend by the child \phpseclib\Crypt\* class * * @access public */ function _clearBuffers() { $this->enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true); $this->debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'demcrypt_init' => true); // mcrypt's handling of invalid's $iv: // $this->encryptIV = $this->decryptIV = strlen($this->iv) == $this->block_size ? $this->iv : str_repeat("\0", $this->block_size); $this->encryptIV = $this->decryptIV = str_pad(substr($this->iv, 0, $this->block_size), $this->block_size, "\0"); } /** * String Shift * * Inspired by array_shift * * @param String $string * @param optional Integer $index * @access private * @return String */ function _stringShift(&$string, $index = 1) { $substr = substr($string, 0, $index); $string = substr($string, $index); return $substr; } /** * Generate CTR XOR encryption key * * Encrypt the output of this and XOR it against the ciphertext / plaintext to get the * plaintext / ciphertext in CTR mode. * * @see \phpseclib\Crypt\Base::decrypt() * @see \phpseclib\Crypt\Base::encrypt() * @param String $iv * @param Integer $length * @access private * @return String $xor */ function _generateXor(&$iv, $length) { $xor = ''; $block_size = $this->block_size; $num_blocks = floor(($length + ($block_size - 1)) / $block_size); for ($i = 0; $i < $num_blocks; $i++) { $xor.= $iv; for ($j = 4; $j <= $block_size; $j+= 4) { $temp = substr($iv, -$j, 4); switch ($temp) { case "\xFF\xFF\xFF\xFF": $iv = substr_replace($iv, "\x00\x00\x00\x00", -$j, 4); break; case "\x7F\xFF\xFF\xFF": $iv = substr_replace($iv, "\x80\x00\x00\x00", -$j, 4); break 2; default: extract(unpack('Ncount', $temp)); $iv = substr_replace($iv, pack('N', $count + 1), -$j, 4); break 2; } } } return $xor; } /** * Setup the performance-optimized function for de/encrypt() * * Stores the created (or existing) callback function-name * in $this->inline_crypt * * Internally for phpseclib developers: * * _setupInlineCrypt() would be called only if: * * - $engine == self::ENGINE_INTERNAL and * * - $use_inline_crypt === true * * - each time on _setup(), after(!) _setupKey() * * * This ensures that _setupInlineCrypt() has always a * full ready2go initializated internal cipher $engine state * where, for example, the keys allready expanded, * keys/block_size calculated and such. * * It is, each time if called, the responsibility of _setupInlineCrypt(): * * - to set $this->inline_crypt to a valid and fully working callback function * as a (faster) replacement for encrypt() / decrypt() * * - NOT to create unlimited callback functions (for memory reasons!) * no matter how often _setupInlineCrypt() would be called. At some * point of amount they must be generic re-useable. * * - the code of _setupInlineCrypt() it self, * and the generated callback code, * must be, in following order: * - 100% safe * - 100% compatible to encrypt()/decrypt() * - using only php5+ features/lang-constructs/php-extensions if * compatibility (down to php4) or fallback is provided * - readable/maintainable/understandable/commented and... not-cryptic-styled-code :-) * - >= 10% faster than encrypt()/decrypt() [which is, by the way, * the reason for the existence of _setupInlineCrypt() :-)] * - memory-nice * - short (as good as possible) * * Note: - _setupInlineCrypt() is using _createInlineCryptFunction() to create the full callback function code. * - In case of using inline crypting, _setupInlineCrypt() must extend by the child \phpseclib\Crypt\* class. * - The following variable names are reserved: * - $_* (all variable names prefixed with an underscore) * - $self (object reference to it self. Do not use $this, but $self instead) * - $in (the content of $in has to en/decrypt by the generated code) * - The callback function should not use the 'return' statement, but en/decrypt'ing the content of $in only * * * @see \phpseclib\Crypt\Base::_setup() * @see \phpseclib\Crypt\Base::_createInlineCryptFunction() * @see \phpseclib\Crypt\Base::encrypt() * @see \phpseclib\Crypt\Base::decrypt() * @access private */ function _setupInlineCrypt() { // If a \phpseclib\Crypt\* class providing inline crypting it must extend _setupInlineCrypt() // If, for any reason, an extending \phpseclib\Crypt\Base() \phpseclib\Crypt\* class // not using inline crypting then it must be ensured that: $this->use_inline_crypt = false // ie in the class var declaration of $use_inline_crypt in general for the \phpseclib\Crypt\* class, // in the constructor at object instance-time // or, if it's runtime-specific, at runtime $this->use_inline_crypt = false; } /** * Creates the performance-optimized function for en/decrypt() * * Internally for phpseclib developers: * * _createInlineCryptFunction(): * * - merge the $cipher_code [setup'ed by _setupInlineCrypt()] * with the current [$this->]mode of operation code * * - create the $inline function, which called by encrypt() / decrypt() * as its replacement to speed up the en/decryption operations. * * - return the name of the created $inline callback function * * - used to speed up en/decryption * * * * The main reason why can speed up things [up to 50%] this way are: * * - using variables more effective then regular. * (ie no use of expensive arrays but integers $k_0, $k_1 ... * or even, for example, the pure $key[] values hardcoded) * * - avoiding 1000's of function calls of ie _encryptBlock() * but inlining the crypt operations. * in the mode of operation for() loop. * * - full loop unroll the (sometimes key-dependent) rounds * avoiding this way ++$i counters and runtime-if's etc... * * The basic code architectur of the generated $inline en/decrypt() * lambda function, in pseudo php, is: * * * +----------------------------------------------------------------------------------------------+ * | callback $inline = create_function: | * | lambda_function_0001_crypt_ECB($action, $text) | * | { | * | INSERT PHP CODE OF: | * | $cipher_code['init_crypt']; // general init code. | * | // ie: $sbox'es declarations used for | * | // encrypt and decrypt'ing. | * | | * | switch ($action) { | * | case 'encrypt': | * | INSERT PHP CODE OF: | * | $cipher_code['init_encrypt']; // encrypt sepcific init code. | * | ie: specified $key or $box | * | declarations for encrypt'ing. | * | | * | foreach ($ciphertext) { | * | $in = $block_size of $ciphertext; | * | | * | INSERT PHP CODE OF: | * | $cipher_code['encrypt_block']; // encrypt's (string) $in, which is always: | * | // strlen($in) == $this->block_size | * | // here comes the cipher algorithm in action | * | // for encryption. | * | // $cipher_code['encrypt_block'] has to | * | // encrypt the content of the $in variable | * | | * | $plaintext .= $in; | * | } | * | return $plaintext; | * | | * | case 'decrypt': | * | INSERT PHP CODE OF: | * | $cipher_code['init_decrypt']; // decrypt sepcific init code | * | ie: specified $key or $box | * | declarations for decrypt'ing. | * | foreach ($plaintext) { | * | $in = $block_size of $plaintext; | * | | * | INSERT PHP CODE OF: | * | $cipher_code['decrypt_block']; // decrypt's (string) $in, which is always | * | // strlen($in) == $this->block_size | * | // here comes the cipher algorithm in action | * | // for decryption. | * | // $cipher_code['decrypt_block'] has to | * | // decrypt the content of the $in variable | * | $ciphertext .= $in; | * | } | * | return $ciphertext; | * | } | * | } | * +----------------------------------------------------------------------------------------------+ * * * See also the \phpseclib\Crypt\*::_setupInlineCrypt()'s for * productive inline $cipher_code's how they works. * * Structure of: * * $cipher_code = array( * 'init_crypt' => (string) '', // optional * 'init_encrypt' => (string) '', // optional * 'init_decrypt' => (string) '', // optional * 'encrypt_block' => (string) '', // required * 'decrypt_block' => (string) '' // required * ); * * * @see \phpseclib\Crypt\Base::_setupInlineCrypt() * @see \phpseclib\Crypt\Base::encrypt() * @see \phpseclib\Crypt\Base::decrypt() * @param Array $cipher_code * @access private * @return String (the name of the created callback function) */ function _createInlineCryptFunction($cipher_code) { $block_size = $this->block_size; // optional $init_crypt = isset($cipher_code['init_crypt']) ? $cipher_code['init_crypt'] : ''; $init_encrypt = isset($cipher_code['init_encrypt']) ? $cipher_code['init_encrypt'] : ''; $init_decrypt = isset($cipher_code['init_decrypt']) ? $cipher_code['init_decrypt'] : ''; // required $encrypt_block = $cipher_code['encrypt_block']; $decrypt_block = $cipher_code['decrypt_block']; // Generating mode of operation inline code, // merged with the $cipher_code algorithm // for encrypt- and decryption. switch ($this->mode) { case self::MODE_ECB: $encrypt = $init_encrypt . ' $_ciphertext = ""; $_text = $self->_pad($_text); $_plaintext_len = strlen($_text); for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') { $in = substr($_text, $_i, '.$block_size.'); '.$encrypt_block.' $_ciphertext.= $in; } return $_ciphertext; '; $decrypt = $init_decrypt . ' $_plaintext = ""; $_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0)); $_ciphertext_len = strlen($_text); for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') { $in = substr($_text, $_i, '.$block_size.'); '.$decrypt_block.' $_plaintext.= $in; } return $self->_unpad($_plaintext); '; break; case self::MODE_CTR: $encrypt = $init_encrypt . ' $_ciphertext = ""; $_plaintext_len = strlen($_text); $_xor = $self->encryptIV; $_buffer = &$self->enbuffer; if (strlen($_buffer["encrypted"])) { for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') { $_block = substr($_text, $_i, '.$block_size.'); if (strlen($_block) > strlen($_buffer["encrypted"])) { $in = $self->_generateXor($_xor, '.$block_size.'); '.$encrypt_block.' $_buffer["encrypted"].= $in; } $_key = $self->_stringShift($_buffer["encrypted"], '.$block_size.'); $_ciphertext.= $_block ^ $_key; } } else { for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') { $_block = substr($_text, $_i, '.$block_size.'); $in = $self->_generateXor($_xor, '.$block_size.'); '.$encrypt_block.' $_key = $in; $_ciphertext.= $_block ^ $_key; } } if ($self->continuousBuffer) { $self->encryptIV = $_xor; if ($_start = $_plaintext_len % '.$block_size.') { $_buffer["encrypted"] = substr($_key, $_start) . $_buffer["encrypted"]; } } return $_ciphertext; '; $decrypt = $init_encrypt . ' $_plaintext = ""; $_ciphertext_len = strlen($_text); $_xor = $self->decryptIV; $_buffer = &$self->debuffer; if (strlen($_buffer["ciphertext"])) { for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') { $_block = substr($_text, $_i, '.$block_size.'); if (strlen($_block) > strlen($_buffer["ciphertext"])) { $in = $self->_generateXor($_xor, '.$block_size.'); '.$encrypt_block.' $_buffer["ciphertext"].= $in; } $_key = $self->_stringShift($_buffer["ciphertext"], '.$block_size.'); $_plaintext.= $_block ^ $_key; } } else { for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') { $_block = substr($_text, $_i, '.$block_size.'); $in = $self->_generateXor($_xor, '.$block_size.'); '.$encrypt_block.' $_key = $in; $_plaintext.= $_block ^ $_key; } } if ($self->continuousBuffer) { $self->decryptIV = $_xor; if ($_start = $_ciphertext_len % '.$block_size.') { $_buffer["ciphertext"] = substr($_key, $_start) . $_buffer["ciphertext"]; } } return $_plaintext; '; break; case self::MODE_CFB: $encrypt = $init_encrypt . ' $_ciphertext = ""; $_buffer = &$self->enbuffer; if ($self->continuousBuffer) { $_iv = &$self->encryptIV; $_pos = &$_buffer["pos"]; } else { $_iv = $self->encryptIV; $_pos = 0; } $_len = strlen($_text); $_i = 0; if ($_pos) { $_orig_pos = $_pos; $_max = '.$block_size.' - $_pos; if ($_len >= $_max) { $_i = $_max; $_len-= $_max; $_pos = 0; } else { $_i = $_len; $_pos+= $_len; $_len = 0; } $_ciphertext = substr($_iv, $_orig_pos) ^ $_text; $_iv = substr_replace($_iv, $_ciphertext, $_orig_pos, $_i); } while ($_len >= '.$block_size.') { $in = $_iv; '.$encrypt_block.'; $_iv = $in ^ substr($_text, $_i, '.$block_size.'); $_ciphertext.= $_iv; $_len-= '.$block_size.'; $_i+= '.$block_size.'; } if ($_len) { $in = $_iv; '.$encrypt_block.' $_iv = $in; $_block = $_iv ^ substr($_text, $_i); $_iv = substr_replace($_iv, $_block, 0, $_len); $_ciphertext.= $_block; $_pos = $_len; } return $_ciphertext; '; $decrypt = $init_encrypt . ' $_plaintext = ""; $_buffer = &$self->debuffer; if ($self->continuousBuffer) { $_iv = &$self->decryptIV; $_pos = &$_buffer["pos"]; } else { $_iv = $self->decryptIV; $_pos = 0; } $_len = strlen($_text); $_i = 0; if ($_pos) { $_orig_pos = $_pos; $_max = '.$block_size.' - $_pos; if ($_len >= $_max) { $_i = $_max; $_len-= $_max; $_pos = 0; } else { $_i = $_len; $_pos+= $_len; $_len = 0; } $_plaintext = substr($_iv, $_orig_pos) ^ $_text; $_iv = substr_replace($_iv, substr($_text, 0, $_i), $_orig_pos, $_i); } while ($_len >= '.$block_size.') { $in = $_iv; '.$encrypt_block.' $_iv = $in; $cb = substr($_text, $_i, '.$block_size.'); $_plaintext.= $_iv ^ $cb; $_iv = $cb; $_len-= '.$block_size.'; $_i+= '.$block_size.'; } if ($_len) { $in = $_iv; '.$encrypt_block.' $_iv = $in; $_plaintext.= $_iv ^ substr($_text, $_i); $_iv = substr_replace($_iv, substr($_text, $_i), 0, $_len); $_pos = $_len; } return $_plaintext; '; break; case self::MODE_OFB: $encrypt = $init_encrypt . ' $_ciphertext = ""; $_plaintext_len = strlen($_text); $_xor = $self->encryptIV; $_buffer = &$self->enbuffer; if (strlen($_buffer["xor"])) { for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') { $_block = substr($_text, $_i, '.$block_size.'); if (strlen($_block) > strlen($_buffer["xor"])) { $in = $_xor; '.$encrypt_block.' $_xor = $in; $_buffer["xor"].= $_xor; } $_key = $self->_stringShift($_buffer["xor"], '.$block_size.'); $_ciphertext.= $_block ^ $_key; } } else { for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') { $in = $_xor; '.$encrypt_block.' $_xor = $in; $_ciphertext.= substr($_text, $_i, '.$block_size.') ^ $_xor; } $_key = $_xor; } if ($self->continuousBuffer) { $self->encryptIV = $_xor; if ($_start = $_plaintext_len % '.$block_size.') { $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"]; } } return $_ciphertext; '; $decrypt = $init_encrypt . ' $_plaintext = ""; $_ciphertext_len = strlen($_text); $_xor = $self->decryptIV; $_buffer = &$self->debuffer; if (strlen($_buffer["xor"])) { for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') { $_block = substr($_text, $_i, '.$block_size.'); if (strlen($_block) > strlen($_buffer["xor"])) { $in = $_xor; '.$encrypt_block.' $_xor = $in; $_buffer["xor"].= $_xor; } $_key = $self->_stringShift($_buffer["xor"], '.$block_size.'); $_plaintext.= $_block ^ $_key; } } else { for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') { $in = $_xor; '.$encrypt_block.' $_xor = $in; $_plaintext.= substr($_text, $_i, '.$block_size.') ^ $_xor; } $_key = $_xor; } if ($self->continuousBuffer) { $self->decryptIV = $_xor; if ($_start = $_ciphertext_len % '.$block_size.') { $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"]; } } return $_plaintext; '; break; case self::MODE_STREAM: $encrypt = $init_encrypt . ' $_ciphertext = ""; '.$encrypt_block.' return $_ciphertext; '; $decrypt = $init_decrypt . ' $_plaintext = ""; '.$decrypt_block.' return $_plaintext; '; break; // case self::MODE_CBC: default: $encrypt = $init_encrypt . ' $_ciphertext = ""; $_text = $self->_pad($_text); $_plaintext_len = strlen($_text); $in = $self->encryptIV; for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') { $in = substr($_text, $_i, '.$block_size.') ^ $in; '.$encrypt_block.' $_ciphertext.= $in; } if ($self->continuousBuffer) { $self->encryptIV = $in; } return $_ciphertext; '; $decrypt = $init_decrypt . ' $_plaintext = ""; $_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0)); $_ciphertext_len = strlen($_text); $_iv = $self->decryptIV; for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') { $in = $_block = substr($_text, $_i, '.$block_size.'); '.$decrypt_block.' $_plaintext.= $in ^ $_iv; $_iv = $_block; } if ($self->continuousBuffer) { $self->decryptIV = $_iv; } return $self->_unpad($_plaintext); '; break; } // Create the $inline function and return its name as string. Ready to run! return create_function('$_action, &$self, $_text', $init_crypt . 'if ($_action == "encrypt") { ' . $encrypt . ' } else { ' . $decrypt . ' }'); } /** * Holds the lambda_functions table (classwide) * * Each name of the lambda function, created from * _setupInlineCrypt() && _createInlineCryptFunction() * is stored, classwide (!), here for reusing. * * The string-based index of $function is a classwide * uniqe value representing, at least, the $mode of * operation (or more... depends of the optimizing level) * for which $mode the lambda function was created. * * @access private * @return &Array */ function &_getLambdaFunctions() { static $functions = array(); return $functions; } } * setKey('12345678901234567890123456789012'); * * $plaintext = str_repeat('a', 1024); * * echo $blowfish->decrypt($blowfish->encrypt($plaintext)); * ?> * * * @category Crypt * @package Blowfish * @author Jim Wigginton * @author Hans-Juergen Petrich * @copyright 2007 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\Crypt; use phpseclib\Crypt\Base; /** * Pure-PHP implementation of Blowfish. * * @package Blowfish * @author Jim Wigginton * @author Hans-Juergen Petrich * @access public */ class Blowfish extends Base { /** * Block Length of the cipher * * @see \phpseclib\Crypt\Base::block_size * @var Integer * @access private */ var $block_size = 8; /** * The default password key_size used by setPassword() * * @see \phpseclib\Crypt\Base::password_key_size * @see \phpseclib\Crypt\Base::setPassword() * @var Integer * @access private */ var $password_key_size = 56; /** * The namespace used by the cipher for its constants. * * @see \phpseclib\Crypt\Base::const_namespace * @var String * @access private */ var $const_namespace = 'BLOWFISH'; /** * The mcrypt specific name of the cipher * * @see \phpseclib\Crypt\Base::cipher_name_mcrypt * @var String * @access private */ var $cipher_name_mcrypt = 'blowfish'; /** * Optimizing value while CFB-encrypting * * @see \phpseclib\Crypt\Base::cfb_init_len * @var Integer * @access private */ var $cfb_init_len = 500; /** * The fixed subkeys boxes ($sbox0 - $sbox3) with 256 entries each * * S-Box 1 * * @access private * @var array */ var $sbox0 = array ( 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a ); /** * S-Box 1 * * @access private * @var array */ var $sbox1 = array( 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 ); /** * S-Box 2 * * @access private * @var array */ var $sbox2 = array( 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 ); /** * S-Box 3 * * @access private * @var array */ var $sbox3 = array( 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 ); /** * P-Array consists of 18 32-bit subkeys * * @var array $parray * @access private */ var $parray = array( 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b ); /** * The BCTX-working Array * * Holds the expanded key [p] and the key-depended s-boxes [sb] * * @var array $bctx * @access private */ var $bctx; /** * Holds the last used key * * @var Array * @access private */ var $kl; /** * Sets the key. * * Keys can be of any length. Blowfish, itself, requires the use of a key between 32 and max. 448-bits long. * If the key is less than 32-bits we NOT fill the key to 32bit but let the key as it is to be compatible * with mcrypt because mcrypt act this way with blowfish key's < 32 bits. * * If the key is more than 448-bits, we trim the excess bits. * * If the key is not explicitly set, or empty, it'll be assumed a 128 bits key to be all null bytes. * * @access public * @see \phpseclib\Crypt\Base::setKey() * @param String $key */ function setKey($key) { $keylength = strlen($key); if (!$keylength) { $key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; } elseif ($keylength > 56) { $key = substr($key, 0, 56); } parent::setKey($key); } /** * Setup the key (expansion) * * @see \phpseclib\Crypt\Base::_setupKey() * @access private */ function _setupKey() { if (isset($this->kl['key']) && $this->key === $this->kl['key']) { // already expanded return; } $this->kl = array('key' => $this->key); /* key-expanding p[] and S-Box building sb[] */ $this->bctx = array( 'p' => array(), 'sb' => array( $this->sbox0, $this->sbox1, $this->sbox2, $this->sbox3 ) ); // unpack binary string in unsigned chars $key = array_values(unpack('C*', $this->key)); $keyl = count($key); for ($j = 0, $i = 0; $i < 18; ++$i) { // xor P1 with the first 32-bits of the key, xor P2 with the second 32-bits ... for ($data = 0, $k = 0; $k < 4; ++$k) { $data = ($data << 8) | $key[$j]; if (++$j >= $keyl) { $j = 0; } } $this->bctx['p'][] = $this->parray[$i] ^ $data; } // encrypt the zero-string, replace P1 and P2 with the encrypted data, // encrypt P3 and P4 with the new P1 and P2, do it with all P-array and subkeys $data = "\0\0\0\0\0\0\0\0"; for ($i = 0; $i < 18; $i += 2) { list($l, $r) = array_values(unpack('N*', $data = $this->_encryptBlock($data))); $this->bctx['p'][$i ] = $l; $this->bctx['p'][$i + 1] = $r; } for ($i = 0; $i < 4; ++$i) { for ($j = 0; $j < 256; $j += 2) { list($l, $r) = array_values(unpack('N*', $data = $this->_encryptBlock($data))); $this->bctx['sb'][$i][$j ] = $l; $this->bctx['sb'][$i][$j + 1] = $r; } } } /** * Encrypts a block * * @access private * @param String $in * @return String */ function _encryptBlock($in) { $p = $this->bctx["p"]; // extract($this->bctx["sb"], EXTR_PREFIX_ALL, "sb"); // slower $sb_0 = $this->bctx["sb"][0]; $sb_1 = $this->bctx["sb"][1]; $sb_2 = $this->bctx["sb"][2]; $sb_3 = $this->bctx["sb"][3]; $in = unpack("N*", $in); $l = $in[1]; $r = $in[2]; for ($i = 0; $i < 16; $i+= 2) { $l^= $p[$i]; $r^= ($sb_0[$l >> 24 & 0xff] + $sb_1[$l >> 16 & 0xff] ^ $sb_2[$l >> 8 & 0xff]) + $sb_3[$l & 0xff]; $r^= $p[$i + 1]; $l^= ($sb_0[$r >> 24 & 0xff] + $sb_1[$r >> 16 & 0xff] ^ $sb_2[$r >> 8 & 0xff]) + $sb_3[$r & 0xff]; } return pack("N*", $r ^ $p[17], $l ^ $p[16]); } /** * Decrypts a block * * @access private * @param String $in * @return String */ function _decryptBlock($in) { $p = $this->bctx["p"]; $sb_0 = $this->bctx["sb"][0]; $sb_1 = $this->bctx["sb"][1]; $sb_2 = $this->bctx["sb"][2]; $sb_3 = $this->bctx["sb"][3]; $in = unpack("N*", $in); $l = $in[1]; $r = $in[2]; for ($i = 17; $i > 2; $i-= 2) { $l^= $p[$i]; $r^= ($sb_0[$l >> 24 & 0xff] + $sb_1[$l >> 16 & 0xff] ^ $sb_2[$l >> 8 & 0xff]) + $sb_3[$l & 0xff]; $r^= $p[$i - 1]; $l^= ($sb_0[$r >> 24 & 0xff] + $sb_1[$r >> 16 & 0xff] ^ $sb_2[$r >> 8 & 0xff]) + $sb_3[$r & 0xff]; } return pack("N*", $r ^ $p[0], $l ^ $p[1]); } /** * Setup the performance-optimized function for de/encrypt() * * @see \phpseclib\Crypt\Base::_setupInlineCrypt() * @access private */ function _setupInlineCrypt() { $lambda_functions =& self::_getLambdaFunctions(); // We create max. 10 hi-optimized code for memory reason. Means: For each $key one ultra fast inline-crypt function. // After that, we'll still create very fast optimized code but not the hi-ultimative code, for each $mode one. $gen_hi_opt_code = (bool)( count($lambda_functions) < 10); switch (true) { case $gen_hi_opt_code: $code_hash = md5(str_pad("Blowfish, {$this->mode}, ", 32, "\0") . $this->key); break; default: $code_hash = "Blowfish, {$this->mode}"; } if (!isset($lambda_functions[$code_hash])) { switch (true) { case $gen_hi_opt_code: $p = $this->bctx['p']; $init_crypt = ' static $sb_0, $sb_1, $sb_2, $sb_3; if (!$sb_0) { $sb_0 = $self->bctx["sb"][0]; $sb_1 = $self->bctx["sb"][1]; $sb_2 = $self->bctx["sb"][2]; $sb_3 = $self->bctx["sb"][3]; } '; break; default: $p = array(); for ($i = 0; $i < 18; ++$i) { $p[] = '$p_' . $i; } $init_crypt = ' list($sb_0, $sb_1, $sb_2, $sb_3) = $self->bctx["sb"]; list(' . implode(',', $p) . ') = $self->bctx["p"]; '; } // Generating encrypt code: $encrypt_block = ' $in = unpack("N*", $in); $l = $in[1]; $r = $in[2]; '; for ($i = 0; $i < 16; $i+= 2) { $encrypt_block.= ' $l^= ' . $p[$i] . '; $r^= ($sb_0[$l >> 24 & 0xff] + $sb_1[$l >> 16 & 0xff] ^ $sb_2[$l >> 8 & 0xff]) + $sb_3[$l & 0xff]; $r^= ' . $p[$i + 1] . '; $l^= ($sb_0[$r >> 24 & 0xff] + $sb_1[$r >> 16 & 0xff] ^ $sb_2[$r >> 8 & 0xff]) + $sb_3[$r & 0xff]; '; } $encrypt_block.= ' $in = pack("N*", $r ^ ' . $p[17] . ', $l ^ ' . $p[16] . ' ); '; // Generating decrypt code: $decrypt_block = ' $in = unpack("N*", $in); $l = $in[1]; $r = $in[2]; '; for ($i = 17; $i > 2; $i-= 2) { $decrypt_block.= ' $l^= ' . $p[$i] . '; $r^= ($sb_0[$l >> 24 & 0xff] + $sb_1[$l >> 16 & 0xff] ^ $sb_2[$l >> 8 & 0xff]) + $sb_3[$l & 0xff]; $r^= ' . $p[$i - 1] . '; $l^= ($sb_0[$r >> 24 & 0xff] + $sb_1[$r >> 16 & 0xff] ^ $sb_2[$r >> 8 & 0xff]) + $sb_3[$r & 0xff]; '; } $decrypt_block.= ' $in = pack("N*", $r ^ ' . $p[0] . ', $l ^ ' . $p[1] . ' ); '; $lambda_functions[$code_hash] = $this->_createInlineCryptFunction( array( 'init_crypt' => $init_crypt, 'init_encrypt' => '', 'init_decrypt' => '', 'encrypt_block' => $encrypt_block, 'decrypt_block' => $decrypt_block ) ); } $this->inline_crypt = $lambda_functions[$code_hash]; } } * setKey('abcdefgh'); * * $size = 10 * 1024; * $plaintext = ''; * for ($i = 0; $i < $size; $i++) { * $plaintext.= 'a'; * } * * echo $des->decrypt($des->encrypt($plaintext)); * ?> * * * @category Crypt * @package DES * @author Jim Wigginton * @copyright 2007 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\Crypt; use phpseclib\Crypt\Base; /** * Pure-PHP implementation of DES. * * @package DES * @author Jim Wigginton * @access public */ class DES extends Base { /**#@+ * @access private * @see \phpseclib\Crypt\DES::_setupKey() * @see \phpseclib\Crypt\DES::_processBlock() */ /** * Contains $keys[self::ENCRYPT] */ const ENCRYPT = 0; /** * Contains $keys[self::DECRYPT] */ const DECRYPT = 1; /**#@-*/ /** * Block Length of the cipher * * @see \phpseclib\Crypt\Base::block_size * @var Integer * @access private */ var $block_size = 8; /** * The Key * * @see \phpseclib\Crypt\Base::key * @see setKey() * @var String * @access private */ var $key = "\0\0\0\0\0\0\0\0"; /** * The default password key_size used by setPassword() * * @see \phpseclib\Crypt\Base::password_key_size * @see \phpseclib\Crypt\Base::setPassword() * @var Integer * @access private */ var $password_key_size = 8; /** * The namespace used by the cipher for its constants. * * @see \phpseclib\Crypt\Base::const_namespace * @var String * @access private */ var $const_namespace = 'DES'; /** * The mcrypt specific name of the cipher * * @see \phpseclib\Crypt\Base::cipher_name_mcrypt * @var String * @access private */ var $cipher_name_mcrypt = 'des'; /** * Optimizing value while CFB-encrypting * * @see \phpseclib\Crypt\Base::cfb_init_len * @var Integer * @access private */ var $cfb_init_len = 500; /** * Switch for DES/3DES encryption * * Used only if $engine == self::ENGINE_INTERNAL * * @see \phpseclib\Crypt\DES::_setupKey() * @see \phpseclib\Crypt\DES::_processBlock() * @var Integer * @access private */ var $des_rounds = 1; /** * max possible size of $key * * @see \phpseclib\Crypt\DES::setKey() * @var String * @access private */ var $key_size_max = 8; /** * The Key Schedule * * @see \phpseclib\Crypt\DES::_setupKey() * @var Array * @access private */ var $keys; /** * Shuffle table. * * For each byte value index, the entry holds an 8-byte string * with each byte containing all bits in the same state as the * corresponding bit in the index value. * * @see \phpseclib\Crypt\DES::_processBlock() * @see \phpseclib\Crypt\DES::_setupKey() * @var Array * @access private */ var $shuffle = array( "\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\xFF", "\x00\x00\x00\x00\x00\x00\xFF\x00", "\x00\x00\x00\x00\x00\x00\xFF\xFF", "\x00\x00\x00\x00\x00\xFF\x00\x00", "\x00\x00\x00\x00\x00\xFF\x00\xFF", "\x00\x00\x00\x00\x00\xFF\xFF\x00", "\x00\x00\x00\x00\x00\xFF\xFF\xFF", "\x00\x00\x00\x00\xFF\x00\x00\x00", "\x00\x00\x00\x00\xFF\x00\x00\xFF", "\x00\x00\x00\x00\xFF\x00\xFF\x00", "\x00\x00\x00\x00\xFF\x00\xFF\xFF", "\x00\x00\x00\x00\xFF\xFF\x00\x00", "\x00\x00\x00\x00\xFF\xFF\x00\xFF", "\x00\x00\x00\x00\xFF\xFF\xFF\x00", "\x00\x00\x00\x00\xFF\xFF\xFF\xFF", "\x00\x00\x00\xFF\x00\x00\x00\x00", "\x00\x00\x00\xFF\x00\x00\x00\xFF", "\x00\x00\x00\xFF\x00\x00\xFF\x00", "\x00\x00\x00\xFF\x00\x00\xFF\xFF", "\x00\x00\x00\xFF\x00\xFF\x00\x00", "\x00\x00\x00\xFF\x00\xFF\x00\xFF", "\x00\x00\x00\xFF\x00\xFF\xFF\x00", "\x00\x00\x00\xFF\x00\xFF\xFF\xFF", "\x00\x00\x00\xFF\xFF\x00\x00\x00", "\x00\x00\x00\xFF\xFF\x00\x00\xFF", "\x00\x00\x00\xFF\xFF\x00\xFF\x00", "\x00\x00\x00\xFF\xFF\x00\xFF\xFF", "\x00\x00\x00\xFF\xFF\xFF\x00\x00", "\x00\x00\x00\xFF\xFF\xFF\x00\xFF", "\x00\x00\x00\xFF\xFF\xFF\xFF\x00", "\x00\x00\x00\xFF\xFF\xFF\xFF\xFF", "\x00\x00\xFF\x00\x00\x00\x00\x00", "\x00\x00\xFF\x00\x00\x00\x00\xFF", "\x00\x00\xFF\x00\x00\x00\xFF\x00", "\x00\x00\xFF\x00\x00\x00\xFF\xFF", "\x00\x00\xFF\x00\x00\xFF\x00\x00", "\x00\x00\xFF\x00\x00\xFF\x00\xFF", "\x00\x00\xFF\x00\x00\xFF\xFF\x00", "\x00\x00\xFF\x00\x00\xFF\xFF\xFF", "\x00\x00\xFF\x00\xFF\x00\x00\x00", "\x00\x00\xFF\x00\xFF\x00\x00\xFF", "\x00\x00\xFF\x00\xFF\x00\xFF\x00", "\x00\x00\xFF\x00\xFF\x00\xFF\xFF", "\x00\x00\xFF\x00\xFF\xFF\x00\x00", "\x00\x00\xFF\x00\xFF\xFF\x00\xFF", "\x00\x00\xFF\x00\xFF\xFF\xFF\x00", "\x00\x00\xFF\x00\xFF\xFF\xFF\xFF", "\x00\x00\xFF\xFF\x00\x00\x00\x00", "\x00\x00\xFF\xFF\x00\x00\x00\xFF", "\x00\x00\xFF\xFF\x00\x00\xFF\x00", "\x00\x00\xFF\xFF\x00\x00\xFF\xFF", "\x00\x00\xFF\xFF\x00\xFF\x00\x00", "\x00\x00\xFF\xFF\x00\xFF\x00\xFF", "\x00\x00\xFF\xFF\x00\xFF\xFF\x00", "\x00\x00\xFF\xFF\x00\xFF\xFF\xFF", "\x00\x00\xFF\xFF\xFF\x00\x00\x00", "\x00\x00\xFF\xFF\xFF\x00\x00\xFF", "\x00\x00\xFF\xFF\xFF\x00\xFF\x00", "\x00\x00\xFF\xFF\xFF\x00\xFF\xFF", "\x00\x00\xFF\xFF\xFF\xFF\x00\x00", "\x00\x00\xFF\xFF\xFF\xFF\x00\xFF", "\x00\x00\xFF\xFF\xFF\xFF\xFF\x00", "\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF", "\x00\xFF\x00\x00\x00\x00\x00\x00", "\x00\xFF\x00\x00\x00\x00\x00\xFF", "\x00\xFF\x00\x00\x00\x00\xFF\x00", "\x00\xFF\x00\x00\x00\x00\xFF\xFF", "\x00\xFF\x00\x00\x00\xFF\x00\x00", "\x00\xFF\x00\x00\x00\xFF\x00\xFF", "\x00\xFF\x00\x00\x00\xFF\xFF\x00", "\x00\xFF\x00\x00\x00\xFF\xFF\xFF", "\x00\xFF\x00\x00\xFF\x00\x00\x00", "\x00\xFF\x00\x00\xFF\x00\x00\xFF", "\x00\xFF\x00\x00\xFF\x00\xFF\x00", "\x00\xFF\x00\x00\xFF\x00\xFF\xFF", "\x00\xFF\x00\x00\xFF\xFF\x00\x00", "\x00\xFF\x00\x00\xFF\xFF\x00\xFF", "\x00\xFF\x00\x00\xFF\xFF\xFF\x00", "\x00\xFF\x00\x00\xFF\xFF\xFF\xFF", "\x00\xFF\x00\xFF\x00\x00\x00\x00", "\x00\xFF\x00\xFF\x00\x00\x00\xFF", "\x00\xFF\x00\xFF\x00\x00\xFF\x00", "\x00\xFF\x00\xFF\x00\x00\xFF\xFF", "\x00\xFF\x00\xFF\x00\xFF\x00\x00", "\x00\xFF\x00\xFF\x00\xFF\x00\xFF", "\x00\xFF\x00\xFF\x00\xFF\xFF\x00", "\x00\xFF\x00\xFF\x00\xFF\xFF\xFF", "\x00\xFF\x00\xFF\xFF\x00\x00\x00", "\x00\xFF\x00\xFF\xFF\x00\x00\xFF", "\x00\xFF\x00\xFF\xFF\x00\xFF\x00", "\x00\xFF\x00\xFF\xFF\x00\xFF\xFF", "\x00\xFF\x00\xFF\xFF\xFF\x00\x00", "\x00\xFF\x00\xFF\xFF\xFF\x00\xFF", "\x00\xFF\x00\xFF\xFF\xFF\xFF\x00", "\x00\xFF\x00\xFF\xFF\xFF\xFF\xFF", "\x00\xFF\xFF\x00\x00\x00\x00\x00", "\x00\xFF\xFF\x00\x00\x00\x00\xFF", "\x00\xFF\xFF\x00\x00\x00\xFF\x00", "\x00\xFF\xFF\x00\x00\x00\xFF\xFF", "\x00\xFF\xFF\x00\x00\xFF\x00\x00", "\x00\xFF\xFF\x00\x00\xFF\x00\xFF", "\x00\xFF\xFF\x00\x00\xFF\xFF\x00", "\x00\xFF\xFF\x00\x00\xFF\xFF\xFF", "\x00\xFF\xFF\x00\xFF\x00\x00\x00", "\x00\xFF\xFF\x00\xFF\x00\x00\xFF", "\x00\xFF\xFF\x00\xFF\x00\xFF\x00", "\x00\xFF\xFF\x00\xFF\x00\xFF\xFF", "\x00\xFF\xFF\x00\xFF\xFF\x00\x00", "\x00\xFF\xFF\x00\xFF\xFF\x00\xFF", "\x00\xFF\xFF\x00\xFF\xFF\xFF\x00", "\x00\xFF\xFF\x00\xFF\xFF\xFF\xFF", "\x00\xFF\xFF\xFF\x00\x00\x00\x00", "\x00\xFF\xFF\xFF\x00\x00\x00\xFF", "\x00\xFF\xFF\xFF\x00\x00\xFF\x00", "\x00\xFF\xFF\xFF\x00\x00\xFF\xFF", "\x00\xFF\xFF\xFF\x00\xFF\x00\x00", "\x00\xFF\xFF\xFF\x00\xFF\x00\xFF", "\x00\xFF\xFF\xFF\x00\xFF\xFF\x00", "\x00\xFF\xFF\xFF\x00\xFF\xFF\xFF", "\x00\xFF\xFF\xFF\xFF\x00\x00\x00", "\x00\xFF\xFF\xFF\xFF\x00\x00\xFF", "\x00\xFF\xFF\xFF\xFF\x00\xFF\x00", "\x00\xFF\xFF\xFF\xFF\x00\xFF\xFF", "\x00\xFF\xFF\xFF\xFF\xFF\x00\x00", "\x00\xFF\xFF\xFF\xFF\xFF\x00\xFF", "\x00\xFF\xFF\xFF\xFF\xFF\xFF\x00", "\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF", "\xFF\x00\x00\x00\x00\x00\x00\x00", "\xFF\x00\x00\x00\x00\x00\x00\xFF", "\xFF\x00\x00\x00\x00\x00\xFF\x00", "\xFF\x00\x00\x00\x00\x00\xFF\xFF", "\xFF\x00\x00\x00\x00\xFF\x00\x00", "\xFF\x00\x00\x00\x00\xFF\x00\xFF", "\xFF\x00\x00\x00\x00\xFF\xFF\x00", "\xFF\x00\x00\x00\x00\xFF\xFF\xFF", "\xFF\x00\x00\x00\xFF\x00\x00\x00", "\xFF\x00\x00\x00\xFF\x00\x00\xFF", "\xFF\x00\x00\x00\xFF\x00\xFF\x00", "\xFF\x00\x00\x00\xFF\x00\xFF\xFF", "\xFF\x00\x00\x00\xFF\xFF\x00\x00", "\xFF\x00\x00\x00\xFF\xFF\x00\xFF", "\xFF\x00\x00\x00\xFF\xFF\xFF\x00", "\xFF\x00\x00\x00\xFF\xFF\xFF\xFF", "\xFF\x00\x00\xFF\x00\x00\x00\x00", "\xFF\x00\x00\xFF\x00\x00\x00\xFF", "\xFF\x00\x00\xFF\x00\x00\xFF\x00", "\xFF\x00\x00\xFF\x00\x00\xFF\xFF", "\xFF\x00\x00\xFF\x00\xFF\x00\x00", "\xFF\x00\x00\xFF\x00\xFF\x00\xFF", "\xFF\x00\x00\xFF\x00\xFF\xFF\x00", "\xFF\x00\x00\xFF\x00\xFF\xFF\xFF", "\xFF\x00\x00\xFF\xFF\x00\x00\x00", "\xFF\x00\x00\xFF\xFF\x00\x00\xFF", "\xFF\x00\x00\xFF\xFF\x00\xFF\x00", "\xFF\x00\x00\xFF\xFF\x00\xFF\xFF", "\xFF\x00\x00\xFF\xFF\xFF\x00\x00", "\xFF\x00\x00\xFF\xFF\xFF\x00\xFF", "\xFF\x00\x00\xFF\xFF\xFF\xFF\x00", "\xFF\x00\x00\xFF\xFF\xFF\xFF\xFF", "\xFF\x00\xFF\x00\x00\x00\x00\x00", "\xFF\x00\xFF\x00\x00\x00\x00\xFF", "\xFF\x00\xFF\x00\x00\x00\xFF\x00", "\xFF\x00\xFF\x00\x00\x00\xFF\xFF", "\xFF\x00\xFF\x00\x00\xFF\x00\x00", "\xFF\x00\xFF\x00\x00\xFF\x00\xFF", "\xFF\x00\xFF\x00\x00\xFF\xFF\x00", "\xFF\x00\xFF\x00\x00\xFF\xFF\xFF", "\xFF\x00\xFF\x00\xFF\x00\x00\x00", "\xFF\x00\xFF\x00\xFF\x00\x00\xFF", "\xFF\x00\xFF\x00\xFF\x00\xFF\x00", "\xFF\x00\xFF\x00\xFF\x00\xFF\xFF", "\xFF\x00\xFF\x00\xFF\xFF\x00\x00", "\xFF\x00\xFF\x00\xFF\xFF\x00\xFF", "\xFF\x00\xFF\x00\xFF\xFF\xFF\x00", "\xFF\x00\xFF\x00\xFF\xFF\xFF\xFF", "\xFF\x00\xFF\xFF\x00\x00\x00\x00", "\xFF\x00\xFF\xFF\x00\x00\x00\xFF", "\xFF\x00\xFF\xFF\x00\x00\xFF\x00", "\xFF\x00\xFF\xFF\x00\x00\xFF\xFF", "\xFF\x00\xFF\xFF\x00\xFF\x00\x00", "\xFF\x00\xFF\xFF\x00\xFF\x00\xFF", "\xFF\x00\xFF\xFF\x00\xFF\xFF\x00", "\xFF\x00\xFF\xFF\x00\xFF\xFF\xFF", "\xFF\x00\xFF\xFF\xFF\x00\x00\x00", "\xFF\x00\xFF\xFF\xFF\x00\x00\xFF", "\xFF\x00\xFF\xFF\xFF\x00\xFF\x00", "\xFF\x00\xFF\xFF\xFF\x00\xFF\xFF", "\xFF\x00\xFF\xFF\xFF\xFF\x00\x00", "\xFF\x00\xFF\xFF\xFF\xFF\x00\xFF", "\xFF\x00\xFF\xFF\xFF\xFF\xFF\x00", "\xFF\x00\xFF\xFF\xFF\xFF\xFF\xFF", "\xFF\xFF\x00\x00\x00\x00\x00\x00", "\xFF\xFF\x00\x00\x00\x00\x00\xFF", "\xFF\xFF\x00\x00\x00\x00\xFF\x00", "\xFF\xFF\x00\x00\x00\x00\xFF\xFF", "\xFF\xFF\x00\x00\x00\xFF\x00\x00", "\xFF\xFF\x00\x00\x00\xFF\x00\xFF", "\xFF\xFF\x00\x00\x00\xFF\xFF\x00", "\xFF\xFF\x00\x00\x00\xFF\xFF\xFF", "\xFF\xFF\x00\x00\xFF\x00\x00\x00", "\xFF\xFF\x00\x00\xFF\x00\x00\xFF", "\xFF\xFF\x00\x00\xFF\x00\xFF\x00", "\xFF\xFF\x00\x00\xFF\x00\xFF\xFF", "\xFF\xFF\x00\x00\xFF\xFF\x00\x00", "\xFF\xFF\x00\x00\xFF\xFF\x00\xFF", "\xFF\xFF\x00\x00\xFF\xFF\xFF\x00", "\xFF\xFF\x00\x00\xFF\xFF\xFF\xFF", "\xFF\xFF\x00\xFF\x00\x00\x00\x00", "\xFF\xFF\x00\xFF\x00\x00\x00\xFF", "\xFF\xFF\x00\xFF\x00\x00\xFF\x00", "\xFF\xFF\x00\xFF\x00\x00\xFF\xFF", "\xFF\xFF\x00\xFF\x00\xFF\x00\x00", "\xFF\xFF\x00\xFF\x00\xFF\x00\xFF", "\xFF\xFF\x00\xFF\x00\xFF\xFF\x00", "\xFF\xFF\x00\xFF\x00\xFF\xFF\xFF", "\xFF\xFF\x00\xFF\xFF\x00\x00\x00", "\xFF\xFF\x00\xFF\xFF\x00\x00\xFF", "\xFF\xFF\x00\xFF\xFF\x00\xFF\x00", "\xFF\xFF\x00\xFF\xFF\x00\xFF\xFF", "\xFF\xFF\x00\xFF\xFF\xFF\x00\x00", "\xFF\xFF\x00\xFF\xFF\xFF\x00\xFF", "\xFF\xFF\x00\xFF\xFF\xFF\xFF\x00", "\xFF\xFF\x00\xFF\xFF\xFF\xFF\xFF", "\xFF\xFF\xFF\x00\x00\x00\x00\x00", "\xFF\xFF\xFF\x00\x00\x00\x00\xFF", "\xFF\xFF\xFF\x00\x00\x00\xFF\x00", "\xFF\xFF\xFF\x00\x00\x00\xFF\xFF", "\xFF\xFF\xFF\x00\x00\xFF\x00\x00", "\xFF\xFF\xFF\x00\x00\xFF\x00\xFF", "\xFF\xFF\xFF\x00\x00\xFF\xFF\x00", "\xFF\xFF\xFF\x00\x00\xFF\xFF\xFF", "\xFF\xFF\xFF\x00\xFF\x00\x00\x00", "\xFF\xFF\xFF\x00\xFF\x00\x00\xFF", "\xFF\xFF\xFF\x00\xFF\x00\xFF\x00", "\xFF\xFF\xFF\x00\xFF\x00\xFF\xFF", "\xFF\xFF\xFF\x00\xFF\xFF\x00\x00", "\xFF\xFF\xFF\x00\xFF\xFF\x00\xFF", "\xFF\xFF\xFF\x00\xFF\xFF\xFF\x00", "\xFF\xFF\xFF\x00\xFF\xFF\xFF\xFF", "\xFF\xFF\xFF\xFF\x00\x00\x00\x00", "\xFF\xFF\xFF\xFF\x00\x00\x00\xFF", "\xFF\xFF\xFF\xFF\x00\x00\xFF\x00", "\xFF\xFF\xFF\xFF\x00\x00\xFF\xFF", "\xFF\xFF\xFF\xFF\x00\xFF\x00\x00", "\xFF\xFF\xFF\xFF\x00\xFF\x00\xFF", "\xFF\xFF\xFF\xFF\x00\xFF\xFF\x00", "\xFF\xFF\xFF\xFF\x00\xFF\xFF\xFF", "\xFF\xFF\xFF\xFF\xFF\x00\x00\x00", "\xFF\xFF\xFF\xFF\xFF\x00\x00\xFF", "\xFF\xFF\xFF\xFF\xFF\x00\xFF\x00", "\xFF\xFF\xFF\xFF\xFF\x00\xFF\xFF", "\xFF\xFF\xFF\xFF\xFF\xFF\x00\x00", "\xFF\xFF\xFF\xFF\xFF\xFF\x00\xFF", "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x00", "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" ); /** * IP mapping helper table. * * Indexing this table with each source byte performs the initial bit permutation. * * @var Array * @access private */ var $ipmap = array( 0x00, 0x10, 0x01, 0x11, 0x20, 0x30, 0x21, 0x31, 0x02, 0x12, 0x03, 0x13, 0x22, 0x32, 0x23, 0x33, 0x40, 0x50, 0x41, 0x51, 0x60, 0x70, 0x61, 0x71, 0x42, 0x52, 0x43, 0x53, 0x62, 0x72, 0x63, 0x73, 0x04, 0x14, 0x05, 0x15, 0x24, 0x34, 0x25, 0x35, 0x06, 0x16, 0x07, 0x17, 0x26, 0x36, 0x27, 0x37, 0x44, 0x54, 0x45, 0x55, 0x64, 0x74, 0x65, 0x75, 0x46, 0x56, 0x47, 0x57, 0x66, 0x76, 0x67, 0x77, 0x80, 0x90, 0x81, 0x91, 0xA0, 0xB0, 0xA1, 0xB1, 0x82, 0x92, 0x83, 0x93, 0xA2, 0xB2, 0xA3, 0xB3, 0xC0, 0xD0, 0xC1, 0xD1, 0xE0, 0xF0, 0xE1, 0xF1, 0xC2, 0xD2, 0xC3, 0xD3, 0xE2, 0xF2, 0xE3, 0xF3, 0x84, 0x94, 0x85, 0x95, 0xA4, 0xB4, 0xA5, 0xB5, 0x86, 0x96, 0x87, 0x97, 0xA6, 0xB6, 0xA7, 0xB7, 0xC4, 0xD4, 0xC5, 0xD5, 0xE4, 0xF4, 0xE5, 0xF5, 0xC6, 0xD6, 0xC7, 0xD7, 0xE6, 0xF6, 0xE7, 0xF7, 0x08, 0x18, 0x09, 0x19, 0x28, 0x38, 0x29, 0x39, 0x0A, 0x1A, 0x0B, 0x1B, 0x2A, 0x3A, 0x2B, 0x3B, 0x48, 0x58, 0x49, 0x59, 0x68, 0x78, 0x69, 0x79, 0x4A, 0x5A, 0x4B, 0x5B, 0x6A, 0x7A, 0x6B, 0x7B, 0x0C, 0x1C, 0x0D, 0x1D, 0x2C, 0x3C, 0x2D, 0x3D, 0x0E, 0x1E, 0x0F, 0x1F, 0x2E, 0x3E, 0x2F, 0x3F, 0x4C, 0x5C, 0x4D, 0x5D, 0x6C, 0x7C, 0x6D, 0x7D, 0x4E, 0x5E, 0x4F, 0x5F, 0x6E, 0x7E, 0x6F, 0x7F, 0x88, 0x98, 0x89, 0x99, 0xA8, 0xB8, 0xA9, 0xB9, 0x8A, 0x9A, 0x8B, 0x9B, 0xAA, 0xBA, 0xAB, 0xBB, 0xC8, 0xD8, 0xC9, 0xD9, 0xE8, 0xF8, 0xE9, 0xF9, 0xCA, 0xDA, 0xCB, 0xDB, 0xEA, 0xFA, 0xEB, 0xFB, 0x8C, 0x9C, 0x8D, 0x9D, 0xAC, 0xBC, 0xAD, 0xBD, 0x8E, 0x9E, 0x8F, 0x9F, 0xAE, 0xBE, 0xAF, 0xBF, 0xCC, 0xDC, 0xCD, 0xDD, 0xEC, 0xFC, 0xED, 0xFD, 0xCE, 0xDE, 0xCF, 0xDF, 0xEE, 0xFE, 0xEF, 0xFF ); /** * Inverse IP mapping helper table. * Indexing this table with a byte value reverses the bit order. * * @var Array * @access private */ var $invipmap = array( 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0, 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4, 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC, 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA, 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6, 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE, 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1, 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9, 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5, 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD, 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3, 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB, 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7, 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF ); /** * Pre-permuted S-box1 * * Each box ($sbox1-$sbox8) has been vectorized, then each value pre-permuted using the * P table: concatenation can then be replaced by exclusive ORs. * * @var Array * @access private */ var $sbox1 = array( 0x00808200, 0x00000000, 0x00008000, 0x00808202, 0x00808002, 0x00008202, 0x00000002, 0x00008000, 0x00000200, 0x00808200, 0x00808202, 0x00000200, 0x00800202, 0x00808002, 0x00800000, 0x00000002, 0x00000202, 0x00800200, 0x00800200, 0x00008200, 0x00008200, 0x00808000, 0x00808000, 0x00800202, 0x00008002, 0x00800002, 0x00800002, 0x00008002, 0x00000000, 0x00000202, 0x00008202, 0x00800000, 0x00008000, 0x00808202, 0x00000002, 0x00808000, 0x00808200, 0x00800000, 0x00800000, 0x00000200, 0x00808002, 0x00008000, 0x00008200, 0x00800002, 0x00000200, 0x00000002, 0x00800202, 0x00008202, 0x00808202, 0x00008002, 0x00808000, 0x00800202, 0x00800002, 0x00000202, 0x00008202, 0x00808200, 0x00000202, 0x00800200, 0x00800200, 0x00000000, 0x00008002, 0x00008200, 0x00000000, 0x00808002 ); /** * Pre-permuted S-box2 * * @var Array * @access private */ var $sbox2 = array( 0x40084010, 0x40004000, 0x00004000, 0x00084010, 0x00080000, 0x00000010, 0x40080010, 0x40004010, 0x40000010, 0x40084010, 0x40084000, 0x40000000, 0x40004000, 0x00080000, 0x00000010, 0x40080010, 0x00084000, 0x00080010, 0x40004010, 0x00000000, 0x40000000, 0x00004000, 0x00084010, 0x40080000, 0x00080010, 0x40000010, 0x00000000, 0x00084000, 0x00004010, 0x40084000, 0x40080000, 0x00004010, 0x00000000, 0x00084010, 0x40080010, 0x00080000, 0x40004010, 0x40080000, 0x40084000, 0x00004000, 0x40080000, 0x40004000, 0x00000010, 0x40084010, 0x00084010, 0x00000010, 0x00004000, 0x40000000, 0x00004010, 0x40084000, 0x00080000, 0x40000010, 0x00080010, 0x40004010, 0x40000010, 0x00080010, 0x00084000, 0x00000000, 0x40004000, 0x00004010, 0x40000000, 0x40080010, 0x40084010, 0x00084000 ); /** * Pre-permuted S-box3 * * @var Array * @access private */ var $sbox3 = array( 0x00000104, 0x04010100, 0x00000000, 0x04010004, 0x04000100, 0x00000000, 0x00010104, 0x04000100, 0x00010004, 0x04000004, 0x04000004, 0x00010000, 0x04010104, 0x00010004, 0x04010000, 0x00000104, 0x04000000, 0x00000004, 0x04010100, 0x00000100, 0x00010100, 0x04010000, 0x04010004, 0x00010104, 0x04000104, 0x00010100, 0x00010000, 0x04000104, 0x00000004, 0x04010104, 0x00000100, 0x04000000, 0x04010100, 0x04000000, 0x00010004, 0x00000104, 0x00010000, 0x04010100, 0x04000100, 0x00000000, 0x00000100, 0x00010004, 0x04010104, 0x04000100, 0x04000004, 0x00000100, 0x00000000, 0x04010004, 0x04000104, 0x00010000, 0x04000000, 0x04010104, 0x00000004, 0x00010104, 0x00010100, 0x04000004, 0x04010000, 0x04000104, 0x00000104, 0x04010000, 0x00010104, 0x00000004, 0x04010004, 0x00010100 ); /** * Pre-permuted S-box4 * * @var Array * @access private */ var $sbox4 = array( 0x80401000, 0x80001040, 0x80001040, 0x00000040, 0x00401040, 0x80400040, 0x80400000, 0x80001000, 0x00000000, 0x00401000, 0x00401000, 0x80401040, 0x80000040, 0x00000000, 0x00400040, 0x80400000, 0x80000000, 0x00001000, 0x00400000, 0x80401000, 0x00000040, 0x00400000, 0x80001000, 0x00001040, 0x80400040, 0x80000000, 0x00001040, 0x00400040, 0x00001000, 0x00401040, 0x80401040, 0x80000040, 0x00400040, 0x80400000, 0x00401000, 0x80401040, 0x80000040, 0x00000000, 0x00000000, 0x00401000, 0x00001040, 0x00400040, 0x80400040, 0x80000000, 0x80401000, 0x80001040, 0x80001040, 0x00000040, 0x80401040, 0x80000040, 0x80000000, 0x00001000, 0x80400000, 0x80001000, 0x00401040, 0x80400040, 0x80001000, 0x00001040, 0x00400000, 0x80401000, 0x00000040, 0x00400000, 0x00001000, 0x00401040 ); /** * Pre-permuted S-box5 * * @var Array * @access private */ var $sbox5 = array( 0x00000080, 0x01040080, 0x01040000, 0x21000080, 0x00040000, 0x00000080, 0x20000000, 0x01040000, 0x20040080, 0x00040000, 0x01000080, 0x20040080, 0x21000080, 0x21040000, 0x00040080, 0x20000000, 0x01000000, 0x20040000, 0x20040000, 0x00000000, 0x20000080, 0x21040080, 0x21040080, 0x01000080, 0x21040000, 0x20000080, 0x00000000, 0x21000000, 0x01040080, 0x01000000, 0x21000000, 0x00040080, 0x00040000, 0x21000080, 0x00000080, 0x01000000, 0x20000000, 0x01040000, 0x21000080, 0x20040080, 0x01000080, 0x20000000, 0x21040000, 0x01040080, 0x20040080, 0x00000080, 0x01000000, 0x21040000, 0x21040080, 0x00040080, 0x21000000, 0x21040080, 0x01040000, 0x00000000, 0x20040000, 0x21000000, 0x00040080, 0x01000080, 0x20000080, 0x00040000, 0x00000000, 0x20040000, 0x01040080, 0x20000080 ); /** * Pre-permuted S-box6 * * @var Array * @access private */ var $sbox6 = array( 0x10000008, 0x10200000, 0x00002000, 0x10202008, 0x10200000, 0x00000008, 0x10202008, 0x00200000, 0x10002000, 0x00202008, 0x00200000, 0x10000008, 0x00200008, 0x10002000, 0x10000000, 0x00002008, 0x00000000, 0x00200008, 0x10002008, 0x00002000, 0x00202000, 0x10002008, 0x00000008, 0x10200008, 0x10200008, 0x00000000, 0x00202008, 0x10202000, 0x00002008, 0x00202000, 0x10202000, 0x10000000, 0x10002000, 0x00000008, 0x10200008, 0x00202000, 0x10202008, 0x00200000, 0x00002008, 0x10000008, 0x00200000, 0x10002000, 0x10000000, 0x00002008, 0x10000008, 0x10202008, 0x00202000, 0x10200000, 0x00202008, 0x10202000, 0x00000000, 0x10200008, 0x00000008, 0x00002000, 0x10200000, 0x00202008, 0x00002000, 0x00200008, 0x10002008, 0x00000000, 0x10202000, 0x10000000, 0x00200008, 0x10002008 ); /** * Pre-permuted S-box7 * * @var Array * @access private */ var $sbox7 = array( 0x00100000, 0x02100001, 0x02000401, 0x00000000, 0x00000400, 0x02000401, 0x00100401, 0x02100400, 0x02100401, 0x00100000, 0x00000000, 0x02000001, 0x00000001, 0x02000000, 0x02100001, 0x00000401, 0x02000400, 0x00100401, 0x00100001, 0x02000400, 0x02000001, 0x02100000, 0x02100400, 0x00100001, 0x02100000, 0x00000400, 0x00000401, 0x02100401, 0x00100400, 0x00000001, 0x02000000, 0x00100400, 0x02000000, 0x00100400, 0x00100000, 0x02000401, 0x02000401, 0x02100001, 0x02100001, 0x00000001, 0x00100001, 0x02000000, 0x02000400, 0x00100000, 0x02100400, 0x00000401, 0x00100401, 0x02100400, 0x00000401, 0x02000001, 0x02100401, 0x02100000, 0x00100400, 0x00000000, 0x00000001, 0x02100401, 0x00000000, 0x00100401, 0x02100000, 0x00000400, 0x02000001, 0x02000400, 0x00000400, 0x00100001 ); /** * Pre-permuted S-box8 * * @var Array * @access private */ var $sbox8 = array( 0x08000820, 0x00000800, 0x00020000, 0x08020820, 0x08000000, 0x08000820, 0x00000020, 0x08000000, 0x00020020, 0x08020000, 0x08020820, 0x00020800, 0x08020800, 0x00020820, 0x00000800, 0x00000020, 0x08020000, 0x08000020, 0x08000800, 0x00000820, 0x00020800, 0x00020020, 0x08020020, 0x08020800, 0x00000820, 0x00000000, 0x00000000, 0x08020020, 0x08000020, 0x08000800, 0x00020820, 0x00020000, 0x00020820, 0x00020000, 0x08020800, 0x00000800, 0x00000020, 0x08020020, 0x00000800, 0x00020820, 0x08000800, 0x00000020, 0x08000020, 0x08020000, 0x08020020, 0x08000000, 0x00020000, 0x08000820, 0x00000000, 0x08020820, 0x00020020, 0x08000020, 0x08020000, 0x08000800, 0x08000820, 0x00000000, 0x08020820, 0x00020800, 0x00020800, 0x00000820, 0x00000820, 0x00020020, 0x08000000, 0x08020800 ); /** * Sets the key. * * Keys can be of any length. DES, itself, uses 64-bit keys (eg. strlen($key) == 8), however, we * only use the first eight, if $key has more then eight characters in it, and pad $key with the * null byte if it is less then eight characters long. * * DES also requires that every eighth bit be a parity bit, however, we'll ignore that. * * If the key is not explicitly set, it'll be assumed to be all zero's. * * @see \phpseclib\Crypt\Base::setKey() * @access public * @param String $key */ function setKey($key) { // We check/cut here only up to max length of the key. // Key padding to the proper length will be done in _setupKey() if (strlen($key) > $this->key_size_max) { $key = substr($key, 0, $this->key_size_max); } // Sets the key parent::setKey($key); } /** * Encrypts a block * * @see \phpseclib\Crypt\Base::_encryptBlock() * @see \phpseclib\Crypt\Base::encrypt() * @see \phpseclib\Crypt\DES::encrypt() * @access private * @param String $in * @return String */ function _encryptBlock($in) { return $this->_processBlock($in, self::ENCRYPT); } /** * Decrypts a block * * @see \phpseclib\Crypt\Base::_decryptBlock() * @see \phpseclib\Crypt\Base::decrypt() * @see \phpseclib\Crypt\DES::decrypt() * @access private * @param String $in * @return String */ function _decryptBlock($in) { return $this->_processBlock($in, self::DECRYPT); } /** * Encrypts or decrypts a 64-bit block * * $mode should be either self::ENCRYPT or self::DECRYPT. See * {@link http://en.wikipedia.org/wiki/Image:Feistel.png Feistel.png} to get a general * idea of what this function does. * * @see \phpseclib\Crypt\DES::_encryptBlock() * @see \phpseclib\Crypt\DES::_decryptBlock() * @access private * @param String $block * @param Integer $mode * @return String */ function _processBlock($block, $mode) { static $sbox1, $sbox2, $sbox3, $sbox4, $sbox5, $sbox6, $sbox7, $sbox8, $shuffleip, $shuffleinvip; if (!$sbox1) { $sbox1 = array_map("intval", $this->sbox1); $sbox2 = array_map("intval", $this->sbox2); $sbox3 = array_map("intval", $this->sbox3); $sbox4 = array_map("intval", $this->sbox4); $sbox5 = array_map("intval", $this->sbox5); $sbox6 = array_map("intval", $this->sbox6); $sbox7 = array_map("intval", $this->sbox7); $sbox8 = array_map("intval", $this->sbox8); /* Merge $shuffle with $[inv]ipmap */ for ($i = 0; $i < 256; ++$i) { $shuffleip[] = $this->shuffle[$this->ipmap[$i]]; $shuffleinvip[] = $this->shuffle[$this->invipmap[$i]]; } } $keys = $this->keys[$mode]; $ki = -1; // Do the initial IP permutation. $t = unpack('Nl/Nr', $block); list($l, $r) = array($t['l'], $t['r']); $block = ($shuffleip[ $r & 0xFF] & "\x80\x80\x80\x80\x80\x80\x80\x80") | ($shuffleip[($r >> 8) & 0xFF] & "\x40\x40\x40\x40\x40\x40\x40\x40") | ($shuffleip[($r >> 16) & 0xFF] & "\x20\x20\x20\x20\x20\x20\x20\x20") | ($shuffleip[($r >> 24) & 0xFF] & "\x10\x10\x10\x10\x10\x10\x10\x10") | ($shuffleip[ $l & 0xFF] & "\x08\x08\x08\x08\x08\x08\x08\x08") | ($shuffleip[($l >> 8) & 0xFF] & "\x04\x04\x04\x04\x04\x04\x04\x04") | ($shuffleip[($l >> 16) & 0xFF] & "\x02\x02\x02\x02\x02\x02\x02\x02") | ($shuffleip[($l >> 24) & 0xFF] & "\x01\x01\x01\x01\x01\x01\x01\x01"); // Extract L0 and R0. $t = unpack('Nl/Nr', $block); list($l, $r) = array($t['l'], $t['r']); for ($des_round = 0; $des_round < $this->des_rounds; ++$des_round) { // Perform the 16 steps. for ($i = 0; $i < 16; $i++) { // start of "the Feistel (F) function" - see the following URL: // http://en.wikipedia.org/wiki/Image:Data_Encryption_Standard_InfoBox_Diagram.png // Merge key schedule. $b1 = (($r >> 3) & 0x1FFFFFFF) ^ ($r << 29) ^ $keys[++$ki]; $b2 = (($r >> 31) & 0x00000001) ^ ($r << 1) ^ $keys[++$ki]; // S-box indexing. $t = $sbox1[($b1 >> 24) & 0x3F] ^ $sbox2[($b2 >> 24) & 0x3F] ^ $sbox3[($b1 >> 16) & 0x3F] ^ $sbox4[($b2 >> 16) & 0x3F] ^ $sbox5[($b1 >> 8) & 0x3F] ^ $sbox6[($b2 >> 8) & 0x3F] ^ $sbox7[ $b1 & 0x3F] ^ $sbox8[ $b2 & 0x3F] ^ $l; // end of "the Feistel (F) function" $l = $r; $r = $t; } // Last step should not permute L & R. $t = $l; $l = $r; $r = $t; } // Perform the inverse IP permutation. return ($shuffleinvip[($r >> 24) & 0xFF] & "\x80\x80\x80\x80\x80\x80\x80\x80") | ($shuffleinvip[($l >> 24) & 0xFF] & "\x40\x40\x40\x40\x40\x40\x40\x40") | ($shuffleinvip[($r >> 16) & 0xFF] & "\x20\x20\x20\x20\x20\x20\x20\x20") | ($shuffleinvip[($l >> 16) & 0xFF] & "\x10\x10\x10\x10\x10\x10\x10\x10") | ($shuffleinvip[($r >> 8) & 0xFF] & "\x08\x08\x08\x08\x08\x08\x08\x08") | ($shuffleinvip[($l >> 8) & 0xFF] & "\x04\x04\x04\x04\x04\x04\x04\x04") | ($shuffleinvip[ $r & 0xFF] & "\x02\x02\x02\x02\x02\x02\x02\x02") | ($shuffleinvip[ $l & 0xFF] & "\x01\x01\x01\x01\x01\x01\x01\x01"); } /** * Creates the key schedule * * @see \phpseclib\Crypt\Base::_setupKey() * @access private */ function _setupKey() { if (isset($this->kl['key']) && $this->key === $this->kl['key'] && $this->des_rounds === $this->kl['des_rounds']) { // already expanded return; } $this->kl = array('key' => $this->key, 'des_rounds' => $this->des_rounds); static $shifts = array( // number of key bits shifted per round 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 ); static $pc1map = array( 0x00, 0x00, 0x08, 0x08, 0x04, 0x04, 0x0C, 0x0C, 0x02, 0x02, 0x0A, 0x0A, 0x06, 0x06, 0x0E, 0x0E, 0x10, 0x10, 0x18, 0x18, 0x14, 0x14, 0x1C, 0x1C, 0x12, 0x12, 0x1A, 0x1A, 0x16, 0x16, 0x1E, 0x1E, 0x20, 0x20, 0x28, 0x28, 0x24, 0x24, 0x2C, 0x2C, 0x22, 0x22, 0x2A, 0x2A, 0x26, 0x26, 0x2E, 0x2E, 0x30, 0x30, 0x38, 0x38, 0x34, 0x34, 0x3C, 0x3C, 0x32, 0x32, 0x3A, 0x3A, 0x36, 0x36, 0x3E, 0x3E, 0x40, 0x40, 0x48, 0x48, 0x44, 0x44, 0x4C, 0x4C, 0x42, 0x42, 0x4A, 0x4A, 0x46, 0x46, 0x4E, 0x4E, 0x50, 0x50, 0x58, 0x58, 0x54, 0x54, 0x5C, 0x5C, 0x52, 0x52, 0x5A, 0x5A, 0x56, 0x56, 0x5E, 0x5E, 0x60, 0x60, 0x68, 0x68, 0x64, 0x64, 0x6C, 0x6C, 0x62, 0x62, 0x6A, 0x6A, 0x66, 0x66, 0x6E, 0x6E, 0x70, 0x70, 0x78, 0x78, 0x74, 0x74, 0x7C, 0x7C, 0x72, 0x72, 0x7A, 0x7A, 0x76, 0x76, 0x7E, 0x7E, 0x80, 0x80, 0x88, 0x88, 0x84, 0x84, 0x8C, 0x8C, 0x82, 0x82, 0x8A, 0x8A, 0x86, 0x86, 0x8E, 0x8E, 0x90, 0x90, 0x98, 0x98, 0x94, 0x94, 0x9C, 0x9C, 0x92, 0x92, 0x9A, 0x9A, 0x96, 0x96, 0x9E, 0x9E, 0xA0, 0xA0, 0xA8, 0xA8, 0xA4, 0xA4, 0xAC, 0xAC, 0xA2, 0xA2, 0xAA, 0xAA, 0xA6, 0xA6, 0xAE, 0xAE, 0xB0, 0xB0, 0xB8, 0xB8, 0xB4, 0xB4, 0xBC, 0xBC, 0xB2, 0xB2, 0xBA, 0xBA, 0xB6, 0xB6, 0xBE, 0xBE, 0xC0, 0xC0, 0xC8, 0xC8, 0xC4, 0xC4, 0xCC, 0xCC, 0xC2, 0xC2, 0xCA, 0xCA, 0xC6, 0xC6, 0xCE, 0xCE, 0xD0, 0xD0, 0xD8, 0xD8, 0xD4, 0xD4, 0xDC, 0xDC, 0xD2, 0xD2, 0xDA, 0xDA, 0xD6, 0xD6, 0xDE, 0xDE, 0xE0, 0xE0, 0xE8, 0xE8, 0xE4, 0xE4, 0xEC, 0xEC, 0xE2, 0xE2, 0xEA, 0xEA, 0xE6, 0xE6, 0xEE, 0xEE, 0xF0, 0xF0, 0xF8, 0xF8, 0xF4, 0xF4, 0xFC, 0xFC, 0xF2, 0xF2, 0xFA, 0xFA, 0xF6, 0xF6, 0xFE, 0xFE ); // Mapping tables for the PC-2 transformation. static $pc2mapc1 = array( 0x00000000, 0x00000400, 0x00200000, 0x00200400, 0x00000001, 0x00000401, 0x00200001, 0x00200401, 0x02000000, 0x02000400, 0x02200000, 0x02200400, 0x02000001, 0x02000401, 0x02200001, 0x02200401 ); static $pc2mapc2 = array( 0x00000000, 0x00000800, 0x08000000, 0x08000800, 0x00010000, 0x00010800, 0x08010000, 0x08010800, 0x00000000, 0x00000800, 0x08000000, 0x08000800, 0x00010000, 0x00010800, 0x08010000, 0x08010800, 0x00000100, 0x00000900, 0x08000100, 0x08000900, 0x00010100, 0x00010900, 0x08010100, 0x08010900, 0x00000100, 0x00000900, 0x08000100, 0x08000900, 0x00010100, 0x00010900, 0x08010100, 0x08010900, 0x00000010, 0x00000810, 0x08000010, 0x08000810, 0x00010010, 0x00010810, 0x08010010, 0x08010810, 0x00000010, 0x00000810, 0x08000010, 0x08000810, 0x00010010, 0x00010810, 0x08010010, 0x08010810, 0x00000110, 0x00000910, 0x08000110, 0x08000910, 0x00010110, 0x00010910, 0x08010110, 0x08010910, 0x00000110, 0x00000910, 0x08000110, 0x08000910, 0x00010110, 0x00010910, 0x08010110, 0x08010910, 0x00040000, 0x00040800, 0x08040000, 0x08040800, 0x00050000, 0x00050800, 0x08050000, 0x08050800, 0x00040000, 0x00040800, 0x08040000, 0x08040800, 0x00050000, 0x00050800, 0x08050000, 0x08050800, 0x00040100, 0x00040900, 0x08040100, 0x08040900, 0x00050100, 0x00050900, 0x08050100, 0x08050900, 0x00040100, 0x00040900, 0x08040100, 0x08040900, 0x00050100, 0x00050900, 0x08050100, 0x08050900, 0x00040010, 0x00040810, 0x08040010, 0x08040810, 0x00050010, 0x00050810, 0x08050010, 0x08050810, 0x00040010, 0x00040810, 0x08040010, 0x08040810, 0x00050010, 0x00050810, 0x08050010, 0x08050810, 0x00040110, 0x00040910, 0x08040110, 0x08040910, 0x00050110, 0x00050910, 0x08050110, 0x08050910, 0x00040110, 0x00040910, 0x08040110, 0x08040910, 0x00050110, 0x00050910, 0x08050110, 0x08050910, 0x01000000, 0x01000800, 0x09000000, 0x09000800, 0x01010000, 0x01010800, 0x09010000, 0x09010800, 0x01000000, 0x01000800, 0x09000000, 0x09000800, 0x01010000, 0x01010800, 0x09010000, 0x09010800, 0x01000100, 0x01000900, 0x09000100, 0x09000900, 0x01010100, 0x01010900, 0x09010100, 0x09010900, 0x01000100, 0x01000900, 0x09000100, 0x09000900, 0x01010100, 0x01010900, 0x09010100, 0x09010900, 0x01000010, 0x01000810, 0x09000010, 0x09000810, 0x01010010, 0x01010810, 0x09010010, 0x09010810, 0x01000010, 0x01000810, 0x09000010, 0x09000810, 0x01010010, 0x01010810, 0x09010010, 0x09010810, 0x01000110, 0x01000910, 0x09000110, 0x09000910, 0x01010110, 0x01010910, 0x09010110, 0x09010910, 0x01000110, 0x01000910, 0x09000110, 0x09000910, 0x01010110, 0x01010910, 0x09010110, 0x09010910, 0x01040000, 0x01040800, 0x09040000, 0x09040800, 0x01050000, 0x01050800, 0x09050000, 0x09050800, 0x01040000, 0x01040800, 0x09040000, 0x09040800, 0x01050000, 0x01050800, 0x09050000, 0x09050800, 0x01040100, 0x01040900, 0x09040100, 0x09040900, 0x01050100, 0x01050900, 0x09050100, 0x09050900, 0x01040100, 0x01040900, 0x09040100, 0x09040900, 0x01050100, 0x01050900, 0x09050100, 0x09050900, 0x01040010, 0x01040810, 0x09040010, 0x09040810, 0x01050010, 0x01050810, 0x09050010, 0x09050810, 0x01040010, 0x01040810, 0x09040010, 0x09040810, 0x01050010, 0x01050810, 0x09050010, 0x09050810, 0x01040110, 0x01040910, 0x09040110, 0x09040910, 0x01050110, 0x01050910, 0x09050110, 0x09050910, 0x01040110, 0x01040910, 0x09040110, 0x09040910, 0x01050110, 0x01050910, 0x09050110, 0x09050910 ); static $pc2mapc3 = array( 0x00000000, 0x00000004, 0x00001000, 0x00001004, 0x00000000, 0x00000004, 0x00001000, 0x00001004, 0x10000000, 0x10000004, 0x10001000, 0x10001004, 0x10000000, 0x10000004, 0x10001000, 0x10001004, 0x00000020, 0x00000024, 0x00001020, 0x00001024, 0x00000020, 0x00000024, 0x00001020, 0x00001024, 0x10000020, 0x10000024, 0x10001020, 0x10001024, 0x10000020, 0x10000024, 0x10001020, 0x10001024, 0x00080000, 0x00080004, 0x00081000, 0x00081004, 0x00080000, 0x00080004, 0x00081000, 0x00081004, 0x10080000, 0x10080004, 0x10081000, 0x10081004, 0x10080000, 0x10080004, 0x10081000, 0x10081004, 0x00080020, 0x00080024, 0x00081020, 0x00081024, 0x00080020, 0x00080024, 0x00081020, 0x00081024, 0x10080020, 0x10080024, 0x10081020, 0x10081024, 0x10080020, 0x10080024, 0x10081020, 0x10081024, 0x20000000, 0x20000004, 0x20001000, 0x20001004, 0x20000000, 0x20000004, 0x20001000, 0x20001004, 0x30000000, 0x30000004, 0x30001000, 0x30001004, 0x30000000, 0x30000004, 0x30001000, 0x30001004, 0x20000020, 0x20000024, 0x20001020, 0x20001024, 0x20000020, 0x20000024, 0x20001020, 0x20001024, 0x30000020, 0x30000024, 0x30001020, 0x30001024, 0x30000020, 0x30000024, 0x30001020, 0x30001024, 0x20080000, 0x20080004, 0x20081000, 0x20081004, 0x20080000, 0x20080004, 0x20081000, 0x20081004, 0x30080000, 0x30080004, 0x30081000, 0x30081004, 0x30080000, 0x30080004, 0x30081000, 0x30081004, 0x20080020, 0x20080024, 0x20081020, 0x20081024, 0x20080020, 0x20080024, 0x20081020, 0x20081024, 0x30080020, 0x30080024, 0x30081020, 0x30081024, 0x30080020, 0x30080024, 0x30081020, 0x30081024, 0x00000002, 0x00000006, 0x00001002, 0x00001006, 0x00000002, 0x00000006, 0x00001002, 0x00001006, 0x10000002, 0x10000006, 0x10001002, 0x10001006, 0x10000002, 0x10000006, 0x10001002, 0x10001006, 0x00000022, 0x00000026, 0x00001022, 0x00001026, 0x00000022, 0x00000026, 0x00001022, 0x00001026, 0x10000022, 0x10000026, 0x10001022, 0x10001026, 0x10000022, 0x10000026, 0x10001022, 0x10001026, 0x00080002, 0x00080006, 0x00081002, 0x00081006, 0x00080002, 0x00080006, 0x00081002, 0x00081006, 0x10080002, 0x10080006, 0x10081002, 0x10081006, 0x10080002, 0x10080006, 0x10081002, 0x10081006, 0x00080022, 0x00080026, 0x00081022, 0x00081026, 0x00080022, 0x00080026, 0x00081022, 0x00081026, 0x10080022, 0x10080026, 0x10081022, 0x10081026, 0x10080022, 0x10080026, 0x10081022, 0x10081026, 0x20000002, 0x20000006, 0x20001002, 0x20001006, 0x20000002, 0x20000006, 0x20001002, 0x20001006, 0x30000002, 0x30000006, 0x30001002, 0x30001006, 0x30000002, 0x30000006, 0x30001002, 0x30001006, 0x20000022, 0x20000026, 0x20001022, 0x20001026, 0x20000022, 0x20000026, 0x20001022, 0x20001026, 0x30000022, 0x30000026, 0x30001022, 0x30001026, 0x30000022, 0x30000026, 0x30001022, 0x30001026, 0x20080002, 0x20080006, 0x20081002, 0x20081006, 0x20080002, 0x20080006, 0x20081002, 0x20081006, 0x30080002, 0x30080006, 0x30081002, 0x30081006, 0x30080002, 0x30080006, 0x30081002, 0x30081006, 0x20080022, 0x20080026, 0x20081022, 0x20081026, 0x20080022, 0x20080026, 0x20081022, 0x20081026, 0x30080022, 0x30080026, 0x30081022, 0x30081026, 0x30080022, 0x30080026, 0x30081022, 0x30081026 ); static $pc2mapc4 = array( 0x00000000, 0x00100000, 0x00000008, 0x00100008, 0x00000200, 0x00100200, 0x00000208, 0x00100208, 0x00000000, 0x00100000, 0x00000008, 0x00100008, 0x00000200, 0x00100200, 0x00000208, 0x00100208, 0x04000000, 0x04100000, 0x04000008, 0x04100008, 0x04000200, 0x04100200, 0x04000208, 0x04100208, 0x04000000, 0x04100000, 0x04000008, 0x04100008, 0x04000200, 0x04100200, 0x04000208, 0x04100208, 0x00002000, 0x00102000, 0x00002008, 0x00102008, 0x00002200, 0x00102200, 0x00002208, 0x00102208, 0x00002000, 0x00102000, 0x00002008, 0x00102008, 0x00002200, 0x00102200, 0x00002208, 0x00102208, 0x04002000, 0x04102000, 0x04002008, 0x04102008, 0x04002200, 0x04102200, 0x04002208, 0x04102208, 0x04002000, 0x04102000, 0x04002008, 0x04102008, 0x04002200, 0x04102200, 0x04002208, 0x04102208, 0x00000000, 0x00100000, 0x00000008, 0x00100008, 0x00000200, 0x00100200, 0x00000208, 0x00100208, 0x00000000, 0x00100000, 0x00000008, 0x00100008, 0x00000200, 0x00100200, 0x00000208, 0x00100208, 0x04000000, 0x04100000, 0x04000008, 0x04100008, 0x04000200, 0x04100200, 0x04000208, 0x04100208, 0x04000000, 0x04100000, 0x04000008, 0x04100008, 0x04000200, 0x04100200, 0x04000208, 0x04100208, 0x00002000, 0x00102000, 0x00002008, 0x00102008, 0x00002200, 0x00102200, 0x00002208, 0x00102208, 0x00002000, 0x00102000, 0x00002008, 0x00102008, 0x00002200, 0x00102200, 0x00002208, 0x00102208, 0x04002000, 0x04102000, 0x04002008, 0x04102008, 0x04002200, 0x04102200, 0x04002208, 0x04102208, 0x04002000, 0x04102000, 0x04002008, 0x04102008, 0x04002200, 0x04102200, 0x04002208, 0x04102208, 0x00020000, 0x00120000, 0x00020008, 0x00120008, 0x00020200, 0x00120200, 0x00020208, 0x00120208, 0x00020000, 0x00120000, 0x00020008, 0x00120008, 0x00020200, 0x00120200, 0x00020208, 0x00120208, 0x04020000, 0x04120000, 0x04020008, 0x04120008, 0x04020200, 0x04120200, 0x04020208, 0x04120208, 0x04020000, 0x04120000, 0x04020008, 0x04120008, 0x04020200, 0x04120200, 0x04020208, 0x04120208, 0x00022000, 0x00122000, 0x00022008, 0x00122008, 0x00022200, 0x00122200, 0x00022208, 0x00122208, 0x00022000, 0x00122000, 0x00022008, 0x00122008, 0x00022200, 0x00122200, 0x00022208, 0x00122208, 0x04022000, 0x04122000, 0x04022008, 0x04122008, 0x04022200, 0x04122200, 0x04022208, 0x04122208, 0x04022000, 0x04122000, 0x04022008, 0x04122008, 0x04022200, 0x04122200, 0x04022208, 0x04122208, 0x00020000, 0x00120000, 0x00020008, 0x00120008, 0x00020200, 0x00120200, 0x00020208, 0x00120208, 0x00020000, 0x00120000, 0x00020008, 0x00120008, 0x00020200, 0x00120200, 0x00020208, 0x00120208, 0x04020000, 0x04120000, 0x04020008, 0x04120008, 0x04020200, 0x04120200, 0x04020208, 0x04120208, 0x04020000, 0x04120000, 0x04020008, 0x04120008, 0x04020200, 0x04120200, 0x04020208, 0x04120208, 0x00022000, 0x00122000, 0x00022008, 0x00122008, 0x00022200, 0x00122200, 0x00022208, 0x00122208, 0x00022000, 0x00122000, 0x00022008, 0x00122008, 0x00022200, 0x00122200, 0x00022208, 0x00122208, 0x04022000, 0x04122000, 0x04022008, 0x04122008, 0x04022200, 0x04122200, 0x04022208, 0x04122208, 0x04022000, 0x04122000, 0x04022008, 0x04122008, 0x04022200, 0x04122200, 0x04022208, 0x04122208 ); static $pc2mapd1 = array( 0x00000000, 0x00000001, 0x08000000, 0x08000001, 0x00200000, 0x00200001, 0x08200000, 0x08200001, 0x00000002, 0x00000003, 0x08000002, 0x08000003, 0x00200002, 0x00200003, 0x08200002, 0x08200003 ); static $pc2mapd2 = array( 0x00000000, 0x00100000, 0x00000800, 0x00100800, 0x00000000, 0x00100000, 0x00000800, 0x00100800, 0x04000000, 0x04100000, 0x04000800, 0x04100800, 0x04000000, 0x04100000, 0x04000800, 0x04100800, 0x00000004, 0x00100004, 0x00000804, 0x00100804, 0x00000004, 0x00100004, 0x00000804, 0x00100804, 0x04000004, 0x04100004, 0x04000804, 0x04100804, 0x04000004, 0x04100004, 0x04000804, 0x04100804, 0x00000000, 0x00100000, 0x00000800, 0x00100800, 0x00000000, 0x00100000, 0x00000800, 0x00100800, 0x04000000, 0x04100000, 0x04000800, 0x04100800, 0x04000000, 0x04100000, 0x04000800, 0x04100800, 0x00000004, 0x00100004, 0x00000804, 0x00100804, 0x00000004, 0x00100004, 0x00000804, 0x00100804, 0x04000004, 0x04100004, 0x04000804, 0x04100804, 0x04000004, 0x04100004, 0x04000804, 0x04100804, 0x00000200, 0x00100200, 0x00000A00, 0x00100A00, 0x00000200, 0x00100200, 0x00000A00, 0x00100A00, 0x04000200, 0x04100200, 0x04000A00, 0x04100A00, 0x04000200, 0x04100200, 0x04000A00, 0x04100A00, 0x00000204, 0x00100204, 0x00000A04, 0x00100A04, 0x00000204, 0x00100204, 0x00000A04, 0x00100A04, 0x04000204, 0x04100204, 0x04000A04, 0x04100A04, 0x04000204, 0x04100204, 0x04000A04, 0x04100A04, 0x00000200, 0x00100200, 0x00000A00, 0x00100A00, 0x00000200, 0x00100200, 0x00000A00, 0x00100A00, 0x04000200, 0x04100200, 0x04000A00, 0x04100A00, 0x04000200, 0x04100200, 0x04000A00, 0x04100A00, 0x00000204, 0x00100204, 0x00000A04, 0x00100A04, 0x00000204, 0x00100204, 0x00000A04, 0x00100A04, 0x04000204, 0x04100204, 0x04000A04, 0x04100A04, 0x04000204, 0x04100204, 0x04000A04, 0x04100A04, 0x00020000, 0x00120000, 0x00020800, 0x00120800, 0x00020000, 0x00120000, 0x00020800, 0x00120800, 0x04020000, 0x04120000, 0x04020800, 0x04120800, 0x04020000, 0x04120000, 0x04020800, 0x04120800, 0x00020004, 0x00120004, 0x00020804, 0x00120804, 0x00020004, 0x00120004, 0x00020804, 0x00120804, 0x04020004, 0x04120004, 0x04020804, 0x04120804, 0x04020004, 0x04120004, 0x04020804, 0x04120804, 0x00020000, 0x00120000, 0x00020800, 0x00120800, 0x00020000, 0x00120000, 0x00020800, 0x00120800, 0x04020000, 0x04120000, 0x04020800, 0x04120800, 0x04020000, 0x04120000, 0x04020800, 0x04120800, 0x00020004, 0x00120004, 0x00020804, 0x00120804, 0x00020004, 0x00120004, 0x00020804, 0x00120804, 0x04020004, 0x04120004, 0x04020804, 0x04120804, 0x04020004, 0x04120004, 0x04020804, 0x04120804, 0x00020200, 0x00120200, 0x00020A00, 0x00120A00, 0x00020200, 0x00120200, 0x00020A00, 0x00120A00, 0x04020200, 0x04120200, 0x04020A00, 0x04120A00, 0x04020200, 0x04120200, 0x04020A00, 0x04120A00, 0x00020204, 0x00120204, 0x00020A04, 0x00120A04, 0x00020204, 0x00120204, 0x00020A04, 0x00120A04, 0x04020204, 0x04120204, 0x04020A04, 0x04120A04, 0x04020204, 0x04120204, 0x04020A04, 0x04120A04, 0x00020200, 0x00120200, 0x00020A00, 0x00120A00, 0x00020200, 0x00120200, 0x00020A00, 0x00120A00, 0x04020200, 0x04120200, 0x04020A00, 0x04120A00, 0x04020200, 0x04120200, 0x04020A00, 0x04120A00, 0x00020204, 0x00120204, 0x00020A04, 0x00120A04, 0x00020204, 0x00120204, 0x00020A04, 0x00120A04, 0x04020204, 0x04120204, 0x04020A04, 0x04120A04, 0x04020204, 0x04120204, 0x04020A04, 0x04120A04 ); static $pc2mapd3 = array( 0x00000000, 0x00010000, 0x02000000, 0x02010000, 0x00000020, 0x00010020, 0x02000020, 0x02010020, 0x00040000, 0x00050000, 0x02040000, 0x02050000, 0x00040020, 0x00050020, 0x02040020, 0x02050020, 0x00002000, 0x00012000, 0x02002000, 0x02012000, 0x00002020, 0x00012020, 0x02002020, 0x02012020, 0x00042000, 0x00052000, 0x02042000, 0x02052000, 0x00042020, 0x00052020, 0x02042020, 0x02052020, 0x00000000, 0x00010000, 0x02000000, 0x02010000, 0x00000020, 0x00010020, 0x02000020, 0x02010020, 0x00040000, 0x00050000, 0x02040000, 0x02050000, 0x00040020, 0x00050020, 0x02040020, 0x02050020, 0x00002000, 0x00012000, 0x02002000, 0x02012000, 0x00002020, 0x00012020, 0x02002020, 0x02012020, 0x00042000, 0x00052000, 0x02042000, 0x02052000, 0x00042020, 0x00052020, 0x02042020, 0x02052020, 0x00000010, 0x00010010, 0x02000010, 0x02010010, 0x00000030, 0x00010030, 0x02000030, 0x02010030, 0x00040010, 0x00050010, 0x02040010, 0x02050010, 0x00040030, 0x00050030, 0x02040030, 0x02050030, 0x00002010, 0x00012010, 0x02002010, 0x02012010, 0x00002030, 0x00012030, 0x02002030, 0x02012030, 0x00042010, 0x00052010, 0x02042010, 0x02052010, 0x00042030, 0x00052030, 0x02042030, 0x02052030, 0x00000010, 0x00010010, 0x02000010, 0x02010010, 0x00000030, 0x00010030, 0x02000030, 0x02010030, 0x00040010, 0x00050010, 0x02040010, 0x02050010, 0x00040030, 0x00050030, 0x02040030, 0x02050030, 0x00002010, 0x00012010, 0x02002010, 0x02012010, 0x00002030, 0x00012030, 0x02002030, 0x02012030, 0x00042010, 0x00052010, 0x02042010, 0x02052010, 0x00042030, 0x00052030, 0x02042030, 0x02052030, 0x20000000, 0x20010000, 0x22000000, 0x22010000, 0x20000020, 0x20010020, 0x22000020, 0x22010020, 0x20040000, 0x20050000, 0x22040000, 0x22050000, 0x20040020, 0x20050020, 0x22040020, 0x22050020, 0x20002000, 0x20012000, 0x22002000, 0x22012000, 0x20002020, 0x20012020, 0x22002020, 0x22012020, 0x20042000, 0x20052000, 0x22042000, 0x22052000, 0x20042020, 0x20052020, 0x22042020, 0x22052020, 0x20000000, 0x20010000, 0x22000000, 0x22010000, 0x20000020, 0x20010020, 0x22000020, 0x22010020, 0x20040000, 0x20050000, 0x22040000, 0x22050000, 0x20040020, 0x20050020, 0x22040020, 0x22050020, 0x20002000, 0x20012000, 0x22002000, 0x22012000, 0x20002020, 0x20012020, 0x22002020, 0x22012020, 0x20042000, 0x20052000, 0x22042000, 0x22052000, 0x20042020, 0x20052020, 0x22042020, 0x22052020, 0x20000010, 0x20010010, 0x22000010, 0x22010010, 0x20000030, 0x20010030, 0x22000030, 0x22010030, 0x20040010, 0x20050010, 0x22040010, 0x22050010, 0x20040030, 0x20050030, 0x22040030, 0x22050030, 0x20002010, 0x20012010, 0x22002010, 0x22012010, 0x20002030, 0x20012030, 0x22002030, 0x22012030, 0x20042010, 0x20052010, 0x22042010, 0x22052010, 0x20042030, 0x20052030, 0x22042030, 0x22052030, 0x20000010, 0x20010010, 0x22000010, 0x22010010, 0x20000030, 0x20010030, 0x22000030, 0x22010030, 0x20040010, 0x20050010, 0x22040010, 0x22050010, 0x20040030, 0x20050030, 0x22040030, 0x22050030, 0x20002010, 0x20012010, 0x22002010, 0x22012010, 0x20002030, 0x20012030, 0x22002030, 0x22012030, 0x20042010, 0x20052010, 0x22042010, 0x22052010, 0x20042030, 0x20052030, 0x22042030, 0x22052030 ); static $pc2mapd4 = array( 0x00000000, 0x00000400, 0x01000000, 0x01000400, 0x00000000, 0x00000400, 0x01000000, 0x01000400, 0x00000100, 0x00000500, 0x01000100, 0x01000500, 0x00000100, 0x00000500, 0x01000100, 0x01000500, 0x10000000, 0x10000400, 0x11000000, 0x11000400, 0x10000000, 0x10000400, 0x11000000, 0x11000400, 0x10000100, 0x10000500, 0x11000100, 0x11000500, 0x10000100, 0x10000500, 0x11000100, 0x11000500, 0x00080000, 0x00080400, 0x01080000, 0x01080400, 0x00080000, 0x00080400, 0x01080000, 0x01080400, 0x00080100, 0x00080500, 0x01080100, 0x01080500, 0x00080100, 0x00080500, 0x01080100, 0x01080500, 0x10080000, 0x10080400, 0x11080000, 0x11080400, 0x10080000, 0x10080400, 0x11080000, 0x11080400, 0x10080100, 0x10080500, 0x11080100, 0x11080500, 0x10080100, 0x10080500, 0x11080100, 0x11080500, 0x00000008, 0x00000408, 0x01000008, 0x01000408, 0x00000008, 0x00000408, 0x01000008, 0x01000408, 0x00000108, 0x00000508, 0x01000108, 0x01000508, 0x00000108, 0x00000508, 0x01000108, 0x01000508, 0x10000008, 0x10000408, 0x11000008, 0x11000408, 0x10000008, 0x10000408, 0x11000008, 0x11000408, 0x10000108, 0x10000508, 0x11000108, 0x11000508, 0x10000108, 0x10000508, 0x11000108, 0x11000508, 0x00080008, 0x00080408, 0x01080008, 0x01080408, 0x00080008, 0x00080408, 0x01080008, 0x01080408, 0x00080108, 0x00080508, 0x01080108, 0x01080508, 0x00080108, 0x00080508, 0x01080108, 0x01080508, 0x10080008, 0x10080408, 0x11080008, 0x11080408, 0x10080008, 0x10080408, 0x11080008, 0x11080408, 0x10080108, 0x10080508, 0x11080108, 0x11080508, 0x10080108, 0x10080508, 0x11080108, 0x11080508, 0x00001000, 0x00001400, 0x01001000, 0x01001400, 0x00001000, 0x00001400, 0x01001000, 0x01001400, 0x00001100, 0x00001500, 0x01001100, 0x01001500, 0x00001100, 0x00001500, 0x01001100, 0x01001500, 0x10001000, 0x10001400, 0x11001000, 0x11001400, 0x10001000, 0x10001400, 0x11001000, 0x11001400, 0x10001100, 0x10001500, 0x11001100, 0x11001500, 0x10001100, 0x10001500, 0x11001100, 0x11001500, 0x00081000, 0x00081400, 0x01081000, 0x01081400, 0x00081000, 0x00081400, 0x01081000, 0x01081400, 0x00081100, 0x00081500, 0x01081100, 0x01081500, 0x00081100, 0x00081500, 0x01081100, 0x01081500, 0x10081000, 0x10081400, 0x11081000, 0x11081400, 0x10081000, 0x10081400, 0x11081000, 0x11081400, 0x10081100, 0x10081500, 0x11081100, 0x11081500, 0x10081100, 0x10081500, 0x11081100, 0x11081500, 0x00001008, 0x00001408, 0x01001008, 0x01001408, 0x00001008, 0x00001408, 0x01001008, 0x01001408, 0x00001108, 0x00001508, 0x01001108, 0x01001508, 0x00001108, 0x00001508, 0x01001108, 0x01001508, 0x10001008, 0x10001408, 0x11001008, 0x11001408, 0x10001008, 0x10001408, 0x11001008, 0x11001408, 0x10001108, 0x10001508, 0x11001108, 0x11001508, 0x10001108, 0x10001508, 0x11001108, 0x11001508, 0x00081008, 0x00081408, 0x01081008, 0x01081408, 0x00081008, 0x00081408, 0x01081008, 0x01081408, 0x00081108, 0x00081508, 0x01081108, 0x01081508, 0x00081108, 0x00081508, 0x01081108, 0x01081508, 0x10081008, 0x10081408, 0x11081008, 0x11081408, 0x10081008, 0x10081408, 0x11081008, 0x11081408, 0x10081108, 0x10081508, 0x11081108, 0x11081508, 0x10081108, 0x10081508, 0x11081108, 0x11081508 ); $keys = array(); for ($des_round = 0; $des_round < $this->des_rounds; ++$des_round) { // pad the key and remove extra characters as appropriate. $key = str_pad(substr($this->key, $des_round * 8, 8), 8, "\0"); // Perform the PC/1 transformation and compute C and D. $t = unpack('Nl/Nr', $key); list($l, $r) = array($t['l'], $t['r']); $key = ($this->shuffle[$pc1map[ $r & 0xFF]] & "\x80\x80\x80\x80\x80\x80\x80\x00") | ($this->shuffle[$pc1map[($r >> 8) & 0xFF]] & "\x40\x40\x40\x40\x40\x40\x40\x00") | ($this->shuffle[$pc1map[($r >> 16) & 0xFF]] & "\x20\x20\x20\x20\x20\x20\x20\x00") | ($this->shuffle[$pc1map[($r >> 24) & 0xFF]] & "\x10\x10\x10\x10\x10\x10\x10\x00") | ($this->shuffle[$pc1map[ $l & 0xFF]] & "\x08\x08\x08\x08\x08\x08\x08\x00") | ($this->shuffle[$pc1map[($l >> 8) & 0xFF]] & "\x04\x04\x04\x04\x04\x04\x04\x00") | ($this->shuffle[$pc1map[($l >> 16) & 0xFF]] & "\x02\x02\x02\x02\x02\x02\x02\x00") | ($this->shuffle[$pc1map[($l >> 24) & 0xFF]] & "\x01\x01\x01\x01\x01\x01\x01\x00"); $key = unpack('Nc/Nd', $key); $c = ( $key['c'] >> 4) & 0x0FFFFFFF; $d = (($key['d'] >> 4) & 0x0FFFFFF0) | ($key['c'] & 0x0F); $keys[$des_round] = array( self::ENCRYPT => array(), self::DECRYPT => array_fill(0, 32, 0) ); for ($i = 0, $ki = 31; $i < 16; ++$i, $ki-= 2) { $c <<= $shifts[$i]; $c = ($c | ($c >> 28)) & 0x0FFFFFFF; $d <<= $shifts[$i]; $d = ($d | ($d >> 28)) & 0x0FFFFFFF; // Perform the PC-2 transformation. $cp = $pc2mapc1[ $c >> 24 ] | $pc2mapc2[($c >> 16) & 0xFF] | $pc2mapc3[($c >> 8) & 0xFF] | $pc2mapc4[ $c & 0xFF]; $dp = $pc2mapd1[ $d >> 24 ] | $pc2mapd2[($d >> 16) & 0xFF] | $pc2mapd3[($d >> 8) & 0xFF] | $pc2mapd4[ $d & 0xFF]; // Reorder: odd bytes/even bytes. Push the result in key schedule. $val1 = ( $cp & 0xFF000000) | (($cp << 8) & 0x00FF0000) | (($dp >> 16) & 0x0000FF00) | (($dp >> 8) & 0x000000FF); $val2 = (($cp << 8) & 0xFF000000) | (($cp << 16) & 0x00FF0000) | (($dp >> 8) & 0x0000FF00) | ( $dp & 0x000000FF); $keys[$des_round][self::ENCRYPT][ ] = $val1; $keys[$des_round][self::DECRYPT][$ki - 1] = $val1; $keys[$des_round][self::ENCRYPT][ ] = $val2; $keys[$des_round][self::DECRYPT][$ki ] = $val2; } } switch ($this->des_rounds) { case 3: // 3DES keys $this->keys = array( self::ENCRYPT => array_merge( $keys[0][self::ENCRYPT], $keys[1][self::DECRYPT], $keys[2][self::ENCRYPT] ), self::DECRYPT => array_merge( $keys[2][self::DECRYPT], $keys[1][self::ENCRYPT], $keys[0][self::DECRYPT] ) ); break; // case 1: // DES keys default: $this->keys = array( self::ENCRYPT => $keys[0][self::ENCRYPT], self::DECRYPT => $keys[0][self::DECRYPT] ); } } /** * Setup the performance-optimized function for de/encrypt() * * @see \phpseclib\Crypt\Base::_setupInlineCrypt() * @access private */ function _setupInlineCrypt() { $lambda_functions =& self::_getLambdaFunctions(); // Engine configuration for: // - DES ($des_rounds == 1) or // - 3DES ($des_rounds == 3) $des_rounds = $this->des_rounds; // We create max. 10 hi-optimized code for memory reason. Means: For each $key one ultra fast inline-crypt function. // After that, we'll still create very fast optimized code but not the hi-ultimative code, for each $mode one $gen_hi_opt_code = (bool)( count($lambda_functions) < 10 ); // Generation of a uniqe hash for our generated code switch (true) { case $gen_hi_opt_code: // For hi-optimized code, we create for each combination of // $mode, $des_rounds and $this->key its own encrypt/decrypt function. $code_hash = md5(str_pad("DES, $des_rounds, {$this->mode}, ", 32, "\0") . $this->key); break; default: // After max 10 hi-optimized functions, we create generic // (still very fast.. but not ultra) functions for each $mode/$des_rounds // Currently 2 * 5 generic functions will be then max. possible. $code_hash = "DES, $des_rounds, {$this->mode}"; } // Is there a re-usable $lambda_functions in there? If not, we have to create it. if (!isset($lambda_functions[$code_hash])) { // Init code for both, encrypt and decrypt. $init_crypt = 'static $sbox1, $sbox2, $sbox3, $sbox4, $sbox5, $sbox6, $sbox7, $sbox8, $shuffleip, $shuffleinvip; if (!$sbox1) { $sbox1 = array_map("intval", $self->sbox1); $sbox2 = array_map("intval", $self->sbox2); $sbox3 = array_map("intval", $self->sbox3); $sbox4 = array_map("intval", $self->sbox4); $sbox5 = array_map("intval", $self->sbox5); $sbox6 = array_map("intval", $self->sbox6); $sbox7 = array_map("intval", $self->sbox7); $sbox8 = array_map("intval", $self->sbox8);' /* Merge $shuffle with $[inv]ipmap */ . ' for ($i = 0; $i < 256; ++$i) { $shuffleip[] = $self->shuffle[$self->ipmap[$i]]; $shuffleinvip[] = $self->shuffle[$self->invipmap[$i]]; } } '; switch (true) { case $gen_hi_opt_code: // In Hi-optimized code mode, we use our [3]DES key schedule as hardcoded integers. // No futher initialisation of the $keys schedule is necessary. // That is the extra performance boost. $k = array( self::ENCRYPT => $this->keys[self::ENCRYPT], self::DECRYPT => $this->keys[self::DECRYPT] ); $init_encrypt = ''; $init_decrypt = ''; break; default: // In generic optimized code mode, we have to use, as the best compromise [currently], // our key schedule as $ke/$kd arrays. (with hardcoded indexes...) $k = array( self::ENCRYPT => array(), self::DECRYPT => array() ); for ($i = 0, $c = count($this->keys[self::ENCRYPT]); $i < $c; ++$i) { $k[self::ENCRYPT][$i] = '$ke[' . $i . ']'; $k[self::DECRYPT][$i] = '$kd[' . $i . ']'; } $init_encrypt = '$ke = $self->keys[self::ENCRYPT];'; $init_decrypt = '$kd = $self->keys[self::DECRYPT];'; break; } // Creating code for en- and decryption. $crypt_block = array(); foreach (array(self::ENCRYPT, self::DECRYPT) as $c) { /* Do the initial IP permutation. */ $crypt_block[$c] = ' $in = unpack("N*", $in); $l = $in[1]; $r = $in[2]; $in = unpack("N*", ($shuffleip[ $r & 0xFF] & "\x80\x80\x80\x80\x80\x80\x80\x80") | ($shuffleip[($r >> 8) & 0xFF] & "\x40\x40\x40\x40\x40\x40\x40\x40") | ($shuffleip[($r >> 16) & 0xFF] & "\x20\x20\x20\x20\x20\x20\x20\x20") | ($shuffleip[($r >> 24) & 0xFF] & "\x10\x10\x10\x10\x10\x10\x10\x10") | ($shuffleip[ $l & 0xFF] & "\x08\x08\x08\x08\x08\x08\x08\x08") | ($shuffleip[($l >> 8) & 0xFF] & "\x04\x04\x04\x04\x04\x04\x04\x04") | ($shuffleip[($l >> 16) & 0xFF] & "\x02\x02\x02\x02\x02\x02\x02\x02") | ($shuffleip[($l >> 24) & 0xFF] & "\x01\x01\x01\x01\x01\x01\x01\x01") ); ' . /* Extract L0 and R0 */ ' $l = $in[1]; $r = $in[2]; '; $l = '$l'; $r = '$r'; // Perform DES or 3DES. for ($ki = -1, $des_round = 0; $des_round < $des_rounds; ++$des_round) { // Perform the 16 steps. for ($i = 0; $i < 16; ++$i) { // start of "the Feistel (F) function" - see the following URL: // http://en.wikipedia.org/wiki/Image:Data_Encryption_Standard_InfoBox_Diagram.png // Merge key schedule. $crypt_block[$c].= ' $b1 = ((' . $r . ' >> 3) & 0x1FFFFFFF) ^ (' . $r . ' << 29) ^ ' . $k[$c][++$ki] . '; $b2 = ((' . $r . ' >> 31) & 0x00000001) ^ (' . $r . ' << 1) ^ ' . $k[$c][++$ki] . ';' . /* S-box indexing. */ $l . ' = $sbox1[($b1 >> 24) & 0x3F] ^ $sbox2[($b2 >> 24) & 0x3F] ^ $sbox3[($b1 >> 16) & 0x3F] ^ $sbox4[($b2 >> 16) & 0x3F] ^ $sbox5[($b1 >> 8) & 0x3F] ^ $sbox6[($b2 >> 8) & 0x3F] ^ $sbox7[ $b1 & 0x3F] ^ $sbox8[ $b2 & 0x3F] ^ ' . $l . '; '; // end of "the Feistel (F) function" // swap L & R list($l, $r) = array($r, $l); } list($l, $r) = array($r, $l); } // Perform the inverse IP permutation. $crypt_block[$c].= '$in = ($shuffleinvip[($l >> 24) & 0xFF] & "\x80\x80\x80\x80\x80\x80\x80\x80") | ($shuffleinvip[($r >> 24) & 0xFF] & "\x40\x40\x40\x40\x40\x40\x40\x40") | ($shuffleinvip[($l >> 16) & 0xFF] & "\x20\x20\x20\x20\x20\x20\x20\x20") | ($shuffleinvip[($r >> 16) & 0xFF] & "\x10\x10\x10\x10\x10\x10\x10\x10") | ($shuffleinvip[($l >> 8) & 0xFF] & "\x08\x08\x08\x08\x08\x08\x08\x08") | ($shuffleinvip[($r >> 8) & 0xFF] & "\x04\x04\x04\x04\x04\x04\x04\x04") | ($shuffleinvip[ $l & 0xFF] & "\x02\x02\x02\x02\x02\x02\x02\x02") | ($shuffleinvip[ $r & 0xFF] & "\x01\x01\x01\x01\x01\x01\x01\x01"); '; } // Creates the inline-crypt function $lambda_functions[$code_hash] = $this->_createInlineCryptFunction( array( 'init_crypt' => $init_crypt, 'init_encrypt' => $init_encrypt, 'init_decrypt' => $init_decrypt, 'encrypt_block' => $crypt_block[self::ENCRYPT], 'decrypt_block' => $crypt_block[self::DECRYPT] ) ); } // Set the inline-crypt function as callback in: $this->inline_crypt $this->inline_crypt = $lambda_functions[$code_hash]; } } * setKey('abcdefg'); * * echo base64_encode($hash->hash('abcdefg')); * ?> * * * @category Crypt * @package Hash * @author Jim Wigginton * @copyright 2007 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\Crypt; use phpseclib\Math\BigInteger; /** * Pure-PHP implementations of keyed-hash message authentication codes (HMACs) and various cryptographic hashing functions. * * @package Hash * @author Jim Wigginton * @access public */ class Hash { /**#@+ * @access private * @see \phpseclib\Crypt\Hash::__construct() */ /** * Toggles the internal implementation */ const MODE_INTERNAL = 1; /** * Toggles the mhash() implementation, which has been deprecated on PHP 5.3.0+. */ const MODE_MHASH = 2; /** * Toggles the hash() implementation, which works on PHP 5.1.2+. */ const MODE_HASH = 3; /**#@-*/ /** * Hash Parameter * * @see \phpseclib\Crypt\Hash::setHash() * @var Integer * @access private */ var $hashParam; /** * Byte-length of compression blocks / key (Internal HMAC) * * @see \phpseclib\Crypt\Hash::setAlgorithm() * @var Integer * @access private */ var $b; /** * Byte-length of hash output (Internal HMAC) * * @see \phpseclib\Crypt\Hash::setHash() * @var Integer * @access private */ var $l = false; /** * Hash Algorithm * * @see \phpseclib\Crypt\Hash::setHash() * @var String * @access private */ var $hash; /** * Key * * @see \phpseclib\Crypt\Hash::setKey() * @var String * @access private */ var $key = false; /** * Outer XOR (Internal HMAC) * * @see \phpseclib\Crypt\Hash::setKey() * @var String * @access private */ var $opad; /** * Inner XOR (Internal HMAC) * * @see \phpseclib\Crypt\Hash::setKey() * @var String * @access private */ var $ipad; /** * Default Constructor. * * @param optional String $hash * @return \phpseclib\Crypt\Hash * @access public */ function __construct($hash = 'sha1') { if ( !defined('CRYPT_HASH_MODE') ) { switch (true) { case extension_loaded('hash'): define('CRYPT_HASH_MODE', self::MODE_HASH); break; case extension_loaded('mhash'): define('CRYPT_HASH_MODE', self::MODE_MHASH); break; default: define('CRYPT_HASH_MODE', self::MODE_INTERNAL); } } $this->setHash($hash); } /** * Sets the key for HMACs * * Keys can be of any length. * * @access public * @param optional String $key */ function setKey($key = false) { $this->key = $key; } /** * Gets the hash function. * * As set by the constructor or by the setHash() method. * * @access public * @return String */ function getHash() { return $this->hashParam; } /** * Sets the hash function. * * @access public * @param String $hash */ function setHash($hash) { $this->hashParam = $hash = strtolower($hash); switch ($hash) { case 'md5-96': case 'sha1-96': case 'sha256-96': case 'sha512-96': $hash = substr($hash, 0, -3); $this->l = 12; // 96 / 8 = 12 break; case 'md2': case 'md5': $this->l = 16; break; case 'sha1': $this->l = 20; break; case 'sha256': $this->l = 32; break; case 'sha384': $this->l = 48; break; case 'sha512': $this->l = 64; } switch ($hash) { case 'md2': $mode = CRYPT_HASH_MODE == self::MODE_HASH && in_array('md2', hash_algos()) ? self::MODE_HASH : self::MODE_INTERNAL; break; case 'sha384': case 'sha512': $mode = CRYPT_HASH_MODE == self::MODE_MHASH ? self::MODE_INTERNAL : CRYPT_HASH_MODE; break; default: $mode = CRYPT_HASH_MODE; } switch ( $mode ) { case self::MODE_MHASH: switch ($hash) { case 'md5': $this->hash = MHASH_MD5; break; case 'sha256': $this->hash = MHASH_SHA256; break; case 'sha1': default: $this->hash = MHASH_SHA1; } return; case self::MODE_HASH: switch ($hash) { case 'md5': $this->hash = 'md5'; return; case 'md2': case 'sha256': case 'sha384': case 'sha512': $this->hash = $hash; return; case 'sha1': default: $this->hash = 'sha1'; } return; } switch ($hash) { case 'md2': $this->b = 16; $this->hash = array($this, '_md2'); break; case 'md5': $this->b = 64; $this->hash = array($this, '_md5'); break; case 'sha256': $this->b = 64; $this->hash = array($this, '_sha256'); break; case 'sha384': case 'sha512': $this->b = 128; $this->hash = array($this, '_sha512'); break; case 'sha1': default: $this->b = 64; $this->hash = array($this, '_sha1'); } $this->ipad = str_repeat(chr(0x36), $this->b); $this->opad = str_repeat(chr(0x5C), $this->b); } /** * Compute the HMAC. * * @access public * @param String $text * @return String */ function hash($text) { $mode = is_array($this->hash) ? self::MODE_INTERNAL : CRYPT_HASH_MODE; if (!empty($this->key) || is_string($this->key)) { switch ( $mode ) { case self::MODE_MHASH: $output = mhash($this->hash, $text, $this->key); break; case self::MODE_HASH: $output = hash_hmac($this->hash, $text, $this->key, true); break; case self::MODE_INTERNAL: /* "Applications that use keys longer than B bytes will first hash the key using H and then use the resultant L byte string as the actual key to HMAC." -- http://tools.ietf.org/html/rfc2104#section-2 */ $key = strlen($this->key) > $this->b ? call_user_func($this->hash, $this->key) : $this->key; $key = str_pad($key, $this->b, chr(0)); // step 1 $temp = $this->ipad ^ $key; // step 2 $temp .= $text; // step 3 $temp = call_user_func($this->hash, $temp); // step 4 $output = $this->opad ^ $key; // step 5 $output.= $temp; // step 6 $output = call_user_func($this->hash, $output); // step 7 } } else { switch ( $mode ) { case self::MODE_MHASH: $output = mhash($this->hash, $text); break; case self::MODE_HASH: $output = hash($this->hash, $text, true); break; case self::MODE_INTERNAL: $output = call_user_func($this->hash, $text); } } return substr($output, 0, $this->l); } /** * Returns the hash length (in bytes) * * @access public * @return Integer */ function getLength() { return $this->l; } /** * Wrapper for MD5 * * @access private * @param String $m */ function _md5($m) { return pack('H*', md5($m)); } /** * Wrapper for SHA1 * * @access private * @param String $m */ function _sha1($m) { return pack('H*', sha1($m)); } /** * Pure-PHP implementation of MD2 * * See {@link http://tools.ietf.org/html/rfc1319 RFC1319}. * * @access private * @param String $m */ function _md2($m) { static $s = array( 41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240, 6, 19, 98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217, 188, 76, 130, 202, 30, 155, 87, 60, 253, 212, 224, 22, 103, 66, 111, 24, 138, 23, 229, 18, 190, 78, 196, 214, 218, 158, 222, 73, 160, 251, 245, 142, 187, 47, 238, 122, 169, 104, 121, 145, 21, 178, 7, 63, 148, 194, 16, 137, 11, 34, 95, 33, 128, 127, 93, 154, 90, 144, 50, 39, 53, 62, 204, 231, 191, 247, 151, 3, 255, 25, 48, 179, 72, 165, 181, 209, 215, 94, 146, 42, 172, 86, 170, 198, 79, 184, 56, 210, 150, 164, 125, 182, 118, 252, 107, 226, 156, 116, 4, 241, 69, 157, 112, 89, 100, 113, 135, 32, 134, 91, 207, 101, 230, 45, 168, 2, 27, 96, 37, 173, 174, 176, 185, 246, 28, 70, 97, 105, 52, 64, 126, 15, 85, 71, 163, 35, 221, 81, 175, 58, 195, 92, 249, 206, 186, 197, 234, 38, 44, 83, 13, 110, 133, 40, 132, 9, 211, 223, 205, 244, 65, 129, 77, 82, 106, 220, 55, 200, 108, 193, 171, 250, 36, 225, 123, 8, 12, 189, 177, 74, 120, 136, 149, 139, 227, 99, 232, 109, 233, 203, 213, 254, 59, 0, 29, 57, 242, 239, 183, 14, 102, 88, 208, 228, 166, 119, 114, 248, 235, 117, 75, 10, 49, 68, 80, 180, 143, 237, 31, 26, 219, 153, 141, 51, 159, 17, 131, 20 ); // Step 1. Append Padding Bytes $pad = 16 - (strlen($m) & 0xF); $m.= str_repeat(chr($pad), $pad); $length = strlen($m); // Step 2. Append Checksum $c = str_repeat(chr(0), 16); $l = chr(0); for ($i = 0; $i < $length; $i+= 16) { for ($j = 0; $j < 16; $j++) { // RFC1319 incorrectly states that C[j] should be set to S[c xor L] //$c[$j] = chr($s[ord($m[$i + $j] ^ $l)]); // per , however, C[j] should be set to S[c xor L] xor C[j] $c[$j] = chr($s[ord($m[$i + $j] ^ $l)] ^ ord($c[$j])); $l = $c[$j]; } } $m.= $c; $length+= 16; // Step 3. Initialize MD Buffer $x = str_repeat(chr(0), 48); // Step 4. Process Message in 16-Byte Blocks for ($i = 0; $i < $length; $i+= 16) { for ($j = 0; $j < 16; $j++) { $x[$j + 16] = $m[$i + $j]; $x[$j + 32] = $x[$j + 16] ^ $x[$j]; } $t = chr(0); for ($j = 0; $j < 18; $j++) { for ($k = 0; $k < 48; $k++) { $x[$k] = $t = $x[$k] ^ chr($s[ord($t)]); //$t = $x[$k] = $x[$k] ^ chr($s[ord($t)]); } $t = chr(ord($t) + $j); } } // Step 5. Output return substr($x, 0, 16); } /** * Pure-PHP implementation of SHA256 * * See {@link http://en.wikipedia.org/wiki/SHA_hash_functions#SHA-256_.28a_SHA-2_variant.29_pseudocode SHA-256 (a SHA-2 variant) pseudocode - Wikipedia}. * * @access private * @param String $m */ function _sha256($m) { if (extension_loaded('suhosin')) { return pack('H*', sha256($m)); } // Initialize variables $hash = array( 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ); // Initialize table of round constants // (first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) static $k = array( 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ); // Pre-processing $length = strlen($m); // to round to nearest 56 mod 64, we'll add 64 - (length + (64 - 56)) % 64 $m.= str_repeat(chr(0), 64 - (($length + 8) & 0x3F)); $m[$length] = chr(0x80); // we don't support hashing strings 512MB long $m.= pack('N2', 0, $length << 3); // Process the message in successive 512-bit chunks $chunks = str_split($m, 64); foreach ($chunks as $chunk) { $w = array(); for ($i = 0; $i < 16; $i++) { extract(unpack('Ntemp', $this->_string_shift($chunk, 4))); $w[] = $temp; } // Extend the sixteen 32-bit words into sixty-four 32-bit words for ($i = 16; $i < 64; $i++) { $s0 = $this->_rightRotate($w[$i - 15], 7) ^ $this->_rightRotate($w[$i - 15], 18) ^ $this->_rightShift( $w[$i - 15], 3); $s1 = $this->_rightRotate($w[$i - 2], 17) ^ $this->_rightRotate($w[$i - 2], 19) ^ $this->_rightShift( $w[$i - 2], 10); $w[$i] = $this->_add($w[$i - 16], $s0, $w[$i - 7], $s1); } // Initialize hash value for this chunk list($a, $b, $c, $d, $e, $f, $g, $h) = $hash; // Main loop for ($i = 0; $i < 64; $i++) { $s0 = $this->_rightRotate($a, 2) ^ $this->_rightRotate($a, 13) ^ $this->_rightRotate($a, 22); $maj = ($a & $b) ^ ($a & $c) ^ ($b & $c); $t2 = $this->_add($s0, $maj); $s1 = $this->_rightRotate($e, 6) ^ $this->_rightRotate($e, 11) ^ $this->_rightRotate($e, 25); $ch = ($e & $f) ^ ($this->_not($e) & $g); $t1 = $this->_add($h, $s1, $ch, $k[$i], $w[$i]); $h = $g; $g = $f; $f = $e; $e = $this->_add($d, $t1); $d = $c; $c = $b; $b = $a; $a = $this->_add($t1, $t2); } // Add this chunk's hash to result so far $hash = array( $this->_add($hash[0], $a), $this->_add($hash[1], $b), $this->_add($hash[2], $c), $this->_add($hash[3], $d), $this->_add($hash[4], $e), $this->_add($hash[5], $f), $this->_add($hash[6], $g), $this->_add($hash[7], $h) ); } // Produce the final hash value (big-endian) return pack('N8', $hash[0], $hash[1], $hash[2], $hash[3], $hash[4], $hash[5], $hash[6], $hash[7]); } /** * Pure-PHP implementation of SHA384 and SHA512 * * @access private * @param String $m */ function _sha512($m) { static $init384, $init512, $k; if (!isset($k)) { // Initialize variables $init384 = array( // initial values for SHA384 'cbbb9d5dc1059ed8', '629a292a367cd507', '9159015a3070dd17', '152fecd8f70e5939', '67332667ffc00b31', '8eb44a8768581511', 'db0c2e0d64f98fa7', '47b5481dbefa4fa4' ); $init512 = array( // initial values for SHA512 '6a09e667f3bcc908', 'bb67ae8584caa73b', '3c6ef372fe94f82b', 'a54ff53a5f1d36f1', '510e527fade682d1', '9b05688c2b3e6c1f', '1f83d9abfb41bd6b', '5be0cd19137e2179' ); for ($i = 0; $i < 8; $i++) { $init384[$i] = new BigInteger($init384[$i], 16); $init384[$i]->setPrecision(64); $init512[$i] = new BigInteger($init512[$i], 16); $init512[$i]->setPrecision(64); } // Initialize table of round constants // (first 64 bits of the fractional parts of the cube roots of the first 80 primes 2..409) $k = array( '428a2f98d728ae22', '7137449123ef65cd', 'b5c0fbcfec4d3b2f', 'e9b5dba58189dbbc', '3956c25bf348b538', '59f111f1b605d019', '923f82a4af194f9b', 'ab1c5ed5da6d8118', 'd807aa98a3030242', '12835b0145706fbe', '243185be4ee4b28c', '550c7dc3d5ffb4e2', '72be5d74f27b896f', '80deb1fe3b1696b1', '9bdc06a725c71235', 'c19bf174cf692694', 'e49b69c19ef14ad2', 'efbe4786384f25e3', '0fc19dc68b8cd5b5', '240ca1cc77ac9c65', '2de92c6f592b0275', '4a7484aa6ea6e483', '5cb0a9dcbd41fbd4', '76f988da831153b5', '983e5152ee66dfab', 'a831c66d2db43210', 'b00327c898fb213f', 'bf597fc7beef0ee4', 'c6e00bf33da88fc2', 'd5a79147930aa725', '06ca6351e003826f', '142929670a0e6e70', '27b70a8546d22ffc', '2e1b21385c26c926', '4d2c6dfc5ac42aed', '53380d139d95b3df', '650a73548baf63de', '766a0abb3c77b2a8', '81c2c92e47edaee6', '92722c851482353b', 'a2bfe8a14cf10364', 'a81a664bbc423001', 'c24b8b70d0f89791', 'c76c51a30654be30', 'd192e819d6ef5218', 'd69906245565a910', 'f40e35855771202a', '106aa07032bbd1b8', '19a4c116b8d2d0c8', '1e376c085141ab53', '2748774cdf8eeb99', '34b0bcb5e19b48a8', '391c0cb3c5c95a63', '4ed8aa4ae3418acb', '5b9cca4f7763e373', '682e6ff3d6b2b8a3', '748f82ee5defb2fc', '78a5636f43172f60', '84c87814a1f0ab72', '8cc702081a6439ec', '90befffa23631e28', 'a4506cebde82bde9', 'bef9a3f7b2c67915', 'c67178f2e372532b', 'ca273eceea26619c', 'd186b8c721c0c207', 'eada7dd6cde0eb1e', 'f57d4f7fee6ed178', '06f067aa72176fba', '0a637dc5a2c898a6', '113f9804bef90dae', '1b710b35131c471b', '28db77f523047d84', '32caab7b40c72493', '3c9ebe0a15c9bebc', '431d67c49c100d4c', '4cc5d4becb3e42b6', '597f299cfc657e2a', '5fcb6fab3ad6faec', '6c44198c4a475817' ); for ($i = 0; $i < 80; $i++) { $k[$i] = new BigInteger($k[$i], 16); } } $hash = $this->l == 48 ? $init384 : $init512; // Pre-processing $length = strlen($m); // to round to nearest 112 mod 128, we'll add 128 - (length + (128 - 112)) % 128 $m.= str_repeat(chr(0), 128 - (($length + 16) & 0x7F)); $m[$length] = chr(0x80); // we don't support hashing strings 512MB long $m.= pack('N4', 0, 0, 0, $length << 3); // Process the message in successive 1024-bit chunks $chunks = str_split($m, 128); foreach ($chunks as $chunk) { $w = array(); for ($i = 0; $i < 16; $i++) { $temp = new BigInteger($this->_string_shift($chunk, 8), 256); $temp->setPrecision(64); $w[] = $temp; } // Extend the sixteen 32-bit words into eighty 32-bit words for ($i = 16; $i < 80; $i++) { $temp = array( $w[$i - 15]->bitwise_rightRotate(1), $w[$i - 15]->bitwise_rightRotate(8), $w[$i - 15]->bitwise_rightShift(7) ); $s0 = $temp[0]->bitwise_xor($temp[1]); $s0 = $s0->bitwise_xor($temp[2]); $temp = array( $w[$i - 2]->bitwise_rightRotate(19), $w[$i - 2]->bitwise_rightRotate(61), $w[$i - 2]->bitwise_rightShift(6) ); $s1 = $temp[0]->bitwise_xor($temp[1]); $s1 = $s1->bitwise_xor($temp[2]); $w[$i] = $w[$i - 16]->copy(); $w[$i] = $w[$i]->add($s0); $w[$i] = $w[$i]->add($w[$i - 7]); $w[$i] = $w[$i]->add($s1); } // Initialize hash value for this chunk $a = $hash[0]->copy(); $b = $hash[1]->copy(); $c = $hash[2]->copy(); $d = $hash[3]->copy(); $e = $hash[4]->copy(); $f = $hash[5]->copy(); $g = $hash[6]->copy(); $h = $hash[7]->copy(); // Main loop for ($i = 0; $i < 80; $i++) { $temp = array( $a->bitwise_rightRotate(28), $a->bitwise_rightRotate(34), $a->bitwise_rightRotate(39) ); $s0 = $temp[0]->bitwise_xor($temp[1]); $s0 = $s0->bitwise_xor($temp[2]); $temp = array( $a->bitwise_and($b), $a->bitwise_and($c), $b->bitwise_and($c) ); $maj = $temp[0]->bitwise_xor($temp[1]); $maj = $maj->bitwise_xor($temp[2]); $t2 = $s0->add($maj); $temp = array( $e->bitwise_rightRotate(14), $e->bitwise_rightRotate(18), $e->bitwise_rightRotate(41) ); $s1 = $temp[0]->bitwise_xor($temp[1]); $s1 = $s1->bitwise_xor($temp[2]); $temp = array( $e->bitwise_and($f), $g->bitwise_and($e->bitwise_not()) ); $ch = $temp[0]->bitwise_xor($temp[1]); $t1 = $h->add($s1); $t1 = $t1->add($ch); $t1 = $t1->add($k[$i]); $t1 = $t1->add($w[$i]); $h = $g->copy(); $g = $f->copy(); $f = $e->copy(); $e = $d->add($t1); $d = $c->copy(); $c = $b->copy(); $b = $a->copy(); $a = $t1->add($t2); } // Add this chunk's hash to result so far $hash = array( $hash[0]->add($a), $hash[1]->add($b), $hash[2]->add($c), $hash[3]->add($d), $hash[4]->add($e), $hash[5]->add($f), $hash[6]->add($g), $hash[7]->add($h) ); } // Produce the final hash value (big-endian) // (\phpseclib\Crypt\Hash::hash() trims the output for hashes but not for HMACs. as such, we trim the output here) $temp = $hash[0]->toBytes() . $hash[1]->toBytes() . $hash[2]->toBytes() . $hash[3]->toBytes() . $hash[4]->toBytes() . $hash[5]->toBytes(); if ($this->l != 48) { $temp.= $hash[6]->toBytes() . $hash[7]->toBytes(); } return $temp; } /** * Right Rotate * * @access private * @param Integer $int * @param Integer $amt * @see _sha256() * @return Integer */ function _rightRotate($int, $amt) { $invamt = 32 - $amt; $mask = (1 << $invamt) - 1; return (($int << $invamt) & 0xFFFFFFFF) | (($int >> $amt) & $mask); } /** * Right Shift * * @access private * @param Integer $int * @param Integer $amt * @see _sha256() * @return Integer */ function _rightShift($int, $amt) { $mask = (1 << (32 - $amt)) - 1; return ($int >> $amt) & $mask; } /** * Not * * @access private * @param Integer $int * @see _sha256() * @return Integer */ function _not($int) { return ~$int & 0xFFFFFFFF; } /** * Add * * _sha256() adds multiple unsigned 32-bit integers. Since PHP doesn't support unsigned integers and since the * possibility of overflow exists, care has to be taken. BigInteger could be used but this should be faster. * * @param Integer $... * @return Integer * @see _sha256() * @access private */ function _add() { static $mod; if (!isset($mod)) { $mod = pow(2, 32); } $result = 0; $arguments = func_get_args(); foreach ($arguments as $argument) { $result+= $argument < 0 ? ($argument & 0x7FFFFFFF) + 0x80000000 : $argument; } return fmod($result, $mod); } /** * String Shift * * Inspired by array_shift * * @param String $string * @param optional Integer $index * @return String * @access private */ function _string_shift(&$string, $index = 1) { $substr = substr($string, 0, $index); $string = substr($string, $index); return $substr; } } * * * * @category Crypt * @package Random * @author Jim Wigginton * @copyright 2007 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\Crypt; use phpseclib\Crypt\AES; use phpseclib\Crypt\Base; use phpseclib\Crypt\Blowfish; use phpseclib\Crypt\DES; use phpseclib\Crypt\RC4; use phpseclib\Crypt\TripleDES; use phpseclib\Crypt\Twofish; /** * Pure-PHP Random Number Generator * * @package Random * @author Jim Wigginton * @access public */ class Random { /** * Generate a random string. * * Although microoptimizations are generally discouraged as they impair readability this function is ripe with * microoptimizations because this function has the potential of being called a huge number of times. * eg. for RSA key generation. * * @param Integer $length * @return String */ public static function string($length) { if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { // method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call. // ie. class_alias is a function that was introduced in PHP 5.3 if (function_exists('mcrypt_create_iv') && function_exists('class_alias')) { return mcrypt_create_iv($length); } // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was, // to quote , "possible blocking behavior". as of 5.3.4 // openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both // call php_win32_get_random_bytes(): // // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008 // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392 // // php_win32_get_random_bytes() is defined thusly: // // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80 // // we're calling it, all the same, in the off chance that the mcrypt extension is not available if (function_exists('openssl_random_pseudo_bytes') && version_compare(PHP_VERSION, '5.3.4', '>=')) { return openssl_random_pseudo_bytes($length); } } else { // method 1. the fastest if (function_exists('openssl_random_pseudo_bytes')) { return openssl_random_pseudo_bytes($length); } // method 2 static $fp = true; if ($fp === true) { // warning's will be output unles the error suppression operator is used. errors such as // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc. $fp = @fopen('/dev/urandom', 'rb'); } if ($fp !== true && $fp !== false) { // surprisingly faster than !is_bool() or is_resource() return fread($fp, $length); } // method 3. pretty much does the same thing as method 2 per the following url: // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391 // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir // restrictions or some such if (function_exists('mcrypt_create_iv')) { return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM); } } // at this point we have no choice but to use a pure-PHP CSPRNG // cascade entropy across multiple PHP instances by fixing the session and collecting all // environmental variables, including the previous session data and the current session // data. // // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively) // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but // PHP isn't low level to be able to use those as sources and on a web server there's not likely // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use // however, a ton of people visiting the website. obviously you don't want to base your seeding // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled // by the user and (2) this isn't just looking at the data sent by the current user - it's based // on the data sent by all users. one user requests the page and a hash of their info is saved. // another user visits the page and the serialization of their data is utilized along with the // server envirnment stuff and a hash of the previous http request data (which itself utilizes // a hash of the session data before that). certainly an attacker should be assumed to have // full control over his own http requests. he, however, is not going to have control over // everyone's http requests. static $crypto = false, $v; if ($crypto === false) { // save old session data $old_session_id = session_id(); $old_use_cookies = ini_get('session.use_cookies'); $old_session_cache_limiter = session_cache_limiter(); $_OLD_SESSION = isset($_SESSION) ? $_SESSION : false; if ($old_session_id != '') { session_write_close(); } session_id(1); ini_set('session.use_cookies', 0); session_cache_limiter(''); session_start(); $v = $seed = $_SESSION['seed'] = pack('H*', sha1( serialize($_SERVER) . serialize($_POST) . serialize($_GET) . serialize($_COOKIE) . serialize($GLOBALS) . serialize($_SESSION) . serialize($_OLD_SESSION) )); if (!isset($_SESSION['count'])) { $_SESSION['count'] = 0; } $_SESSION['count']++; session_write_close(); // restore old session data if ($old_session_id != '') { session_id($old_session_id); session_start(); ini_set('session.use_cookies', $old_use_cookies); session_cache_limiter($old_session_cache_limiter); } else { if ($_OLD_SESSION !== false) { $_SESSION = $_OLD_SESSION; unset($_OLD_SESSION); } else { unset($_SESSION); } } // in SSH2 a shared secret and an exchange hash are generated through the key exchange process. // the IV client to server is the hash of that "nonce" with the letter A and for the encryption key it's the letter C. // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the // original hash and the current hash. we'll be emulating that. for more info see the following URL: // // http://tools.ietf.org/html/rfc4253#section-7.2 // // see the is_string($crypto) part for an example of how to expand the keys $key = pack('H*', sha1($seed . 'A')); $iv = pack('H*', sha1($seed . 'C')); // ciphers are used as per the nist.gov link below. also, see this link: // // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives switch (true) { case class_exists('\phpseclib\Crypt\AES'): $crypto = new AES(Base::MODE_CTR); break; case class_exists('\phpseclib\Crypt\Twofish'): $crypto = new Twofish(Base::MODE_CTR); break; case class_exists('\phpseclib\Crypt\Blowfish'): $crypto = new Blowfish(Base::MODE_CTR); break; case class_exists('\phpseclib\Crypt\TripleDES'): $crypto = new TripleDES(Base::MODE_CTR); break; case class_exists('\phpseclib\Crypt\DES'): $crypto = new DES(Base::MODE_CTR); break; case class_exists('\phpseclib\Crypt\RC4'): $crypto = new RC4(); break; default: user_error(__CLASS__ . ' requires at least one symmetric cipher be loaded'); return false; } $crypto->setKey($key); $crypto->setIV($iv); $crypto->enableContinuousBuffer(); } //return $crypto->encrypt(str_repeat("\0", $length)); // the following is based off of ANSI X9.31: // // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf // // OpenSSL uses that same standard for it's random numbers: // // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c // (do a search for "ANS X9.31 A.2.4") $result = ''; while (strlen($result) < $length) { $i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21 $r = $crypto->encrypt($i ^ $v); // strlen($v) == 20 $v = $crypto->encrypt($r ^ $i); // strlen($r) == 20 $result.= $r; } return substr($result, 0, $length); } } * setKey('abcdefgh'); * * $plaintext = str_repeat('a', 1024); * * echo $rc2->decrypt($rc2->encrypt($plaintext)); * ?> * * * @category Crypt * @package RC2 * @author Patrick Monnerat * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\Crypt; use phpseclib\Crypt\Base; /** * Pure-PHP implementation of RC2. * * @package RC2 * @access public */ class RC2 extends Base { /** * Block Length of the cipher * * @see \phpseclib\Crypt\Base::block_size * @var Integer * @access private */ var $block_size = 8; /** * The Key * * @see \phpseclib\Crypt\Base::key * @see setKey() * @var String * @access private */ var $key = "\0"; /** * The default password key_size used by setPassword() * * @see \phpseclib\Crypt\Base::password_key_size * @see \phpseclib\Crypt\Base::setPassword() * @var Integer * @access private */ var $password_key_size = 16; // = 128 bits /** * The namespace used by the cipher for its constants. * * @see \phpseclib\Crypt\Base::const_namespace * @var String * @access private */ var $const_namespace = 'RC2'; /** * The mcrypt specific name of the cipher * * @see \phpseclib\Crypt\Base::cipher_name_mcrypt * @var String * @access private */ var $cipher_name_mcrypt = 'rc2'; /** * Optimizing value while CFB-encrypting * * @see \phpseclib\Crypt\Base::cfb_init_len * @var Integer * @access private */ var $cfb_init_len = 500; /** * The key length in bits. * * @see \phpseclib\Crypt\RC2::setKeyLength() * @see \phpseclib\Crypt\RC2::setKey() * @var Integer * @access private * @internal Should be in range [1..1024]. * @internal Changing this value after setting the key has no effect. */ var $default_key_length = 1024; /** * The Key Schedule * * @see \phpseclib\Crypt\RC2::_setupKey() * @var Array * @access private */ var $keys; /** * Key expansion randomization table. * Twice the same 256-value sequence to save a modulus in key expansion. * * @see \phpseclib\Crypt\RC2::setKey() * @var Array * @access private */ var $pitable = array( 0xD9, 0x78, 0xF9, 0xC4, 0x19, 0xDD, 0xB5, 0xED, 0x28, 0xE9, 0xFD, 0x79, 0x4A, 0xA0, 0xD8, 0x9D, 0xC6, 0x7E, 0x37, 0x83, 0x2B, 0x76, 0x53, 0x8E, 0x62, 0x4C, 0x64, 0x88, 0x44, 0x8B, 0xFB, 0xA2, 0x17, 0x9A, 0x59, 0xF5, 0x87, 0xB3, 0x4F, 0x13, 0x61, 0x45, 0x6D, 0x8D, 0x09, 0x81, 0x7D, 0x32, 0xBD, 0x8F, 0x40, 0xEB, 0x86, 0xB7, 0x7B, 0x0B, 0xF0, 0x95, 0x21, 0x22, 0x5C, 0x6B, 0x4E, 0x82, 0x54, 0xD6, 0x65, 0x93, 0xCE, 0x60, 0xB2, 0x1C, 0x73, 0x56, 0xC0, 0x14, 0xA7, 0x8C, 0xF1, 0xDC, 0x12, 0x75, 0xCA, 0x1F, 0x3B, 0xBE, 0xE4, 0xD1, 0x42, 0x3D, 0xD4, 0x30, 0xA3, 0x3C, 0xB6, 0x26, 0x6F, 0xBF, 0x0E, 0xDA, 0x46, 0x69, 0x07, 0x57, 0x27, 0xF2, 0x1D, 0x9B, 0xBC, 0x94, 0x43, 0x03, 0xF8, 0x11, 0xC7, 0xF6, 0x90, 0xEF, 0x3E, 0xE7, 0x06, 0xC3, 0xD5, 0x2F, 0xC8, 0x66, 0x1E, 0xD7, 0x08, 0xE8, 0xEA, 0xDE, 0x80, 0x52, 0xEE, 0xF7, 0x84, 0xAA, 0x72, 0xAC, 0x35, 0x4D, 0x6A, 0x2A, 0x96, 0x1A, 0xD2, 0x71, 0x5A, 0x15, 0x49, 0x74, 0x4B, 0x9F, 0xD0, 0x5E, 0x04, 0x18, 0xA4, 0xEC, 0xC2, 0xE0, 0x41, 0x6E, 0x0F, 0x51, 0xCB, 0xCC, 0x24, 0x91, 0xAF, 0x50, 0xA1, 0xF4, 0x70, 0x39, 0x99, 0x7C, 0x3A, 0x85, 0x23, 0xB8, 0xB4, 0x7A, 0xFC, 0x02, 0x36, 0x5B, 0x25, 0x55, 0x97, 0x31, 0x2D, 0x5D, 0xFA, 0x98, 0xE3, 0x8A, 0x92, 0xAE, 0x05, 0xDF, 0x29, 0x10, 0x67, 0x6C, 0xBA, 0xC9, 0xD3, 0x00, 0xE6, 0xCF, 0xE1, 0x9E, 0xA8, 0x2C, 0x63, 0x16, 0x01, 0x3F, 0x58, 0xE2, 0x89, 0xA9, 0x0D, 0x38, 0x34, 0x1B, 0xAB, 0x33, 0xFF, 0xB0, 0xBB, 0x48, 0x0C, 0x5F, 0xB9, 0xB1, 0xCD, 0x2E, 0xC5, 0xF3, 0xDB, 0x47, 0xE5, 0xA5, 0x9C, 0x77, 0x0A, 0xA6, 0x20, 0x68, 0xFE, 0x7F, 0xC1, 0xAD, 0xD9, 0x78, 0xF9, 0xC4, 0x19, 0xDD, 0xB5, 0xED, 0x28, 0xE9, 0xFD, 0x79, 0x4A, 0xA0, 0xD8, 0x9D, 0xC6, 0x7E, 0x37, 0x83, 0x2B, 0x76, 0x53, 0x8E, 0x62, 0x4C, 0x64, 0x88, 0x44, 0x8B, 0xFB, 0xA2, 0x17, 0x9A, 0x59, 0xF5, 0x87, 0xB3, 0x4F, 0x13, 0x61, 0x45, 0x6D, 0x8D, 0x09, 0x81, 0x7D, 0x32, 0xBD, 0x8F, 0x40, 0xEB, 0x86, 0xB7, 0x7B, 0x0B, 0xF0, 0x95, 0x21, 0x22, 0x5C, 0x6B, 0x4E, 0x82, 0x54, 0xD6, 0x65, 0x93, 0xCE, 0x60, 0xB2, 0x1C, 0x73, 0x56, 0xC0, 0x14, 0xA7, 0x8C, 0xF1, 0xDC, 0x12, 0x75, 0xCA, 0x1F, 0x3B, 0xBE, 0xE4, 0xD1, 0x42, 0x3D, 0xD4, 0x30, 0xA3, 0x3C, 0xB6, 0x26, 0x6F, 0xBF, 0x0E, 0xDA, 0x46, 0x69, 0x07, 0x57, 0x27, 0xF2, 0x1D, 0x9B, 0xBC, 0x94, 0x43, 0x03, 0xF8, 0x11, 0xC7, 0xF6, 0x90, 0xEF, 0x3E, 0xE7, 0x06, 0xC3, 0xD5, 0x2F, 0xC8, 0x66, 0x1E, 0xD7, 0x08, 0xE8, 0xEA, 0xDE, 0x80, 0x52, 0xEE, 0xF7, 0x84, 0xAA, 0x72, 0xAC, 0x35, 0x4D, 0x6A, 0x2A, 0x96, 0x1A, 0xD2, 0x71, 0x5A, 0x15, 0x49, 0x74, 0x4B, 0x9F, 0xD0, 0x5E, 0x04, 0x18, 0xA4, 0xEC, 0xC2, 0xE0, 0x41, 0x6E, 0x0F, 0x51, 0xCB, 0xCC, 0x24, 0x91, 0xAF, 0x50, 0xA1, 0xF4, 0x70, 0x39, 0x99, 0x7C, 0x3A, 0x85, 0x23, 0xB8, 0xB4, 0x7A, 0xFC, 0x02, 0x36, 0x5B, 0x25, 0x55, 0x97, 0x31, 0x2D, 0x5D, 0xFA, 0x98, 0xE3, 0x8A, 0x92, 0xAE, 0x05, 0xDF, 0x29, 0x10, 0x67, 0x6C, 0xBA, 0xC9, 0xD3, 0x00, 0xE6, 0xCF, 0xE1, 0x9E, 0xA8, 0x2C, 0x63, 0x16, 0x01, 0x3F, 0x58, 0xE2, 0x89, 0xA9, 0x0D, 0x38, 0x34, 0x1B, 0xAB, 0x33, 0xFF, 0xB0, 0xBB, 0x48, 0x0C, 0x5F, 0xB9, 0xB1, 0xCD, 0x2E, 0xC5, 0xF3, 0xDB, 0x47, 0xE5, 0xA5, 0x9C, 0x77, 0x0A, 0xA6, 0x20, 0x68, 0xFE, 0x7F, 0xC1, 0xAD ); /** * Inverse key expansion randomization table. * * @see \phpseclib\Crypt\RC2::setKey() * @var Array * @access private */ var $invpitable = array( 0xD1, 0xDA, 0xB9, 0x6F, 0x9C, 0xC8, 0x78, 0x66, 0x80, 0x2C, 0xF8, 0x37, 0xEA, 0xE0, 0x62, 0xA4, 0xCB, 0x71, 0x50, 0x27, 0x4B, 0x95, 0xD9, 0x20, 0x9D, 0x04, 0x91, 0xE3, 0x47, 0x6A, 0x7E, 0x53, 0xFA, 0x3A, 0x3B, 0xB4, 0xA8, 0xBC, 0x5F, 0x68, 0x08, 0xCA, 0x8F, 0x14, 0xD7, 0xC0, 0xEF, 0x7B, 0x5B, 0xBF, 0x2F, 0xE5, 0xE2, 0x8C, 0xBA, 0x12, 0xE1, 0xAF, 0xB2, 0x54, 0x5D, 0x59, 0x76, 0xDB, 0x32, 0xA2, 0x58, 0x6E, 0x1C, 0x29, 0x64, 0xF3, 0xE9, 0x96, 0x0C, 0x98, 0x19, 0x8D, 0x3E, 0x26, 0xAB, 0xA5, 0x85, 0x16, 0x40, 0xBD, 0x49, 0x67, 0xDC, 0x22, 0x94, 0xBB, 0x3C, 0xC1, 0x9B, 0xEB, 0x45, 0x28, 0x18, 0xD8, 0x1A, 0x42, 0x7D, 0xCC, 0xFB, 0x65, 0x8E, 0x3D, 0xCD, 0x2A, 0xA3, 0x60, 0xAE, 0x93, 0x8A, 0x48, 0x97, 0x51, 0x15, 0xF7, 0x01, 0x0B, 0xB7, 0x36, 0xB1, 0x2E, 0x11, 0xFD, 0x84, 0x2D, 0x3F, 0x13, 0x88, 0xB3, 0x34, 0x24, 0x1B, 0xDE, 0xC5, 0x1D, 0x4D, 0x2B, 0x17, 0x31, 0x74, 0xA9, 0xC6, 0x43, 0x6D, 0x39, 0x90, 0xBE, 0xC3, 0xB0, 0x21, 0x6B, 0xF6, 0x0F, 0xD5, 0x99, 0x0D, 0xAC, 0x1F, 0x5C, 0x9E, 0xF5, 0xF9, 0x4C, 0xD6, 0xDF, 0x89, 0xE4, 0x8B, 0xFF, 0xC7, 0xAA, 0xE7, 0xED, 0x46, 0x25, 0xB6, 0x06, 0x5E, 0x35, 0xB5, 0xEC, 0xCE, 0xE8, 0x6C, 0x30, 0x55, 0x61, 0x4A, 0xFE, 0xA0, 0x79, 0x03, 0xF0, 0x10, 0x72, 0x7C, 0xCF, 0x52, 0xA6, 0xA7, 0xEE, 0x44, 0xD3, 0x9A, 0x57, 0x92, 0xD0, 0x5A, 0x7A, 0x41, 0x7F, 0x0E, 0x00, 0x63, 0xF2, 0x4F, 0x05, 0x83, 0xC9, 0xA1, 0xD4, 0xDD, 0xC4, 0x56, 0xF4, 0xD2, 0x77, 0x81, 0x09, 0x82, 0x33, 0x9F, 0x07, 0x86, 0x75, 0x38, 0x4E, 0x69, 0xF1, 0xAD, 0x23, 0x73, 0x87, 0x70, 0x02, 0xC2, 0x1E, 0xB8, 0x0A, 0xFC, 0xE6 ); /** * Default Constructor. * * Determines whether or not the mcrypt extension should be used. * * $mode could be: * * - \phpseclib\Crypt\Base::MODE_ECB * * - \phpseclib\Crypt\Base::MODE_CBC * * - \phpseclib\Crypt\Base::MODE_CTR * * - \phpseclib\Crypt\Base::MODE_CFB * * - \phpseclib\Crypt\Base::MODE_OFB * * If not explicitly set, \phpseclib\Crypt\Base::MODE_CBC will be used. * * @see \phpseclib\Crypt\Base::__construct() * @param optional Integer $mode * @access public */ function __construct($mode = Base::MODE_CBC) { parent::__construct($mode); $this->setKey(''); } /** * Sets the key length * * Valid key lengths are 1 to 1024. * Calling this function after setting the key has no effect until the next * \phpseclib\Crypt\RC2::setKey() call. * * @access public * @param Integer $length in bits */ function setKeyLength($length) { if ($length >= 1 && $length <= 1024) { $this->default_key_length = $length; } } /** * Sets the key. * * Keys can be of any length. RC2, itself, uses 1 to 1024 bit keys (eg. * strlen($key) <= 128), however, we only use the first 128 bytes if $key * has more then 128 bytes in it, and set $key to a single null byte if * it is empty. * * If the key is not explicitly set, it'll be assumed to be a single * null byte. * * @see \phpseclib\Crypt\Base::setKey() * @access public * @param String $key * @param Integer $t1 optional Effective key length in bits. */ function setKey($key, $t1 = 0) { if ($t1 <= 0) { $t1 = $this->default_key_length; } else if ($t1 > 1024) { $t1 = 1024; } // Key byte count should be 1..128. $key = strlen($key) ? substr($key, 0, 128) : "\x00"; $t = strlen($key); // The mcrypt RC2 implementation only supports effective key length // of 1024 bits. It is however possible to handle effective key // lengths in range 1..1024 by expanding the key and applying // inverse pitable mapping to the first byte before submitting it // to mcrypt. // Key expansion. $l = array_values(unpack('C*', $key)); $t8 = ($t1 + 7) >> 3; $tm = 0xFF >> (8 * $t8 - $t1); // Expand key. $pitable = $this->pitable; for ($i = $t; $i < 128; $i++) { $l[$i] = $pitable[$l[$i - 1] + $l[$i - $t]]; } $i = 128 - $t8; $l[$i] = $pitable[$l[$i] & $tm]; while ($i--) { $l[$i] = $pitable[$l[$i + 1] ^ $l[$i + $t8]]; } // Prepare the key for mcrypt. $l[0] = $this->invpitable[$l[0]]; array_unshift($l, 'C*'); parent::setKey(call_user_func_array('pack', $l)); } /** * Encrypts a block * * @see \phpseclib\Crypt\Base::_encryptBlock() * @see \phpseclib\Crypt\Base::encrypt() * @access private * @param String $in * @return String */ function _encryptBlock($in) { list($r0, $r1, $r2, $r3) = array_values(unpack('v*', $in)); $keys = $this->keys; $limit = 20; $actions = array($limit => 44, 44 => 64); $j = 0; for (;;) { // Mixing round. $r0 = (($r0 + $keys[$j++] + ((($r1 ^ $r2) & $r3) ^ $r1)) & 0xFFFF) << 1; $r0 |= $r0 >> 16; $r1 = (($r1 + $keys[$j++] + ((($r2 ^ $r3) & $r0) ^ $r2)) & 0xFFFF) << 2; $r1 |= $r1 >> 16; $r2 = (($r2 + $keys[$j++] + ((($r3 ^ $r0) & $r1) ^ $r3)) & 0xFFFF) << 3; $r2 |= $r2 >> 16; $r3 = (($r3 + $keys[$j++] + ((($r0 ^ $r1) & $r2) ^ $r0)) & 0xFFFF) << 5; $r3 |= $r3 >> 16; if ($j === $limit) { if ($limit === 64) { break; } // Mashing round. $r0 += $keys[$r3 & 0x3F]; $r1 += $keys[$r0 & 0x3F]; $r2 += $keys[$r1 & 0x3F]; $r3 += $keys[$r2 & 0x3F]; $limit = $actions[$limit]; } } return pack('vvvv', $r0, $r1, $r2, $r3); } /** * Decrypts a block * * @see \phpseclib\Crypt\Base::_decryptBlock() * @see \phpseclib\Crypt\Base::decrypt() * @access private * @param String $in * @return String */ function _decryptBlock($in) { list($r0, $r1, $r2, $r3) = array_values(unpack('v*', $in)); $keys = $this->keys; $limit = 44; $actions = array($limit => 20, 20 => 0); $j = 64; for (;;) { // R-mixing round. $r3 = ($r3 | ($r3 << 16)) >> 5; $r3 = ($r3 - $keys[--$j] - ((($r0 ^ $r1) & $r2) ^ $r0)) & 0xFFFF; $r2 = ($r2 | ($r2 << 16)) >> 3; $r2 = ($r2 - $keys[--$j] - ((($r3 ^ $r0) & $r1) ^ $r3)) & 0xFFFF; $r1 = ($r1 | ($r1 << 16)) >> 2; $r1 = ($r1 - $keys[--$j] - ((($r2 ^ $r3) & $r0) ^ $r2)) & 0xFFFF; $r0 = ($r0 | ($r0 << 16)) >> 1; $r0 = ($r0 - $keys[--$j] - ((($r1 ^ $r2) & $r3) ^ $r1)) & 0xFFFF; if ($j === $limit) { if ($limit === 0) { break; } // R-mashing round. $r3 = ($r3 - $keys[$r2 & 0x3F]) & 0xFFFF; $r2 = ($r2 - $keys[$r1 & 0x3F]) & 0xFFFF; $r1 = ($r1 - $keys[$r0 & 0x3F]) & 0xFFFF; $r0 = ($r0 - $keys[$r3 & 0x3F]) & 0xFFFF; $limit = $actions[$limit]; } } return pack('vvvv', $r0, $r1, $r2, $r3); } /** * Creates the key schedule * * @see \phpseclib\Crypt\Base::_setupKey() * @access private */ function _setupKey() { // Key has already been expanded in \phpseclib\Crypt\RC2::setKey(): // Only the first value must be altered. $l = unpack('Ca/Cb/v*', $this->key); array_unshift($l, $this->pitable[$l['a']] | ($l['b'] << 8)); unset($l['a']); unset($l['b']); $this->keys = $l; } /** * Setup the performance-optimized function for de/encrypt() * * @see \phpseclib\Crypt\Base::_setupInlineCrypt() * @access private */ function _setupInlineCrypt() { $lambda_functions =& self::_getLambdaFunctions(); // The first 10 generated $lambda_functions will use the $keys hardcoded as integers // for the mixing rounds, for better inline crypt performance [~20% faster]. // But for memory reason we have to limit those ultra-optimized $lambda_functions to an amount of 10. $keys = $this->keys; if (count($lambda_functions) >= 10) { foreach ($this->keys as $k => $v) { $keys[$k] = '$keys[' . $k . ']'; } } $code_hash = md5(str_pad("RC2, {$this->mode}, ", 32, "\0") . implode(',', $keys)); // Is there a re-usable $lambda_functions in there? // If not, we have to create it. if (!isset($lambda_functions[$code_hash])) { // Init code for both, encrypt and decrypt. $init_crypt = '$keys = $self->keys;'; // $in is the current 8 bytes block which has to be en/decrypt $encrypt_block = $decrypt_block = ' $in = unpack("v4", $in); $r0 = $in[1]; $r1 = $in[2]; $r2 = $in[3]; $r3 = $in[4]; '; // Create code for encryption. $limit = 20; $actions = array($limit => 44, 44 => 64); $j = 0; for (;;) { // Mixing round. $encrypt_block .= ' $r0 = (($r0 + ' . $keys[$j++] . ' + ((($r1 ^ $r2) & $r3) ^ $r1)) & 0xFFFF) << 1; $r0 |= $r0 >> 16; $r1 = (($r1 + ' . $keys[$j++] . ' + ((($r2 ^ $r3) & $r0) ^ $r2)) & 0xFFFF) << 2; $r1 |= $r1 >> 16; $r2 = (($r2 + ' . $keys[$j++] . ' + ((($r3 ^ $r0) & $r1) ^ $r3)) & 0xFFFF) << 3; $r2 |= $r2 >> 16; $r3 = (($r3 + ' . $keys[$j++] . ' + ((($r0 ^ $r1) & $r2) ^ $r0)) & 0xFFFF) << 5; $r3 |= $r3 >> 16;'; if ($j === $limit) { if ($limit === 64) { break; } // Mashing round. $encrypt_block .= ' $r0 += $keys[$r3 & 0x3F]; $r1 += $keys[$r0 & 0x3F]; $r2 += $keys[$r1 & 0x3F]; $r3 += $keys[$r2 & 0x3F];'; $limit = $actions[$limit]; } } $encrypt_block .= '$in = pack("v4", $r0, $r1, $r2, $r3);'; // Create code for decryption. $limit = 44; $actions = array($limit => 20, 20 => 0); $j = 64; for (;;) { // R-mixing round. $decrypt_block .= ' $r3 = ($r3 | ($r3 << 16)) >> 5; $r3 = ($r3 - ' . $keys[--$j] . ' - ((($r0 ^ $r1) & $r2) ^ $r0)) & 0xFFFF; $r2 = ($r2 | ($r2 << 16)) >> 3; $r2 = ($r2 - ' . $keys[--$j] . ' - ((($r3 ^ $r0) & $r1) ^ $r3)) & 0xFFFF; $r1 = ($r1 | ($r1 << 16)) >> 2; $r1 = ($r1 - ' . $keys[--$j] . ' - ((($r2 ^ $r3) & $r0) ^ $r2)) & 0xFFFF; $r0 = ($r0 | ($r0 << 16)) >> 1; $r0 = ($r0 - ' . $keys[--$j] . ' - ((($r1 ^ $r2) & $r3) ^ $r1)) & 0xFFFF;'; if ($j === $limit) { if ($limit === 0) { break; } // R-mashing round. $decrypt_block .= ' $r3 = ($r3 - $keys[$r2 & 0x3F]) & 0xFFFF; $r2 = ($r2 - $keys[$r1 & 0x3F]) & 0xFFFF; $r1 = ($r1 - $keys[$r0 & 0x3F]) & 0xFFFF; $r0 = ($r0 - $keys[$r3 & 0x3F]) & 0xFFFF;'; $limit = $actions[$limit]; } } $decrypt_block .= '$in = pack("v4", $r0, $r1, $r2, $r3);'; // Creates the inline-crypt function $lambda_functions[$code_hash] = $this->_createInlineCryptFunction( array( 'init_crypt' => $init_crypt, 'encrypt_block' => $encrypt_block, 'decrypt_block' => $decrypt_block ) ); } // Set the inline-crypt function as callback in: $this->inline_crypt $this->inline_crypt = $lambda_functions[$code_hash]; } } * setKey('abcdefgh'); * * $size = 10 * 1024; * $plaintext = ''; * for ($i = 0; $i < $size; $i++) { * $plaintext.= 'a'; * } * * echo $rc4->decrypt($rc4->encrypt($plaintext)); * ?> * * * @category Crypt * @package RC4 * @author Jim Wigginton * @copyright 2007 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\Crypt; use phpseclib\Crypt\Base; /** * Pure-PHP implementation of RC4. * * @package RC4 * @author Jim Wigginton * @access public */ class RC4 extends Base { /**#@+ * @access private * @see \phpseclib\Crypt\RC4::_crypt() */ const ENCRYPT = 0; const DECRYPT = 1; /**#@-*/ /** * Block Length of the cipher * * RC4 is a stream cipher * so we the block_size to 0 * * @see \phpseclib\Crypt\Base::block_size * @var Integer * @access private */ var $block_size = 0; /** * The default password key_size used by setPassword() * * @see \phpseclib\Crypt\Base::password_key_size * @see \phpseclib\Crypt\Base::setPassword() * @var Integer * @access private */ var $password_key_size = 128; // = 1024 bits /** * The namespace used by the cipher for its constants. * * @see \phpseclib\Crypt\Base::const_namespace * @var String * @access private */ var $const_namespace = 'RC4'; /** * The mcrypt specific name of the cipher * * @see \phpseclib\Crypt\Base::cipher_name_mcrypt * @var String * @access private */ var $cipher_name_mcrypt = 'arcfour'; /** * Holds whether performance-optimized $inline_crypt() can/should be used. * * @see \phpseclib\Crypt\Base::inline_crypt * @var mixed * @access private */ var $use_inline_crypt = false; // currently not available /** * The Key * * @see \phpseclib\Crypt\RC4::setKey() * @var String * @access private */ var $key = "\0"; /** * The Key Stream for decryption and encryption * * @see \phpseclib\Crypt\RC4::setKey() * @var Array * @access private */ var $stream; /** * Default Constructor. * * Determines whether or not the mcrypt extension should be used. * * @see \phpseclib\Crypt\Base::__construct() * @return \phpseclib\Crypt\RC4 * @access public */ function __construct() { parent::__construct(Base::MODE_STREAM); } /** * Dummy function. * * Some protocols, such as WEP, prepend an "initialization vector" to the key, effectively creating a new key [1]. * If you need to use an initialization vector in this manner, feel free to prepend it to the key, yourself, before * calling setKey(). * * [1] WEP's initialization vectors (IV's) are used in a somewhat insecure way. Since, in that protocol, * the IV's are relatively easy to predict, an attack described by * {@link http://www.drizzle.com/~aboba/IEEE/rc4_ksaproc.pdf Scott Fluhrer, Itsik Mantin, and Adi Shamir} * can be used to quickly guess at the rest of the key. The following links elaborate: * * {@link http://www.rsa.com/rsalabs/node.asp?id=2009 http://www.rsa.com/rsalabs/node.asp?id=2009} * {@link http://en.wikipedia.org/wiki/Related_key_attack http://en.wikipedia.org/wiki/Related_key_attack} * * @param String $iv * @see \phpseclib\Crypt\RC4::setKey() * @access public */ function setIV($iv) { } /** * Sets the key. * * Keys can be between 1 and 256 bytes long. If they are longer then 256 bytes, the first 256 bytes will * be used. If no key is explicitly set, it'll be assumed to be a single null byte. * * @access public * @see \phpseclib\Crypt\Base::setKey() * @param String $key */ function setKey($key) { parent::setKey(substr($key, 0, 256)); } /** * Encrypts a message. * * @see \phpseclib\Crypt\Base::decrypt() * @see \phpseclib\Crypt\RC4::_crypt() * @access public * @param String $plaintext * @return String $ciphertext */ function encrypt($plaintext) { if ($this->engine == Base::ENGINE_MCRYPT) { return parent::encrypt($plaintext); } return $this->_crypt($plaintext, self::ENCRYPT); } /** * Decrypts a message. * * $this->decrypt($this->encrypt($plaintext)) == $this->encrypt($this->encrypt($plaintext)). * At least if the continuous buffer is disabled. * * @see \phpseclib\Crypt\Base::encrypt() * @see \phpseclib\Crypt\RC4::_crypt() * @access public * @param String $ciphertext * @return String $plaintext */ function decrypt($ciphertext) { if ($this->engine == Base::ENGINE_MCRYPT) { return parent::decrypt($ciphertext); } return $this->_crypt($ciphertext, self::DECRYPT); } /** * Setup the key (expansion) * * @see \phpseclib\Crypt\Base::_setupKey() * @access private */ function _setupKey() { $key = $this->key; $keyLength = strlen($key); $keyStream = range(0, 255); $j = 0; for ($i = 0; $i < 256; $i++) { $j = ($j + $keyStream[$i] + ord($key[$i % $keyLength])) & 255; $temp = $keyStream[$i]; $keyStream[$i] = $keyStream[$j]; $keyStream[$j] = $temp; } $this->stream = array(); $this->stream[self::DECRYPT] = $this->stream[self::ENCRYPT] = array( 0, // index $i 0, // index $j $keyStream ); } /** * Encrypts or decrypts a message. * * @see \phpseclib\Crypt\RC4::encrypt() * @see \phpseclib\Crypt\RC4::decrypt() * @access private * @param String $text * @param Integer $mode * @return String $text */ function _crypt($text, $mode) { if ($this->changed) { $this->_setup(); $this->changed = false; } $stream = &$this->stream[$mode]; if ($this->continuousBuffer) { $i = &$stream[0]; $j = &$stream[1]; $keyStream = &$stream[2]; } else { $i = $stream[0]; $j = $stream[1]; $keyStream = $stream[2]; } $len = strlen($text); for ($k = 0; $k < $len; ++$k) { $i = ($i + 1) & 255; $ksi = $keyStream[$i]; $j = ($j + $ksi) & 255; $ksj = $keyStream[$j]; $keyStream[$i] = $ksj; $keyStream[$j] = $ksi; $text[$k] = $text[$k] ^ chr($keyStream[($ksj + $ksi) & 255]); } return $text; } } * setKey('abcdefghijklmnop'); * * $size = 10 * 1024; * $plaintext = ''; * for ($i = 0; $i < $size; $i++) { * $plaintext.= 'a'; * } * * echo $rijndael->decrypt($rijndael->encrypt($plaintext)); * ?> * * * @category Crypt * @package Rijndael * @author Jim Wigginton * @copyright 2008 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\Crypt; use phpseclib\Crypt\Base; /** * Pure-PHP implementation of Rijndael. * * @package Rijndael * @author Jim Wigginton * @access public */ class Rijndael extends Base { /** * The default password key_size used by setPassword() * * @see \phpseclib\Crypt\Base::password_key_size * @see \phpseclib\Crypt\Base::setPassword() * @var Integer * @access private */ var $password_key_size = 16; /** * The namespace used by the cipher for its constants. * * @see \phpseclib\Crypt\Base::const_namespace * @var String * @access private */ var $const_namespace = 'RIJNDAEL'; /** * The mcrypt specific name of the cipher * * Mcrypt is useable for 128/192/256-bit $block_size/$key_size. For 160/224 not. * \phpseclib\Crypt\Rijndael determines automatically whether mcrypt is useable * or not for the current $block_size/$key_size. * In case of, $cipher_name_mcrypt will be set dynamically at run time accordingly. * * @see \phpseclib\Crypt\Base::cipher_name_mcrypt * @see \phpseclib\Crypt\Base::engine * @see _setupEngine() * @var String * @access private */ var $cipher_name_mcrypt = 'rijndael-128'; /** * The default salt used by setPassword() * * @see \phpseclib\Crypt\Base::password_default_salt * @see \phpseclib\Crypt\Base::setPassword() * @var String * @access private */ var $password_default_salt = 'phpseclib'; /** * Has the key length explicitly been set or should it be derived from the key, itself? * * @see setKeyLength() * @var Boolean * @access private */ var $explicit_key_length = false; /** * The Key Schedule * * @see _setup() * @var Array * @access private */ var $w; /** * The Inverse Key Schedule * * @see _setup() * @var Array * @access private */ var $dw; /** * The Block Length divided by 32 * * @see setBlockLength() * @var Integer * @access private * @internal The max value is 256 / 32 = 8, the min value is 128 / 32 = 4. Exists in conjunction with $block_size * because the encryption / decryption / key schedule creation requires this number and not $block_size. We could * derive this from $block_size or vice versa, but that'd mean we'd have to do multiple shift operations, so in lieu * of that, we'll just precompute it once. * */ var $Nb = 4; /** * The Key Length * * @see setKeyLength() * @var Integer * @access private * @internal The max value is 256 / 8 = 32, the min value is 128 / 8 = 16. Exists in conjunction with $Nk * because the encryption / decryption / key schedule creation requires this number and not $key_size. We could * derive this from $key_size or vice versa, but that'd mean we'd have to do multiple shift operations, so in lieu * of that, we'll just precompute it once. */ var $key_size = 16; /** * The Key Length divided by 32 * * @see setKeyLength() * @var Integer * @access private * @internal The max value is 256 / 32 = 8, the min value is 128 / 32 = 4 */ var $Nk = 4; /** * The Number of Rounds * * @var Integer * @access private * @internal The max value is 14, the min value is 10. */ var $Nr; /** * Shift offsets * * @var Array * @access private */ var $c; /** * Holds the last used key- and block_size information * * @var Array * @access private */ var $kl; /** * Precomputed mixColumns table * * According to (section 5.2.1), * precomputed tables can be used in the mixColumns phase. in that example, they're assigned t0...t3, so * those are the names we'll use. * * @see \phpseclib\Crypt\Rijndael:_encryptBlock() * @see \phpseclib\Crypt\Rijndael:_decryptBlock() * @var Array * @access private */ var $t0 = array( 0xC66363A5, 0xF87C7C84, 0xEE777799, 0xF67B7B8D, 0xFFF2F20D, 0xD66B6BBD, 0xDE6F6FB1, 0x91C5C554, 0x60303050, 0x02010103, 0xCE6767A9, 0x562B2B7D, 0xE7FEFE19, 0xB5D7D762, 0x4DABABE6, 0xEC76769A, 0x8FCACA45, 0x1F82829D, 0x89C9C940, 0xFA7D7D87, 0xEFFAFA15, 0xB25959EB, 0x8E4747C9, 0xFBF0F00B, 0x41ADADEC, 0xB3D4D467, 0x5FA2A2FD, 0x45AFAFEA, 0x239C9CBF, 0x53A4A4F7, 0xE4727296, 0x9BC0C05B, 0x75B7B7C2, 0xE1FDFD1C, 0x3D9393AE, 0x4C26266A, 0x6C36365A, 0x7E3F3F41, 0xF5F7F702, 0x83CCCC4F, 0x6834345C, 0x51A5A5F4, 0xD1E5E534, 0xF9F1F108, 0xE2717193, 0xABD8D873, 0x62313153, 0x2A15153F, 0x0804040C, 0x95C7C752, 0x46232365, 0x9DC3C35E, 0x30181828, 0x379696A1, 0x0A05050F, 0x2F9A9AB5, 0x0E070709, 0x24121236, 0x1B80809B, 0xDFE2E23D, 0xCDEBEB26, 0x4E272769, 0x7FB2B2CD, 0xEA75759F, 0x1209091B, 0x1D83839E, 0x582C2C74, 0x341A1A2E, 0x361B1B2D, 0xDC6E6EB2, 0xB45A5AEE, 0x5BA0A0FB, 0xA45252F6, 0x763B3B4D, 0xB7D6D661, 0x7DB3B3CE, 0x5229297B, 0xDDE3E33E, 0x5E2F2F71, 0x13848497, 0xA65353F5, 0xB9D1D168, 0x00000000, 0xC1EDED2C, 0x40202060, 0xE3FCFC1F, 0x79B1B1C8, 0xB65B5BED, 0xD46A6ABE, 0x8DCBCB46, 0x67BEBED9, 0x7239394B, 0x944A4ADE, 0x984C4CD4, 0xB05858E8, 0x85CFCF4A, 0xBBD0D06B, 0xC5EFEF2A, 0x4FAAAAE5, 0xEDFBFB16, 0x864343C5, 0x9A4D4DD7, 0x66333355, 0x11858594, 0x8A4545CF, 0xE9F9F910, 0x04020206, 0xFE7F7F81, 0xA05050F0, 0x783C3C44, 0x259F9FBA, 0x4BA8A8E3, 0xA25151F3, 0x5DA3A3FE, 0x804040C0, 0x058F8F8A, 0x3F9292AD, 0x219D9DBC, 0x70383848, 0xF1F5F504, 0x63BCBCDF, 0x77B6B6C1, 0xAFDADA75, 0x42212163, 0x20101030, 0xE5FFFF1A, 0xFDF3F30E, 0xBFD2D26D, 0x81CDCD4C, 0x180C0C14, 0x26131335, 0xC3ECEC2F, 0xBE5F5FE1, 0x359797A2, 0x884444CC, 0x2E171739, 0x93C4C457, 0x55A7A7F2, 0xFC7E7E82, 0x7A3D3D47, 0xC86464AC, 0xBA5D5DE7, 0x3219192B, 0xE6737395, 0xC06060A0, 0x19818198, 0x9E4F4FD1, 0xA3DCDC7F, 0x44222266, 0x542A2A7E, 0x3B9090AB, 0x0B888883, 0x8C4646CA, 0xC7EEEE29, 0x6BB8B8D3, 0x2814143C, 0xA7DEDE79, 0xBC5E5EE2, 0x160B0B1D, 0xADDBDB76, 0xDBE0E03B, 0x64323256, 0x743A3A4E, 0x140A0A1E, 0x924949DB, 0x0C06060A, 0x4824246C, 0xB85C5CE4, 0x9FC2C25D, 0xBDD3D36E, 0x43ACACEF, 0xC46262A6, 0x399191A8, 0x319595A4, 0xD3E4E437, 0xF279798B, 0xD5E7E732, 0x8BC8C843, 0x6E373759, 0xDA6D6DB7, 0x018D8D8C, 0xB1D5D564, 0x9C4E4ED2, 0x49A9A9E0, 0xD86C6CB4, 0xAC5656FA, 0xF3F4F407, 0xCFEAEA25, 0xCA6565AF, 0xF47A7A8E, 0x47AEAEE9, 0x10080818, 0x6FBABAD5, 0xF0787888, 0x4A25256F, 0x5C2E2E72, 0x381C1C24, 0x57A6A6F1, 0x73B4B4C7, 0x97C6C651, 0xCBE8E823, 0xA1DDDD7C, 0xE874749C, 0x3E1F1F21, 0x964B4BDD, 0x61BDBDDC, 0x0D8B8B86, 0x0F8A8A85, 0xE0707090, 0x7C3E3E42, 0x71B5B5C4, 0xCC6666AA, 0x904848D8, 0x06030305, 0xF7F6F601, 0x1C0E0E12, 0xC26161A3, 0x6A35355F, 0xAE5757F9, 0x69B9B9D0, 0x17868691, 0x99C1C158, 0x3A1D1D27, 0x279E9EB9, 0xD9E1E138, 0xEBF8F813, 0x2B9898B3, 0x22111133, 0xD26969BB, 0xA9D9D970, 0x078E8E89, 0x339494A7, 0x2D9B9BB6, 0x3C1E1E22, 0x15878792, 0xC9E9E920, 0x87CECE49, 0xAA5555FF, 0x50282878, 0xA5DFDF7A, 0x038C8C8F, 0x59A1A1F8, 0x09898980, 0x1A0D0D17, 0x65BFBFDA, 0xD7E6E631, 0x844242C6, 0xD06868B8, 0x824141C3, 0x299999B0, 0x5A2D2D77, 0x1E0F0F11, 0x7BB0B0CB, 0xA85454FC, 0x6DBBBBD6, 0x2C16163A ); /** * Precomputed mixColumns table * * @see \phpseclib\Crypt\Rijndael:_encryptBlock() * @see \phpseclib\Crypt\Rijndael:_decryptBlock() * @var Array * @access private */ var $t1 = array( 0xA5C66363, 0x84F87C7C, 0x99EE7777, 0x8DF67B7B, 0x0DFFF2F2, 0xBDD66B6B, 0xB1DE6F6F, 0x5491C5C5, 0x50603030, 0x03020101, 0xA9CE6767, 0x7D562B2B, 0x19E7FEFE, 0x62B5D7D7, 0xE64DABAB, 0x9AEC7676, 0x458FCACA, 0x9D1F8282, 0x4089C9C9, 0x87FA7D7D, 0x15EFFAFA, 0xEBB25959, 0xC98E4747, 0x0BFBF0F0, 0xEC41ADAD, 0x67B3D4D4, 0xFD5FA2A2, 0xEA45AFAF, 0xBF239C9C, 0xF753A4A4, 0x96E47272, 0x5B9BC0C0, 0xC275B7B7, 0x1CE1FDFD, 0xAE3D9393, 0x6A4C2626, 0x5A6C3636, 0x417E3F3F, 0x02F5F7F7, 0x4F83CCCC, 0x5C683434, 0xF451A5A5, 0x34D1E5E5, 0x08F9F1F1, 0x93E27171, 0x73ABD8D8, 0x53623131, 0x3F2A1515, 0x0C080404, 0x5295C7C7, 0x65462323, 0x5E9DC3C3, 0x28301818, 0xA1379696, 0x0F0A0505, 0xB52F9A9A, 0x090E0707, 0x36241212, 0x9B1B8080, 0x3DDFE2E2, 0x26CDEBEB, 0x694E2727, 0xCD7FB2B2, 0x9FEA7575, 0x1B120909, 0x9E1D8383, 0x74582C2C, 0x2E341A1A, 0x2D361B1B, 0xB2DC6E6E, 0xEEB45A5A, 0xFB5BA0A0, 0xF6A45252, 0x4D763B3B, 0x61B7D6D6, 0xCE7DB3B3, 0x7B522929, 0x3EDDE3E3, 0x715E2F2F, 0x97138484, 0xF5A65353, 0x68B9D1D1, 0x00000000, 0x2CC1EDED, 0x60402020, 0x1FE3FCFC, 0xC879B1B1, 0xEDB65B5B, 0xBED46A6A, 0x468DCBCB, 0xD967BEBE, 0x4B723939, 0xDE944A4A, 0xD4984C4C, 0xE8B05858, 0x4A85CFCF, 0x6BBBD0D0, 0x2AC5EFEF, 0xE54FAAAA, 0x16EDFBFB, 0xC5864343, 0xD79A4D4D, 0x55663333, 0x94118585, 0xCF8A4545, 0x10E9F9F9, 0x06040202, 0x81FE7F7F, 0xF0A05050, 0x44783C3C, 0xBA259F9F, 0xE34BA8A8, 0xF3A25151, 0xFE5DA3A3, 0xC0804040, 0x8A058F8F, 0xAD3F9292, 0xBC219D9D, 0x48703838, 0x04F1F5F5, 0xDF63BCBC, 0xC177B6B6, 0x75AFDADA, 0x63422121, 0x30201010, 0x1AE5FFFF, 0x0EFDF3F3, 0x6DBFD2D2, 0x4C81CDCD, 0x14180C0C, 0x35261313, 0x2FC3ECEC, 0xE1BE5F5F, 0xA2359797, 0xCC884444, 0x392E1717, 0x5793C4C4, 0xF255A7A7, 0x82FC7E7E, 0x477A3D3D, 0xACC86464, 0xE7BA5D5D, 0x2B321919, 0x95E67373, 0xA0C06060, 0x98198181, 0xD19E4F4F, 0x7FA3DCDC, 0x66442222, 0x7E542A2A, 0xAB3B9090, 0x830B8888, 0xCA8C4646, 0x29C7EEEE, 0xD36BB8B8, 0x3C281414, 0x79A7DEDE, 0xE2BC5E5E, 0x1D160B0B, 0x76ADDBDB, 0x3BDBE0E0, 0x56643232, 0x4E743A3A, 0x1E140A0A, 0xDB924949, 0x0A0C0606, 0x6C482424, 0xE4B85C5C, 0x5D9FC2C2, 0x6EBDD3D3, 0xEF43ACAC, 0xA6C46262, 0xA8399191, 0xA4319595, 0x37D3E4E4, 0x8BF27979, 0x32D5E7E7, 0x438BC8C8, 0x596E3737, 0xB7DA6D6D, 0x8C018D8D, 0x64B1D5D5, 0xD29C4E4E, 0xE049A9A9, 0xB4D86C6C, 0xFAAC5656, 0x07F3F4F4, 0x25CFEAEA, 0xAFCA6565, 0x8EF47A7A, 0xE947AEAE, 0x18100808, 0xD56FBABA, 0x88F07878, 0x6F4A2525, 0x725C2E2E, 0x24381C1C, 0xF157A6A6, 0xC773B4B4, 0x5197C6C6, 0x23CBE8E8, 0x7CA1DDDD, 0x9CE87474, 0x213E1F1F, 0xDD964B4B, 0xDC61BDBD, 0x860D8B8B, 0x850F8A8A, 0x90E07070, 0x427C3E3E, 0xC471B5B5, 0xAACC6666, 0xD8904848, 0x05060303, 0x01F7F6F6, 0x121C0E0E, 0xA3C26161, 0x5F6A3535, 0xF9AE5757, 0xD069B9B9, 0x91178686, 0x5899C1C1, 0x273A1D1D, 0xB9279E9E, 0x38D9E1E1, 0x13EBF8F8, 0xB32B9898, 0x33221111, 0xBBD26969, 0x70A9D9D9, 0x89078E8E, 0xA7339494, 0xB62D9B9B, 0x223C1E1E, 0x92158787, 0x20C9E9E9, 0x4987CECE, 0xFFAA5555, 0x78502828, 0x7AA5DFDF, 0x8F038C8C, 0xF859A1A1, 0x80098989, 0x171A0D0D, 0xDA65BFBF, 0x31D7E6E6, 0xC6844242, 0xB8D06868, 0xC3824141, 0xB0299999, 0x775A2D2D, 0x111E0F0F, 0xCB7BB0B0, 0xFCA85454, 0xD66DBBBB, 0x3A2C1616 ); /** * Precomputed mixColumns table * * @see \phpseclib\Crypt\Rijndael:_encryptBlock() * @see \phpseclib\Crypt\Rijndael:_decryptBlock() * @var Array * @access private */ var $t2 = array( 0x63A5C663, 0x7C84F87C, 0x7799EE77, 0x7B8DF67B, 0xF20DFFF2, 0x6BBDD66B, 0x6FB1DE6F, 0xC55491C5, 0x30506030, 0x01030201, 0x67A9CE67, 0x2B7D562B, 0xFE19E7FE, 0xD762B5D7, 0xABE64DAB, 0x769AEC76, 0xCA458FCA, 0x829D1F82, 0xC94089C9, 0x7D87FA7D, 0xFA15EFFA, 0x59EBB259, 0x47C98E47, 0xF00BFBF0, 0xADEC41AD, 0xD467B3D4, 0xA2FD5FA2, 0xAFEA45AF, 0x9CBF239C, 0xA4F753A4, 0x7296E472, 0xC05B9BC0, 0xB7C275B7, 0xFD1CE1FD, 0x93AE3D93, 0x266A4C26, 0x365A6C36, 0x3F417E3F, 0xF702F5F7, 0xCC4F83CC, 0x345C6834, 0xA5F451A5, 0xE534D1E5, 0xF108F9F1, 0x7193E271, 0xD873ABD8, 0x31536231, 0x153F2A15, 0x040C0804, 0xC75295C7, 0x23654623, 0xC35E9DC3, 0x18283018, 0x96A13796, 0x050F0A05, 0x9AB52F9A, 0x07090E07, 0x12362412, 0x809B1B80, 0xE23DDFE2, 0xEB26CDEB, 0x27694E27, 0xB2CD7FB2, 0x759FEA75, 0x091B1209, 0x839E1D83, 0x2C74582C, 0x1A2E341A, 0x1B2D361B, 0x6EB2DC6E, 0x5AEEB45A, 0xA0FB5BA0, 0x52F6A452, 0x3B4D763B, 0xD661B7D6, 0xB3CE7DB3, 0x297B5229, 0xE33EDDE3, 0x2F715E2F, 0x84971384, 0x53F5A653, 0xD168B9D1, 0x00000000, 0xED2CC1ED, 0x20604020, 0xFC1FE3FC, 0xB1C879B1, 0x5BEDB65B, 0x6ABED46A, 0xCB468DCB, 0xBED967BE, 0x394B7239, 0x4ADE944A, 0x4CD4984C, 0x58E8B058, 0xCF4A85CF, 0xD06BBBD0, 0xEF2AC5EF, 0xAAE54FAA, 0xFB16EDFB, 0x43C58643, 0x4DD79A4D, 0x33556633, 0x85941185, 0x45CF8A45, 0xF910E9F9, 0x02060402, 0x7F81FE7F, 0x50F0A050, 0x3C44783C, 0x9FBA259F, 0xA8E34BA8, 0x51F3A251, 0xA3FE5DA3, 0x40C08040, 0x8F8A058F, 0x92AD3F92, 0x9DBC219D, 0x38487038, 0xF504F1F5, 0xBCDF63BC, 0xB6C177B6, 0xDA75AFDA, 0x21634221, 0x10302010, 0xFF1AE5FF, 0xF30EFDF3, 0xD26DBFD2, 0xCD4C81CD, 0x0C14180C, 0x13352613, 0xEC2FC3EC, 0x5FE1BE5F, 0x97A23597, 0x44CC8844, 0x17392E17, 0xC45793C4, 0xA7F255A7, 0x7E82FC7E, 0x3D477A3D, 0x64ACC864, 0x5DE7BA5D, 0x192B3219, 0x7395E673, 0x60A0C060, 0x81981981, 0x4FD19E4F, 0xDC7FA3DC, 0x22664422, 0x2A7E542A, 0x90AB3B90, 0x88830B88, 0x46CA8C46, 0xEE29C7EE, 0xB8D36BB8, 0x143C2814, 0xDE79A7DE, 0x5EE2BC5E, 0x0B1D160B, 0xDB76ADDB, 0xE03BDBE0, 0x32566432, 0x3A4E743A, 0x0A1E140A, 0x49DB9249, 0x060A0C06, 0x246C4824, 0x5CE4B85C, 0xC25D9FC2, 0xD36EBDD3, 0xACEF43AC, 0x62A6C462, 0x91A83991, 0x95A43195, 0xE437D3E4, 0x798BF279, 0xE732D5E7, 0xC8438BC8, 0x37596E37, 0x6DB7DA6D, 0x8D8C018D, 0xD564B1D5, 0x4ED29C4E, 0xA9E049A9, 0x6CB4D86C, 0x56FAAC56, 0xF407F3F4, 0xEA25CFEA, 0x65AFCA65, 0x7A8EF47A, 0xAEE947AE, 0x08181008, 0xBAD56FBA, 0x7888F078, 0x256F4A25, 0x2E725C2E, 0x1C24381C, 0xA6F157A6, 0xB4C773B4, 0xC65197C6, 0xE823CBE8, 0xDD7CA1DD, 0x749CE874, 0x1F213E1F, 0x4BDD964B, 0xBDDC61BD, 0x8B860D8B, 0x8A850F8A, 0x7090E070, 0x3E427C3E, 0xB5C471B5, 0x66AACC66, 0x48D89048, 0x03050603, 0xF601F7F6, 0x0E121C0E, 0x61A3C261, 0x355F6A35, 0x57F9AE57, 0xB9D069B9, 0x86911786, 0xC15899C1, 0x1D273A1D, 0x9EB9279E, 0xE138D9E1, 0xF813EBF8, 0x98B32B98, 0x11332211, 0x69BBD269, 0xD970A9D9, 0x8E89078E, 0x94A73394, 0x9BB62D9B, 0x1E223C1E, 0x87921587, 0xE920C9E9, 0xCE4987CE, 0x55FFAA55, 0x28785028, 0xDF7AA5DF, 0x8C8F038C, 0xA1F859A1, 0x89800989, 0x0D171A0D, 0xBFDA65BF, 0xE631D7E6, 0x42C68442, 0x68B8D068, 0x41C38241, 0x99B02999, 0x2D775A2D, 0x0F111E0F, 0xB0CB7BB0, 0x54FCA854, 0xBBD66DBB, 0x163A2C16 ); /** * Precomputed mixColumns table * * @see \phpseclib\Crypt\Rijndael:_encryptBlock() * @see \phpseclib\Crypt\Rijndael:_decryptBlock() * @var Array * @access private */ var $t3 = array( 0x6363A5C6, 0x7C7C84F8, 0x777799EE, 0x7B7B8DF6, 0xF2F20DFF, 0x6B6BBDD6, 0x6F6FB1DE, 0xC5C55491, 0x30305060, 0x01010302, 0x6767A9CE, 0x2B2B7D56, 0xFEFE19E7, 0xD7D762B5, 0xABABE64D, 0x76769AEC, 0xCACA458F, 0x82829D1F, 0xC9C94089, 0x7D7D87FA, 0xFAFA15EF, 0x5959EBB2, 0x4747C98E, 0xF0F00BFB, 0xADADEC41, 0xD4D467B3, 0xA2A2FD5F, 0xAFAFEA45, 0x9C9CBF23, 0xA4A4F753, 0x727296E4, 0xC0C05B9B, 0xB7B7C275, 0xFDFD1CE1, 0x9393AE3D, 0x26266A4C, 0x36365A6C, 0x3F3F417E, 0xF7F702F5, 0xCCCC4F83, 0x34345C68, 0xA5A5F451, 0xE5E534D1, 0xF1F108F9, 0x717193E2, 0xD8D873AB, 0x31315362, 0x15153F2A, 0x04040C08, 0xC7C75295, 0x23236546, 0xC3C35E9D, 0x18182830, 0x9696A137, 0x05050F0A, 0x9A9AB52F, 0x0707090E, 0x12123624, 0x80809B1B, 0xE2E23DDF, 0xEBEB26CD, 0x2727694E, 0xB2B2CD7F, 0x75759FEA, 0x09091B12, 0x83839E1D, 0x2C2C7458, 0x1A1A2E34, 0x1B1B2D36, 0x6E6EB2DC, 0x5A5AEEB4, 0xA0A0FB5B, 0x5252F6A4, 0x3B3B4D76, 0xD6D661B7, 0xB3B3CE7D, 0x29297B52, 0xE3E33EDD, 0x2F2F715E, 0x84849713, 0x5353F5A6, 0xD1D168B9, 0x00000000, 0xEDED2CC1, 0x20206040, 0xFCFC1FE3, 0xB1B1C879, 0x5B5BEDB6, 0x6A6ABED4, 0xCBCB468D, 0xBEBED967, 0x39394B72, 0x4A4ADE94, 0x4C4CD498, 0x5858E8B0, 0xCFCF4A85, 0xD0D06BBB, 0xEFEF2AC5, 0xAAAAE54F, 0xFBFB16ED, 0x4343C586, 0x4D4DD79A, 0x33335566, 0x85859411, 0x4545CF8A, 0xF9F910E9, 0x02020604, 0x7F7F81FE, 0x5050F0A0, 0x3C3C4478, 0x9F9FBA25, 0xA8A8E34B, 0x5151F3A2, 0xA3A3FE5D, 0x4040C080, 0x8F8F8A05, 0x9292AD3F, 0x9D9DBC21, 0x38384870, 0xF5F504F1, 0xBCBCDF63, 0xB6B6C177, 0xDADA75AF, 0x21216342, 0x10103020, 0xFFFF1AE5, 0xF3F30EFD, 0xD2D26DBF, 0xCDCD4C81, 0x0C0C1418, 0x13133526, 0xECEC2FC3, 0x5F5FE1BE, 0x9797A235, 0x4444CC88, 0x1717392E, 0xC4C45793, 0xA7A7F255, 0x7E7E82FC, 0x3D3D477A, 0x6464ACC8, 0x5D5DE7BA, 0x19192B32, 0x737395E6, 0x6060A0C0, 0x81819819, 0x4F4FD19E, 0xDCDC7FA3, 0x22226644, 0x2A2A7E54, 0x9090AB3B, 0x8888830B, 0x4646CA8C, 0xEEEE29C7, 0xB8B8D36B, 0x14143C28, 0xDEDE79A7, 0x5E5EE2BC, 0x0B0B1D16, 0xDBDB76AD, 0xE0E03BDB, 0x32325664, 0x3A3A4E74, 0x0A0A1E14, 0x4949DB92, 0x06060A0C, 0x24246C48, 0x5C5CE4B8, 0xC2C25D9F, 0xD3D36EBD, 0xACACEF43, 0x6262A6C4, 0x9191A839, 0x9595A431, 0xE4E437D3, 0x79798BF2, 0xE7E732D5, 0xC8C8438B, 0x3737596E, 0x6D6DB7DA, 0x8D8D8C01, 0xD5D564B1, 0x4E4ED29C, 0xA9A9E049, 0x6C6CB4D8, 0x5656FAAC, 0xF4F407F3, 0xEAEA25CF, 0x6565AFCA, 0x7A7A8EF4, 0xAEAEE947, 0x08081810, 0xBABAD56F, 0x787888F0, 0x25256F4A, 0x2E2E725C, 0x1C1C2438, 0xA6A6F157, 0xB4B4C773, 0xC6C65197, 0xE8E823CB, 0xDDDD7CA1, 0x74749CE8, 0x1F1F213E, 0x4B4BDD96, 0xBDBDDC61, 0x8B8B860D, 0x8A8A850F, 0x707090E0, 0x3E3E427C, 0xB5B5C471, 0x6666AACC, 0x4848D890, 0x03030506, 0xF6F601F7, 0x0E0E121C, 0x6161A3C2, 0x35355F6A, 0x5757F9AE, 0xB9B9D069, 0x86869117, 0xC1C15899, 0x1D1D273A, 0x9E9EB927, 0xE1E138D9, 0xF8F813EB, 0x9898B32B, 0x11113322, 0x6969BBD2, 0xD9D970A9, 0x8E8E8907, 0x9494A733, 0x9B9BB62D, 0x1E1E223C, 0x87879215, 0xE9E920C9, 0xCECE4987, 0x5555FFAA, 0x28287850, 0xDFDF7AA5, 0x8C8C8F03, 0xA1A1F859, 0x89898009, 0x0D0D171A, 0xBFBFDA65, 0xE6E631D7, 0x4242C684, 0x6868B8D0, 0x4141C382, 0x9999B029, 0x2D2D775A, 0x0F0F111E, 0xB0B0CB7B, 0x5454FCA8, 0xBBBBD66D, 0x16163A2C ); /** * Precomputed invMixColumns table * * @see \phpseclib\Crypt\Rijndael:_encryptBlock() * @see \phpseclib\Crypt\Rijndael:_decryptBlock() * @var Array * @access private */ var $dt0 = array( 0x51F4A750, 0x7E416553, 0x1A17A4C3, 0x3A275E96, 0x3BAB6BCB, 0x1F9D45F1, 0xACFA58AB, 0x4BE30393, 0x2030FA55, 0xAD766DF6, 0x88CC7691, 0xF5024C25, 0x4FE5D7FC, 0xC52ACBD7, 0x26354480, 0xB562A38F, 0xDEB15A49, 0x25BA1B67, 0x45EA0E98, 0x5DFEC0E1, 0xC32F7502, 0x814CF012, 0x8D4697A3, 0x6BD3F9C6, 0x038F5FE7, 0x15929C95, 0xBF6D7AEB, 0x955259DA, 0xD4BE832D, 0x587421D3, 0x49E06929, 0x8EC9C844, 0x75C2896A, 0xF48E7978, 0x99583E6B, 0x27B971DD, 0xBEE14FB6, 0xF088AD17, 0xC920AC66, 0x7DCE3AB4, 0x63DF4A18, 0xE51A3182, 0x97513360, 0x62537F45, 0xB16477E0, 0xBB6BAE84, 0xFE81A01C, 0xF9082B94, 0x70486858, 0x8F45FD19, 0x94DE6C87, 0x527BF8B7, 0xAB73D323, 0x724B02E2, 0xE31F8F57, 0x6655AB2A, 0xB2EB2807, 0x2FB5C203, 0x86C57B9A, 0xD33708A5, 0x302887F2, 0x23BFA5B2, 0x02036ABA, 0xED16825C, 0x8ACF1C2B, 0xA779B492, 0xF307F2F0, 0x4E69E2A1, 0x65DAF4CD, 0x0605BED5, 0xD134621F, 0xC4A6FE8A, 0x342E539D, 0xA2F355A0, 0x058AE132, 0xA4F6EB75, 0x0B83EC39, 0x4060EFAA, 0x5E719F06, 0xBD6E1051, 0x3E218AF9, 0x96DD063D, 0xDD3E05AE, 0x4DE6BD46, 0x91548DB5, 0x71C45D05, 0x0406D46F, 0x605015FF, 0x1998FB24, 0xD6BDE997, 0x894043CC, 0x67D99E77, 0xB0E842BD, 0x07898B88, 0xE7195B38, 0x79C8EEDB, 0xA17C0A47, 0x7C420FE9, 0xF8841EC9, 0x00000000, 0x09808683, 0x322BED48, 0x1E1170AC, 0x6C5A724E, 0xFD0EFFFB, 0x0F853856, 0x3DAED51E, 0x362D3927, 0x0A0FD964, 0x685CA621, 0x9B5B54D1, 0x24362E3A, 0x0C0A67B1, 0x9357E70F, 0xB4EE96D2, 0x1B9B919E, 0x80C0C54F, 0x61DC20A2, 0x5A774B69, 0x1C121A16, 0xE293BA0A, 0xC0A02AE5, 0x3C22E043, 0x121B171D, 0x0E090D0B, 0xF28BC7AD, 0x2DB6A8B9, 0x141EA9C8, 0x57F11985, 0xAF75074C, 0xEE99DDBB, 0xA37F60FD, 0xF701269F, 0x5C72F5BC, 0x44663BC5, 0x5BFB7E34, 0x8B432976, 0xCB23C6DC, 0xB6EDFC68, 0xB8E4F163, 0xD731DCCA, 0x42638510, 0x13972240, 0x84C61120, 0x854A247D, 0xD2BB3DF8, 0xAEF93211, 0xC729A16D, 0x1D9E2F4B, 0xDCB230F3, 0x0D8652EC, 0x77C1E3D0, 0x2BB3166C, 0xA970B999, 0x119448FA, 0x47E96422, 0xA8FC8CC4, 0xA0F03F1A, 0x567D2CD8, 0x223390EF, 0x87494EC7, 0xD938D1C1, 0x8CCAA2FE, 0x98D40B36, 0xA6F581CF, 0xA57ADE28, 0xDAB78E26, 0x3FADBFA4, 0x2C3A9DE4, 0x5078920D, 0x6A5FCC9B, 0x547E4662, 0xF68D13C2, 0x90D8B8E8, 0x2E39F75E, 0x82C3AFF5, 0x9F5D80BE, 0x69D0937C, 0x6FD52DA9, 0xCF2512B3, 0xC8AC993B, 0x10187DA7, 0xE89C636E, 0xDB3BBB7B, 0xCD267809, 0x6E5918F4, 0xEC9AB701, 0x834F9AA8, 0xE6956E65, 0xAAFFE67E, 0x21BCCF08, 0xEF15E8E6, 0xBAE79BD9, 0x4A6F36CE, 0xEA9F09D4, 0x29B07CD6, 0x31A4B2AF, 0x2A3F2331, 0xC6A59430, 0x35A266C0, 0x744EBC37, 0xFC82CAA6, 0xE090D0B0, 0x33A7D815, 0xF104984A, 0x41ECDAF7, 0x7FCD500E, 0x1791F62F, 0x764DD68D, 0x43EFB04D, 0xCCAA4D54, 0xE49604DF, 0x9ED1B5E3, 0x4C6A881B, 0xC12C1FB8, 0x4665517F, 0x9D5EEA04, 0x018C355D, 0xFA877473, 0xFB0B412E, 0xB3671D5A, 0x92DBD252, 0xE9105633, 0x6DD64713, 0x9AD7618C, 0x37A10C7A, 0x59F8148E, 0xEB133C89, 0xCEA927EE, 0xB761C935, 0xE11CE5ED, 0x7A47B13C, 0x9CD2DF59, 0x55F2733F, 0x1814CE79, 0x73C737BF, 0x53F7CDEA, 0x5FFDAA5B, 0xDF3D6F14, 0x7844DB86, 0xCAAFF381, 0xB968C43E, 0x3824342C, 0xC2A3405F, 0x161DC372, 0xBCE2250C, 0x283C498B, 0xFF0D9541, 0x39A80171, 0x080CB3DE, 0xD8B4E49C, 0x6456C190, 0x7BCB8461, 0xD532B670, 0x486C5C74, 0xD0B85742 ); /** * Precomputed invMixColumns table * * @see \phpseclib\Crypt\Rijndael:_encryptBlock() * @see \phpseclib\Crypt\Rijndael:_decryptBlock() * @var Array * @access private */ var $dt1 = array( 0x5051F4A7, 0x537E4165, 0xC31A17A4, 0x963A275E, 0xCB3BAB6B, 0xF11F9D45, 0xABACFA58, 0x934BE303, 0x552030FA, 0xF6AD766D, 0x9188CC76, 0x25F5024C, 0xFC4FE5D7, 0xD7C52ACB, 0x80263544, 0x8FB562A3, 0x49DEB15A, 0x6725BA1B, 0x9845EA0E, 0xE15DFEC0, 0x02C32F75, 0x12814CF0, 0xA38D4697, 0xC66BD3F9, 0xE7038F5F, 0x9515929C, 0xEBBF6D7A, 0xDA955259, 0x2DD4BE83, 0xD3587421, 0x2949E069, 0x448EC9C8, 0x6A75C289, 0x78F48E79, 0x6B99583E, 0xDD27B971, 0xB6BEE14F, 0x17F088AD, 0x66C920AC, 0xB47DCE3A, 0x1863DF4A, 0x82E51A31, 0x60975133, 0x4562537F, 0xE0B16477, 0x84BB6BAE, 0x1CFE81A0, 0x94F9082B, 0x58704868, 0x198F45FD, 0x8794DE6C, 0xB7527BF8, 0x23AB73D3, 0xE2724B02, 0x57E31F8F, 0x2A6655AB, 0x07B2EB28, 0x032FB5C2, 0x9A86C57B, 0xA5D33708, 0xF2302887, 0xB223BFA5, 0xBA02036A, 0x5CED1682, 0x2B8ACF1C, 0x92A779B4, 0xF0F307F2, 0xA14E69E2, 0xCD65DAF4, 0xD50605BE, 0x1FD13462, 0x8AC4A6FE, 0x9D342E53, 0xA0A2F355, 0x32058AE1, 0x75A4F6EB, 0x390B83EC, 0xAA4060EF, 0x065E719F, 0x51BD6E10, 0xF93E218A, 0x3D96DD06, 0xAEDD3E05, 0x464DE6BD, 0xB591548D, 0x0571C45D, 0x6F0406D4, 0xFF605015, 0x241998FB, 0x97D6BDE9, 0xCC894043, 0x7767D99E, 0xBDB0E842, 0x8807898B, 0x38E7195B, 0xDB79C8EE, 0x47A17C0A, 0xE97C420F, 0xC9F8841E, 0x00000000, 0x83098086, 0x48322BED, 0xAC1E1170, 0x4E6C5A72, 0xFBFD0EFF, 0x560F8538, 0x1E3DAED5, 0x27362D39, 0x640A0FD9, 0x21685CA6, 0xD19B5B54, 0x3A24362E, 0xB10C0A67, 0x0F9357E7, 0xD2B4EE96, 0x9E1B9B91, 0x4F80C0C5, 0xA261DC20, 0x695A774B, 0x161C121A, 0x0AE293BA, 0xE5C0A02A, 0x433C22E0, 0x1D121B17, 0x0B0E090D, 0xADF28BC7, 0xB92DB6A8, 0xC8141EA9, 0x8557F119, 0x4CAF7507, 0xBBEE99DD, 0xFDA37F60, 0x9FF70126, 0xBC5C72F5, 0xC544663B, 0x345BFB7E, 0x768B4329, 0xDCCB23C6, 0x68B6EDFC, 0x63B8E4F1, 0xCAD731DC, 0x10426385, 0x40139722, 0x2084C611, 0x7D854A24, 0xF8D2BB3D, 0x11AEF932, 0x6DC729A1, 0x4B1D9E2F, 0xF3DCB230, 0xEC0D8652, 0xD077C1E3, 0x6C2BB316, 0x99A970B9, 0xFA119448, 0x2247E964, 0xC4A8FC8C, 0x1AA0F03F, 0xD8567D2C, 0xEF223390, 0xC787494E, 0xC1D938D1, 0xFE8CCAA2, 0x3698D40B, 0xCFA6F581, 0x28A57ADE, 0x26DAB78E, 0xA43FADBF, 0xE42C3A9D, 0x0D507892, 0x9B6A5FCC, 0x62547E46, 0xC2F68D13, 0xE890D8B8, 0x5E2E39F7, 0xF582C3AF, 0xBE9F5D80, 0x7C69D093, 0xA96FD52D, 0xB3CF2512, 0x3BC8AC99, 0xA710187D, 0x6EE89C63, 0x7BDB3BBB, 0x09CD2678, 0xF46E5918, 0x01EC9AB7, 0xA8834F9A, 0x65E6956E, 0x7EAAFFE6, 0x0821BCCF, 0xE6EF15E8, 0xD9BAE79B, 0xCE4A6F36, 0xD4EA9F09, 0xD629B07C, 0xAF31A4B2, 0x312A3F23, 0x30C6A594, 0xC035A266, 0x37744EBC, 0xA6FC82CA, 0xB0E090D0, 0x1533A7D8, 0x4AF10498, 0xF741ECDA, 0x0E7FCD50, 0x2F1791F6, 0x8D764DD6, 0x4D43EFB0, 0x54CCAA4D, 0xDFE49604, 0xE39ED1B5, 0x1B4C6A88, 0xB8C12C1F, 0x7F466551, 0x049D5EEA, 0x5D018C35, 0x73FA8774, 0x2EFB0B41, 0x5AB3671D, 0x5292DBD2, 0x33E91056, 0x136DD647, 0x8C9AD761, 0x7A37A10C, 0x8E59F814, 0x89EB133C, 0xEECEA927, 0x35B761C9, 0xEDE11CE5, 0x3C7A47B1, 0x599CD2DF, 0x3F55F273, 0x791814CE, 0xBF73C737, 0xEA53F7CD, 0x5B5FFDAA, 0x14DF3D6F, 0x867844DB, 0x81CAAFF3, 0x3EB968C4, 0x2C382434, 0x5FC2A340, 0x72161DC3, 0x0CBCE225, 0x8B283C49, 0x41FF0D95, 0x7139A801, 0xDE080CB3, 0x9CD8B4E4, 0x906456C1, 0x617BCB84, 0x70D532B6, 0x74486C5C, 0x42D0B857 ); /** * Precomputed invMixColumns table * * @see \phpseclib\Crypt\Rijndael:_encryptBlock() * @see \phpseclib\Crypt\Rijndael:_decryptBlock() * @var Array * @access private */ var $dt2 = array( 0xA75051F4, 0x65537E41, 0xA4C31A17, 0x5E963A27, 0x6BCB3BAB, 0x45F11F9D, 0x58ABACFA, 0x03934BE3, 0xFA552030, 0x6DF6AD76, 0x769188CC, 0x4C25F502, 0xD7FC4FE5, 0xCBD7C52A, 0x44802635, 0xA38FB562, 0x5A49DEB1, 0x1B6725BA, 0x0E9845EA, 0xC0E15DFE, 0x7502C32F, 0xF012814C, 0x97A38D46, 0xF9C66BD3, 0x5FE7038F, 0x9C951592, 0x7AEBBF6D, 0x59DA9552, 0x832DD4BE, 0x21D35874, 0x692949E0, 0xC8448EC9, 0x896A75C2, 0x7978F48E, 0x3E6B9958, 0x71DD27B9, 0x4FB6BEE1, 0xAD17F088, 0xAC66C920, 0x3AB47DCE, 0x4A1863DF, 0x3182E51A, 0x33609751, 0x7F456253, 0x77E0B164, 0xAE84BB6B, 0xA01CFE81, 0x2B94F908, 0x68587048, 0xFD198F45, 0x6C8794DE, 0xF8B7527B, 0xD323AB73, 0x02E2724B, 0x8F57E31F, 0xAB2A6655, 0x2807B2EB, 0xC2032FB5, 0x7B9A86C5, 0x08A5D337, 0x87F23028, 0xA5B223BF, 0x6ABA0203, 0x825CED16, 0x1C2B8ACF, 0xB492A779, 0xF2F0F307, 0xE2A14E69, 0xF4CD65DA, 0xBED50605, 0x621FD134, 0xFE8AC4A6, 0x539D342E, 0x55A0A2F3, 0xE132058A, 0xEB75A4F6, 0xEC390B83, 0xEFAA4060, 0x9F065E71, 0x1051BD6E, 0x8AF93E21, 0x063D96DD, 0x05AEDD3E, 0xBD464DE6, 0x8DB59154, 0x5D0571C4, 0xD46F0406, 0x15FF6050, 0xFB241998, 0xE997D6BD, 0x43CC8940, 0x9E7767D9, 0x42BDB0E8, 0x8B880789, 0x5B38E719, 0xEEDB79C8, 0x0A47A17C, 0x0FE97C42, 0x1EC9F884, 0x00000000, 0x86830980, 0xED48322B, 0x70AC1E11, 0x724E6C5A, 0xFFFBFD0E, 0x38560F85, 0xD51E3DAE, 0x3927362D, 0xD9640A0F, 0xA621685C, 0x54D19B5B, 0x2E3A2436, 0x67B10C0A, 0xE70F9357, 0x96D2B4EE, 0x919E1B9B, 0xC54F80C0, 0x20A261DC, 0x4B695A77, 0x1A161C12, 0xBA0AE293, 0x2AE5C0A0, 0xE0433C22, 0x171D121B, 0x0D0B0E09, 0xC7ADF28B, 0xA8B92DB6, 0xA9C8141E, 0x198557F1, 0x074CAF75, 0xDDBBEE99, 0x60FDA37F, 0x269FF701, 0xF5BC5C72, 0x3BC54466, 0x7E345BFB, 0x29768B43, 0xC6DCCB23, 0xFC68B6ED, 0xF163B8E4, 0xDCCAD731, 0x85104263, 0x22401397, 0x112084C6, 0x247D854A, 0x3DF8D2BB, 0x3211AEF9, 0xA16DC729, 0x2F4B1D9E, 0x30F3DCB2, 0x52EC0D86, 0xE3D077C1, 0x166C2BB3, 0xB999A970, 0x48FA1194, 0x642247E9, 0x8CC4A8FC, 0x3F1AA0F0, 0x2CD8567D, 0x90EF2233, 0x4EC78749, 0xD1C1D938, 0xA2FE8CCA, 0x0B3698D4, 0x81CFA6F5, 0xDE28A57A, 0x8E26DAB7, 0xBFA43FAD, 0x9DE42C3A, 0x920D5078, 0xCC9B6A5F, 0x4662547E, 0x13C2F68D, 0xB8E890D8, 0xF75E2E39, 0xAFF582C3, 0x80BE9F5D, 0x937C69D0, 0x2DA96FD5, 0x12B3CF25, 0x993BC8AC, 0x7DA71018, 0x636EE89C, 0xBB7BDB3B, 0x7809CD26, 0x18F46E59, 0xB701EC9A, 0x9AA8834F, 0x6E65E695, 0xE67EAAFF, 0xCF0821BC, 0xE8E6EF15, 0x9BD9BAE7, 0x36CE4A6F, 0x09D4EA9F, 0x7CD629B0, 0xB2AF31A4, 0x23312A3F, 0x9430C6A5, 0x66C035A2, 0xBC37744E, 0xCAA6FC82, 0xD0B0E090, 0xD81533A7, 0x984AF104, 0xDAF741EC, 0x500E7FCD, 0xF62F1791, 0xD68D764D, 0xB04D43EF, 0x4D54CCAA, 0x04DFE496, 0xB5E39ED1, 0x881B4C6A, 0x1FB8C12C, 0x517F4665, 0xEA049D5E, 0x355D018C, 0x7473FA87, 0x412EFB0B, 0x1D5AB367, 0xD25292DB, 0x5633E910, 0x47136DD6, 0x618C9AD7, 0x0C7A37A1, 0x148E59F8, 0x3C89EB13, 0x27EECEA9, 0xC935B761, 0xE5EDE11C, 0xB13C7A47, 0xDF599CD2, 0x733F55F2, 0xCE791814, 0x37BF73C7, 0xCDEA53F7, 0xAA5B5FFD, 0x6F14DF3D, 0xDB867844, 0xF381CAAF, 0xC43EB968, 0x342C3824, 0x405FC2A3, 0xC372161D, 0x250CBCE2, 0x498B283C, 0x9541FF0D, 0x017139A8, 0xB3DE080C, 0xE49CD8B4, 0xC1906456, 0x84617BCB, 0xB670D532, 0x5C74486C, 0x5742D0B8 ); /** * Precomputed invMixColumns table * * @see \phpseclib\Crypt\Rijndael:_encryptBlock() * @see \phpseclib\Crypt\Rijndael:_decryptBlock() * @var Array * @access private */ var $dt3 = array( 0xF4A75051, 0x4165537E, 0x17A4C31A, 0x275E963A, 0xAB6BCB3B, 0x9D45F11F, 0xFA58ABAC, 0xE303934B, 0x30FA5520, 0x766DF6AD, 0xCC769188, 0x024C25F5, 0xE5D7FC4F, 0x2ACBD7C5, 0x35448026, 0x62A38FB5, 0xB15A49DE, 0xBA1B6725, 0xEA0E9845, 0xFEC0E15D, 0x2F7502C3, 0x4CF01281, 0x4697A38D, 0xD3F9C66B, 0x8F5FE703, 0x929C9515, 0x6D7AEBBF, 0x5259DA95, 0xBE832DD4, 0x7421D358, 0xE0692949, 0xC9C8448E, 0xC2896A75, 0x8E7978F4, 0x583E6B99, 0xB971DD27, 0xE14FB6BE, 0x88AD17F0, 0x20AC66C9, 0xCE3AB47D, 0xDF4A1863, 0x1A3182E5, 0x51336097, 0x537F4562, 0x6477E0B1, 0x6BAE84BB, 0x81A01CFE, 0x082B94F9, 0x48685870, 0x45FD198F, 0xDE6C8794, 0x7BF8B752, 0x73D323AB, 0x4B02E272, 0x1F8F57E3, 0x55AB2A66, 0xEB2807B2, 0xB5C2032F, 0xC57B9A86, 0x3708A5D3, 0x2887F230, 0xBFA5B223, 0x036ABA02, 0x16825CED, 0xCF1C2B8A, 0x79B492A7, 0x07F2F0F3, 0x69E2A14E, 0xDAF4CD65, 0x05BED506, 0x34621FD1, 0xA6FE8AC4, 0x2E539D34, 0xF355A0A2, 0x8AE13205, 0xF6EB75A4, 0x83EC390B, 0x60EFAA40, 0x719F065E, 0x6E1051BD, 0x218AF93E, 0xDD063D96, 0x3E05AEDD, 0xE6BD464D, 0x548DB591, 0xC45D0571, 0x06D46F04, 0x5015FF60, 0x98FB2419, 0xBDE997D6, 0x4043CC89, 0xD99E7767, 0xE842BDB0, 0x898B8807, 0x195B38E7, 0xC8EEDB79, 0x7C0A47A1, 0x420FE97C, 0x841EC9F8, 0x00000000, 0x80868309, 0x2BED4832, 0x1170AC1E, 0x5A724E6C, 0x0EFFFBFD, 0x8538560F, 0xAED51E3D, 0x2D392736, 0x0FD9640A, 0x5CA62168, 0x5B54D19B, 0x362E3A24, 0x0A67B10C, 0x57E70F93, 0xEE96D2B4, 0x9B919E1B, 0xC0C54F80, 0xDC20A261, 0x774B695A, 0x121A161C, 0x93BA0AE2, 0xA02AE5C0, 0x22E0433C, 0x1B171D12, 0x090D0B0E, 0x8BC7ADF2, 0xB6A8B92D, 0x1EA9C814, 0xF1198557, 0x75074CAF, 0x99DDBBEE, 0x7F60FDA3, 0x01269FF7, 0x72F5BC5C, 0x663BC544, 0xFB7E345B, 0x4329768B, 0x23C6DCCB, 0xEDFC68B6, 0xE4F163B8, 0x31DCCAD7, 0x63851042, 0x97224013, 0xC6112084, 0x4A247D85, 0xBB3DF8D2, 0xF93211AE, 0x29A16DC7, 0x9E2F4B1D, 0xB230F3DC, 0x8652EC0D, 0xC1E3D077, 0xB3166C2B, 0x70B999A9, 0x9448FA11, 0xE9642247, 0xFC8CC4A8, 0xF03F1AA0, 0x7D2CD856, 0x3390EF22, 0x494EC787, 0x38D1C1D9, 0xCAA2FE8C, 0xD40B3698, 0xF581CFA6, 0x7ADE28A5, 0xB78E26DA, 0xADBFA43F, 0x3A9DE42C, 0x78920D50, 0x5FCC9B6A, 0x7E466254, 0x8D13C2F6, 0xD8B8E890, 0x39F75E2E, 0xC3AFF582, 0x5D80BE9F, 0xD0937C69, 0xD52DA96F, 0x2512B3CF, 0xAC993BC8, 0x187DA710, 0x9C636EE8, 0x3BBB7BDB, 0x267809CD, 0x5918F46E, 0x9AB701EC, 0x4F9AA883, 0x956E65E6, 0xFFE67EAA, 0xBCCF0821, 0x15E8E6EF, 0xE79BD9BA, 0x6F36CE4A, 0x9F09D4EA, 0xB07CD629, 0xA4B2AF31, 0x3F23312A, 0xA59430C6, 0xA266C035, 0x4EBC3774, 0x82CAA6FC, 0x90D0B0E0, 0xA7D81533, 0x04984AF1, 0xECDAF741, 0xCD500E7F, 0x91F62F17, 0x4DD68D76, 0xEFB04D43, 0xAA4D54CC, 0x9604DFE4, 0xD1B5E39E, 0x6A881B4C, 0x2C1FB8C1, 0x65517F46, 0x5EEA049D, 0x8C355D01, 0x877473FA, 0x0B412EFB, 0x671D5AB3, 0xDBD25292, 0x105633E9, 0xD647136D, 0xD7618C9A, 0xA10C7A37, 0xF8148E59, 0x133C89EB, 0xA927EECE, 0x61C935B7, 0x1CE5EDE1, 0x47B13C7A, 0xD2DF599C, 0xF2733F55, 0x14CE7918, 0xC737BF73, 0xF7CDEA53, 0xFDAA5B5F, 0x3D6F14DF, 0x44DB8678, 0xAFF381CA, 0x68C43EB9, 0x24342C38, 0xA3405FC2, 0x1DC37216, 0xE2250CBC, 0x3C498B28, 0x0D9541FF, 0xA8017139, 0x0CB3DE08, 0xB4E49CD8, 0x56C19064, 0xCB84617B, 0x32B670D5, 0x6C5C7448, 0xB85742D0 ); /** * The SubByte S-Box * * @see \phpseclib\Crypt\Rijndael::_encryptBlock() * @var Array * @access private */ var $sbox = array( 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 ); /** * The inverse SubByte S-Box * * @see \phpseclib\Crypt\Rijndael::_decryptBlock() * @var Array * @access private */ var $isbox = array( 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D ); /** * Sets the key. * * Keys can be of any length. Rijndael, itself, requires the use of a key that's between 128-bits and 256-bits long and * whose length is a multiple of 32. If the key is less than 256-bits and the key length isn't set, we round the length * up to the closest valid key length, padding $key with null bytes. If the key is more than 256-bits, we trim the * excess bits. * * If the key is not explicitly set, it'll be assumed to be all null bytes. * * Note: 160/224-bit keys must explicitly set by setKeyLength(), otherwise they will be round/pad up to 192/256 bits. * * @see \phpseclib\Crypt\Base:setKey() * @see setKeyLength() * @access public * @param String $key */ function setKey($key) { parent::setKey($key); if (!$this->explicit_key_length) { $length = strlen($key); switch (true) { case $length <= 16: $this->key_size = 16; break; case $length <= 20: $this->key_size = 20; break; case $length <= 24: $this->key_size = 24; break; case $length <= 28: $this->key_size = 28; break; default: $this->key_size = 32; } $this->_setupEngine(); } } /** * Sets the key length * * Valid key lengths are 128, 160, 192, 224, and 256. If the length is less than 128, it will be rounded up to * 128. If the length is greater than 128 and invalid, it will be rounded down to the closest valid amount. * * Note: phpseclib extends Rijndael (and AES) for using 160- and 224-bit keys but they are officially not defined * and the most (if not all) implementations are not able using 160/224-bit keys but round/pad them up to * 192/256 bits as, for example, mcrypt will do. * * That said, if you want be compatible with other Rijndael and AES implementations, * you should not setKeyLength(160) or setKeyLength(224). * * Additional: In case of 160- and 224-bit keys, phpseclib will/can, for that reason, not use * the mcrypt php extension, even if available. * This results then in slower encryption. * * @access public * @param Integer $length */ function setKeyLength($length) { switch (true) { case $length == 160: $this->key_size = 20; break; case $length == 224: $this->key_size = 28; break; case $length <= 128: $this->key_size = 16; break; case $length <= 192: $this->key_size = 24; break; default: $this->key_size = 32; } $this->explicit_key_length = true; $this->changed = true; $this->_setupEngine(); } /** * Sets the block length * * Valid block lengths are 128, 160, 192, 224, and 256. If the length is less than 128, it will be rounded up to * 128. If the length is greater than 128 and invalid, it will be rounded down to the closest valid amount. * * @access public * @param Integer $length */ function setBlockLength($length) { $length >>= 5; if ($length > 8) { $length = 8; } else if ($length < 4) { $length = 4; } $this->Nb = $length; $this->block_size = $length << 2; $this->changed = true; $this->_setupEngine(); } /** * Setup the fastest possible $engine * * Determines if the mcrypt (\phpseclib\Crypt\Base::ENGINE_MCRYPT) $engine available * and usable for the current $block_size and $key_size. * * If not, the slower \phpseclib\Crypt\Base::ENGINE_INTERNAL $engine will be set. * * @see setKey() * @see setKeyLength() * @see setBlockLength() * @access private */ function _setupEngine() { if (constant('CRYPT_' . $this->const_namespace . '_MODE') == Base::ENGINE_INTERNAL) { // No mcrypt support at all for rijndael return; } // The required mcrypt module name for the current $block_size of rijndael $cipher_name_mcrypt = 'rijndael-' . ($this->block_size << 3); // Determining the availibility/usability of $cipher_name_mcrypt switch (true) { case $this->key_size % 8: // mcrypt is not usable for 160/224-bit keys, only for 128/192/256-bit keys case !in_array($cipher_name_mcrypt, mcrypt_list_algorithms()): // $cipher_name_mcrypt is not available for the current $block_size $engine = Base::ENGINE_INTERNAL; break; default: $engine = Base::ENGINE_MCRYPT; } if ($this->engine == $engine && $this->cipher_name_mcrypt == $cipher_name_mcrypt) { // allready set, so we not unnecessary close $this->enmcrypt/demcrypt/ecb return; } // Set the $engine $this->engine = $engine; $this->cipher_name_mcrypt = $cipher_name_mcrypt; if ($this->enmcrypt) { // Closing the current mcrypt resource(s). _mcryptSetup() will, if needed, // (re)open them with the module named in $this->cipher_name_mcrypt mcrypt_module_close($this->enmcrypt); mcrypt_module_close($this->demcrypt); $this->enmcrypt = null; $this->demcrypt = null; if ($this->ecb) { mcrypt_module_close($this->ecb); $this->ecb = null; } } } /** * Setup the \phpseclib\Crypt\Base::ENGINE_MCRYPT $engine * * @see \phpseclib\Crypt\Base::_setupMcrypt() * @access private */ function _setupMcrypt() { $this->key = str_pad(substr($this->key, 0, $this->key_size), $this->key_size, "\0"); parent::_setupMcrypt(); } /** * Encrypts a block * * @access private * @param String $in * @return String */ function _encryptBlock($in) { static $t0, $t1, $t2, $t3, $sbox; if (!$t0) { for ($i = 0; $i < 256; ++$i) { $t0[] = (int)$this->t0[$i]; $t1[] = (int)$this->t1[$i]; $t2[] = (int)$this->t2[$i]; $t3[] = (int)$this->t3[$i]; $sbox[] = (int)$this->sbox[$i]; } } $state = array(); $words = unpack('N*', $in); $c = $this->c; $w = $this->w; $Nb = $this->Nb; $Nr = $this->Nr; // addRoundKey $i = -1; foreach ($words as $word) { $state[] = $word ^ $w[0][++$i]; } // fips-197.pdf#page=19, "Figure 5. Pseudo Code for the Cipher", states that this loop has four components - // subBytes, shiftRows, mixColumns, and addRoundKey. fips-197.pdf#page=30, "Implementation Suggestions Regarding // Various Platforms" suggests that performs enhanced implementations are described in Rijndael-ammended.pdf. // Rijndael-ammended.pdf#page=20, "Implementation aspects / 32-bit processor", discusses such an optimization. // Unfortunately, the description given there is not quite correct. Per aes.spec.v316.pdf#page=19 [1], // equation (7.4.7) is supposed to use addition instead of subtraction, so we'll do that here, as well. // [1] http://fp.gladman.plus.com/cryptography_technology/rijndael/aes.spec.v316.pdf $temp = array(); for ($round = 1; $round < $Nr; ++$round) { $i = 0; // $c[0] == 0 $j = $c[1]; $k = $c[2]; $l = $c[3]; while ($i < $Nb) { $temp[$i] = $t0[$state[$i] >> 24 & 0x000000FF] ^ $t1[$state[$j] >> 16 & 0x000000FF] ^ $t2[$state[$k] >> 8 & 0x000000FF] ^ $t3[$state[$l] & 0x000000FF] ^ $w[$round][$i]; ++$i; $j = ($j + 1) % $Nb; $k = ($k + 1) % $Nb; $l = ($l + 1) % $Nb; } $state = $temp; } // subWord for ($i = 0; $i < $Nb; ++$i) { $state[$i] = $sbox[$state[$i] & 0x000000FF] | ($sbox[$state[$i] >> 8 & 0x000000FF] << 8) | ($sbox[$state[$i] >> 16 & 0x000000FF] << 16) | ($sbox[$state[$i] >> 24 & 0x000000FF] << 24); } // shiftRows + addRoundKey $i = 0; // $c[0] == 0 $j = $c[1]; $k = $c[2]; $l = $c[3]; while ($i < $Nb) { $temp[$i] = ($state[$i] & 0xFF000000) ^ ($state[$j] & 0x00FF0000) ^ ($state[$k] & 0x0000FF00) ^ ($state[$l] & 0x000000FF) ^ $w[$Nr][$i]; ++$i; $j = ($j + 1) % $Nb; $k = ($k + 1) % $Nb; $l = ($l + 1) % $Nb; } switch ($Nb) { case 8: return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6], $temp[7]); case 7: return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6]); case 6: return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5]); case 5: return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4]); default: return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3]); } } /** * Decrypts a block * * @access private * @param String $in * @return String */ function _decryptBlock($in) { static $dt0, $dt1, $dt2, $dt3, $isbox; if (!$dt0) { for ($i = 0; $i < 256; ++$i) { $dt0[] = (int)$this->dt0[$i]; $dt1[] = (int)$this->dt1[$i]; $dt2[] = (int)$this->dt2[$i]; $dt3[] = (int)$this->dt3[$i]; $isbox[] = (int)$this->isbox[$i]; } } $state = array(); $words = unpack('N*', $in); $c = $this->c; $dw = $this->dw; $Nb = $this->Nb; $Nr = $this->Nr; // addRoundKey $i = -1; foreach ($words as $word) { $state[] = $word ^ $dw[$Nr][++$i]; } $temp = array(); for ($round = $Nr - 1; $round > 0; --$round) { $i = 0; // $c[0] == 0 $j = $Nb - $c[1]; $k = $Nb - $c[2]; $l = $Nb - $c[3]; while ($i < $Nb) { $temp[$i] = $dt0[$state[$i] >> 24 & 0x000000FF] ^ $dt1[$state[$j] >> 16 & 0x000000FF] ^ $dt2[$state[$k] >> 8 & 0x000000FF] ^ $dt3[$state[$l] & 0x000000FF] ^ $dw[$round][$i]; ++$i; $j = ($j + 1) % $Nb; $k = ($k + 1) % $Nb; $l = ($l + 1) % $Nb; } $state = $temp; } // invShiftRows + invSubWord + addRoundKey $i = 0; // $c[0] == 0 $j = $Nb - $c[1]; $k = $Nb - $c[2]; $l = $Nb - $c[3]; while ($i < $Nb) { $word = ($state[$i] & 0xFF000000) | ($state[$j] & 0x00FF0000) | ($state[$k] & 0x0000FF00) | ($state[$l] & 0x000000FF); $temp[$i] = $dw[0][$i] ^ ($isbox[$word & 0x000000FF] | ($isbox[$word >> 8 & 0x000000FF] << 8) | ($isbox[$word >> 16 & 0x000000FF] << 16) | ($isbox[$word >> 24 & 0x000000FF] << 24)); ++$i; $j = ($j + 1) % $Nb; $k = ($k + 1) % $Nb; $l = ($l + 1) % $Nb; } switch ($Nb) { case 8: return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6], $temp[7]); case 7: return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6]); case 6: return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5]); case 5: return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4]); default: return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3]); } } /** * Setup the key (expansion) * * @see \phpseclib\Crypt\Base::_setupKey() * @access private */ function _setupKey() { // Each number in $rcon is equal to the previous number multiplied by two in Rijndael's finite field. // See http://en.wikipedia.org/wiki/Finite_field_arithmetic#Multiplicative_inverse static $rcon = array(0, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000, 0x1B000000, 0x36000000, 0x6C000000, 0xD8000000, 0xAB000000, 0x4D000000, 0x9A000000, 0x2F000000, 0x5E000000, 0xBC000000, 0x63000000, 0xC6000000, 0x97000000, 0x35000000, 0x6A000000, 0xD4000000, 0xB3000000, 0x7D000000, 0xFA000000, 0xEF000000, 0xC5000000, 0x91000000 ); $this->key = str_pad(substr($this->key, 0, $this->key_size), $this->key_size, "\0"); if (isset($this->kl['key']) && $this->key === $this->kl['key'] && $this->key_size === $this->kl['key_size'] && $this->block_size === $this->kl['block_size']) { // already expanded return; } $this->kl = array('key' => $this->key, 'key_size' => $this->key_size, 'block_size' => $this->block_size); $this->Nk = $this->key_size >> 2; // see Rijndael-ammended.pdf#page=44 $this->Nr = max($this->Nk, $this->Nb) + 6; // shift offsets for Nb = 5, 7 are defined in Rijndael-ammended.pdf#page=44, // "Table 8: Shift offsets in Shiftrow for the alternative block lengths" // shift offsets for Nb = 4, 6, 8 are defined in Rijndael-ammended.pdf#page=14, // "Table 2: Shift offsets for different block lengths" switch ($this->Nb) { case 4: case 5: case 6: $this->c = array(0, 1, 2, 3); break; case 7: $this->c = array(0, 1, 2, 4); break; case 8: $this->c = array(0, 1, 3, 4); } $w = array_values(unpack('N*words', $this->key)); $length = $this->Nb * ($this->Nr + 1); for ($i = $this->Nk; $i < $length; $i++) { $temp = $w[$i - 1]; if ($i % $this->Nk == 0) { // according to , "the size of an integer is platform-dependent". // on a 32-bit machine, it's 32-bits, and on a 64-bit machine, it's 64-bits. on a 32-bit machine, // 0xFFFFFFFF << 8 == 0xFFFFFF00, but on a 64-bit machine, it equals 0xFFFFFFFF00. as such, doing 'and' // with 0xFFFFFFFF (or 0xFFFFFF00) on a 32-bit machine is unnecessary, but on a 64-bit machine, it is. $temp = (($temp << 8) & 0xFFFFFF00) | (($temp >> 24) & 0x000000FF); // rotWord $temp = $this->_subWord($temp) ^ $rcon[$i / $this->Nk]; } else if ($this->Nk > 6 && $i % $this->Nk == 4) { $temp = $this->_subWord($temp); } $w[$i] = $w[$i - $this->Nk] ^ $temp; } // convert the key schedule from a vector of $Nb * ($Nr + 1) length to a matrix with $Nr + 1 rows and $Nb columns // and generate the inverse key schedule. more specifically, // according to (section 5.3.3), // "The key expansion for the Inverse Cipher is defined as follows: // 1. Apply the Key Expansion. // 2. Apply InvMixColumn to all Round Keys except the first and the last one." // also, see fips-197.pdf#page=27, "5.3.5 Equivalent Inverse Cipher" $temp = $this->w = $this->dw = array(); for ($i = $row = $col = 0; $i < $length; $i++, $col++) { if ($col == $this->Nb) { if ($row == 0) { $this->dw[0] = $this->w[0]; } else { // subWord + invMixColumn + invSubWord = invMixColumn $j = 0; while ($j < $this->Nb) { $dw = $this->_subWord($this->w[$row][$j]); $temp[$j] = $this->dt0[$dw >> 24 & 0x000000FF] ^ $this->dt1[$dw >> 16 & 0x000000FF] ^ $this->dt2[$dw >> 8 & 0x000000FF] ^ $this->dt3[$dw & 0x000000FF]; $j++; } $this->dw[$row] = $temp; } $col = 0; $row++; } $this->w[$row][$col] = $w[$i]; } $this->dw[$row] = $this->w[$row]; // In case of $this->use_inline_crypt === true we have to use 1-dim key arrays (both ascending) if ($this->use_inline_crypt) { $this->dw = array_reverse($this->dw); $w = array_pop($this->w); $dw = array_pop($this->dw); foreach ($this->w as $r => $wr) { foreach ($wr as $c => $wc) { $w[] = $wc; $dw[] = $this->dw[$r][$c]; } } $this->w = $w; $this->dw = $dw; } } /** * Performs S-Box substitutions * * @access private * @param Integer $word */ function _subWord($word) { $sbox = $this->sbox; return $sbox[$word & 0x000000FF] | ($sbox[$word >> 8 & 0x000000FF] << 8) | ($sbox[$word >> 16 & 0x000000FF] << 16) | ($sbox[$word >> 24 & 0x000000FF] << 24); } /** * Setup the performance-optimized function for de/encrypt() * * @see \phpseclib\Crypt\Base::_setupInlineCrypt() * @access private */ function _setupInlineCrypt() { // Note: _setupInlineCrypt() will be called only if $this->changed === true // So here we are'nt under the same heavy timing-stress as we are in _de/encryptBlock() or de/encrypt(). // However...the here generated function- $code, stored as php callback in $this->inline_crypt, must work as fast as even possible. $lambda_functions =& self::_getLambdaFunctions(); // The first 10 generated $lambda_functions will use the key-words hardcoded for better performance. // For memory reason we limit those ultra-optimized functions. // After that, we use pure (extracted) integer vars for the key-words which is faster than accessing them via array. if (count($lambda_functions) < 10) { $w = $this->w; $dw = $this->dw; $init_encrypt = ''; $init_decrypt = ''; } else { for ($i = 0, $cw = count($this->w); $i < $cw; ++$i) { $w[] = '$w[' . $i . ']'; $dw[] = '$dw[' . $i . ']'; } $init_encrypt = '$w = $self->w;'; $init_decrypt = '$dw = $self->dw;'; } $code_hash = md5(str_pad("Rijndael, {$this->mode}, {$this->block_size}, ", 32, "\0") . implode(',', $w)); if (!isset($lambda_functions[$code_hash])) { $Nr = $this->Nr; $Nb = $this->Nb; $c = $this->c; // Generating encrypt code: $init_encrypt.= ' static $t0, $t1, $t2, $t3, $sbox; if (!$t0) { for ($i = 0; $i < 256; ++$i) { $t0[$i] = (int)$self->t0[$i]; $t1[$i] = (int)$self->t1[$i]; $t2[$i] = (int)$self->t2[$i]; $t3[$i] = (int)$self->t3[$i]; $sbox[$i] = (int)$self->sbox[$i]; } } '; $s = 'e'; $e = 's'; $wc = $Nb - 1; // Preround: addRoundKey $encrypt_block = '$in = unpack("N*", $in);'."\n"; for ($i = 0; $i < $Nb; ++$i) { $encrypt_block .= '$s'.$i.' = $in['.($i + 1).'] ^ '.$w[++$wc].";\n"; } // Mainrounds: shiftRows + subWord + mixColumns + addRoundKey for ($round = 1; $round < $Nr; ++$round) { list($s, $e) = array($e, $s); for ($i = 0; $i < $Nb; ++$i) { $encrypt_block.= '$'.$e.$i.' = $t0[($'.$s.$i .' >> 24) & 0xff] ^ $t1[($'.$s.(($i + $c[1]) % $Nb).' >> 16) & 0xff] ^ $t2[($'.$s.(($i + $c[2]) % $Nb).' >> 8) & 0xff] ^ $t3[ $'.$s.(($i + $c[3]) % $Nb).' & 0xff] ^ '.$w[++$wc].";\n"; } } // Finalround: subWord + shiftRows + addRoundKey for ($i = 0; $i < $Nb; ++$i) { $encrypt_block.= '$'.$e.$i.' = $sbox[ $'.$e.$i.' & 0xff] | ($sbox[($'.$e.$i.' >> 8) & 0xff] << 8) | ($sbox[($'.$e.$i.' >> 16) & 0xff] << 16) | ($sbox[($'.$e.$i.' >> 24) & 0xff] << 24);'."\n"; } $encrypt_block .= '$in = pack("N*"'."\n"; for ($i = 0; $i < $Nb; ++$i) { $encrypt_block.= ', ($'.$e.$i .' & 0xFF000000) ^ ($'.$e.(($i + $c[1]) % $Nb).' & 0x00FF0000) ^ ($'.$e.(($i + $c[2]) % $Nb).' & 0x0000FF00) ^ ($'.$e.(($i + $c[3]) % $Nb).' & 0x000000FF) ^ '.$w[$i]."\n"; } $encrypt_block .= ');'; // Generating decrypt code: $init_decrypt.= ' static $dt0, $dt1, $dt2, $dt3, $isbox; if (!$dt0) { for ($i = 0; $i < 256; ++$i) { $dt0[$i] = (int)$self->dt0[$i]; $dt1[$i] = (int)$self->dt1[$i]; $dt2[$i] = (int)$self->dt2[$i]; $dt3[$i] = (int)$self->dt3[$i]; $isbox[$i] = (int)$self->isbox[$i]; } } '; $s = 'e'; $e = 's'; $wc = $Nb - 1; // Preround: addRoundKey $decrypt_block = '$in = unpack("N*", $in);'."\n"; for ($i = 0; $i < $Nb; ++$i) { $decrypt_block .= '$s'.$i.' = $in['.($i + 1).'] ^ '.$dw[++$wc].';'."\n"; } // Mainrounds: shiftRows + subWord + mixColumns + addRoundKey for ($round = 1; $round < $Nr; ++$round) { list($s, $e) = array($e, $s); for ($i = 0; $i < $Nb; ++$i) { $decrypt_block.= '$'.$e.$i.' = $dt0[($'.$s.$i .' >> 24) & 0xff] ^ $dt1[($'.$s.(($Nb + $i - $c[1]) % $Nb).' >> 16) & 0xff] ^ $dt2[($'.$s.(($Nb + $i - $c[2]) % $Nb).' >> 8) & 0xff] ^ $dt3[ $'.$s.(($Nb + $i - $c[3]) % $Nb).' & 0xff] ^ '.$dw[++$wc].";\n"; } } // Finalround: subWord + shiftRows + addRoundKey for ($i = 0; $i < $Nb; ++$i) { $decrypt_block.= '$'.$e.$i.' = $isbox[ $'.$e.$i.' & 0xff] | ($isbox[($'.$e.$i.' >> 8) & 0xff] << 8) | ($isbox[($'.$e.$i.' >> 16) & 0xff] << 16) | ($isbox[($'.$e.$i.' >> 24) & 0xff] << 24);'."\n"; } $decrypt_block .= '$in = pack("N*"'."\n"; for ($i = 0; $i < $Nb; ++$i) { $decrypt_block.= ', ($'.$e.$i. ' & 0xFF000000) ^ ($'.$e.(($Nb + $i - $c[1]) % $Nb).' & 0x00FF0000) ^ ($'.$e.(($Nb + $i - $c[2]) % $Nb).' & 0x0000FF00) ^ ($'.$e.(($Nb + $i - $c[3]) % $Nb).' & 0x000000FF) ^ '.$dw[$i]."\n"; } $decrypt_block .= ');'; $lambda_functions[$code_hash] = $this->_createInlineCryptFunction( array( 'init_crypt' => '', 'init_encrypt' => $init_encrypt, 'init_decrypt' => $init_decrypt, 'encrypt_block' => $encrypt_block, 'decrypt_block' => $decrypt_block ) ); } $this->inline_crypt = $lambda_functions[$code_hash]; } } * createKey()); * * $plaintext = 'terrafrost'; * * $rsa->loadKey($privatekey); * $ciphertext = $rsa->encrypt($plaintext); * * $rsa->loadKey($publickey); * echo $rsa->decrypt($ciphertext); * ?> * * * Here's an example of how to create signatures and verify signatures with this library: * * createKey()); * * $plaintext = 'terrafrost'; * * $rsa->loadKey($privatekey); * $signature = $rsa->sign($plaintext); * * $rsa->loadKey($publickey); * echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified'; * ?> * * * @category Crypt * @package RSA * @author Jim Wigginton * @copyright 2009 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\Crypt; use phpseclib\Crypt\AES; use phpseclib\Crypt\Base; use phpseclib\Crypt\DES; use phpseclib\Crypt\Hash; use phpseclib\Crypt\Random; use phpseclib\Crypt\RSA; use phpseclib\Crypt\TripleDES; use phpseclib\Math\BigInteger; /** * Pure-PHP PKCS#1 compliant implementation of RSA. * * @package RSA * @author Jim Wigginton * @access public */ class RSA { /**#@+ * @access public * @see \phpseclib\Crypt\RSA::encrypt() * @see \phpseclib\Crypt\RSA::decrypt() */ /** * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding} * (OAEP) for encryption / decryption. * * Uses sha1 by default. * * @see \phpseclib\Crypt\RSA::setHash() * @see \phpseclib\Crypt\RSA::setMGFHash() */ const ENCRYPTION_OAEP = 1; /** * Use PKCS#1 padding. * * Although self::ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards * compatibility with protocols (like SSH-1) written before OAEP's introduction. */ const ENCRYPTION_PKCS1 = 2; /**#@-*/ /**#@+ * @access public * @see \phpseclib\Crypt\RSA::sign() * @see \phpseclib\Crypt\RSA::verify() * @see \phpseclib\Crypt\RSA::setHash() */ /** * Use the Probabilistic Signature Scheme for signing * * Uses sha1 by default. * * @see \phpseclib\Crypt\RSA::setSaltLength() * @see \phpseclib\Crypt\RSA::setMGFHash() */ const SIGNATURE_PSS = 1; /** * Use the PKCS#1 scheme by default. * * Although self::SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards * compatibility with protocols (like SSH-2) written before PSS's introduction. */ const SIGNATURE_PKCS1 = 2; /**#@-*/ /**#@+ * @access private * @see \phpseclib\Crypt\RSA::createKey() */ /** * ASN1 Integer */ const ASN1_INTEGER = 2; /** * ASN1 Bit String */ const ASN1_BITSTRING = 3; /** * ASN1 Octet String */ const ASN1_OCTETSTRING = 4; /** * ASN1 Object Identifier */ const ASN1_OBJECT = 6; /** * ASN1 Sequence (with the constucted bit set) */ const ASN1_SEQUENCE = 48; /**#@-*/ /**#@+ * @access private * @see \phpseclib\Crypt\RSA::__construct() */ /** * To use the pure-PHP implementation */ const MODE_INTERNAL = 1; /** * To use the OpenSSL library * * (if enabled; otherwise, the internal implementation will be used) */ const MODE_OPENSSL = 2; /**#@-*/ /**#@+ * @access public * @see \phpseclib\Crypt\RSA::createKey() * @see \phpseclib\Crypt\RSA::setPrivateKeyFormat() */ /** * PKCS#1 formatted private key * * Used by OpenSSH */ const PRIVATE_FORMAT_PKCS1 = 0; /** * PuTTY formatted private key */ const PRIVATE_FORMAT_PUTTY = 1; /** * XML formatted private key */ const PRIVATE_FORMAT_XML = 2; /** * PKCS#8 formatted private key */ const PRIVATE_FORMAT_PKCS8 = 3; /**#@-*/ /**#@+ * @access public * @see \phpseclib\Crypt\RSA::createKey() * @see \phpseclib\Crypt\RSA::setPublicKeyFormat() */ /** * Raw public key * * An array containing two \phpseclib\Math\BigInteger objects. * * The exponent can be indexed with any of the following: * * 0, e, exponent, publicExponent * * The modulus can be indexed with any of the following: * * 1, n, modulo, modulus */ const PUBLIC_FORMAT_RAW = 3; /** * PKCS#1 formatted public key (raw) * * Used by File/X509.php * * Has the following header: * * -----BEGIN RSA PUBLIC KEY----- * * Analogous to ssh-keygen's pem format (as specified by -m) */ const PUBLIC_FORMAT_PKCS1 = 4; const PUBLIC_FORMAT_PKCS1_RAW = 4; /** * XML formatted public key */ const PUBLIC_FORMAT_XML = 5; /** * OpenSSH formatted public key * * Place in $HOME/.ssh/authorized_keys */ const PUBLIC_FORMAT_OPENSSH = 6; /** * PKCS#1 formatted public key (encapsulated) * * Used by PHP's openssl_public_encrypt() and openssl's rsautl (when -pubin is set) * * Has the following header: * * -----BEGIN PUBLIC KEY----- * * Analogous to ssh-keygen's pkcs8 format (as specified by -m). Although PKCS8 * is specific to private keys it's basically creating a DER-encoded wrapper * for keys. This just extends that same concept to public keys (much like ssh-keygen) */ const PUBLIC_FORMAT_PKCS8 = 7; /**#@-*/ /** * Precomputed Zero * * @var Array * @access private */ var $zero; /** * Precomputed One * * @var Array * @access private */ var $one; /** * Private Key Format * * @var Integer * @access private */ var $privateKeyFormat = self::PRIVATE_FORMAT_PKCS1; /** * Public Key Format * * @var Integer * @access public */ var $publicKeyFormat = self::PUBLIC_FORMAT_PKCS8; /** * Modulus (ie. n) * * @var \phpseclib\Math\BigInteger * @access private */ var $modulus; /** * Modulus length * * @var \phpseclib\Math\BigInteger * @access private */ var $k; /** * Exponent (ie. e or d) * * @var \phpseclib\Math\BigInteger * @access private */ var $exponent; /** * Primes for Chinese Remainder Theorem (ie. p and q) * * @var Array * @access private */ var $primes; /** * Exponents for Chinese Remainder Theorem (ie. dP and dQ) * * @var Array * @access private */ var $exponents; /** * Coefficients for Chinese Remainder Theorem (ie. qInv) * * @var Array * @access private */ var $coefficients; /** * Hash name * * @var String * @access private */ var $hashName; /** * Hash function * * @var \phpseclib\Crypt\Hash * @access private */ var $hash; /** * Length of hash function output * * @var Integer * @access private */ var $hLen; /** * Length of salt * * @var Integer * @access private */ var $sLen; /** * Hash function for the Mask Generation Function * * @var \phpseclib\Crypt\Hash * @access private */ var $mgfHash; /** * Length of MGF hash function output * * @var Integer * @access private */ var $mgfHLen; /** * Encryption mode * * @var Integer * @access private */ var $encryptionMode = self::ENCRYPTION_OAEP; /** * Signature mode * * @var Integer * @access private */ var $signatureMode = self::SIGNATURE_PSS; /** * Public Exponent * * @var Mixed * @access private */ var $publicExponent = false; /** * Password * * @var String * @access private */ var $password = false; /** * Components * * For use with parsing XML formatted keys. PHP's XML Parser functions use utilized - instead of PHP's DOM functions - * because PHP's XML Parser functions work on PHP4 whereas PHP's DOM functions - although surperior - don't. * * @see \phpseclib\Crypt\RSA::_start_element_handler() * @var Array * @access private */ var $components = array(); /** * Current String * * For use with parsing XML formatted keys. * * @see \phpseclib\Crypt\RSA::_character_handler() * @see \phpseclib\Crypt\RSA::_stop_element_handler() * @var Mixed * @access private */ var $current; /** * OpenSSL configuration file name. * * Set to null to use system configuration file. * @see \phpseclib\Crypt\RSA::createKey() * @var Mixed * @Access public */ var $configFile; /** * Public key comment field. * * @var String * @access private */ var $comment = 'phpseclib-generated-key'; /** * The constructor * * If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason * \phpseclib\Crypt\RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires * openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late. * * @return \phpseclib\Crypt\RSA * @access public */ function __construct() { $this->configFile = dirname(__FILE__) . '/../openssl.cnf'; if ( !defined('CRYPT_RSA_MODE') ) { switch (true) { // Math/BigInteger's openssl requirements are a little less stringent than Crypt/RSA's. in particular, // Math/BigInteger doesn't require an openssl.cfg file whereas Crypt/RSA does. so if Math/BigInteger // can't use OpenSSL it can be pretty trivially assumed, then, that Crypt/RSA can't either. case defined('MATH_BIGINTEGER_OPENSSL_DISABLE'): define('CRYPT_RSA_MODE', self::MODE_INTERNAL); break; // openssl_pkey_get_details - which is used in the only place Crypt/RSA.php uses OpenSSL - was introduced in PHP 5.2.0 case !function_exists('openssl_pkey_get_details'): define('CRYPT_RSA_MODE', self::MODE_INTERNAL); break; case extension_loaded('openssl') && version_compare(PHP_VERSION, '4.2.0', '>=') && file_exists($this->configFile): // some versions of XAMPP have mismatched versions of OpenSSL which causes it not to work ob_start(); @phpinfo(); $content = ob_get_contents(); ob_end_clean(); preg_match_all('#OpenSSL (Header|Library) Version(.*)#im', $content, $matches); $versions = array(); if (!empty($matches[1])) { for ($i = 0; $i < count($matches[1]); $i++) { $fullVersion = trim(str_replace('=>', '', strip_tags($matches[2][$i]))); // Remove letter part in OpenSSL version if (!preg_match('/(\d+\.\d+\.\d+)/i', $fullVersion, $m)) { $versions[$matches[1][$i]] = $fullVersion; } else { $versions[$matches[1][$i]] = $m[0]; } } } // it doesn't appear that OpenSSL versions were reported upon until PHP 5.3+ switch (true) { case !isset($versions['Header']): case !isset($versions['Library']): case $versions['Header'] == $versions['Library']: define('CRYPT_RSA_MODE', self::MODE_OPENSSL); break; default: define('CRYPT_RSA_MODE', self::MODE_INTERNAL); define('MATH_BIGINTEGER_OPENSSL_DISABLE', true); } break; default: define('CRYPT_RSA_MODE', self::MODE_INTERNAL); } } $this->zero = new BigInteger(); $this->one = new BigInteger(1); $this->hash = new Hash('sha1'); $this->hLen = $this->hash->getLength(); $this->hashName = 'sha1'; $this->mgfHash = new Hash('sha1'); $this->mgfHLen = $this->mgfHash->getLength(); } /** * Create public / private key pair * * Returns an array with the following three elements: * - 'privatekey': The private key. * - 'publickey': The public key. * - 'partialkey': A partially computed key (if the execution time exceeded $timeout). * Will need to be passed back to \phpseclib\Crypt\RSA::createKey() as the third parameter for further processing. * * @access public * @param optional Integer $bits * @param optional Integer $timeout * @param optional array $p */ function createKey($bits = 1024, $timeout = false, $partial = array()) { if (!defined('CRYPT_RSA_EXPONENT')) { // http://en.wikipedia.org/wiki/65537_%28number%29 define('CRYPT_RSA_EXPONENT', '65537'); } // per , this number ought not result in primes smaller // than 256 bits. as a consequence if the key you're trying to create is 1024 bits and you've set CRYPT_RSA_SMALLEST_PRIME // to 384 bits then you're going to get a 384 bit prime and a 640 bit prime (384 + 1024 % 384). at least if // CRYPT_RSA_MODE is set to self::MODE_INTERNAL. if CRYPT_RSA_MODE is set to self::MODE_OPENSSL then // CRYPT_RSA_SMALLEST_PRIME is ignored (ie. multi-prime RSA support is more intended as a way to speed up RSA key // generation when there's a chance neither gmp nor OpenSSL are installed) if (!defined('CRYPT_RSA_SMALLEST_PRIME')) { define('CRYPT_RSA_SMALLEST_PRIME', 4096); } // OpenSSL uses 65537 as the exponent and requires RSA keys be 384 bits minimum if ( CRYPT_RSA_MODE == self::MODE_OPENSSL && $bits >= 384 && CRYPT_RSA_EXPONENT == 65537) { $config = array(); if (isset($this->configFile)) { $config['config'] = $this->configFile; } $rsa = openssl_pkey_new(array('private_key_bits' => $bits) + $config); openssl_pkey_export($rsa, $privatekey, null, $config); $publickey = openssl_pkey_get_details($rsa); $publickey = $publickey['key']; $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, self::PRIVATE_FORMAT_PKCS1))); $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, self::PUBLIC_FORMAT_PKCS1))); // clear the buffer of error strings stemming from a minimalistic openssl.cnf while (openssl_error_string() !== false); return array( 'privatekey' => $privatekey, 'publickey' => $publickey, 'partialkey' => false ); } static $e; if (!isset($e)) { $e = new BigInteger(CRYPT_RSA_EXPONENT); } extract($this->_generateMinMax($bits)); $absoluteMin = $min; $temp = $bits >> 1; // divide by two to see how many bits P and Q would be if ($temp > CRYPT_RSA_SMALLEST_PRIME) { $num_primes = floor($bits / CRYPT_RSA_SMALLEST_PRIME); $temp = CRYPT_RSA_SMALLEST_PRIME; } else { $num_primes = 2; } extract($this->_generateMinMax($temp + $bits % $temp)); $finalMax = $max; extract($this->_generateMinMax($temp)); $generator = new BigInteger(); $n = $this->one->copy(); if (!empty($partial)) { extract(unserialize($partial)); } else { $exponents = $coefficients = $primes = array(); $lcm = array( 'top' => $this->one->copy(), 'bottom' => false ); } $start = time(); $i0 = count($primes) + 1; do { for ($i = $i0; $i <= $num_primes; $i++) { if ($timeout !== false) { $timeout-= time() - $start; $start = time(); if ($timeout <= 0) { return array( 'privatekey' => '', 'publickey' => '', 'partialkey' => serialize(array( 'primes' => $primes, 'coefficients' => $coefficients, 'lcm' => $lcm, 'exponents' => $exponents )) ); } } if ($i == $num_primes) { list($min, $temp) = $absoluteMin->divide($n); if (!$temp->equals($this->zero)) { $min = $min->add($this->one); // ie. ceil() } $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout); } else { $primes[$i] = $generator->randomPrime($min, $max, $timeout); } if ($primes[$i] === false) { // if we've reached the timeout if (count($primes) > 1) { $partialkey = ''; } else { array_pop($primes); $partialkey = serialize(array( 'primes' => $primes, 'coefficients' => $coefficients, 'lcm' => $lcm, 'exponents' => $exponents )); } return array( 'privatekey' => '', 'publickey' => '', 'partialkey' => $partialkey ); } // the first coefficient is calculated differently from the rest // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1]) if ($i > 2) { $coefficients[$i] = $n->modInverse($primes[$i]); } $n = $n->multiply($primes[$i]); $temp = $primes[$i]->subtract($this->one); // textbook RSA implementations use Euler's totient function instead of the least common multiple. // see http://en.wikipedia.org/wiki/Euler%27s_totient_function $lcm['top'] = $lcm['top']->multiply($temp); $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp); $exponents[$i] = $e->modInverse($temp); } list($temp) = $lcm['top']->divide($lcm['bottom']); $gcd = $temp->gcd($e); $i0 = 1; } while (!$gcd->equals($this->one)); $d = $e->modInverse($temp); $coefficients[2] = $primes[2]->modInverse($primes[1]); // from : // RSAPrivateKey ::= SEQUENCE { // version Version, // modulus INTEGER, -- n // publicExponent INTEGER, -- e // privateExponent INTEGER, -- d // prime1 INTEGER, -- p // prime2 INTEGER, -- q // exponent1 INTEGER, -- d mod (p-1) // exponent2 INTEGER, -- d mod (q-1) // coefficient INTEGER, -- (inverse of q) mod p // otherPrimeInfos OtherPrimeInfos OPTIONAL // } return array( 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients), 'publickey' => $this->_convertPublicKey($n, $e), 'partialkey' => false ); } /** * Convert a private key to the appropriate format. * * @access private * @see setPrivateKeyFormat() * @param String $RSAPrivateKey * @return String */ function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients) { $signed = $this->privateKeyFormat != self::PRIVATE_FORMAT_XML; $num_primes = count($primes); $raw = array( 'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi 'modulus' => $n->toBytes($signed), 'publicExponent' => $e->toBytes($signed), 'privateExponent' => $d->toBytes($signed), 'prime1' => $primes[1]->toBytes($signed), 'prime2' => $primes[2]->toBytes($signed), 'exponent1' => $exponents[1]->toBytes($signed), 'exponent2' => $exponents[2]->toBytes($signed), 'coefficient' => $coefficients[2]->toBytes($signed) ); // if the format in question does not support multi-prime rsa and multi-prime rsa was used, // call _convertPublicKey() instead. switch ($this->privateKeyFormat) { case self::PRIVATE_FORMAT_XML: if ($num_primes != 2) { return false; } return "\r\n" . ' ' . base64_encode($raw['modulus']) . "\r\n" . ' ' . base64_encode($raw['publicExponent']) . "\r\n" . '

' . base64_encode($raw['prime1']) . "

\r\n" . ' ' . base64_encode($raw['prime2']) . "\r\n" . ' ' . base64_encode($raw['exponent1']) . "\r\n" . ' ' . base64_encode($raw['exponent2']) . "\r\n" . ' ' . base64_encode($raw['coefficient']) . "\r\n" . ' ' . base64_encode($raw['privateExponent']) . "\r\n" . '
'; break; case self::PRIVATE_FORMAT_PUTTY: if ($num_primes != 2) { return false; } $key = "PuTTY-User-Key-File-2: ssh-rsa\r\nEncryption: "; $encryption = (!empty($this->password) || is_string($this->password)) ? 'aes256-cbc' : 'none'; $key.= $encryption; $key.= "\r\nComment: " . $this->comment . "\r\n"; $public = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($raw['publicExponent']), $raw['publicExponent'], strlen($raw['modulus']), $raw['modulus'] ); $source = pack('Na*Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($encryption), $encryption, strlen($this->comment), $this->comment, strlen($public), $public ); $public = base64_encode($public); $key.= "Public-Lines: " . ((strlen($public) + 63) >> 6) . "\r\n"; $key.= chunk_split($public, 64); $private = pack('Na*Na*Na*Na*', strlen($raw['privateExponent']), $raw['privateExponent'], strlen($raw['prime1']), $raw['prime1'], strlen($raw['prime2']), $raw['prime2'], strlen($raw['coefficient']), $raw['coefficient'] ); if (empty($this->password) && !is_string($this->password)) { $source.= pack('Na*', strlen($private), $private); $hashkey = 'putty-private-key-file-mac-key'; } else { $private.= Random::string(16 - (strlen($private) & 15)); $source.= pack('Na*', strlen($private), $private); $sequence = 0; $symkey = ''; while (strlen($symkey) < 32) { $temp = pack('Na*', $sequence++, $this->password); $symkey.= pack('H*', sha1($temp)); } $symkey = substr($symkey, 0, 32); $crypto = new AES(); $crypto->setKey($symkey); $crypto->disablePadding(); $private = $crypto->encrypt($private); $hashkey = 'putty-private-key-file-mac-key' . $this->password; } $private = base64_encode($private); $key.= 'Private-Lines: ' . ((strlen($private) + 63) >> 6) . "\r\n"; $key.= chunk_split($private, 64); $hash = new Hash('sha1'); $hash->setKey(pack('H*', sha1($hashkey))); $key.= 'Private-MAC: ' . bin2hex($hash->hash($source)) . "\r\n"; return $key; default: // eg. self::PRIVATE_FORMAT_PKCS1 $components = array(); foreach ($raw as $name => $value) { $components[$name] = pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value); } $RSAPrivateKey = implode('', $components); if ($num_primes > 2) { $OtherPrimeInfos = ''; for ($i = 3; $i <= $num_primes; $i++) { // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo // // OtherPrimeInfo ::= SEQUENCE { // prime INTEGER, -- ri // exponent INTEGER, -- di // coefficient INTEGER -- ti // } $OtherPrimeInfo = pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true)); $OtherPrimeInfo.= pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true)); $OtherPrimeInfo.= pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true)); $OtherPrimeInfos.= pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo); } $RSAPrivateKey.= pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos); } $RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey); if ($this->privateKeyFormat == self::PRIVATE_FORMAT_PKCS8) { $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA $RSAPrivateKey = pack('Ca*a*Ca*a*', self::ASN1_INTEGER, "\01\00", $rsaOID, 4, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey ); $RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey); if (!empty($this->password) || is_string($this->password)) { $salt = Random::string(8); $iterationCount = 2048; $crypto = new DES(); $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount); $RSAPrivateKey = $crypto->encrypt($RSAPrivateKey); $parameters = pack('Ca*a*Ca*N', self::ASN1_OCTETSTRING, $this->_encodeLength(strlen($salt)), $salt, self::ASN1_INTEGER, $this->_encodeLength(4), $iterationCount ); $pbeWithMD5AndDES_CBC = "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03"; $encryptionAlgorithm = pack('Ca*a*Ca*a*', self::ASN1_OBJECT, $this->_encodeLength(strlen($pbeWithMD5AndDES_CBC)), $pbeWithMD5AndDES_CBC, self::ASN1_SEQUENCE, $this->_encodeLength(strlen($parameters)), $parameters ); $RSAPrivateKey = pack('Ca*a*Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($encryptionAlgorithm)), $encryptionAlgorithm, self::ASN1_OCTETSTRING, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey ); $RSAPrivateKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey); $RSAPrivateKey = "-----BEGIN ENCRYPTED PRIVATE KEY-----\r\n" . chunk_split(base64_encode($RSAPrivateKey), 64) . '-----END ENCRYPTED PRIVATE KEY-----'; } else { $RSAPrivateKey = "-----BEGIN PRIVATE KEY-----\r\n" . chunk_split(base64_encode($RSAPrivateKey), 64) . '-----END PRIVATE KEY-----'; } return $RSAPrivateKey; } if (!empty($this->password) || is_string($this->password)) { $iv = Random::string(8); $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8); $des = new TripleDES(); $des->setKey($symkey); $des->setIV($iv); $iv = strtoupper(bin2hex($iv)); $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" . "Proc-Type: 4,ENCRYPTED\r\n" . "DEK-Info: DES-EDE3-CBC,$iv\r\n" . "\r\n" . chunk_split(base64_encode($des->encrypt($RSAPrivateKey)), 64) . '-----END RSA PRIVATE KEY-----'; } else { $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" . chunk_split(base64_encode($RSAPrivateKey), 64) . '-----END RSA PRIVATE KEY-----'; } return $RSAPrivateKey; } } /** * Convert a public key to the appropriate format * * @access private * @see setPublicKeyFormat() * @param String $RSAPrivateKey * @return String */ function _convertPublicKey($n, $e) { $signed = $this->publicKeyFormat != self::PUBLIC_FORMAT_XML; $modulus = $n->toBytes($signed); $publicExponent = $e->toBytes($signed); switch ($this->publicKeyFormat) { case self::PUBLIC_FORMAT_RAW: return array('e' => $e->copy(), 'n' => $n->copy()); case self::PUBLIC_FORMAT_XML: return "\r\n" . ' ' . base64_encode($modulus) . "\r\n" . ' ' . base64_encode($publicExponent) . "\r\n" . ''; break; case self::PUBLIC_FORMAT_OPENSSH: // from : // string "ssh-rsa" // mpint e // mpint n $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus); $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . $this->comment; return $RSAPublicKey; default: // eg. self::PUBLIC_FORMAT_PKCS1_RAW or self::PUBLIC_FORMAT_PKCS1 // from : // RSAPublicKey ::= SEQUENCE { // modulus INTEGER, -- n // publicExponent INTEGER -- e // } $components = array( 'modulus' => pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus), 'publicExponent' => pack('Ca*a*', self::ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent) ); $RSAPublicKey = pack('Ca*a*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])), $components['modulus'], $components['publicExponent'] ); if ($this->publicKeyFormat == self::PUBLIC_FORMAT_PKCS1_RAW) { $RSAPublicKey = "-----BEGIN RSA PUBLIC KEY-----\r\n" . chunk_split(base64_encode($RSAPublicKey), 64) . '-----END RSA PUBLIC KEY-----'; } else { // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption. $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA $RSAPublicKey = chr(0) . $RSAPublicKey; $RSAPublicKey = chr(3) . $this->_encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey; $RSAPublicKey = pack('Ca*a*', self::ASN1_SEQUENCE, $this->_encodeLength(strlen($rsaOID . $RSAPublicKey)), $rsaOID . $RSAPublicKey ); $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" . chunk_split(base64_encode($RSAPublicKey), 64) . '-----END PUBLIC KEY-----'; } return $RSAPublicKey; } } /** * Break a public or private key down into its constituant components * * @access private * @see _convertPublicKey() * @see _convertPrivateKey() * @param String $key * @param Integer $type * @return Array */ function _parseKey($key, $type) { if ($type != self::PUBLIC_FORMAT_RAW && !is_string($key)) { return false; } switch ($type) { case self::PUBLIC_FORMAT_RAW: if (!is_array($key)) { return false; } $components = array(); switch (true) { case isset($key['e']): $components['publicExponent'] = $key['e']->copy(); break; case isset($key['exponent']): $components['publicExponent'] = $key['exponent']->copy(); break; case isset($key['publicExponent']): $components['publicExponent'] = $key['publicExponent']->copy(); break; case isset($key[0]): $components['publicExponent'] = $key[0]->copy(); } switch (true) { case isset($key['n']): $components['modulus'] = $key['n']->copy(); break; case isset($key['modulo']): $components['modulus'] = $key['modulo']->copy(); break; case isset($key['modulus']): $components['modulus'] = $key['modulus']->copy(); break; case isset($key[1]): $components['modulus'] = $key[1]->copy(); } return isset($components['modulus']) && isset($components['publicExponent']) ? $components : false; case self::PRIVATE_FORMAT_PKCS1: case self::PRIVATE_FORMAT_PKCS8: case self::PUBLIC_FORMAT_PKCS1: /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is "outside the scope" of PKCS#1. PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to protect private keys, however, that's not what OpenSSL* does. OpenSSL protects private keys by adding two new "fields" to the key - DEK-Info and Proc-Type. These fields are discussed here: http://tools.ietf.org/html/rfc1421#section-4.6.1.1 http://tools.ietf.org/html/rfc1421#section-4.6.1.3 DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell. DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation function. As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's own implementation. ie. the implementation *is* the standard and any bugs that may exist in that implementation are part of the standard, as well. * OpenSSL is the de facto standard. It's utilized by OpenSSH and other projects */ if (preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)) { $iv = pack('H*', trim($matches[2])); $symkey = pack('H*', md5($this->password . substr($iv, 0, 8))); // symkey is short for symmetric key $symkey.= pack('H*', md5($symkey . $this->password . substr($iv, 0, 8))); // remove the Proc-Type / DEK-Info sections as they're no longer needed $key = preg_replace('#^(?:Proc-Type|DEK-Info): .*#m', '', $key); $ciphertext = $this->_extractBER($key); if ($ciphertext === false) { $ciphertext = $key; } switch ($matches[1]) { case 'AES-256-CBC': $crypto = new AES(); break; case 'AES-128-CBC': $symkey = substr($symkey, 0, 16); $crypto = new AES(); break; case 'DES-EDE3-CFB': $crypto = new TripleDES(Base::MODE_CFB); break; case 'DES-EDE3-CBC': $symkey = substr($symkey, 0, 24); $crypto = new TripleDES(); break; case 'DES-CBC': $crypto = new DES(); break; default: return false; } $crypto->setKey($symkey); $crypto->setIV($iv); $decoded = $crypto->decrypt($ciphertext); } else { $decoded = $this->_extractBER($key); } if ($decoded !== false) { $key = $decoded; } $components = array(); if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) { return false; } if ($this->_decodeLength($key) != strlen($key)) { return false; } $tag = ord($this->_string_shift($key)); /* intended for keys for which OpenSSL's asn1parse returns the following: 0:d=0 hl=4 l= 631 cons: SEQUENCE 4:d=1 hl=2 l= 1 prim: INTEGER :00 7:d=1 hl=2 l= 13 cons: SEQUENCE 9:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption 20:d=2 hl=2 l= 0 prim: NULL 22:d=1 hl=4 l= 609 prim: OCTET STRING ie. PKCS8 keys*/ if ($tag == self::ASN1_INTEGER && substr($key, 0, 3) == "\x01\x00\x30") { $this->_string_shift($key, 3); $tag = self::ASN1_SEQUENCE; } if ($tag == self::ASN1_SEQUENCE) { $temp = $this->_string_shift($key, $this->_decodeLength($key)); if (ord($this->_string_shift($temp)) != self::ASN1_OBJECT) { return false; } $length = $this->_decodeLength($temp); switch ($this->_string_shift($temp, $length)) { case "\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01": // rsaEncryption break; case "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03": // pbeWithMD5AndDES-CBC /* PBEParameter ::= SEQUENCE { salt OCTET STRING (SIZE(8)), iterationCount INTEGER } */ if (ord($this->_string_shift($temp)) != self::ASN1_SEQUENCE) { return false; } if ($this->_decodeLength($temp) != strlen($temp)) { return false; } $this->_string_shift($temp); // assume it's an octet string $salt = $this->_string_shift($temp, $this->_decodeLength($temp)); if (ord($this->_string_shift($temp)) != self::ASN1_INTEGER) { return false; } $this->_decodeLength($temp); list(, $iterationCount) = unpack('N', str_pad($temp, 4, chr(0), STR_PAD_LEFT)); $this->_string_shift($key); // assume it's an octet string $length = $this->_decodeLength($key); if (strlen($key) != $length) { return false; } $crypto = new DES(); $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount); $key = $crypto->decrypt($key); if ($key === false) { return false; } return $this->_parseKey($key, self::PRIVATE_FORMAT_PKCS1); default: return false; } /* intended for keys for which OpenSSL's asn1parse returns the following: 0:d=0 hl=4 l= 290 cons: SEQUENCE 4:d=1 hl=2 l= 13 cons: SEQUENCE 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption 17:d=2 hl=2 l= 0 prim: NULL 19:d=1 hl=4 l= 271 prim: BIT STRING */ $tag = ord($this->_string_shift($key)); // skip over the BIT STRING / OCTET STRING tag $this->_decodeLength($key); // skip over the BIT STRING / OCTET STRING length // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of // unused bits in the final subsequent octet. The number shall be in the range zero to seven." // -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2) if ($tag == self::ASN1_BITSTRING) { $this->_string_shift($key); } if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) { return false; } if ($this->_decodeLength($key) != strlen($key)) { return false; } $tag = ord($this->_string_shift($key)); } if ($tag != self::ASN1_INTEGER) { return false; } $length = $this->_decodeLength($key); $temp = $this->_string_shift($key, $length); if (strlen($temp) != 1 || ord($temp) > 2) { $components['modulus'] = new BigInteger($temp, 256); $this->_string_shift($key); // skip over self::ASN1_INTEGER $length = $this->_decodeLength($key); $components[$type == self::PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new BigInteger($this->_string_shift($key, $length), 256); return $components; } if (ord($this->_string_shift($key)) != self::ASN1_INTEGER) { return false; } $length = $this->_decodeLength($key); $components['modulus'] = new BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['publicExponent'] = new BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['privateExponent'] = new BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['primes'] = array(1 => new BigInteger($this->_string_shift($key, $length), 256)); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['primes'][] = new BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['exponents'] = array(1 => new BigInteger($this->_string_shift($key, $length), 256)); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['exponents'][] = new BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['coefficients'] = array(2 => new BigInteger($this->_string_shift($key, $length), 256)); if (!empty($key)) { if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) { return false; } $this->_decodeLength($key); while (!empty($key)) { if (ord($this->_string_shift($key)) != self::ASN1_SEQUENCE) { return false; } $this->_decodeLength($key); $key = substr($key, 1); $length = $this->_decodeLength($key); $components['primes'][] = new BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['exponents'][] = new BigInteger($this->_string_shift($key, $length), 256); $this->_string_shift($key); $length = $this->_decodeLength($key); $components['coefficients'][] = new BigInteger($this->_string_shift($key, $length), 256); } } return $components; case self::PUBLIC_FORMAT_OPENSSH: $parts = explode(' ', $key, 3); $key = isset($parts[1]) ? base64_decode($parts[1]) : false; if ($key === false) { return false; } $comment = isset($parts[2]) ? $parts[2] : false; $cleanup = substr($key, 0, 11) == "\0\0\0\7ssh-rsa"; if (strlen($key) <= 4) { return false; } extract(unpack('Nlength', $this->_string_shift($key, 4))); $publicExponent = new BigInteger($this->_string_shift($key, $length), -256); if (strlen($key) <= 4) { return false; } extract(unpack('Nlength', $this->_string_shift($key, 4))); $modulus = new BigInteger($this->_string_shift($key, $length), -256); if ($cleanup && strlen($key)) { if (strlen($key) <= 4) { return false; } extract(unpack('Nlength', $this->_string_shift($key, 4))); $realModulus = new BigInteger($this->_string_shift($key, $length), -256); return strlen($key) ? false : array( 'modulus' => $realModulus, 'publicExponent' => $modulus, 'comment' => $comment ); } else { return strlen($key) ? false : array( 'modulus' => $modulus, 'publicExponent' => $publicExponent, 'comment' => $comment ); } // http://www.w3.org/TR/xmldsig-core/#sec-RSAKeyValue // http://en.wikipedia.org/wiki/XML_Signature case self::PRIVATE_FORMAT_XML: case self::PUBLIC_FORMAT_XML: $this->components = array(); $xml = xml_parser_create('UTF-8'); xml_set_object($xml, $this); xml_set_element_handler($xml, '_start_element_handler', '_stop_element_handler'); xml_set_character_data_handler($xml, '_data_handler'); // add to account for "dangling" tags like ... that are sometimes added if (!xml_parse($xml, '' . $key . '')) { return false; } return isset($this->components['modulus']) && isset($this->components['publicExponent']) ? $this->components : false; // from PuTTY's SSHPUBK.C case self::PRIVATE_FORMAT_PUTTY: $components = array(); $key = preg_split('#\r\n|\r|\n#', $key); $type = trim(preg_replace('#PuTTY-User-Key-File-2: (.+)#', '$1', $key[0])); if ($type != 'ssh-rsa') { return false; } $encryption = trim(preg_replace('#Encryption: (.+)#', '$1', $key[1])); $comment = trim(preg_replace('#Comment: (.+)#', '$1', $key[2])); $publicLength = trim(preg_replace('#Public-Lines: (\d+)#', '$1', $key[3])); $public = base64_decode(implode('', array_map('trim', array_slice($key, 4, $publicLength)))); $public = substr($public, 11); extract(unpack('Nlength', $this->_string_shift($public, 4))); $components['publicExponent'] = new BigInteger($this->_string_shift($public, $length), -256); extract(unpack('Nlength', $this->_string_shift($public, 4))); $components['modulus'] = new BigInteger($this->_string_shift($public, $length), -256); $privateLength = trim(preg_replace('#Private-Lines: (\d+)#', '$1', $key[$publicLength + 4])); $private = base64_decode(implode('', array_map('trim', array_slice($key, $publicLength + 5, $privateLength)))); switch ($encryption) { case 'aes256-cbc': $symkey = ''; $sequence = 0; while (strlen($symkey) < 32) { $temp = pack('Na*', $sequence++, $this->password); $symkey.= pack('H*', sha1($temp)); } $symkey = substr($symkey, 0, 32); $crypto = new AES(); } if ($encryption != 'none') { $crypto->setKey($symkey); $crypto->disablePadding(); $private = $crypto->decrypt($private); if ($private === false) { return false; } } extract(unpack('Nlength', $this->_string_shift($private, 4))); if (strlen($private) < $length) { return false; } $components['privateExponent'] = new BigInteger($this->_string_shift($private, $length), -256); extract(unpack('Nlength', $this->_string_shift($private, 4))); if (strlen($private) < $length) { return false; } $components['primes'] = array(1 => new BigInteger($this->_string_shift($private, $length), -256)); extract(unpack('Nlength', $this->_string_shift($private, 4))); if (strlen($private) < $length) { return false; } $components['primes'][] = new BigInteger($this->_string_shift($private, $length), -256); $temp = $components['primes'][1]->subtract($this->one); $components['exponents'] = array(1 => $components['publicExponent']->modInverse($temp)); $temp = $components['primes'][2]->subtract($this->one); $components['exponents'][] = $components['publicExponent']->modInverse($temp); extract(unpack('Nlength', $this->_string_shift($private, 4))); if (strlen($private) < $length) { return false; } $components['coefficients'] = array(2 => new BigInteger($this->_string_shift($private, $length), -256)); return $components; } } /** * Returns the key size * * More specifically, this returns the size of the modulo in bits. * * @access public * @return Integer */ function getSize() { return !isset($this->modulus) ? 0 : strlen($this->modulus->toBits()); } /** * Start Element Handler * * Called by xml_set_element_handler() * * @access private * @param Resource $parser * @param String $name * @param Array $attribs */ function _start_element_handler($parser, $name, $attribs) { //$name = strtoupper($name); switch ($name) { case 'MODULUS': $this->current = &$this->components['modulus']; break; case 'EXPONENT': $this->current = &$this->components['publicExponent']; break; case 'P': $this->current = &$this->components['primes'][1]; break; case 'Q': $this->current = &$this->components['primes'][2]; break; case 'DP': $this->current = &$this->components['exponents'][1]; break; case 'DQ': $this->current = &$this->components['exponents'][2]; break; case 'INVERSEQ': $this->current = &$this->components['coefficients'][2]; break; case 'D': $this->current = &$this->components['privateExponent']; } $this->current = ''; } /** * Stop Element Handler * * Called by xml_set_element_handler() * * @access private * @param Resource $parser * @param String $name */ function _stop_element_handler($parser, $name) { if (isset($this->current)) { $this->current = new BigInteger(base64_decode($this->current), 256); unset($this->current); } } /** * Data Handler * * Called by xml_set_character_data_handler() * * @access private * @param Resource $parser * @param String $data */ function _data_handler($parser, $data) { if (!isset($this->current) || is_object($this->current)) { return; } $this->current.= trim($data); } /** * Loads a public or private key * * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed) * * @access public * @param String $key * @param Integer $type optional */ function loadKey($key, $type = false) { if ($key instanceof RSA) { $this->privateKeyFormat = $key->privateKeyFormat; $this->publicKeyFormat = $key->publicKeyFormat; $this->k = $key->k; $this->hLen = $key->hLen; $this->sLen = $key->sLen; $this->mgfHLen = $key->mgfHLen; $this->encryptionMode = $key->encryptionMode; $this->signatureMode = $key->signatureMode; $this->password = $key->password; $this->configFile = $key->configFile; $this->comment = $key->comment; if (is_object($key->hash)) { $this->hash = new Hash($key->hash->getHash()); } if (is_object($key->mgfHash)) { $this->mgfHash = new Hash($key->mgfHash->getHash()); } if (is_object($key->modulus)) { $this->modulus = $key->modulus->copy(); } if (is_object($key->exponent)) { $this->exponent = $key->exponent->copy(); } if (is_object($key->publicExponent)) { $this->publicExponent = $key->publicExponent->copy(); } $this->primes = array(); $this->exponents = array(); $this->coefficients = array(); foreach ($this->primes as $prime) { $this->primes[] = $prime->copy(); } foreach ($this->exponents as $exponent) { $this->exponents[] = $exponent->copy(); } foreach ($this->coefficients as $coefficient) { $this->coefficients[] = $coefficient->copy(); } return true; } if ($type === false) { $types = array( self::PUBLIC_FORMAT_RAW, self::PRIVATE_FORMAT_PKCS1, self::PRIVATE_FORMAT_XML, self::PRIVATE_FORMAT_PUTTY, self::PUBLIC_FORMAT_OPENSSH ); foreach ($types as $type) { $components = $this->_parseKey($key, $type); if ($components !== false) { break; } } } else { $components = $this->_parseKey($key, $type); } if ($components === false) { return false; } if (isset($components['comment']) && $components['comment'] !== false) { $this->comment = $components['comment']; } $this->modulus = $components['modulus']; $this->k = strlen($this->modulus->toBytes()); $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent']; if (isset($components['primes'])) { $this->primes = $components['primes']; $this->exponents = $components['exponents']; $this->coefficients = $components['coefficients']; $this->publicExponent = $components['publicExponent']; } else { $this->primes = array(); $this->exponents = array(); $this->coefficients = array(); $this->publicExponent = false; } switch ($type) { case self::PUBLIC_FORMAT_OPENSSH: case self::PUBLIC_FORMAT_RAW: $this->setPublicKey(); break; case self::PRIVATE_FORMAT_PKCS1: switch (true) { case strpos($key, '-BEGIN PUBLIC KEY-') !== false: case strpos($key, '-BEGIN RSA PUBLIC KEY-') !== false: $this->setPublicKey(); } } return true; } /** * Sets the password * * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false. * Or rather, pass in $password such that empty($password) && !is_string($password) is true. * * @see createKey() * @see loadKey() * @access public * @param String $password */ function setPassword($password = false) { $this->password = $password; } /** * Defines the public key * * Some private key formats define the public exponent and some don't. Those that don't define it are problematic when * used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a * message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys * and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public * exponent this won't work unless you manually add the public exponent. phpseclib tries to guess if the key being used * is the public key but in the event that it guesses incorrectly you might still want to explicitly set the key as being * public. * * Do note that when a new key is loaded the index will be cleared. * * Returns true on success, false on failure * * @see getPublicKey() * @access public * @param String $key optional * @param Integer $type optional * @return Boolean */ function setPublicKey($key = false, $type = false) { // if a public key has already been loaded return false if (!empty($this->publicExponent)) { return false; } if ($key === false && !empty($this->modulus)) { $this->publicExponent = $this->exponent; return true; } if ($type === false) { $types = array( self::PUBLIC_FORMAT_RAW, self::PUBLIC_FORMAT_PKCS1, self::PUBLIC_FORMAT_XML, self::PUBLIC_FORMAT_OPENSSH ); foreach ($types as $type) { $components = $this->_parseKey($key, $type); if ($components !== false) { break; } } } else { $components = $this->_parseKey($key, $type); } if ($components === false) { return false; } if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) { $this->modulus = $components['modulus']; $this->exponent = $this->publicExponent = $components['publicExponent']; return true; } $this->publicExponent = $components['publicExponent']; return true; } /** * Defines the private key * * If phpseclib guessed a private key was a public key and loaded it as such it might be desirable to force * phpseclib to treat the key as a private key. This function will do that. * * Do note that when a new key is loaded the index will be cleared. * * Returns true on success, false on failure * * @see getPublicKey() * @access public * @param String $key optional * @param Integer $type optional * @return Boolean */ function setPrivateKey($key = false, $type = false) { if ($key === false && !empty($this->publicExponent)) { unset($this->publicExponent); return true; } $rsa = new RSA(); if (!$rsa->loadKey($key, $type)) { return false; } unset($rsa->publicExponent); // don't overwrite the old key if the new key is invalid $this->loadKey($rsa); return true; } /** * Returns the public key * * The public key is only returned under two circumstances - if the private key had the public key embedded within it * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this * function won't return it since this library, for the most part, doesn't distinguish between public and private keys. * * @see getPublicKey() * @access public * @param String $key * @param Integer $type optional */ function getPublicKey($type = self::PUBLIC_FORMAT_PKCS8) { if (empty($this->modulus) || empty($this->publicExponent)) { return false; } $oldFormat = $this->publicKeyFormat; $this->publicKeyFormat = $type; $temp = $this->_convertPublicKey($this->modulus, $this->publicExponent); $this->publicKeyFormat = $oldFormat; return $temp; } /** * Returns the private key * * The private key is only returned if the currently loaded key contains the constituent prime numbers. * * @see getPublicKey() * @access public * @param String $key * @param Integer $type optional */ function getPrivateKey($type = self::PUBLIC_FORMAT_PKCS1) { if (empty($this->primes)) { return false; } $oldFormat = $this->privateKeyFormat; $this->privateKeyFormat = $type; $temp = $this->_convertPrivateKey($this->modulus, $this->publicExponent, $this->exponent, $this->primes, $this->exponents, $this->coefficients); $this->privateKeyFormat = $oldFormat; return $temp; } /** * Returns a minimalistic private key * * Returns the private key without the prime number constituants. Structurally identical to a public key that * hasn't been set as the public key * * @see getPrivateKey() * @access private * @param String $key * @param Integer $type optional */ function _getPrivatePublicKey($mode = self::PUBLIC_FORMAT_PKCS8) { if (empty($this->modulus) || empty($this->exponent)) { return false; } $oldFormat = $this->publicKeyFormat; $this->publicKeyFormat = $mode; $temp = $this->_convertPublicKey($this->modulus, $this->exponent); $this->publicKeyFormat = $oldFormat; return $temp; } /** * __toString() magic method * * @access public */ function __toString() { $key = $this->getPrivateKey($this->privateKeyFormat); if ($key !== false) { return $key; } $key = $this->_getPrivatePublicKey($this->publicKeyFormat); return $key !== false ? $key : ''; } /** * __clone() magic method * * @access public */ function __clone() { $key = new RSA(); $key->loadKey($this); return $key; } /** * Generates the smallest and largest numbers requiring $bits bits * * @access private * @param Integer $bits * @return Array */ function _generateMinMax($bits) { $bytes = $bits >> 3; $min = str_repeat(chr(0), $bytes); $max = str_repeat(chr(0xFF), $bytes); $msb = $bits & 7; if ($msb) { $min = chr(1 << ($msb - 1)) . $min; $max = chr((1 << $msb) - 1) . $max; } else { $min[0] = chr(0x80); } return array( 'min' => new BigInteger($min, 256), 'max' => new BigInteger($max, 256) ); } /** * DER-decode the length * * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information. * * @access private * @param String $string * @return Integer */ function _decodeLength(&$string) { $length = ord($this->_string_shift($string)); if ( $length & 0x80 ) { // definite length, long form $length&= 0x7F; $temp = $this->_string_shift($string, $length); list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4)); } return $length; } /** * DER-encode the length * * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information. * * @access private * @param Integer $length * @return String */ function _encodeLength($length) { if ($length <= 0x7F) { return chr($length); } $temp = ltrim(pack('N', $length), chr(0)); return pack('Ca*', 0x80 | strlen($temp), $temp); } /** * String Shift * * Inspired by array_shift * * @param String $string * @param optional Integer $index * @return String * @access private */ function _string_shift(&$string, $index = 1) { $substr = substr($string, 0, $index); $string = substr($string, $index); return $substr; } /** * Determines the private key format * * @see createKey() * @access public * @param Integer $format */ function setPrivateKeyFormat($format) { $this->privateKeyFormat = $format; } /** * Determines the public key format * * @see createKey() * @access public * @param Integer $format */ function setPublicKeyFormat($format) { $this->publicKeyFormat = $format; } /** * Determines which hashing function should be used * * Used with signature production / verification and (if the encryption mode is self::ENCRYPTION_OAEP) encryption and * decryption. If $hash isn't supported, sha1 is used. * * @access public * @param String $hash */ function setHash($hash) { // \phpseclib\Crypt\Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example. switch ($hash) { case 'md2': case 'md5': case 'sha1': case 'sha256': case 'sha384': case 'sha512': $this->hash = new Hash($hash); $this->hashName = $hash; break; default: $this->hash = new Hash('sha1'); $this->hashName = 'sha1'; } $this->hLen = $this->hash->getLength(); } /** * Determines which hashing function should be used for the mask generation function * * The mask generation function is used by self::ENCRYPTION_OAEP and self::SIGNATURE_PSS and although it's * best if Hash and MGFHash are set to the same thing this is not a requirement. * * @access public * @param String $hash */ function setMGFHash($hash) { // \phpseclib\Crypt\Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example. switch ($hash) { case 'md2': case 'md5': case 'sha1': case 'sha256': case 'sha384': case 'sha512': $this->mgfHash = new Hash($hash); break; default: $this->mgfHash = new Hash('sha1'); } $this->mgfHLen = $this->mgfHash->getLength(); } /** * Determines the salt length * * To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}: * * Typical salt lengths in octets are hLen (the length of the output * of the hash function Hash) and 0. * * @access public * @param Integer $format */ function setSaltLength($sLen) { $this->sLen = $sLen; } /** * Integer-to-Octet-String primitive * * See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}. * * @access private * @param \phpseclib\Math\BigInteger $x * @param Integer $xLen * @return String */ function _i2osp($x, $xLen) { $x = $x->toBytes(); if (strlen($x) > $xLen) { user_error('Integer too large'); return false; } return str_pad($x, $xLen, chr(0), STR_PAD_LEFT); } /** * Octet-String-to-Integer primitive * * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}. * * @access private * @param String $x * @return \phpseclib\Math\BigInteger */ function _os2ip($x) { return new BigInteger($x, 256); } /** * Exponentiate with or without Chinese Remainder Theorem * * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}. * * @access private * @param \phpseclib\Math\BigInteger $x * @return \phpseclib\Math\BigInteger */ function _exponentiate($x) { if (empty($this->primes) || empty($this->coefficients) || empty($this->exponents)) { return $x->modPow($this->exponent, $this->modulus); } $num_primes = count($this->primes); if (defined('CRYPT_RSA_DISABLE_BLINDING')) { $m_i = array( 1 => $x->modPow($this->exponents[1], $this->primes[1]), 2 => $x->modPow($this->exponents[2], $this->primes[2]) ); $h = $m_i[1]->subtract($m_i[2]); $h = $h->multiply($this->coefficients[2]); list(, $h) = $h->divide($this->primes[1]); $m = $m_i[2]->add($h->multiply($this->primes[2])); $r = $this->primes[1]; for ($i = 3; $i <= $num_primes; $i++) { $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]); $r = $r->multiply($this->primes[$i - 1]); $h = $m_i->subtract($m); $h = $h->multiply($this->coefficients[$i]); list(, $h) = $h->divide($this->primes[$i]); $m = $m->add($r->multiply($h)); } } else { $smallest = $this->primes[1]; for ($i = 2; $i <= $num_primes; $i++) { if ($smallest->compare($this->primes[$i]) > 0) { $smallest = $this->primes[$i]; } } $one = new BigInteger(1); $r = $one->random($one, $smallest->subtract($one)); $m_i = array( 1 => $this->_blind($x, $r, 1), 2 => $this->_blind($x, $r, 2) ); $h = $m_i[1]->subtract($m_i[2]); $h = $h->multiply($this->coefficients[2]); list(, $h) = $h->divide($this->primes[1]); $m = $m_i[2]->add($h->multiply($this->primes[2])); $r = $this->primes[1]; for ($i = 3; $i <= $num_primes; $i++) { $m_i = $this->_blind($x, $r, $i); $r = $r->multiply($this->primes[$i - 1]); $h = $m_i->subtract($m); $h = $h->multiply($this->coefficients[$i]); list(, $h) = $h->divide($this->primes[$i]); $m = $m->add($r->multiply($h)); } } return $m; } /** * Performs RSA Blinding * * Protects against timing attacks by employing RSA Blinding. * Returns $x->modPow($this->exponents[$i], $this->primes[$i]) * * @access private * @param \phpseclib\Math\BigInteger $x * @param \phpseclib\Math\BigInteger $r * @param Integer $i * @return \phpseclib\Math\BigInteger */ function _blind($x, $r, $i) { $x = $x->multiply($r->modPow($this->publicExponent, $this->primes[$i])); $x = $x->modPow($this->exponents[$i], $this->primes[$i]); $r = $r->modInverse($this->primes[$i]); $x = $x->multiply($r); list(, $x) = $x->divide($this->primes[$i]); return $x; } /** * Performs blinded RSA equality testing * * Protects against a particular type of timing attack described. * * See {@link http://codahale.com/a-lesson-in-timing-attacks/ A Lesson In Timing Attacks (or, Don't use MessageDigest.isEquals)} * * Thanks for the heads up singpolyma! * * @access private * @param String $x * @param String $y * @return Boolean */ function _equals($x, $y) { if (strlen($x) != strlen($y)) { return false; } $result = 0; for ($i = 0; $i < strlen($x); $i++) { $result |= ord($x[$i]) ^ ord($y[$i]); } return $result == 0; } /** * RSAEP * * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}. * * @access private * @param \phpseclib\Math\BigInteger $m * @return \phpseclib\Math\BigInteger */ function _rsaep($m) { if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) { user_error('Message representative out of range'); return false; } return $this->_exponentiate($m); } /** * RSADP * * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}. * * @access private * @param \phpseclib\Math\BigInteger $c * @return \phpseclib\Math\BigInteger */ function _rsadp($c) { if ($c->compare($this->zero) < 0 || $c->compare($this->modulus) > 0) { user_error('Ciphertext representative out of range'); return false; } return $this->_exponentiate($c); } /** * RSASP1 * * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}. * * @access private * @param \phpseclib\Math\BigInteger $m * @return \phpseclib\Math\BigInteger */ function _rsasp1($m) { if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) { user_error('Message representative out of range'); return false; } return $this->_exponentiate($m); } /** * RSAVP1 * * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}. * * @access private * @param \phpseclib\Math\BigInteger $s * @return \phpseclib\Math\BigInteger */ function _rsavp1($s) { if ($s->compare($this->zero) < 0 || $s->compare($this->modulus) > 0) { user_error('Signature representative out of range'); return false; } return $this->_exponentiate($s); } /** * MGF1 * * See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}. * * @access private * @param String $mgfSeed * @param Integer $mgfLen * @return String */ function _mgf1($mgfSeed, $maskLen) { // if $maskLen would yield strings larger than 4GB, PKCS#1 suggests a "Mask too long" error be output. $t = ''; $count = ceil($maskLen / $this->mgfHLen); for ($i = 0; $i < $count; $i++) { $c = pack('N', $i); $t.= $this->mgfHash->hash($mgfSeed . $c); } return substr($t, 0, $maskLen); } /** * RSAES-OAEP-ENCRYPT * * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.1 RFC3447#section-7.1.1} and * {http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding OAES}. * * @access private * @param String $m * @param String $l * @return String */ function _rsaes_oaep_encrypt($m, $l = '') { $mLen = strlen($m); // Length checking // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error // be output. if ($mLen > $this->k - 2 * $this->hLen - 2) { user_error('Message too long'); return false; } // EME-OAEP encoding $lHash = $this->hash->hash($l); $ps = str_repeat(chr(0), $this->k - $mLen - 2 * $this->hLen - 2); $db = $lHash . $ps . chr(1) . $m; $seed = Random::string($this->hLen); $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1); $maskedDB = $db ^ $dbMask; $seedMask = $this->_mgf1($maskedDB, $this->hLen); $maskedSeed = $seed ^ $seedMask; $em = chr(0) . $maskedSeed . $maskedDB; // RSA encryption $m = $this->_os2ip($em); $c = $this->_rsaep($m); $c = $this->_i2osp($c, $this->k); // Output the ciphertext C return $c; } /** * RSAES-OAEP-DECRYPT * * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.2 RFC3447#section-7.1.2}. The fact that the error * messages aren't distinguishable from one another hinders debugging, but, to quote from RFC3447#section-7.1.2: * * Note. Care must be taken to ensure that an opponent cannot * distinguish the different error conditions in Step 3.g, whether by * error message or timing, or, more generally, learn partial * information about the encoded message EM. Otherwise an opponent may * be able to obtain useful information about the decryption of the * ciphertext C, leading to a chosen-ciphertext attack such as the one * observed by Manger [36]. * * As for $l... to quote from {@link http://tools.ietf.org/html/rfc3447#page-17 RFC3447#page-17}: * * Both the encryption and the decryption operations of RSAES-OAEP take * the value of a label L as input. In this version of PKCS #1, L is * the empty string; other uses of the label are outside the scope of * this document. * * @access private * @param String $c * @param String $l * @return String */ function _rsaes_oaep_decrypt($c, $l = '') { // Length checking // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error // be output. if (strlen($c) != $this->k || $this->k < 2 * $this->hLen + 2) { user_error('Decryption error'); return false; } // RSA decryption $c = $this->_os2ip($c); $m = $this->_rsadp($c); if ($m === false) { user_error('Decryption error'); return false; } $em = $this->_i2osp($m, $this->k); // EME-OAEP decoding $lHash = $this->hash->hash($l); $y = ord($em[0]); $maskedSeed = substr($em, 1, $this->hLen); $maskedDB = substr($em, $this->hLen + 1); $seedMask = $this->_mgf1($maskedDB, $this->hLen); $seed = $maskedSeed ^ $seedMask; $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1); $db = $maskedDB ^ $dbMask; $lHash2 = substr($db, 0, $this->hLen); $m = substr($db, $this->hLen); if ($lHash != $lHash2) { user_error('Decryption error'); return false; } $m = ltrim($m, chr(0)); if (ord($m[0]) != 1) { user_error('Decryption error'); return false; } // Output the message M return substr($m, 1); } /** * RSAES-PKCS1-V1_5-ENCRYPT * * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}. * * @access private * @param String $m * @return String */ function _rsaes_pkcs1_v1_5_encrypt($m) { $mLen = strlen($m); // Length checking if ($mLen > $this->k - 11) { user_error('Message too long'); return false; } // EME-PKCS1-v1_5 encoding $psLen = $this->k - $mLen - 3; $ps = ''; while (strlen($ps) != $psLen) { $temp = Random::string($psLen - strlen($ps)); $temp = str_replace("\x00", '', $temp); $ps.= $temp; } $type = 2; // see the comments of _rsaes_pkcs1_v1_5_decrypt() to understand why this is being done if (defined('CRYPT_RSA_PKCS15_COMPAT') && (!isset($this->publicExponent) || $this->exponent !== $this->publicExponent)) { $type = 1; // "The padding string PS shall consist of k-3-||D|| octets. ... for block type 01, they shall have value FF" $ps = str_repeat("\xFF", $psLen); } $em = chr(0) . chr($type) . $ps . chr(0) . $m; // RSA encryption $m = $this->_os2ip($em); $c = $this->_rsaep($m); $c = $this->_i2osp($c, $this->k); // Output the ciphertext C return $c; } /** * RSAES-PKCS1-V1_5-DECRYPT * * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.2 RFC3447#section-7.2.2}. * * For compatibility purposes, this function departs slightly from the description given in RFC3447. * The reason being that RFC2313#section-8.1 (PKCS#1 v1.5) states that ciphertext's encrypted by the * private key should have the second byte set to either 0 or 1 and that ciphertext's encrypted by the * public key should have the second byte set to 2. In RFC3447 (PKCS#1 v2.1), the second byte is supposed * to be 2 regardless of which key is used. For compatibility purposes, we'll just check to make sure the * second byte is 2 or less. If it is, we'll accept the decrypted string as valid. * * As a consequence of this, a private key encrypted ciphertext produced with \phpseclib\Crypt\RSA may not decrypt * with a strictly PKCS#1 v1.5 compliant RSA implementation. Public key encrypted ciphertext's should but * not private key encrypted ciphertext's. * * @access private * @param String $c * @return String */ function _rsaes_pkcs1_v1_5_decrypt($c) { // Length checking if (strlen($c) != $this->k) { // or if k < 11 user_error('Decryption error'); return false; } // RSA decryption $c = $this->_os2ip($c); $m = $this->_rsadp($c); if ($m === false) { user_error('Decryption error'); return false; } $em = $this->_i2osp($m, $this->k); // EME-PKCS1-v1_5 decoding if (ord($em[0]) != 0 || ord($em[1]) > 2) { user_error('Decryption error'); return false; } $ps = substr($em, 2, strpos($em, chr(0), 2) - 2); $m = substr($em, strlen($ps) + 3); if (strlen($ps) < 8) { user_error('Decryption error'); return false; } // Output M return $m; } /** * EMSA-PSS-ENCODE * * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}. * * @access private * @param String $m * @param Integer $emBits */ function _emsa_pss_encode($m, $emBits) { // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error // be output. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8) $sLen = $this->sLen == false ? $this->hLen : $this->sLen; $mHash = $this->hash->hash($m); if ($emLen < $this->hLen + $sLen + 2) { user_error('Encoding error'); return false; } $salt = Random::string($sLen); $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt; $h = $this->hash->hash($m2); $ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2); $db = $ps . chr(1) . $salt; $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1); $maskedDB = $db ^ $dbMask; $maskedDB[0] = ~chr(0xFF << ($emBits & 7)) & $maskedDB[0]; $em = $maskedDB . $h . chr(0xBC); return $em; } /** * EMSA-PSS-VERIFY * * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.2 RFC3447#section-9.1.2}. * * @access private * @param String $m * @param String $em * @param Integer $emBits * @return String */ function _emsa_pss_verify($m, $em, $emBits) { // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error // be output. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8); $sLen = $this->sLen == false ? $this->hLen : $this->sLen; $mHash = $this->hash->hash($m); if ($emLen < $this->hLen + $sLen + 2) { return false; } if ($em[strlen($em) - 1] != chr(0xBC)) { return false; } $maskedDB = substr($em, 0, -$this->hLen - 1); $h = substr($em, -$this->hLen - 1, $this->hLen); $temp = chr(0xFF << ($emBits & 7)); if ((~$maskedDB[0] & $temp) != $temp) { return false; } $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1); $db = $maskedDB ^ $dbMask; $db[0] = ~chr(0xFF << ($emBits & 7)) & $db[0]; $temp = $emLen - $this->hLen - $sLen - 2; if (substr($db, 0, $temp) != str_repeat(chr(0), $temp) || ord($db[$temp]) != 1) { return false; } $salt = substr($db, $temp + 1); // should be $sLen long $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt; $h2 = $this->hash->hash($m2); return $this->_equals($h, $h2); } /** * RSASSA-PSS-SIGN * * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.1 RFC3447#section-8.1.1}. * * @access private * @param String $m * @return String */ function _rsassa_pss_sign($m) { // EMSA-PSS encoding $em = $this->_emsa_pss_encode($m, 8 * $this->k - 1); // RSA signature $m = $this->_os2ip($em); $s = $this->_rsasp1($m); $s = $this->_i2osp($s, $this->k); // Output the signature S return $s; } /** * RSASSA-PSS-VERIFY * * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.2 RFC3447#section-8.1.2}. * * @access private * @param String $m * @param String $s * @return String */ function _rsassa_pss_verify($m, $s) { // Length checking if (strlen($s) != $this->k) { user_error('Invalid signature'); return false; } // RSA verification $modBits = 8 * $this->k; $s2 = $this->_os2ip($s); $m2 = $this->_rsavp1($s2); if ($m2 === false) { user_error('Invalid signature'); return false; } $em = $this->_i2osp($m2, $modBits >> 3); if ($em === false) { user_error('Invalid signature'); return false; } // EMSA-PSS verification return $this->_emsa_pss_verify($m, $em, $modBits - 1); } /** * EMSA-PKCS1-V1_5-ENCODE * * See {@link http://tools.ietf.org/html/rfc3447#section-9.2 RFC3447#section-9.2}. * * @access private * @param String $m * @param Integer $emLen * @return String */ function _emsa_pkcs1_v1_5_encode($m, $emLen) { $h = $this->hash->hash($m); if ($h === false) { return false; } // see http://tools.ietf.org/html/rfc3447#page-43 switch ($this->hashName) { case 'md2': $t = pack('H*', '3020300c06082a864886f70d020205000410'); break; case 'md5': $t = pack('H*', '3020300c06082a864886f70d020505000410'); break; case 'sha1': $t = pack('H*', '3021300906052b0e03021a05000414'); break; case 'sha256': $t = pack('H*', '3031300d060960864801650304020105000420'); break; case 'sha384': $t = pack('H*', '3041300d060960864801650304020205000430'); break; case 'sha512': $t = pack('H*', '3051300d060960864801650304020305000440'); } $t.= $h; $tLen = strlen($t); if ($emLen < $tLen + 11) { user_error('Intended encoded message length too short'); return false; } $ps = str_repeat(chr(0xFF), $emLen - $tLen - 3); $em = "\0\1$ps\0$t"; return $em; } /** * RSASSA-PKCS1-V1_5-SIGN * * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.1 RFC3447#section-8.2.1}. * * @access private * @param String $m * @return String */ function _rsassa_pkcs1_v1_5_sign($m) { // EMSA-PKCS1-v1_5 encoding $em = $this->_emsa_pkcs1_v1_5_encode($m, $this->k); if ($em === false) { user_error('RSA modulus too short'); return false; } // RSA signature $m = $this->_os2ip($em); $s = $this->_rsasp1($m); $s = $this->_i2osp($s, $this->k); // Output the signature S return $s; } /** * RSASSA-PKCS1-V1_5-VERIFY * * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.2 RFC3447#section-8.2.2}. * * @access private * @param String $m * @return String */ function _rsassa_pkcs1_v1_5_verify($m, $s) { // Length checking if (strlen($s) != $this->k) { user_error('Invalid signature'); return false; } // RSA verification $s = $this->_os2ip($s); $m2 = $this->_rsavp1($s); if ($m2 === false) { user_error('Invalid signature'); return false; } $em = $this->_i2osp($m2, $this->k); if ($em === false) { user_error('Invalid signature'); return false; } // EMSA-PKCS1-v1_5 encoding $em2 = $this->_emsa_pkcs1_v1_5_encode($m, $this->k); if ($em2 === false) { user_error('RSA modulus too short'); return false; } // Compare return $this->_equals($em, $em2); } /** * Set Encryption Mode * * Valid values include self::ENCRYPTION_OAEP and self::ENCRYPTION_PKCS1. * * @access public * @param Integer $mode */ function setEncryptionMode($mode) { $this->encryptionMode = $mode; } /** * Set Signature Mode * * Valid values include self::SIGNATURE_PSS and self::SIGNATURE_PKCS1 * * @access public * @param Integer $mode */ function setSignatureMode($mode) { $this->signatureMode = $mode; } /** * Set public key comment. * * @access public * @param String $comment */ function setComment($comment) { $this->comment = $comment; } /** * Get public key comment. * * @access public * @return String */ function getComment() { return $this->comment; } /** * Encryption * * Both self::ENCRYPTION_OAEP and self::ENCRYPTION_PKCS1 both place limits on how long $plaintext can be. * If $plaintext exceeds those limits it will be broken up so that it does and the resultant ciphertext's will * be concatenated together. * * @see decrypt() * @access public * @param String $plaintext * @return String */ function encrypt($plaintext) { switch ($this->encryptionMode) { case self::ENCRYPTION_PKCS1: $length = $this->k - 11; if ($length <= 0) { return false; } $plaintext = str_split($plaintext, $length); $ciphertext = ''; foreach ($plaintext as $m) { $ciphertext.= $this->_rsaes_pkcs1_v1_5_encrypt($m); } return $ciphertext; //case self::ENCRYPTION_OAEP: default: $length = $this->k - 2 * $this->hLen - 2; if ($length <= 0) { return false; } $plaintext = str_split($plaintext, $length); $ciphertext = ''; foreach ($plaintext as $m) { $ciphertext.= $this->_rsaes_oaep_encrypt($m); } return $ciphertext; } } /** * Decryption * * @see encrypt() * @access public * @param String $plaintext * @return String */ function decrypt($ciphertext) { if ($this->k <= 0) { return false; } $ciphertext = str_split($ciphertext, $this->k); $ciphertext[count($ciphertext) - 1] = str_pad($ciphertext[count($ciphertext) - 1], $this->k, chr(0), STR_PAD_LEFT); $plaintext = ''; switch ($this->encryptionMode) { case self::ENCRYPTION_PKCS1: $decrypt = '_rsaes_pkcs1_v1_5_decrypt'; break; //case self::ENCRYPTION_OAEP: default: $decrypt = '_rsaes_oaep_decrypt'; } foreach ($ciphertext as $c) { $temp = $this->$decrypt($c); if ($temp === false) { return false; } $plaintext.= $temp; } return $plaintext; } /** * Create a signature * * @see verify() * @access public * @param String $message * @return String */ function sign($message) { if (empty($this->modulus) || empty($this->exponent)) { return false; } switch ($this->signatureMode) { case self::SIGNATURE_PKCS1: return $this->_rsassa_pkcs1_v1_5_sign($message); //case self::SIGNATURE_PSS: default: return $this->_rsassa_pss_sign($message); } } /** * Verifies a signature * * @see sign() * @access public * @param String $message * @param String $signature * @return Boolean */ function verify($message, $signature) { if (empty($this->modulus) || empty($this->exponent)) { return false; } switch ($this->signatureMode) { case self::SIGNATURE_PKCS1: return $this->_rsassa_pkcs1_v1_5_verify($message, $signature); //case self::SIGNATURE_PSS: default: return $this->_rsassa_pss_verify($message, $signature); } } /** * Extract raw BER from Base64 encoding * * @access private * @param String $str * @return String */ function _extractBER($str) { /* X.509 certs are assumed to be base64 encoded but sometimes they'll have additional things in them * above and beyond the ceritificate. * ie. some may have the following preceding the -----BEGIN CERTIFICATE----- line: * * Bag Attributes * localKeyID: 01 00 00 00 * subject=/O=organization/OU=org unit/CN=common name * issuer=/O=organization/CN=common name */ $temp = preg_replace('#.*?^-+[^-]+-+#ms', '', $str, 1); // remove the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- stuff $temp = preg_replace('#-+[^-]+-+#', '', $temp); // remove new lines $temp = str_replace(array("\r", "\n", ' '), '', $temp); $temp = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $temp) ? base64_decode($temp) : false; return $temp != false ? $temp : $str; } } * setKey('abcdefghijklmnopqrstuvwx'); * * $size = 10 * 1024; * $plaintext = ''; * for ($i = 0; $i < $size; $i++) { * $plaintext.= 'a'; * } * * echo $des->decrypt($des->encrypt($plaintext)); * ?> * * * @category Crypt * @package TripleDES * @author Jim Wigginton * @copyright 2007 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\Crypt; use phpseclib\Crypt\Base; use phpseclib\Crypt\DES; /** * Pure-PHP implementation of Triple DES. * * @package TripleDES * @author Jim Wigginton * @access public */ class TripleDES extends DES { /** * Encrypt / decrypt using inner chaining * * Inner chaining is used by SSH-1 and is generally considered to be less secure then outer chaining (self::MODE_CBC3). */ const MODE_3CBC = -2; /** * Encrypt / decrypt using outer chaining * * Outer chaining is used by SSH-2 and when the mode is set to \phpseclib\Crypt\Base::MODE_CBC. */ const MODE_CBC3 = Base::MODE_CBC; /** * The default password key_size used by setPassword() * * @see \phpseclib\Crypt\DES::password_key_size * @see \phpseclib\Crypt\Base::password_key_size * @see \phpseclib\Crypt\Base::setPassword() * @var Integer * @access private */ var $password_key_size = 24; /** * The default salt used by setPassword() * * @see \phpseclib\Crypt\Base::password_default_salt * @see \phpseclib\Crypt\Base::setPassword() * @var String * @access private */ var $password_default_salt = 'phpseclib'; /** * The namespace used by the cipher for its constants. * * @see \phpseclib\Crypt\DES::const_namespace * @see \phpseclib\Crypt\Base::const_namespace * @var String * @access private */ var $const_namespace = 'DES'; /** * The mcrypt specific name of the cipher * * @see \phpseclib\Crypt\DES::cipher_name_mcrypt * @see \phpseclib\Crypt\Base::cipher_name_mcrypt * @var String * @access private */ var $cipher_name_mcrypt = 'tripledes'; /** * Optimizing value while CFB-encrypting * * @see \phpseclib\Crypt\Base::cfb_init_len * @var Integer * @access private */ var $cfb_init_len = 750; /** * max possible size of $key * * @see \phpseclib\Crypt\TripleDES::setKey() * @see \phpseclib\Crypt\DES::setKey() * @var String * @access private */ var $key_size_max = 24; /** * Internal flag whether using self::MODE_3CBC or not * * @var Boolean * @access private */ var $mode_3cbc; /** * The \phpseclib\Crypt\DES objects * * Used only if $mode_3cbc === true * * @var Array * @access private */ var $des; /** * Default Constructor. * * Determines whether or not the mcrypt extension should be used. * * $mode could be: * * - \phpseclib\Crypt\Base::MODE_ECB * * - \phpseclib\Crypt\Base::MODE_CBC * * - \phpseclib\Crypt\Base::MODE_CTR * * - \phpseclib\Crypt\Base::MODE_CFB * * - \phpseclib\Crypt\Base::MODE_OFB * * - \phpseclib\Crypt\TripleDES::MODE_3CBC * * If not explicitly set, \phpseclib\Crypt\Base::MODE_CBC will be used. * * @see \phpseclib\Crypt\DES::__construct() * @see \phpseclib\Crypt\Base::__construct() * @param optional Integer $mode * @access public */ function __construct($mode = Base::MODE_CBC) { switch ($mode) { // In case of self::MODE_3CBC, we init as CRYPT_DES_MODE_CBC // and additional flag us internally as 3CBC case self::MODE_3CBC: parent::__construct(Base::MODE_CBC); $this->mode_3cbc = true; // This three $des'es will do the 3CBC work (if $key > 64bits) $this->des = array( new DES(Base::MODE_CBC), new DES(Base::MODE_CBC), new DES(Base::MODE_CBC), ); // we're going to be doing the padding, ourselves, so disable it in the \phpseclib\Crypt\DES objects $this->des[0]->disablePadding(); $this->des[1]->disablePadding(); $this->des[2]->disablePadding(); break; // If not 3CBC, we init as usual default: parent::__construct($mode); } } /** * Sets the initialization vector. (optional) * * SetIV is not required when \phpseclib\Crypt\Base::MODE_ECB is being used. If not explicitly set, it'll be assumed * to be all zero's. * * @see \phpseclib\Crypt\Base::setIV() * @access public * @param String $iv */ function setIV($iv) { parent::setIV($iv); if ($this->mode_3cbc) { $this->des[0]->setIV($iv); $this->des[1]->setIV($iv); $this->des[2]->setIV($iv); } } /** * Sets the key. * * Keys can be of any length. Triple DES, itself, can use 128-bit (eg. strlen($key) == 16) or * 192-bit (eg. strlen($key) == 24) keys. This function pads and truncates $key as appropriate. * * DES also requires that every eighth bit be a parity bit, however, we'll ignore that. * * If the key is not explicitly set, it'll be assumed to be all null bytes. * * @access public * @see \phpseclib\Crypt\DES::setKey() * @see \phpseclib\Crypt\Base::setKey() * @param String $key */ function setKey($key) { $length = strlen($key); if ($length > 8) { $key = str_pad(substr($key, 0, 24), 24, chr(0)); // if $key is between 64 and 128-bits, use the first 64-bits as the last, per this: // http://php.net/function.mcrypt-encrypt#47973 //$key = $length <= 16 ? substr_replace($key, substr($key, 0, 8), 16) : substr($key, 0, 24); } else { $key = str_pad($key, 8, chr(0)); } parent::setKey($key); // And in case of self::MODE_3CBC: // if key <= 64bits we not need the 3 $des to work, // because we will then act as regular DES-CBC with just a <= 64bit key. // So only if the key > 64bits (> 8 bytes) we will call setKey() for the 3 $des. if ($this->mode_3cbc && $length > 8) { $this->des[0]->setKey(substr($key, 0, 8)); $this->des[1]->setKey(substr($key, 8, 8)); $this->des[2]->setKey(substr($key, 16, 8)); } } /** * Encrypts a message. * * @see \phpseclib\Crypt\Base::encrypt() * @access public * @param String $plaintext * @return String $cipertext */ function encrypt($plaintext) { // parent::en/decrypt() is able to do all the work for all modes and keylengths, // except for: self::MODE_3CBC (inner chaining CBC) with a key > 64bits // if the key is smaller then 8, do what we'd normally do if ($this->mode_3cbc && strlen($this->key) > 8) { return $this->des[2]->encrypt( $this->des[1]->decrypt( $this->des[0]->encrypt( $this->_pad($plaintext) ) ) ); } return parent::encrypt($plaintext); } /** * Decrypts a message. * * @see \phpseclib\Crypt\Base::decrypt() * @access public * @param String $ciphertext * @return String $plaintext */ function decrypt($ciphertext) { if ($this->mode_3cbc && strlen($this->key) > 8) { return $this->_unpad( $this->des[0]->decrypt( $this->des[1]->encrypt( $this->des[2]->decrypt( str_pad($ciphertext, (strlen($ciphertext) + 7) & 0xFFFFFFF8, "\0") ) ) ) ); } return parent::decrypt($ciphertext); } /** * Treat consecutive "packets" as if they are a continuous buffer. * * Say you have a 16-byte plaintext $plaintext. Using the default behavior, the two following code snippets * will yield different outputs: * * * echo $des->encrypt(substr($plaintext, 0, 8)); * echo $des->encrypt(substr($plaintext, 8, 8)); * * * echo $des->encrypt($plaintext); * * * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates * another, as demonstrated with the following: * * * $des->encrypt(substr($plaintext, 0, 8)); * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8))); * * * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8))); * * * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different * outputs. The reason is due to the fact that the initialization vector's change after every encryption / * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant. * * Put another way, when the continuous buffer is enabled, the state of the \phpseclib\Crypt\DES() object changes after each * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them), * however, they are also less intuitive and more likely to cause you problems. * * @see \phpseclib\Crypt\Base::enableContinuousBuffer() * @see \phpseclib\Crypt\TripleDES::disableContinuousBuffer() * @access public */ function enableContinuousBuffer() { parent::enableContinuousBuffer(); if ($this->mode_3cbc) { $this->des[0]->enableContinuousBuffer(); $this->des[1]->enableContinuousBuffer(); $this->des[2]->enableContinuousBuffer(); } } /** * Treat consecutive packets as if they are a discontinuous buffer. * * The default behavior. * * @see \phpseclib\Crypt\Base::disableContinuousBuffer() * @see \phpseclib\Crypt\TripleDES::enableContinuousBuffer() * @access public */ function disableContinuousBuffer() { parent::disableContinuousBuffer(); if ($this->mode_3cbc) { $this->des[0]->disableContinuousBuffer(); $this->des[1]->disableContinuousBuffer(); $this->des[2]->disableContinuousBuffer(); } } /** * Creates the key schedule * * @see \phpseclib\Crypt\DES::_setupKey() * @see \phpseclib\Crypt\Base::_setupKey() * @access private */ function _setupKey() { switch (true) { // if $key <= 64bits we configure our internal pure-php cipher engine // to act as regular [1]DES, not as 3DES. mcrypt.so::tripledes does the same. case strlen($this->key) <= 8: $this->des_rounds = 1; break; // otherwise, if $key > 64bits, we configure our engine to work as 3DES. default: $this->des_rounds = 3; // (only) if 3CBC is used we have, of course, to setup the $des[0-2] keys also separately. if ($this->mode_3cbc) { $this->des[0]->_setupKey(); $this->des[1]->_setupKey(); $this->des[2]->_setupKey(); // because $des[0-2] will, now, do all the work we can return here // not need unnecessary stress parent::_setupKey() with our, now unused, $key. return; } } // setup our key parent::_setupKey(); } } * setKey('12345678901234567890123456789012'); * * $plaintext = str_repeat('a', 1024); * * echo $twofish->decrypt($twofish->encrypt($plaintext)); * ?> * * * @category Crypt * @package Twofish * @author Jim Wigginton * @author Hans-Juergen Petrich * @copyright 2007 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\Crypt; use phpseclib\Crypt\Base; /** * Pure-PHP implementation of Twofish. * * @package Twofish * @author Jim Wigginton * @author Hans-Juergen Petrich * @access public */ class Twofish extends Base { /** * The namespace used by the cipher for its constants. * * @see \phpseclib\Crypt\Base::const_namespace * @var String * @access private */ var $const_namespace = 'TWOFISH'; /** * The mcrypt specific name of the cipher * * @see \phpseclib\Crypt\Base::cipher_name_mcrypt * @var String * @access private */ var $cipher_name_mcrypt = 'twofish'; /** * Optimizing value while CFB-encrypting * * @see \phpseclib\Crypt\Base::cfb_init_len * @var Integer * @access private */ var $cfb_init_len = 800; /** * Q-Table * * @var Array * @access private */ var $q0 = array ( 0xA9, 0x67, 0xB3, 0xE8, 0x04, 0xFD, 0xA3, 0x76, 0x9A, 0x92, 0x80, 0x78, 0xE4, 0xDD, 0xD1, 0x38, 0x0D, 0xC6, 0x35, 0x98, 0x18, 0xF7, 0xEC, 0x6C, 0x43, 0x75, 0x37, 0x26, 0xFA, 0x13, 0x94, 0x48, 0xF2, 0xD0, 0x8B, 0x30, 0x84, 0x54, 0xDF, 0x23, 0x19, 0x5B, 0x3D, 0x59, 0xF3, 0xAE, 0xA2, 0x82, 0x63, 0x01, 0x83, 0x2E, 0xD9, 0x51, 0x9B, 0x7C, 0xA6, 0xEB, 0xA5, 0xBE, 0x16, 0x0C, 0xE3, 0x61, 0xC0, 0x8C, 0x3A, 0xF5, 0x73, 0x2C, 0x25, 0x0B, 0xBB, 0x4E, 0x89, 0x6B, 0x53, 0x6A, 0xB4, 0xF1, 0xE1, 0xE6, 0xBD, 0x45, 0xE2, 0xF4, 0xB6, 0x66, 0xCC, 0x95, 0x03, 0x56, 0xD4, 0x1C, 0x1E, 0xD7, 0xFB, 0xC3, 0x8E, 0xB5, 0xE9, 0xCF, 0xBF, 0xBA, 0xEA, 0x77, 0x39, 0xAF, 0x33, 0xC9, 0x62, 0x71, 0x81, 0x79, 0x09, 0xAD, 0x24, 0xCD, 0xF9, 0xD8, 0xE5, 0xC5, 0xB9, 0x4D, 0x44, 0x08, 0x86, 0xE7, 0xA1, 0x1D, 0xAA, 0xED, 0x06, 0x70, 0xB2, 0xD2, 0x41, 0x7B, 0xA0, 0x11, 0x31, 0xC2, 0x27, 0x90, 0x20, 0xF6, 0x60, 0xFF, 0x96, 0x5C, 0xB1, 0xAB, 0x9E, 0x9C, 0x52, 0x1B, 0x5F, 0x93, 0x0A, 0xEF, 0x91, 0x85, 0x49, 0xEE, 0x2D, 0x4F, 0x8F, 0x3B, 0x47, 0x87, 0x6D, 0x46, 0xD6, 0x3E, 0x69, 0x64, 0x2A, 0xCE, 0xCB, 0x2F, 0xFC, 0x97, 0x05, 0x7A, 0xAC, 0x7F, 0xD5, 0x1A, 0x4B, 0x0E, 0xA7, 0x5A, 0x28, 0x14, 0x3F, 0x29, 0x88, 0x3C, 0x4C, 0x02, 0xB8, 0xDA, 0xB0, 0x17, 0x55, 0x1F, 0x8A, 0x7D, 0x57, 0xC7, 0x8D, 0x74, 0xB7, 0xC4, 0x9F, 0x72, 0x7E, 0x15, 0x22, 0x12, 0x58, 0x07, 0x99, 0x34, 0x6E, 0x50, 0xDE, 0x68, 0x65, 0xBC, 0xDB, 0xF8, 0xC8, 0xA8, 0x2B, 0x40, 0xDC, 0xFE, 0x32, 0xA4, 0xCA, 0x10, 0x21, 0xF0, 0xD3, 0x5D, 0x0F, 0x00, 0x6F, 0x9D, 0x36, 0x42, 0x4A, 0x5E, 0xC1, 0xE0 ); /** * Q-Table * * @var Array * @access private */ var $q1 = array ( 0x75, 0xF3, 0xC6, 0xF4, 0xDB, 0x7B, 0xFB, 0xC8, 0x4A, 0xD3, 0xE6, 0x6B, 0x45, 0x7D, 0xE8, 0x4B, 0xD6, 0x32, 0xD8, 0xFD, 0x37, 0x71, 0xF1, 0xE1, 0x30, 0x0F, 0xF8, 0x1B, 0x87, 0xFA, 0x06, 0x3F, 0x5E, 0xBA, 0xAE, 0x5B, 0x8A, 0x00, 0xBC, 0x9D, 0x6D, 0xC1, 0xB1, 0x0E, 0x80, 0x5D, 0xD2, 0xD5, 0xA0, 0x84, 0x07, 0x14, 0xB5, 0x90, 0x2C, 0xA3, 0xB2, 0x73, 0x4C, 0x54, 0x92, 0x74, 0x36, 0x51, 0x38, 0xB0, 0xBD, 0x5A, 0xFC, 0x60, 0x62, 0x96, 0x6C, 0x42, 0xF7, 0x10, 0x7C, 0x28, 0x27, 0x8C, 0x13, 0x95, 0x9C, 0xC7, 0x24, 0x46, 0x3B, 0x70, 0xCA, 0xE3, 0x85, 0xCB, 0x11, 0xD0, 0x93, 0xB8, 0xA6, 0x83, 0x20, 0xFF, 0x9F, 0x77, 0xC3, 0xCC, 0x03, 0x6F, 0x08, 0xBF, 0x40, 0xE7, 0x2B, 0xE2, 0x79, 0x0C, 0xAA, 0x82, 0x41, 0x3A, 0xEA, 0xB9, 0xE4, 0x9A, 0xA4, 0x97, 0x7E, 0xDA, 0x7A, 0x17, 0x66, 0x94, 0xA1, 0x1D, 0x3D, 0xF0, 0xDE, 0xB3, 0x0B, 0x72, 0xA7, 0x1C, 0xEF, 0xD1, 0x53, 0x3E, 0x8F, 0x33, 0x26, 0x5F, 0xEC, 0x76, 0x2A, 0x49, 0x81, 0x88, 0xEE, 0x21, 0xC4, 0x1A, 0xEB, 0xD9, 0xC5, 0x39, 0x99, 0xCD, 0xAD, 0x31, 0x8B, 0x01, 0x18, 0x23, 0xDD, 0x1F, 0x4E, 0x2D, 0xF9, 0x48, 0x4F, 0xF2, 0x65, 0x8E, 0x78, 0x5C, 0x58, 0x19, 0x8D, 0xE5, 0x98, 0x57, 0x67, 0x7F, 0x05, 0x64, 0xAF, 0x63, 0xB6, 0xFE, 0xF5, 0xB7, 0x3C, 0xA5, 0xCE, 0xE9, 0x68, 0x44, 0xE0, 0x4D, 0x43, 0x69, 0x29, 0x2E, 0xAC, 0x15, 0x59, 0xA8, 0x0A, 0x9E, 0x6E, 0x47, 0xDF, 0x34, 0x35, 0x6A, 0xCF, 0xDC, 0x22, 0xC9, 0xC0, 0x9B, 0x89, 0xD4, 0xED, 0xAB, 0x12, 0xA2, 0x0D, 0x52, 0xBB, 0x02, 0x2F, 0xA9, 0xD7, 0x61, 0x1E, 0xB4, 0x50, 0x04, 0xF6, 0xC2, 0x16, 0x25, 0x86, 0x56, 0x55, 0x09, 0xBE, 0x91 ); /** * M-Table * * @var Array * @access private */ var $m0 = array ( 0xBCBC3275, 0xECEC21F3, 0x202043C6, 0xB3B3C9F4, 0xDADA03DB, 0x02028B7B, 0xE2E22BFB, 0x9E9EFAC8, 0xC9C9EC4A, 0xD4D409D3, 0x18186BE6, 0x1E1E9F6B, 0x98980E45, 0xB2B2387D, 0xA6A6D2E8, 0x2626B74B, 0x3C3C57D6, 0x93938A32, 0x8282EED8, 0x525298FD, 0x7B7BD437, 0xBBBB3771, 0x5B5B97F1, 0x474783E1, 0x24243C30, 0x5151E20F, 0xBABAC6F8, 0x4A4AF31B, 0xBFBF4887, 0x0D0D70FA, 0xB0B0B306, 0x7575DE3F, 0xD2D2FD5E, 0x7D7D20BA, 0x666631AE, 0x3A3AA35B, 0x59591C8A, 0x00000000, 0xCDCD93BC, 0x1A1AE09D, 0xAEAE2C6D, 0x7F7FABC1, 0x2B2BC7B1, 0xBEBEB90E, 0xE0E0A080, 0x8A8A105D, 0x3B3B52D2, 0x6464BAD5, 0xD8D888A0, 0xE7E7A584, 0x5F5FE807, 0x1B1B1114, 0x2C2CC2B5, 0xFCFCB490, 0x3131272C, 0x808065A3, 0x73732AB2, 0x0C0C8173, 0x79795F4C, 0x6B6B4154, 0x4B4B0292, 0x53536974, 0x94948F36, 0x83831F51, 0x2A2A3638, 0xC4C49CB0, 0x2222C8BD, 0xD5D5F85A, 0xBDBDC3FC, 0x48487860, 0xFFFFCE62, 0x4C4C0796, 0x4141776C, 0xC7C7E642, 0xEBEB24F7, 0x1C1C1410, 0x5D5D637C, 0x36362228, 0x6767C027, 0xE9E9AF8C, 0x4444F913, 0x1414EA95, 0xF5F5BB9C, 0xCFCF18C7, 0x3F3F2D24, 0xC0C0E346, 0x7272DB3B, 0x54546C70, 0x29294CCA, 0xF0F035E3, 0x0808FE85, 0xC6C617CB, 0xF3F34F11, 0x8C8CE4D0, 0xA4A45993, 0xCACA96B8, 0x68683BA6, 0xB8B84D83, 0x38382820, 0xE5E52EFF, 0xADAD569F, 0x0B0B8477, 0xC8C81DC3, 0x9999FFCC, 0x5858ED03, 0x19199A6F, 0x0E0E0A08, 0x95957EBF, 0x70705040, 0xF7F730E7, 0x6E6ECF2B, 0x1F1F6EE2, 0xB5B53D79, 0x09090F0C, 0x616134AA, 0x57571682, 0x9F9F0B41, 0x9D9D803A, 0x111164EA, 0x2525CDB9, 0xAFAFDDE4, 0x4545089A, 0xDFDF8DA4, 0xA3A35C97, 0xEAEAD57E, 0x353558DA, 0xEDEDD07A, 0x4343FC17, 0xF8F8CB66, 0xFBFBB194, 0x3737D3A1, 0xFAFA401D, 0xC2C2683D, 0xB4B4CCF0, 0x32325DDE, 0x9C9C71B3, 0x5656E70B, 0xE3E3DA72, 0x878760A7, 0x15151B1C, 0xF9F93AEF, 0x6363BFD1, 0x3434A953, 0x9A9A853E, 0xB1B1428F, 0x7C7CD133, 0x88889B26, 0x3D3DA65F, 0xA1A1D7EC, 0xE4E4DF76, 0x8181942A, 0x91910149, 0x0F0FFB81, 0xEEEEAA88, 0x161661EE, 0xD7D77321, 0x9797F5C4, 0xA5A5A81A, 0xFEFE3FEB, 0x6D6DB5D9, 0x7878AEC5, 0xC5C56D39, 0x1D1DE599, 0x7676A4CD, 0x3E3EDCAD, 0xCBCB6731, 0xB6B6478B, 0xEFEF5B01, 0x12121E18, 0x6060C523, 0x6A6AB0DD, 0x4D4DF61F, 0xCECEE94E, 0xDEDE7C2D, 0x55559DF9, 0x7E7E5A48, 0x2121B24F, 0x03037AF2, 0xA0A02665, 0x5E5E198E, 0x5A5A6678, 0x65654B5C, 0x62624E58, 0xFDFD4519, 0x0606F48D, 0x404086E5, 0xF2F2BE98, 0x3333AC57, 0x17179067, 0x05058E7F, 0xE8E85E05, 0x4F4F7D64, 0x89896AAF, 0x10109563, 0x74742FB6, 0x0A0A75FE, 0x5C5C92F5, 0x9B9B74B7, 0x2D2D333C, 0x3030D6A5, 0x2E2E49CE, 0x494989E9, 0x46467268, 0x77775544, 0xA8A8D8E0, 0x9696044D, 0x2828BD43, 0xA9A92969, 0xD9D97929, 0x8686912E, 0xD1D187AC, 0xF4F44A15, 0x8D8D1559, 0xD6D682A8, 0xB9B9BC0A, 0x42420D9E, 0xF6F6C16E, 0x2F2FB847, 0xDDDD06DF, 0x23233934, 0xCCCC6235, 0xF1F1C46A, 0xC1C112CF, 0x8585EBDC, 0x8F8F9E22, 0x7171A1C9, 0x9090F0C0, 0xAAAA539B, 0x0101F189, 0x8B8BE1D4, 0x4E4E8CED, 0x8E8E6FAB, 0xABABA212, 0x6F6F3EA2, 0xE6E6540D, 0xDBDBF252, 0x92927BBB, 0xB7B7B602, 0x6969CA2F, 0x3939D9A9, 0xD3D30CD7, 0xA7A72361, 0xA2A2AD1E, 0xC3C399B4, 0x6C6C4450, 0x07070504, 0x04047FF6, 0x272746C2, 0xACACA716, 0xD0D07625, 0x50501386, 0xDCDCF756, 0x84841A55, 0xE1E15109, 0x7A7A25BE, 0x1313EF91 ); /** * M-Table * * @var Array * @access private */ var $m1 = array ( 0xA9D93939, 0x67901717, 0xB3719C9C, 0xE8D2A6A6, 0x04050707, 0xFD985252, 0xA3658080, 0x76DFE4E4, 0x9A084545, 0x92024B4B, 0x80A0E0E0, 0x78665A5A, 0xE4DDAFAF, 0xDDB06A6A, 0xD1BF6363, 0x38362A2A, 0x0D54E6E6, 0xC6432020, 0x3562CCCC, 0x98BEF2F2, 0x181E1212, 0xF724EBEB, 0xECD7A1A1, 0x6C774141, 0x43BD2828, 0x7532BCBC, 0x37D47B7B, 0x269B8888, 0xFA700D0D, 0x13F94444, 0x94B1FBFB, 0x485A7E7E, 0xF27A0303, 0xD0E48C8C, 0x8B47B6B6, 0x303C2424, 0x84A5E7E7, 0x54416B6B, 0xDF06DDDD, 0x23C56060, 0x1945FDFD, 0x5BA33A3A, 0x3D68C2C2, 0x59158D8D, 0xF321ECEC, 0xAE316666, 0xA23E6F6F, 0x82165757, 0x63951010, 0x015BEFEF, 0x834DB8B8, 0x2E918686, 0xD9B56D6D, 0x511F8383, 0x9B53AAAA, 0x7C635D5D, 0xA63B6868, 0xEB3FFEFE, 0xA5D63030, 0xBE257A7A, 0x16A7ACAC, 0x0C0F0909, 0xE335F0F0, 0x6123A7A7, 0xC0F09090, 0x8CAFE9E9, 0x3A809D9D, 0xF5925C5C, 0x73810C0C, 0x2C273131, 0x2576D0D0, 0x0BE75656, 0xBB7B9292, 0x4EE9CECE, 0x89F10101, 0x6B9F1E1E, 0x53A93434, 0x6AC4F1F1, 0xB499C3C3, 0xF1975B5B, 0xE1834747, 0xE66B1818, 0xBDC82222, 0x450E9898, 0xE26E1F1F, 0xF4C9B3B3, 0xB62F7474, 0x66CBF8F8, 0xCCFF9999, 0x95EA1414, 0x03ED5858, 0x56F7DCDC, 0xD4E18B8B, 0x1C1B1515, 0x1EADA2A2, 0xD70CD3D3, 0xFB2BE2E2, 0xC31DC8C8, 0x8E195E5E, 0xB5C22C2C, 0xE9894949, 0xCF12C1C1, 0xBF7E9595, 0xBA207D7D, 0xEA641111, 0x77840B0B, 0x396DC5C5, 0xAF6A8989, 0x33D17C7C, 0xC9A17171, 0x62CEFFFF, 0x7137BBBB, 0x81FB0F0F, 0x793DB5B5, 0x0951E1E1, 0xADDC3E3E, 0x242D3F3F, 0xCDA47676, 0xF99D5555, 0xD8EE8282, 0xE5864040, 0xC5AE7878, 0xB9CD2525, 0x4D049696, 0x44557777, 0x080A0E0E, 0x86135050, 0xE730F7F7, 0xA1D33737, 0x1D40FAFA, 0xAA346161, 0xED8C4E4E, 0x06B3B0B0, 0x706C5454, 0xB22A7373, 0xD2523B3B, 0x410B9F9F, 0x7B8B0202, 0xA088D8D8, 0x114FF3F3, 0x3167CBCB, 0xC2462727, 0x27C06767, 0x90B4FCFC, 0x20283838, 0xF67F0404, 0x60784848, 0xFF2EE5E5, 0x96074C4C, 0x5C4B6565, 0xB1C72B2B, 0xAB6F8E8E, 0x9E0D4242, 0x9CBBF5F5, 0x52F2DBDB, 0x1BF34A4A, 0x5FA63D3D, 0x9359A4A4, 0x0ABCB9B9, 0xEF3AF9F9, 0x91EF1313, 0x85FE0808, 0x49019191, 0xEE611616, 0x2D7CDEDE, 0x4FB22121, 0x8F42B1B1, 0x3BDB7272, 0x47B82F2F, 0x8748BFBF, 0x6D2CAEAE, 0x46E3C0C0, 0xD6573C3C, 0x3E859A9A, 0x6929A9A9, 0x647D4F4F, 0x2A948181, 0xCE492E2E, 0xCB17C6C6, 0x2FCA6969, 0xFCC3BDBD, 0x975CA3A3, 0x055EE8E8, 0x7AD0EDED, 0xAC87D1D1, 0x7F8E0505, 0xD5BA6464, 0x1AA8A5A5, 0x4BB72626, 0x0EB9BEBE, 0xA7608787, 0x5AF8D5D5, 0x28223636, 0x14111B1B, 0x3FDE7575, 0x2979D9D9, 0x88AAEEEE, 0x3C332D2D, 0x4C5F7979, 0x02B6B7B7, 0xB896CACA, 0xDA583535, 0xB09CC4C4, 0x17FC4343, 0x551A8484, 0x1FF64D4D, 0x8A1C5959, 0x7D38B2B2, 0x57AC3333, 0xC718CFCF, 0x8DF40606, 0x74695353, 0xB7749B9B, 0xC4F59797, 0x9F56ADAD, 0x72DAE3E3, 0x7ED5EAEA, 0x154AF4F4, 0x229E8F8F, 0x12A2ABAB, 0x584E6262, 0x07E85F5F, 0x99E51D1D, 0x34392323, 0x6EC1F6F6, 0x50446C6C, 0xDE5D3232, 0x68724646, 0x6526A0A0, 0xBC93CDCD, 0xDB03DADA, 0xF8C6BABA, 0xC8FA9E9E, 0xA882D6D6, 0x2BCF6E6E, 0x40507070, 0xDCEB8585, 0xFE750A0A, 0x328A9393, 0xA48DDFDF, 0xCA4C2929, 0x10141C1C, 0x2173D7D7, 0xF0CCB4B4, 0xD309D4D4, 0x5D108A8A, 0x0FE25151, 0x00000000, 0x6F9A1919, 0x9DE01A1A, 0x368F9494, 0x42E6C7C7, 0x4AECC9C9, 0x5EFDD2D2, 0xC1AB7F7F, 0xE0D8A8A8 ); /** * M-Table * * @var Array * @access private */ var $m2 = array ( 0xBC75BC32, 0xECF3EC21, 0x20C62043, 0xB3F4B3C9, 0xDADBDA03, 0x027B028B, 0xE2FBE22B, 0x9EC89EFA, 0xC94AC9EC, 0xD4D3D409, 0x18E6186B, 0x1E6B1E9F, 0x9845980E, 0xB27DB238, 0xA6E8A6D2, 0x264B26B7, 0x3CD63C57, 0x9332938A, 0x82D882EE, 0x52FD5298, 0x7B377BD4, 0xBB71BB37, 0x5BF15B97, 0x47E14783, 0x2430243C, 0x510F51E2, 0xBAF8BAC6, 0x4A1B4AF3, 0xBF87BF48, 0x0DFA0D70, 0xB006B0B3, 0x753F75DE, 0xD25ED2FD, 0x7DBA7D20, 0x66AE6631, 0x3A5B3AA3, 0x598A591C, 0x00000000, 0xCDBCCD93, 0x1A9D1AE0, 0xAE6DAE2C, 0x7FC17FAB, 0x2BB12BC7, 0xBE0EBEB9, 0xE080E0A0, 0x8A5D8A10, 0x3BD23B52, 0x64D564BA, 0xD8A0D888, 0xE784E7A5, 0x5F075FE8, 0x1B141B11, 0x2CB52CC2, 0xFC90FCB4, 0x312C3127, 0x80A38065, 0x73B2732A, 0x0C730C81, 0x794C795F, 0x6B546B41, 0x4B924B02, 0x53745369, 0x9436948F, 0x8351831F, 0x2A382A36, 0xC4B0C49C, 0x22BD22C8, 0xD55AD5F8, 0xBDFCBDC3, 0x48604878, 0xFF62FFCE, 0x4C964C07, 0x416C4177, 0xC742C7E6, 0xEBF7EB24, 0x1C101C14, 0x5D7C5D63, 0x36283622, 0x672767C0, 0xE98CE9AF, 0x441344F9, 0x149514EA, 0xF59CF5BB, 0xCFC7CF18, 0x3F243F2D, 0xC046C0E3, 0x723B72DB, 0x5470546C, 0x29CA294C, 0xF0E3F035, 0x088508FE, 0xC6CBC617, 0xF311F34F, 0x8CD08CE4, 0xA493A459, 0xCAB8CA96, 0x68A6683B, 0xB883B84D, 0x38203828, 0xE5FFE52E, 0xAD9FAD56, 0x0B770B84, 0xC8C3C81D, 0x99CC99FF, 0x580358ED, 0x196F199A, 0x0E080E0A, 0x95BF957E, 0x70407050, 0xF7E7F730, 0x6E2B6ECF, 0x1FE21F6E, 0xB579B53D, 0x090C090F, 0x61AA6134, 0x57825716, 0x9F419F0B, 0x9D3A9D80, 0x11EA1164, 0x25B925CD, 0xAFE4AFDD, 0x459A4508, 0xDFA4DF8D, 0xA397A35C, 0xEA7EEAD5, 0x35DA3558, 0xED7AEDD0, 0x431743FC, 0xF866F8CB, 0xFB94FBB1, 0x37A137D3, 0xFA1DFA40, 0xC23DC268, 0xB4F0B4CC, 0x32DE325D, 0x9CB39C71, 0x560B56E7, 0xE372E3DA, 0x87A78760, 0x151C151B, 0xF9EFF93A, 0x63D163BF, 0x345334A9, 0x9A3E9A85, 0xB18FB142, 0x7C337CD1, 0x8826889B, 0x3D5F3DA6, 0xA1ECA1D7, 0xE476E4DF, 0x812A8194, 0x91499101, 0x0F810FFB, 0xEE88EEAA, 0x16EE1661, 0xD721D773, 0x97C497F5, 0xA51AA5A8, 0xFEEBFE3F, 0x6DD96DB5, 0x78C578AE, 0xC539C56D, 0x1D991DE5, 0x76CD76A4, 0x3EAD3EDC, 0xCB31CB67, 0xB68BB647, 0xEF01EF5B, 0x1218121E, 0x602360C5, 0x6ADD6AB0, 0x4D1F4DF6, 0xCE4ECEE9, 0xDE2DDE7C, 0x55F9559D, 0x7E487E5A, 0x214F21B2, 0x03F2037A, 0xA065A026, 0x5E8E5E19, 0x5A785A66, 0x655C654B, 0x6258624E, 0xFD19FD45, 0x068D06F4, 0x40E54086, 0xF298F2BE, 0x335733AC, 0x17671790, 0x057F058E, 0xE805E85E, 0x4F644F7D, 0x89AF896A, 0x10631095, 0x74B6742F, 0x0AFE0A75, 0x5CF55C92, 0x9BB79B74, 0x2D3C2D33, 0x30A530D6, 0x2ECE2E49, 0x49E94989, 0x46684672, 0x77447755, 0xA8E0A8D8, 0x964D9604, 0x284328BD, 0xA969A929, 0xD929D979, 0x862E8691, 0xD1ACD187, 0xF415F44A, 0x8D598D15, 0xD6A8D682, 0xB90AB9BC, 0x429E420D, 0xF66EF6C1, 0x2F472FB8, 0xDDDFDD06, 0x23342339, 0xCC35CC62, 0xF16AF1C4, 0xC1CFC112, 0x85DC85EB, 0x8F228F9E, 0x71C971A1, 0x90C090F0, 0xAA9BAA53, 0x018901F1, 0x8BD48BE1, 0x4EED4E8C, 0x8EAB8E6F, 0xAB12ABA2, 0x6FA26F3E, 0xE60DE654, 0xDB52DBF2, 0x92BB927B, 0xB702B7B6, 0x692F69CA, 0x39A939D9, 0xD3D7D30C, 0xA761A723, 0xA21EA2AD, 0xC3B4C399, 0x6C506C44, 0x07040705, 0x04F6047F, 0x27C22746, 0xAC16ACA7, 0xD025D076, 0x50865013, 0xDC56DCF7, 0x8455841A, 0xE109E151, 0x7ABE7A25, 0x139113EF ); /** * M-Table * * @var Array * @access private */ var $m3 = array ( 0xD939A9D9, 0x90176790, 0x719CB371, 0xD2A6E8D2, 0x05070405, 0x9852FD98, 0x6580A365, 0xDFE476DF, 0x08459A08, 0x024B9202, 0xA0E080A0, 0x665A7866, 0xDDAFE4DD, 0xB06ADDB0, 0xBF63D1BF, 0x362A3836, 0x54E60D54, 0x4320C643, 0x62CC3562, 0xBEF298BE, 0x1E12181E, 0x24EBF724, 0xD7A1ECD7, 0x77416C77, 0xBD2843BD, 0x32BC7532, 0xD47B37D4, 0x9B88269B, 0x700DFA70, 0xF94413F9, 0xB1FB94B1, 0x5A7E485A, 0x7A03F27A, 0xE48CD0E4, 0x47B68B47, 0x3C24303C, 0xA5E784A5, 0x416B5441, 0x06DDDF06, 0xC56023C5, 0x45FD1945, 0xA33A5BA3, 0x68C23D68, 0x158D5915, 0x21ECF321, 0x3166AE31, 0x3E6FA23E, 0x16578216, 0x95106395, 0x5BEF015B, 0x4DB8834D, 0x91862E91, 0xB56DD9B5, 0x1F83511F, 0x53AA9B53, 0x635D7C63, 0x3B68A63B, 0x3FFEEB3F, 0xD630A5D6, 0x257ABE25, 0xA7AC16A7, 0x0F090C0F, 0x35F0E335, 0x23A76123, 0xF090C0F0, 0xAFE98CAF, 0x809D3A80, 0x925CF592, 0x810C7381, 0x27312C27, 0x76D02576, 0xE7560BE7, 0x7B92BB7B, 0xE9CE4EE9, 0xF10189F1, 0x9F1E6B9F, 0xA93453A9, 0xC4F16AC4, 0x99C3B499, 0x975BF197, 0x8347E183, 0x6B18E66B, 0xC822BDC8, 0x0E98450E, 0x6E1FE26E, 0xC9B3F4C9, 0x2F74B62F, 0xCBF866CB, 0xFF99CCFF, 0xEA1495EA, 0xED5803ED, 0xF7DC56F7, 0xE18BD4E1, 0x1B151C1B, 0xADA21EAD, 0x0CD3D70C, 0x2BE2FB2B, 0x1DC8C31D, 0x195E8E19, 0xC22CB5C2, 0x8949E989, 0x12C1CF12, 0x7E95BF7E, 0x207DBA20, 0x6411EA64, 0x840B7784, 0x6DC5396D, 0x6A89AF6A, 0xD17C33D1, 0xA171C9A1, 0xCEFF62CE, 0x37BB7137, 0xFB0F81FB, 0x3DB5793D, 0x51E10951, 0xDC3EADDC, 0x2D3F242D, 0xA476CDA4, 0x9D55F99D, 0xEE82D8EE, 0x8640E586, 0xAE78C5AE, 0xCD25B9CD, 0x04964D04, 0x55774455, 0x0A0E080A, 0x13508613, 0x30F7E730, 0xD337A1D3, 0x40FA1D40, 0x3461AA34, 0x8C4EED8C, 0xB3B006B3, 0x6C54706C, 0x2A73B22A, 0x523BD252, 0x0B9F410B, 0x8B027B8B, 0x88D8A088, 0x4FF3114F, 0x67CB3167, 0x4627C246, 0xC06727C0, 0xB4FC90B4, 0x28382028, 0x7F04F67F, 0x78486078, 0x2EE5FF2E, 0x074C9607, 0x4B655C4B, 0xC72BB1C7, 0x6F8EAB6F, 0x0D429E0D, 0xBBF59CBB, 0xF2DB52F2, 0xF34A1BF3, 0xA63D5FA6, 0x59A49359, 0xBCB90ABC, 0x3AF9EF3A, 0xEF1391EF, 0xFE0885FE, 0x01914901, 0x6116EE61, 0x7CDE2D7C, 0xB2214FB2, 0x42B18F42, 0xDB723BDB, 0xB82F47B8, 0x48BF8748, 0x2CAE6D2C, 0xE3C046E3, 0x573CD657, 0x859A3E85, 0x29A96929, 0x7D4F647D, 0x94812A94, 0x492ECE49, 0x17C6CB17, 0xCA692FCA, 0xC3BDFCC3, 0x5CA3975C, 0x5EE8055E, 0xD0ED7AD0, 0x87D1AC87, 0x8E057F8E, 0xBA64D5BA, 0xA8A51AA8, 0xB7264BB7, 0xB9BE0EB9, 0x6087A760, 0xF8D55AF8, 0x22362822, 0x111B1411, 0xDE753FDE, 0x79D92979, 0xAAEE88AA, 0x332D3C33, 0x5F794C5F, 0xB6B702B6, 0x96CAB896, 0x5835DA58, 0x9CC4B09C, 0xFC4317FC, 0x1A84551A, 0xF64D1FF6, 0x1C598A1C, 0x38B27D38, 0xAC3357AC, 0x18CFC718, 0xF4068DF4, 0x69537469, 0x749BB774, 0xF597C4F5, 0x56AD9F56, 0xDAE372DA, 0xD5EA7ED5, 0x4AF4154A, 0x9E8F229E, 0xA2AB12A2, 0x4E62584E, 0xE85F07E8, 0xE51D99E5, 0x39233439, 0xC1F66EC1, 0x446C5044, 0x5D32DE5D, 0x72466872, 0x26A06526, 0x93CDBC93, 0x03DADB03, 0xC6BAF8C6, 0xFA9EC8FA, 0x82D6A882, 0xCF6E2BCF, 0x50704050, 0xEB85DCEB, 0x750AFE75, 0x8A93328A, 0x8DDFA48D, 0x4C29CA4C, 0x141C1014, 0x73D72173, 0xCCB4F0CC, 0x09D4D309, 0x108A5D10, 0xE2510FE2, 0x00000000, 0x9A196F9A, 0xE01A9DE0, 0x8F94368F, 0xE6C742E6, 0xECC94AEC, 0xFDD25EFD, 0xAB7FC1AB, 0xD8A8E0D8 ); /** * The Key Schedule Array * * @var Array * @access private */ var $K = array(); /** * The Key depended S-Table 0 * * @var Array * @access private */ var $S0 = array(); /** * The Key depended S-Table 1 * * @var Array * @access private */ var $S1 = array(); /** * The Key depended S-Table 2 * * @var Array * @access private */ var $S2 = array(); /** * The Key depended S-Table 3 * * @var Array * @access private */ var $S3 = array(); /** * Holds the last used key * * @var Array * @access private */ var $kl; /** * Sets the key. * * Keys can be of any length. Twofish, itself, requires the use of a key that's 128, 192 or 256-bits long. * If the key is less than 256-bits we round the length up to the closest valid key length, * padding $key with null bytes. If the key is more than 256-bits, we trim the excess bits. * * If the key is not explicitly set, it'll be assumed a 128 bits key to be all null bytes. * * @access public * @see \phpseclib\Crypt\Base::setKey() * @param String $key */ function setKey($key) { $keylength = strlen($key); switch (true) { case $keylength <= 16: $key = str_pad($key, 16, "\0"); break; case $keylength <= 24: $key = str_pad($key, 24, "\0"); break; case $keylength < 32: $key = str_pad($key, 32, "\0"); break; case $keylength > 32: $key = substr($key, 0, 32); } parent::setKey($key); } /** * Setup the key (expansion) * * @see \phpseclib\Crypt\Base::_setupKey() * @access private */ function _setupKey() { if (isset($this->kl['key']) && $this->key === $this->kl['key']) { // already expanded return; } $this->kl = array('key' => $this->key); /* Key expanding and generating the key-depended s-boxes */ $le_longs = unpack('V*', $this->key); $key = unpack('C*', $this->key); $m0 = $this->m0; $m1 = $this->m1; $m2 = $this->m2; $m3 = $this->m3; $q0 = $this->q0; $q1 = $this->q1; $K = $S0 = $S1 = $S2 = $S3 = array(); switch (strlen($this->key)) { case 16: list ($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[1], $le_longs[2]); list ($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[3], $le_longs[4]); for ($i = 0, $j = 1; $i < 40; $i+= 2,$j+= 2) { $A = $m0[$q0[$q0[$i] ^ $key[ 9]] ^ $key[1]] ^ $m1[$q0[$q1[$i] ^ $key[10]] ^ $key[2]] ^ $m2[$q1[$q0[$i] ^ $key[11]] ^ $key[3]] ^ $m3[$q1[$q1[$i] ^ $key[12]] ^ $key[4]]; $B = $m0[$q0[$q0[$j] ^ $key[13]] ^ $key[5]] ^ $m1[$q0[$q1[$j] ^ $key[14]] ^ $key[6]] ^ $m2[$q1[$q0[$j] ^ $key[15]] ^ $key[7]] ^ $m3[$q1[$q1[$j] ^ $key[16]] ^ $key[8]]; $B = ($B << 8) | ($B >> 24 & 0xff); $K[] = $A+= $B; $K[] = (($A+= $B) << 9 | $A >> 23 & 0x1ff); } for ($i = 0; $i < 256; ++$i) { $S0[$i] = $m0[$q0[$q0[$i] ^ $s4] ^ $s0]; $S1[$i] = $m1[$q0[$q1[$i] ^ $s5] ^ $s1]; $S2[$i] = $m2[$q1[$q0[$i] ^ $s6] ^ $s2]; $S3[$i] = $m3[$q1[$q1[$i] ^ $s7] ^ $s3]; } break; case 24: list ($sb, $sa, $s9, $s8) = $this->_mdsrem($le_longs[1], $le_longs[2]); list ($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[3], $le_longs[4]); list ($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[5], $le_longs[6]); for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) { $A = $m0[$q0[$q0[$q1[$i] ^ $key[17]] ^ $key[ 9]] ^ $key[1]] ^ $m1[$q0[$q1[$q1[$i] ^ $key[18]] ^ $key[10]] ^ $key[2]] ^ $m2[$q1[$q0[$q0[$i] ^ $key[19]] ^ $key[11]] ^ $key[3]] ^ $m3[$q1[$q1[$q0[$i] ^ $key[20]] ^ $key[12]] ^ $key[4]]; $B = $m0[$q0[$q0[$q1[$j] ^ $key[21]] ^ $key[13]] ^ $key[5]] ^ $m1[$q0[$q1[$q1[$j] ^ $key[22]] ^ $key[14]] ^ $key[6]] ^ $m2[$q1[$q0[$q0[$j] ^ $key[23]] ^ $key[15]] ^ $key[7]] ^ $m3[$q1[$q1[$q0[$j] ^ $key[24]] ^ $key[16]] ^ $key[8]]; $B = ($B << 8) | ($B >> 24 & 0xff); $K[] = $A+= $B; $K[] = (($A+= $B) << 9 | $A >> 23 & 0x1ff); } for ($i = 0; $i < 256; ++$i) { $S0[$i] = $m0[$q0[$q0[$q1[$i] ^ $s8] ^ $s4] ^ $s0]; $S1[$i] = $m1[$q0[$q1[$q1[$i] ^ $s9] ^ $s5] ^ $s1]; $S2[$i] = $m2[$q1[$q0[$q0[$i] ^ $sa] ^ $s6] ^ $s2]; $S3[$i] = $m3[$q1[$q1[$q0[$i] ^ $sb] ^ $s7] ^ $s3]; } break; default: // 32 list ($sf, $se, $sd, $sc) = $this->_mdsrem($le_longs[1], $le_longs[2]); list ($sb, $sa, $s9, $s8) = $this->_mdsrem($le_longs[3], $le_longs[4]); list ($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[5], $le_longs[6]); list ($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[7], $le_longs[8]); for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) { $A = $m0[$q0[$q0[$q1[$q1[$i] ^ $key[25]] ^ $key[17]] ^ $key[ 9]] ^ $key[1]] ^ $m1[$q0[$q1[$q1[$q0[$i] ^ $key[26]] ^ $key[18]] ^ $key[10]] ^ $key[2]] ^ $m2[$q1[$q0[$q0[$q0[$i] ^ $key[27]] ^ $key[19]] ^ $key[11]] ^ $key[3]] ^ $m3[$q1[$q1[$q0[$q1[$i] ^ $key[28]] ^ $key[20]] ^ $key[12]] ^ $key[4]]; $B = $m0[$q0[$q0[$q1[$q1[$j] ^ $key[29]] ^ $key[21]] ^ $key[13]] ^ $key[5]] ^ $m1[$q0[$q1[$q1[$q0[$j] ^ $key[30]] ^ $key[22]] ^ $key[14]] ^ $key[6]] ^ $m2[$q1[$q0[$q0[$q0[$j] ^ $key[31]] ^ $key[23]] ^ $key[15]] ^ $key[7]] ^ $m3[$q1[$q1[$q0[$q1[$j] ^ $key[32]] ^ $key[24]] ^ $key[16]] ^ $key[8]]; $B = ($B << 8) | ($B >> 24 & 0xff); $K[] = $A+= $B; $K[] = (($A+= $B) << 9 | $A >> 23 & 0x1ff); } for ($i = 0; $i < 256; ++$i) { $S0[$i] = $m0[$q0[$q0[$q1[$q1[$i] ^ $sc] ^ $s8] ^ $s4] ^ $s0]; $S1[$i] = $m1[$q0[$q1[$q1[$q0[$i] ^ $sd] ^ $s9] ^ $s5] ^ $s1]; $S2[$i] = $m2[$q1[$q0[$q0[$q0[$i] ^ $se] ^ $sa] ^ $s6] ^ $s2]; $S3[$i] = $m3[$q1[$q1[$q0[$q1[$i] ^ $sf] ^ $sb] ^ $s7] ^ $s3]; } } $this->K = $K; $this->S0 = $S0; $this->S1 = $S1; $this->S2 = $S2; $this->S3 = $S3; } /** * _mdsrem function using by the twofish cipher algorithm * * @access private * @param String $A * @param String $B * @return Array */ function _mdsrem($A, $B) { // No gain by unrolling this loop. for ($i = 0; $i < 8; ++$i) { // Get most significant coefficient. $t = 0xff & ($B >> 24); // Shift the others up. $B = ($B << 8) | (0xff & ($A >> 24)); $A<<= 8; $u = $t << 1; // Subtract the modular polynomial on overflow. if ($t & 0x80) { $u^= 0x14d; } // Remove t * (a * x^2 + 1). $B ^= $t ^ ($u << 16); // Form u = a*t + t/a = t*(a + 1/a). $u^= 0x7fffffff & ($t >> 1); // Add the modular polynomial on underflow. if ($t & 0x01) $u^= 0xa6 ; // Remove t * (a + 1/a) * (x^3 + x). $B^= ($u << 24) | ($u << 8); } return array( 0xff & $B >> 24, 0xff & $B >> 16, 0xff & $B >> 8, 0xff & $B); } /** * Encrypts a block * * @access private * @param String $in * @return String */ function _encryptBlock($in) { $S0 = $this->S0; $S1 = $this->S1; $S2 = $this->S2; $S3 = $this->S3; $K = $this->K; $in = unpack("V4", $in); $R0 = $K[0] ^ $in[1]; $R1 = $K[1] ^ $in[2]; $R2 = $K[2] ^ $in[3]; $R3 = $K[3] ^ $in[4]; $ki = 7; while ($ki < 39) { $t0 = $S0[ $R0 & 0xff] ^ $S1[($R0 >> 8) & 0xff] ^ $S2[($R0 >> 16) & 0xff] ^ $S3[($R0 >> 24) & 0xff]; $t1 = $S0[($R1 >> 24) & 0xff] ^ $S1[ $R1 & 0xff] ^ $S2[($R1 >> 8) & 0xff] ^ $S3[($R1 >> 16) & 0xff]; $R2^= $t0 + $t1 + $K[++$ki]; $R2 = ($R2 >> 1 & 0x7fffffff) | ($R2 << 31); $R3 = ((($R3 >> 31) & 1) | ($R3 << 1)) ^ ($t0 + ($t1 << 1) + $K[++$ki]); $t0 = $S0[ $R2 & 0xff] ^ $S1[($R2 >> 8) & 0xff] ^ $S2[($R2 >> 16) & 0xff] ^ $S3[($R2 >> 24) & 0xff]; $t1 = $S0[($R3 >> 24) & 0xff] ^ $S1[ $R3 & 0xff] ^ $S2[($R3 >> 8) & 0xff] ^ $S3[($R3 >> 16) & 0xff]; $R0^= ($t0 + $t1 + $K[++$ki]); $R0 = ($R0 >> 1 & 0x7fffffff) | ($R0 << 31); $R1 = ((($R1 >> 31) & 1) | ($R1 << 1)) ^ ($t0 + ($t1 << 1) + $K[++$ki]); } // @codingStandardsIgnoreStart return pack("V4", $K[4] ^ $R2, $K[5] ^ $R3, $K[6] ^ $R0, $K[7] ^ $R1); // @codingStandardsIgnoreEnd } /** * Decrypts a block * * @access private * @param String $in * @return String */ function _decryptBlock($in) { $S0 = $this->S0; $S1 = $this->S1; $S2 = $this->S2; $S3 = $this->S3; $K = $this->K; $in = unpack("V4", $in); $R0 = $K[4] ^ $in[1]; $R1 = $K[5] ^ $in[2]; $R2 = $K[6] ^ $in[3]; $R3 = $K[7] ^ $in[4]; $ki = 40; while ($ki > 8) { $t0 = $S0[$R0 & 0xff] ^ $S1[$R0 >> 8 & 0xff] ^ $S2[$R0 >> 16 & 0xff] ^ $S3[$R0 >> 24 & 0xff]; $t1 = $S0[$R1 >> 24 & 0xff] ^ $S1[$R1 & 0xff] ^ $S2[$R1 >> 8 & 0xff] ^ $S3[$R1 >> 16 & 0xff]; $R3^= $t0 + ($t1 << 1) + $K[--$ki]; $R3 = $R3 >> 1 & 0x7fffffff | $R3 << 31; $R2 = ($R2 >> 31 & 0x1 | $R2 << 1) ^ ($t0 + $t1 + $K[--$ki]); $t0 = $S0[$R2 & 0xff] ^ $S1[$R2 >> 8 & 0xff] ^ $S2[$R2 >> 16 & 0xff] ^ $S3[$R2 >> 24 & 0xff]; $t1 = $S0[$R3 >> 24 & 0xff] ^ $S1[$R3 & 0xff] ^ $S2[$R3 >> 8 & 0xff] ^ $S3[$R3 >> 16 & 0xff]; $R1^= $t0 + ($t1 << 1) + $K[--$ki]; $R1 = $R1 >> 1 & 0x7fffffff | $R1 << 31; $R0 = ($R0 >> 31 & 0x1 | $R0 << 1) ^ ($t0 + $t1 + $K[--$ki]); } // @codingStandardsIgnoreStart return pack("V4", $K[0] ^ $R2, $K[1] ^ $R3, $K[2] ^ $R0, $K[3] ^ $R1); // @codingStandardsIgnoreEnd } /** * Setup the performance-optimized function for de/encrypt() * * @see \phpseclib\Crypt\Base::_setupInlineCrypt() * @access private */ function _setupInlineCrypt() { $lambda_functions =& self::_getLambdaFunctions(); // Max. 10 Ultra-Hi-optimized inline-crypt functions. After that, we'll (still) create very fast code, but not the ultimate fast one. $gen_hi_opt_code = (bool)( count($lambda_functions) < 10 ); switch (true) { case $gen_hi_opt_code: $code_hash = md5(str_pad("Twofish, {$this->mode}, ", 32, "\0") . $this->key); break; default: $code_hash = "Twofish, {$this->mode}"; } if (!isset($lambda_functions[$code_hash])) { switch (true) { case $gen_hi_opt_code: $K = $this->K; $init_crypt = ' static $S0, $S1, $S2, $S3; if (!$S0) { for ($i = 0; $i < 256; ++$i) { $S0[] = (int)$self->S0[$i]; $S1[] = (int)$self->S1[$i]; $S2[] = (int)$self->S2[$i]; $S3[] = (int)$self->S3[$i]; } } '; break; default: $K = array(); for ($i = 0; $i < 40; ++$i) { $K[] = '$K_' . $i; } $init_crypt = ' $S0 = $self->S0; $S1 = $self->S1; $S2 = $self->S2; $S3 = $self->S3; list(' . implode(',', $K) . ') = $self->K; '; } // Generating encrypt code: $encrypt_block = ' $in = unpack("V4", $in); $R0 = '.$K[0].' ^ $in[1]; $R1 = '.$K[1].' ^ $in[2]; $R2 = '.$K[2].' ^ $in[3]; $R3 = '.$K[3].' ^ $in[4]; '; for ($ki = 7, $i = 0; $i < 8; ++$i) { $encrypt_block.= ' $t0 = $S0[ $R0 & 0xff] ^ $S1[($R0 >> 8) & 0xff] ^ $S2[($R0 >> 16) & 0xff] ^ $S3[($R0 >> 24) & 0xff]; $t1 = $S0[($R1 >> 24) & 0xff] ^ $S1[ $R1 & 0xff] ^ $S2[($R1 >> 8) & 0xff] ^ $S3[($R1 >> 16) & 0xff]; $R2^= ($t0 + $t1 + '.$K[++$ki].'); $R2 = ($R2 >> 1 & 0x7fffffff) | ($R2 << 31); $R3 = ((($R3 >> 31) & 1) | ($R3 << 1)) ^ ($t0 + ($t1 << 1) + '.$K[++$ki].'); $t0 = $S0[ $R2 & 0xff] ^ $S1[($R2 >> 8) & 0xff] ^ $S2[($R2 >> 16) & 0xff] ^ $S3[($R2 >> 24) & 0xff]; $t1 = $S0[($R3 >> 24) & 0xff] ^ $S1[ $R3 & 0xff] ^ $S2[($R3 >> 8) & 0xff] ^ $S3[($R3 >> 16) & 0xff]; $R0^= ($t0 + $t1 + '.$K[++$ki].'); $R0 = ($R0 >> 1 & 0x7fffffff) | ($R0 << 31); $R1 = ((($R1 >> 31) & 1) | ($R1 << 1)) ^ ($t0 + ($t1 << 1) + '.$K[++$ki].'); '; } $encrypt_block.= ' $in = pack("V4", '.$K[4].' ^ $R2, '.$K[5].' ^ $R3, '.$K[6].' ^ $R0, '.$K[7].' ^ $R1); '; // Generating decrypt code: $decrypt_block = ' $in = unpack("V4", $in); $R0 = '.$K[4].' ^ $in[1]; $R1 = '.$K[5].' ^ $in[2]; $R2 = '.$K[6].' ^ $in[3]; $R3 = '.$K[7].' ^ $in[4]; '; for ($ki = 40, $i = 0; $i < 8; ++$i) { $decrypt_block.= ' $t0 = $S0[$R0 & 0xff] ^ $S1[$R0 >> 8 & 0xff] ^ $S2[$R0 >> 16 & 0xff] ^ $S3[$R0 >> 24 & 0xff]; $t1 = $S0[$R1 >> 24 & 0xff] ^ $S1[$R1 & 0xff] ^ $S2[$R1 >> 8 & 0xff] ^ $S3[$R1 >> 16 & 0xff]; $R3^= $t0 + ($t1 << 1) + '.$K[--$ki].'; $R3 = $R3 >> 1 & 0x7fffffff | $R3 << 31; $R2 = ($R2 >> 31 & 0x1 | $R2 << 1) ^ ($t0 + $t1 + '.$K[--$ki].'); $t0 = $S0[$R2 & 0xff] ^ $S1[$R2 >> 8 & 0xff] ^ $S2[$R2 >> 16 & 0xff] ^ $S3[$R2 >> 24 & 0xff]; $t1 = $S0[$R3 >> 24 & 0xff] ^ $S1[$R3 & 0xff] ^ $S2[$R3 >> 8 & 0xff] ^ $S3[$R3 >> 16 & 0xff]; $R1^= $t0 + ($t1 << 1) + '.$K[--$ki].'; $R1 = $R1 >> 1 & 0x7fffffff | $R1 << 31; $R0 = ($R0 >> 31 & 0x1 | $R0 << 1) ^ ($t0 + $t1 + '.$K[--$ki].'); '; } $decrypt_block.= ' $in = pack("V4", '.$K[0].' ^ $R2, '.$K[1].' ^ $R3, '.$K[2].' ^ $R0, '.$K[3].' ^ $R1); '; $lambda_functions[$code_hash] = $this->_createInlineCryptFunction( array( 'init_crypt' => $init_crypt, 'init_encrypt' => '', 'init_decrypt' => '', 'encrypt_block' => $encrypt_block, 'decrypt_block' => $decrypt_block ) ); } $this->inline_crypt = $lambda_functions[$code_hash]; } } * @copyright 2012 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\File; /** * Pure-PHP ANSI Decoder * * @package ANSI * @author Jim Wigginton * @access public */ class ANSI { /** * Max Width * * @var Integer * @access private */ var $max_x; /** * Max Height * * @var Integer * @access private */ var $max_y; /** * Max History * * @var Integer * @access private */ var $max_history; /** * History * * @var Array * @access private */ var $history; /** * History Attributes * * @var Array * @access private */ var $history_attrs; /** * Current Column * * @var Integer * @access private */ var $x; /** * Current Row * * @var Integer * @access private */ var $y; /** * Old Column * * @var Integer * @access private */ var $old_x; /** * Old Row * * @var Integer * @access private */ var $old_y; /** * An empty attribute row * * @var Array * @access private */ var $attr_row; /** * The current screen text * * @var Array * @access private */ var $screen; /** * The current screen attributes * * @var Array * @access private */ var $attrs; /** * The current foreground color * * @var String * @access private */ var $foreground; /** * The current background color * * @var String * @access private */ var $background; /** * Bold flag * * @var Boolean * @access private */ var $bold; /** * Underline flag * * @var Boolean * @access private */ var $underline; /** * Blink flag * * @var Boolean * @access private */ var $blink; /** * Reverse flag * * @var Boolean * @access private */ var $reverse; /** * Color flag * * @var Boolean * @access private */ var $color; /** * Current ANSI code * * @var String * @access private */ var $ansi; /** * Default Constructor. * * @return \phpseclib\File\ANSI * @access public */ function __construct() { $this->setHistory(200); $this->setDimensions(80, 24); } /** * Set terminal width and height * * Resets the screen as well * * @param Integer $x * @param Integer $y * @access public */ function setDimensions($x, $y) { $this->max_x = $x - 1; $this->max_y = $y - 1; $this->x = $this->y = 0; $this->history = $this->history_attrs = array(); $this->attr_row = array_fill(0, $this->max_x + 1, ''); $this->screen = array_fill(0, $this->max_y + 1, ''); $this->attrs = array_fill(0, $this->max_y + 1, $this->attr_row); $this->foreground = 'white'; $this->background = 'black'; $this->bold = false; $this->underline = false; $this->blink = false; $this->reverse = false; $this->color = false; $this->ansi = ''; } /** * Set the number of lines that should be logged past the terminal height * * @param Integer $x * @param Integer $y * @access public */ function setHistory($history) { $this->max_history = $history; } /** * Load a string * * @param String $source * @access public */ function loadString($source) { $this->setDimensions($this->max_x + 1, $this->max_y + 1); $this->appendString($source); } /** * Appdend a string * * @param String $source * @access public */ function appendString($source) { for ($i = 0; $i < strlen($source); $i++) { if (strlen($this->ansi)) { $this->ansi.= $source[$i]; $chr = ord($source[$i]); // http://en.wikipedia.org/wiki/ANSI_escape_code#Sequence_elements // single character CSI's not currently supported switch (true) { case $this->ansi == "\x1B=": $this->ansi = ''; continue 2; case strlen($this->ansi) == 2 && $chr >= 64 && $chr <= 95 && $chr != ord('['): case strlen($this->ansi) > 2 && $chr >= 64 && $chr <= 126: break; default: continue 2; } // http://ascii-table.com/ansi-escape-sequences-vt-100.php switch ($this->ansi) { case "\x1B[H": // Move cursor to upper left corner $this->old_x = $this->x; $this->old_y = $this->y; $this->x = $this->y = 0; break; case "\x1B[J": // Clear screen from cursor down $this->history = array_merge($this->history, array_slice(array_splice($this->screen, $this->y + 1), 0, $this->old_y)); $this->screen = array_merge($this->screen, array_fill($this->y, $this->max_y, '')); $this->history_attrs = array_merge($this->history_attrs, array_slice(array_splice($this->attrs, $this->y + 1), 0, $this->old_y)); $this->attrs = array_merge($this->attrs, array_fill($this->y, $this->max_y, $this->attr_row)); if (count($this->history) == $this->max_history) { array_shift($this->history); array_shift($this->history_attrs); } case "\x1B[K": // Clear screen from cursor right $this->screen[$this->y] = substr($this->screen[$this->y], 0, $this->x); array_splice($this->attrs[$this->y], $this->x + 1); break; case "\x1B[2K": // Clear entire line $this->screen[$this->y] = str_repeat(' ', $this->x); $this->attrs[$this->y] = $this->attr_row; break; case "\x1B[?1h": // set cursor key to application case "\x1B[?25h": // show the cursor break; case "\x1BE": // Move to next line $this->_newLine(); $this->x = 0; break; default: switch (true) { case preg_match('#\x1B\[(\d+);(\d+)H#', $this->ansi, $match): // Move cursor to screen location v,h $this->old_x = $this->x; $this->old_y = $this->y; $this->x = $match[2] - 1; $this->y = $match[1] - 1; break; case preg_match('#\x1B\[(\d+)C#', $this->ansi, $match): // Move cursor right n lines $this->old_x = $this->x; $x = $match[1] - 1; break; case preg_match('#\x1B\[(\d+);(\d+)r#', $this->ansi, $match): // Set top and bottom lines of a window break; case preg_match('#\x1B\[(\d*(?:;\d*)*)m#', $this->ansi, $match): // character attributes $mods = explode(';', $match[1]); foreach ($mods as $mod) { switch ($mod) { case 0: // Turn off character attributes $this->attrs[$this->y][$this->x] = ''; if ($this->bold) $this->attrs[$this->y][$this->x].= ''; if ($this->underline) $this->attrs[$this->y][$this->x].= ''; if ($this->blink) $this->attrs[$this->y][$this->x].= ''; if ($this->color) $this->attrs[$this->y][$this->x].= ''; if ($this->reverse) { $temp = $this->background; $this->background = $this->foreground; $this->foreground = $temp; } $this->bold = $this->underline = $this->blink = $this->color = $this->reverse = false; break; case 1: // Turn bold mode on if (!$this->bold) { $this->attrs[$this->y][$this->x] = ''; $this->bold = true; } break; case 4: // Turn underline mode on if (!$this->underline) { $this->attrs[$this->y][$this->x] = ''; $this->underline = true; } break; case 5: // Turn blinking mode on if (!$this->blink) { $this->attrs[$this->y][$this->x] = ''; $this->blink = true; } break; case 7: // Turn reverse video on $this->reverse = !$this->reverse; $temp = $this->background; $this->background = $this->foreground; $this->foreground = $temp; $this->attrs[$this->y][$this->x] = ''; if ($this->color) { $this->attrs[$this->y][$this->x] = '' . $this->attrs[$this->y][$this->x]; } $this->color = true; break; default: // set colors //$front = $this->reverse ? &$this->background : &$this->foreground; $front = &$this->{ $this->reverse ? 'background' : 'foreground' }; //$back = $this->reverse ? &$this->foreground : &$this->background; $back = &$this->{ $this->reverse ? 'foreground' : 'background' }; switch ($mod) { case 30: $front = 'black'; break; case 31: $front = 'red'; break; case 32: $front = 'green'; break; case 33: $front = 'yellow'; break; case 34: $front = 'blue'; break; case 35: $front = 'magenta'; break; case 36: $front = 'cyan'; break; case 37: $front = 'white'; break; case 40: $back = 'black'; break; case 41: $back = 'red'; break; case 42: $back = 'green'; break; case 43: $back = 'yellow'; break; case 44: $back = 'blue'; break; case 45: $back = 'magenta'; break; case 46: $back = 'cyan'; break; case 47: $back = 'white'; break; default: user_error('Unsupported attribute: ' . $mod); $this->ansi = ''; break 2; } unset($temp); $this->attrs[$this->y][$this->x] = ''; if ($this->color) { $this->attrs[$this->y][$this->x] = '' . $this->attrs[$this->y][$this->x]; } $this->color = true; } } break; default: user_error("{$this->ansi} unsupported\r\n"); } } $this->ansi = ''; continue; } switch ($source[$i]) { case "\r": $this->x = 0; break; case "\n": $this->_newLine(); break; case "\x0F": // shift break; case "\x1B": // start ANSI escape code $this->ansi.= "\x1B"; break; default: $this->screen[$this->y] = substr_replace( $this->screen[$this->y], $source[$i], $this->x, 1 ); if ($this->x > $this->max_x) { $this->x = 0; $this->y++; } else { $this->x++; } } } } /** * Add a new line * * Also update the $this->screen and $this->history buffers * * @access private */ function _newLine() { //if ($this->y < $this->max_y) { // $this->y++; //} while ($this->y >= $this->max_y) { $this->history = array_merge($this->history, array(array_shift($this->screen))); $this->screen[] = ''; $this->history_attrs = array_merge($this->history_attrs, array(array_shift($this->attrs))); $this->attrs[] = $this->attr_row; if (count($this->history) >= $this->max_history) { array_shift($this->history); array_shift($this->history_attrs); } $this->y--; } $this->y++; } /** * Returns the current screen without preformating * * @access private * @return String */ function _getScreen() { $output = ''; for ($i = 0; $i <= $this->max_y; $i++) { for ($j = 0; $j <= $this->max_x + 1; $j++) { if (isset($this->attrs[$i][$j])) { $output.= $this->attrs[$i][$j]; } if (isset($this->screen[$i][$j])) { $output.= htmlspecialchars($this->screen[$i][$j]); } } $output.= "\r\n"; } return rtrim($output); } /** * Returns the current screen * * @access public * @return String */ function getScreen() { return '
' . $this->_getScreen() . '
'; } /** * Returns the current screen and the x previous lines * * @access public * @return String */ function getHistory() { $scrollback = ''; for ($i = 0; $i < count($this->history); $i++) { for ($j = 0; $j <= $this->max_x + 1; $j++) { if (isset($this->history_attrs[$i][$j])) { $scrollback.= $this->history_attrs[$i][$j]; } if (isset($this->history[$i][$j])) { $scrollback.= htmlspecialchars($this->history[$i][$j]); } } $scrollback.= "\r\n"; } $scrollback.= $this->_getScreen(); return '
' . $scrollback . '
'; } } * @copyright 2012 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\File\ASN1; /** * ASN.1 Element * * Bypass normal encoding rules in phpseclib\File\ASN1::encodeDER() * * @package ASN1 * @author Jim Wigginton * @access public */ class Element { /** * Raw element value * * @var String * @access private */ var $element; /** * Constructor * * @param String $encoded * @return \phpseclib\File\ASN1\Element * @access public */ function __construct($encoded) { $this->element = $encoded; } } * @copyright 2012 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\File; use phpseclib\File\ASN1\Element; use phpseclib\Math\BigInteger; /** * Pure-PHP ASN.1 Parser * * @package ASN1 * @author Jim Wigginton * @access public */ class ASN1 { /**#@+ * Tag Classes * * @access private * @link http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#page=12 */ const CLASS_UNIVERSAL = 0; const CLASS_APPLICATION = 1; const CLASS_CONTEXT_SPECIFIC = 2; const CLASS_PRIVATE = 3; /**#@-*/ /**#@+ * Tag Classes * * @access private * @link http://www.obj-sys.com/asn1tutorial/node124.html */ const TYPE_BOOLEAN = 1; const TYPE_INTEGER = 2; const TYPE_BIT_STRING = 3; const TYPE_OCTET_STRING = 4; const TYPE_NULL = 5; const TYPE_OBJECT_IDENTIFIER = 6; //const TYPE_OBJECT_DESCRIPTOR = 7; //const TYPE_INSTANCE_OF = 8; // EXTERNAL const TYPE_REAL = 9; const TYPE_ENUMERATED = 10; //const TYPE_EMBEDDED = 11; const TYPE_UTF8_STRING = 12; //const TYPE_RELATIVE_OID = 13; const TYPE_SEQUENCE = 16; // SEQUENCE OF const TYPE_SET = 17; // SET OF /**#@-*/ /**#@+ * More Tag Classes * * @access private * @link http://www.obj-sys.com/asn1tutorial/node10.html */ const TYPE_NUMERIC_STRING = 18; const TYPE_PRINTABLE_STRING = 19; const TYPE_TELETEX_STRING = 20; // T61String const TYPE_VIDEOTEX_STRING = 21; const TYPE_IA5_STRING = 22; const TYPE_UTC_TIME = 23; const TYPE_GENERALIZED_TIME = 24; const TYPE_GRAPHIC_STRING = 25; const TYPE_VISIBLE_STRING = 26; // ISO646String const TYPE_GENERAL_STRING = 27; const TYPE_UNIVERSAL_STRING = 28; //const TYPE_CHARACTER_STRING = 29; const TYPE_BMP_STRING = 30; /**#@-*/ /**#@+ * Tag Aliases * * These tags are kinda place holders for other tags. * * @access private */ const TYPE_CHOICE = -1; const TYPE_ANY = -2; /**#@-*/ /** * ASN.1 object identifier * * @var Array * @access private * @link http://en.wikipedia.org/wiki/Object_identifier */ var $oids = array(); /** * Default date format * * @var String * @access private * @link http://php.net/class.datetime */ var $format = 'D, d M Y H:i:s O'; /** * Default date format * * @var Array * @access private * @see \phpseclib\File\ASN1::setTimeFormat() * @see \phpseclib\File\ASN1::asn1map() * @link http://php.net/class.datetime */ var $encoded; /** * Filters * * If the mapping type is self::TYPE_ANY what do we actually encode it as? * * @var Array * @access private * @see \phpseclib\File\ASN1::_encode_der() */ var $filters; /** * Type mapping table for the ANY type. * * Structured or unknown types are mapped to a \phpseclib\File\ASN1\Element. * Unambiguous types get the direct mapping (int/real/bool). * Others are mapped as a choice, with an extra indexing level. * * @var Array * @access public */ var $ANYmap = array( self::TYPE_BOOLEAN => true, self::TYPE_INTEGER => true, self::TYPE_BIT_STRING => 'bitString', self::TYPE_OCTET_STRING => 'octetString', self::TYPE_NULL => 'null', self::TYPE_OBJECT_IDENTIFIER => 'objectIdentifier', self::TYPE_REAL => true, self::TYPE_ENUMERATED => 'enumerated', self::TYPE_UTF8_STRING => 'utf8String', self::TYPE_NUMERIC_STRING => 'numericString', self::TYPE_PRINTABLE_STRING => 'printableString', self::TYPE_TELETEX_STRING => 'teletexString', self::TYPE_VIDEOTEX_STRING => 'videotexString', self::TYPE_IA5_STRING => 'ia5String', self::TYPE_UTC_TIME => 'utcTime', self::TYPE_GENERALIZED_TIME => 'generalTime', self::TYPE_GRAPHIC_STRING => 'graphicString', self::TYPE_VISIBLE_STRING => 'visibleString', self::TYPE_GENERAL_STRING => 'generalString', self::TYPE_UNIVERSAL_STRING => 'universalString', //self::TYPE_CHARACTER_STRING => 'characterString', self::TYPE_BMP_STRING => 'bmpString' ); /** * String type to character size mapping table. * * Non-convertable types are absent from this table. * size == 0 indicates variable length encoding. * * @var Array * @access public */ var $stringTypeSize = array( self::TYPE_UTF8_STRING => 0, self::TYPE_BMP_STRING => 2, self::TYPE_UNIVERSAL_STRING => 4, self::TYPE_PRINTABLE_STRING => 1, self::TYPE_TELETEX_STRING => 1, self::TYPE_IA5_STRING => 1, self::TYPE_VISIBLE_STRING => 1, ); /** * Parse BER-encoding * * Serves a similar purpose to openssl's asn1parse * * @param String $encoded * @return Array * @access public */ function decodeBER($encoded) { if ($encoded instanceof Element) { $encoded = $encoded->element; } $this->encoded = $encoded; // encapsulate in an array for BC with the old decodeBER return array($this->_decode_ber($encoded)); } /** * Parse BER-encoding (Helper function) * * Sometimes we want to get the BER encoding of a particular tag. $start lets us do that without having to reencode. * $encoded is passed by reference for the recursive calls done for self::TYPE_BIT_STRING and * self::TYPE_OCTET_STRING. In those cases, the indefinite length is used. * * @param String $encoded * @param Integer $start * @return Array * @access private */ function _decode_ber($encoded, $start = 0) { $current = array('start' => $start); $type = ord($this->_string_shift($encoded)); $start++; $constructed = ($type >> 5) & 1; $tag = $type & 0x1F; if ($tag == 0x1F) { $tag = 0; // process septets (since the eighth bit is ignored, it's not an octet) do { $loop = ord($encoded[0]) >> 7; $tag <<= 7; $tag |= ord($this->_string_shift($encoded)) & 0x7F; $start++; } while ( $loop ); } // Length, as discussed in paragraph 8.1.3 of X.690-0207.pdf#page=13 $length = ord($this->_string_shift($encoded)); $start++; if ( $length == 0x80 ) { // indefinite length // "[A sender shall] use the indefinite form (see 8.1.3.6) if the encoding is constructed and is not all // immediately available." -- paragraph 8.1.3.2.c $length = strlen($encoded); } elseif ( $length & 0x80 ) { // definite length, long form // technically, the long form of the length can be represented by up to 126 octets (bytes), but we'll only // support it up to four. $length&= 0x7F; $temp = $this->_string_shift($encoded, $length); // tags of indefinte length don't really have a header length; this length includes the tag $current+= array('headerlength' => $length + 2); $start+= $length; extract(unpack('Nlength', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4))); } else { $current+= array('headerlength' => 2); } $content = $this->_string_shift($encoded, $length); // at this point $length can be overwritten. it's only accurate for definite length things as is /* Class is UNIVERSAL, APPLICATION, PRIVATE, or CONTEXT-SPECIFIC. The UNIVERSAL class is restricted to the ASN.1 built-in types. It defines an application-independent data type that must be distinguishable from all other data types. The other three classes are user defined. The APPLICATION class distinguishes data types that have a wide, scattered use within a particular presentation context. PRIVATE distinguishes data types within a particular organization or country. CONTEXT-SPECIFIC distinguishes members of a sequence or set, the alternatives of a CHOICE, or universally tagged set members. Only the class number appears in braces for this data type; the term CONTEXT-SPECIFIC does not appear. -- http://www.obj-sys.com/asn1tutorial/node12.html */ $class = ($type >> 6) & 3; switch ($class) { case self::CLASS_APPLICATION: case self::CLASS_PRIVATE: case self::CLASS_CONTEXT_SPECIFIC: if (!$constructed) { return array( 'type' => $class, 'constant' => $tag, 'content' => $content, 'length' => $length + $start - $current['start'] ); } $newcontent = array(); if (strlen($content)) { $newcontent = $this->_decode_ber($content, $start); $length = $newcontent['length']; if (substr($content, $length, 2) == "\0\0") { $length+= 2; } $start+= $length; $newcontent = array($newcontent); } return array( 'type' => $class, 'constant' => $tag, // the array encapsulation is for BC with the old format 'content' => $newcontent, // the only time when $content['headerlength'] isn't defined is when the length is indefinite. // the absence of $content['headerlength'] is how we know if something is indefinite or not. // technically, it could be defined to be 2 and then another indicator could be used but whatever. 'length' => $start - $current['start'] ) + $current; } $current+= array('type' => $tag); // decode UNIVERSAL tags switch ($tag) { case self::TYPE_BOOLEAN: // "The contents octets shall consist of a single octet." -- paragraph 8.2.1 //if (strlen($content) != 1) { // return false; //} $current['content'] = (bool) ord($content[0]); break; case self::TYPE_INTEGER: case self::TYPE_ENUMERATED: $current['content'] = new BigInteger($content, -256); break; case self::TYPE_REAL: // not currently supported return false; case self::TYPE_BIT_STRING: // The initial octet shall encode, as an unsigned binary integer with bit 1 as the least significant bit, // the number of unused bits in the final subsequent octet. The number shall be in the range zero to // seven. if (!$constructed) { $current['content'] = $content; } else { $temp = $this->_decode_ber($content, $start); $length-= strlen($content); $last = count($temp) - 1; for ($i = 0; $i < $last; $i++) { // all subtags should be bit strings //if ($temp[$i]['type'] != self::TYPE_BIT_STRING) { // return false; //} $current['content'].= substr($temp[$i]['content'], 1); } // all subtags should be bit strings //if ($temp[$last]['type'] != self::TYPE_BIT_STRING) { // return false; //} $current['content'] = $temp[$last]['content'][0] . $current['content'] . substr($temp[$i]['content'], 1); } break; case self::TYPE_OCTET_STRING: if (!$constructed) { $current['content'] = $content; } else { $current['content'] = ''; $length = 0; while (substr($content, 0, 2) != "\0\0") { $temp = $this->_decode_ber($content, $length + $start); $this->_string_shift($content, $temp['length']); // all subtags should be octet strings //if ($temp['type'] != self::TYPE_OCTET_STRING) { // return false; //} $current['content'].= $temp['content']; $length+= $temp['length']; } if (substr($content, 0, 2) == "\0\0") { $length+= 2; // +2 for the EOC } } break; case self::TYPE_NULL: // "The contents octets shall not contain any octets." -- paragraph 8.8.2 //if (strlen($content)) { // return false; //} break; case self::TYPE_SEQUENCE: case self::TYPE_SET: $offset = 0; $current['content'] = array(); while (strlen($content)) { // if indefinite length construction was used and we have an end-of-content string next // see paragraphs 8.1.1.3, 8.1.3.2, 8.1.3.6, 8.1.5, and (for an example) 8.6.4.2 if (!isset($current['headerlength']) && substr($content, 0, 2) == "\0\0") { $length = $offset + 2; // +2 for the EOC break 2; } $temp = $this->_decode_ber($content, $start + $offset); $this->_string_shift($content, $temp['length']); $current['content'][] = $temp; $offset+= $temp['length']; } break; case self::TYPE_OBJECT_IDENTIFIER: $temp = ord($this->_string_shift($content)); $current['content'] = sprintf('%d.%d', floor($temp / 40), $temp % 40); $valuen = 0; // process septets while (strlen($content)) { $temp = ord($this->_string_shift($content)); $valuen <<= 7; $valuen |= $temp & 0x7F; if (~$temp & 0x80) { $current['content'].= ".$valuen"; $valuen = 0; } } // the eighth bit of the last byte should not be 1 //if ($temp >> 7) { // return false; //} break; /* Each character string type shall be encoded as if it had been declared: [UNIVERSAL x] IMPLICIT OCTET STRING -- X.690-0207.pdf#page=23 (paragraph 8.21.3) Per that, we're not going to do any validation. If there are any illegal characters in the string, we don't really care */ case self::TYPE_NUMERIC_STRING: // 0,1,2,3,4,5,6,7,8,9, and space case self::TYPE_PRINTABLE_STRING: // Upper and lower case letters, digits, space, apostrophe, left/right parenthesis, plus sign, comma, // hyphen, full stop, solidus, colon, equal sign, question mark case self::TYPE_TELETEX_STRING: // The Teletex character set in CCITT's T61, space, and delete // see http://en.wikipedia.org/wiki/Teletex#Character_sets case self::TYPE_VIDEOTEX_STRING: // The Videotex character set in CCITT's T.100 and T.101, space, and delete case self::TYPE_VISIBLE_STRING: // Printing character sets of international ASCII, and space case self::TYPE_IA5_STRING: // International Alphabet 5 (International ASCII) case self::TYPE_GRAPHIC_STRING: // All registered G sets, and space case self::TYPE_GENERAL_STRING: // All registered C and G sets, space and delete case self::TYPE_UTF8_STRING: // ???? case self::TYPE_BMP_STRING: $current['content'] = $content; break; case self::TYPE_UTC_TIME: case self::TYPE_GENERALIZED_TIME: $current['content'] = $this->_decodeTime($content, $tag); default: } $start+= $length; // ie. length is the length of the full TLV encoding - it's not just the length of the value return $current + array('length' => $start - $current['start']); } /** * ASN.1 Map * * Provides an ASN.1 semantic mapping ($mapping) from a parsed BER-encoding to a human readable format. * * "Special" mappings may be applied on a per tag-name basis via $special. * * @param Array $decoded * @param Array $mapping * @param Array $special * @return Array * @access public */ function asn1map($decoded, $mapping, $special = array()) { if (isset($mapping['explicit']) && is_array($decoded['content'])) { $decoded = $decoded['content'][0]; } switch (true) { case $mapping['type'] == self::TYPE_ANY: $intype = $decoded['type']; if (isset($decoded['constant']) || !isset($this->ANYmap[$intype]) || ($this->encoded[$decoded['start']] & 0x20)) { return new Element(substr($this->encoded, $decoded['start'], $decoded['length'])); } $inmap = $this->ANYmap[$intype]; if (is_string($inmap)) { return array($inmap => $this->asn1map($decoded, array('type' => $intype) + $mapping, $special)); } break; case $mapping['type'] == self::TYPE_CHOICE: foreach ($mapping['children'] as $key => $option) { switch (true) { case isset($option['constant']) && $option['constant'] == $decoded['constant']: case !isset($option['constant']) && $option['type'] == $decoded['type']: $value = $this->asn1map($decoded, $option, $special); break; case !isset($option['constant']) && $option['type'] == self::TYPE_CHOICE: $v = $this->asn1map($decoded, $option, $special); if (isset($v)) { $value = $v; } } if (isset($value)) { if (isset($special[$key])) { $value = call_user_func($special[$key], $value); } return array($key => $value); } } return null; case isset($mapping['implicit']): case isset($mapping['explicit']): case $decoded['type'] == $mapping['type']: break; default: // if $decoded['type'] and $mapping['type'] are both strings, but different types of strings, // let it through switch (true) { case $decoded['type'] < 18: // self::TYPE_NUMERIC_STRING == 18 case $decoded['type'] > 30: // self::TYPE_BMP_STRING == 30 case $mapping['type'] < 18: case $mapping['type'] > 30: return null; } } if (isset($mapping['implicit'])) { $decoded['type'] = $mapping['type']; } switch ($decoded['type']) { case self::TYPE_SEQUENCE: $map = array(); // ignore the min and max if (isset($mapping['min']) && isset($mapping['max'])) { $child = $mapping['children']; foreach ($decoded['content'] as $content) { if (($map[] = $this->asn1map($content, $child, $special)) === null) { return null; } } return $map; } $n = count($decoded['content']); $i = 0; foreach ($mapping['children'] as $key => $child) { $maymatch = $i < $n; // Match only existing input. if ($maymatch) { $temp = $decoded['content'][$i]; if ($child['type'] != self::TYPE_CHOICE) { // Get the mapping and input class & constant. $childClass = $tempClass = self::CLASS_UNIVERSAL; $constant = null; if (isset($temp['constant'])) { $tempClass = isset($temp['class']) ? $temp['class'] : self::CLASS_CONTEXT_SPECIFIC; } if (isset($child['class'])) { $childClass = $child['class']; $constant = $child['cast']; } elseif (isset($child['constant'])) { $childClass = self::CLASS_CONTEXT_SPECIFIC; $constant = $child['constant']; } if (isset($constant) && isset($temp['constant'])) { // Can only match if constants and class match. $maymatch = $constant == $temp['constant'] && $childClass == $tempClass; } else { // Can only match if no constant expected and type matches or is generic. $maymatch = !isset($child['constant']) && array_search($child['type'], array($temp['type'], self::TYPE_ANY, self::TYPE_CHOICE)) !== false; } } } if ($maymatch) { // Attempt submapping. $candidate = $this->asn1map($temp, $child, $special); $maymatch = $candidate !== null; } if ($maymatch) { // Got the match: use it. if (isset($special[$key])) { $candidate = call_user_func($special[$key], $candidate); } $map[$key] = $candidate; $i++; } elseif (isset($child['default'])) { $map[$key] = $child['default']; // Use default. } elseif (!isset($child['optional'])) { return null; // Syntax error. } } // Fail mapping if all input items have not been consumed. return $i < $n? null: $map; // the main diff between sets and sequences is the encapsulation of the foreach in another for loop case self::TYPE_SET: $map = array(); // ignore the min and max if (isset($mapping['min']) && isset($mapping['max'])) { $child = $mapping['children']; foreach ($decoded['content'] as $content) { if (($map[] = $this->asn1map($content, $child, $special)) === null) { return null; } } return $map; } for ($i = 0; $i < count($decoded['content']); $i++) { $temp = $decoded['content'][$i]; $tempClass = self::CLASS_UNIVERSAL; if (isset($temp['constant'])) { $tempClass = isset($temp['class']) ? $temp['class'] : self::CLASS_CONTEXT_SPECIFIC; } foreach ($mapping['children'] as $key => $child) { if (isset($map[$key])) { continue; } $maymatch = true; if ($child['type'] != self::TYPE_CHOICE) { $childClass = self::CLASS_UNIVERSAL; $constant = null; if (isset($child['class'])) { $childClass = $child['class']; $constant = $child['cast']; } elseif (isset($child['constant'])) { $childClass = self::CLASS_CONTEXT_SPECIFIC; $constant = $child['constant']; } if (isset($constant) && isset($temp['constant'])) { // Can only match if constants and class match. $maymatch = $constant == $temp['constant'] && $childClass == $tempClass; } else { // Can only match if no constant expected and type matches or is generic. $maymatch = !isset($child['constant']) && array_search($child['type'], array($temp['type'], self::TYPE_ANY, self::TYPE_CHOICE)) !== false; } } if ($maymatch) { // Attempt submapping. $candidate = $this->asn1map($temp, $child, $special); $maymatch = $candidate !== null; } if (!$maymatch) { break; } // Got the match: use it. if (isset($special[$key])) { $candidate = call_user_func($special[$key], $candidate); } $map[$key] = $candidate; break; } } foreach ($mapping['children'] as $key => $child) { if (!isset($map[$key])) { if (isset($child['default'])) { $map[$key] = $child['default']; } elseif (!isset($child['optional'])) { return null; } } } return $map; case self::TYPE_OBJECT_IDENTIFIER: return isset($this->oids[$decoded['content']]) ? $this->oids[$decoded['content']] : $decoded['content']; case self::TYPE_UTC_TIME: case self::TYPE_GENERALIZED_TIME: if (isset($mapping['implicit'])) { $decoded['content'] = $this->_decodeTime($decoded['content'], $decoded['type']); } return @date($this->format, $decoded['content']); case self::TYPE_BIT_STRING: if (isset($mapping['mapping'])) { $offset = ord($decoded['content'][0]); $size = (strlen($decoded['content']) - 1) * 8 - $offset; /* From X.680-0207.pdf#page=46 (21.7): "When a "NamedBitList" is used in defining a bitstring type ASN.1 encoding rules are free to add (or remove) arbitrarily any trailing 0 bits to (or from) values that are being encoded or decoded. Application designers should therefore ensure that different semantics are not associated with such values which differ only in the number of trailing 0 bits." */ $bits = count($mapping['mapping']) == $size ? array() : array_fill(0, count($mapping['mapping']) - $size, false); for ($i = strlen($decoded['content']) - 1; $i > 0; $i--) { $current = ord($decoded['content'][$i]); for ($j = $offset; $j < 8; $j++) { $bits[] = (bool) ($current & (1 << $j)); } $offset = 0; } $values = array(); $map = array_reverse($mapping['mapping']); foreach ($map as $i => $value) { if ($bits[$i]) { $values[] = $value; } } return $values; } case self::TYPE_OCTET_STRING: return base64_encode($decoded['content']); case self::TYPE_NULL: return ''; case self::TYPE_BOOLEAN: return $decoded['content']; case self::TYPE_NUMERIC_STRING: case self::TYPE_PRINTABLE_STRING: case self::TYPE_TELETEX_STRING: case self::TYPE_VIDEOTEX_STRING: case self::TYPE_IA5_STRING: case self::TYPE_GRAPHIC_STRING: case self::TYPE_VISIBLE_STRING: case self::TYPE_GENERAL_STRING: case self::TYPE_UNIVERSAL_STRING: case self::TYPE_UTF8_STRING: case self::TYPE_BMP_STRING: return $decoded['content']; case self::TYPE_INTEGER: case self::TYPE_ENUMERATED: $temp = $decoded['content']; if (isset($mapping['implicit'])) { $temp = new BigInteger($decoded['content'], -256); } if (isset($mapping['mapping'])) { $temp = (int) $temp->toString(); return isset($mapping['mapping'][$temp]) ? $mapping['mapping'][$temp] : false; } return $temp; } } /** * ASN.1 Encode * * DER-encodes an ASN.1 semantic mapping ($mapping). Some libraries would probably call this function * an ASN.1 compiler. * * "Special" mappings can be applied via $special. * * @param String $source * @param String $mapping * @param Integer $idx * @return String * @access public */ function encodeDER($source, $mapping, $special = array()) { $this->location = array(); return $this->_encode_der($source, $mapping, null, $special); } /** * ASN.1 Encode (Helper function) * * @param String $source * @param String $mapping * @param Integer $idx * @return String * @access private */ function _encode_der($source, $mapping, $idx = null, $special = array()) { if ($source instanceof Element) { return $source->element; } // do not encode (implicitly optional) fields with value set to default if (isset($mapping['default']) && $source === $mapping['default']) { return ''; } if (isset($idx)) { if (isset($special[$idx])) { $source = call_user_func($special[$idx], $source); } $this->location[] = $idx; } $tag = $mapping['type']; switch ($tag) { case self::TYPE_SET: // Children order is not important, thus process in sequence. case self::TYPE_SEQUENCE: $tag|= 0x20; // set the constructed bit $value = ''; // ignore the min and max if (isset($mapping['min']) && isset($mapping['max'])) { $child = $mapping['children']; foreach ($source as $content) { $temp = $this->_encode_der($content, $child, null, $special); if ($temp === false) { return false; } $value.= $temp; } break; } foreach ($mapping['children'] as $key => $child) { if (!isset($source[$key])) { if (!isset($child['optional'])) { return false; } continue; } $temp = $this->_encode_der($source[$key], $child, $key, $special); if ($temp === false) { return false; } // An empty child encoding means it has been optimized out. // Else we should have at least one tag byte. if ($temp === '') { continue; } // if isset($child['constant']) is true then isset($child['optional']) should be true as well if (isset($child['constant'])) { /* From X.680-0207.pdf#page=58 (30.6): "The tagging construction specifies explicit tagging if any of the following holds: ... c) the "Tag Type" alternative is used and the value of "TagDefault" for the module is IMPLICIT TAGS or AUTOMATIC TAGS, but the type defined by "Type" is an untagged choice type, an untagged open type, or an untagged "DummyReference" (see ITU-T Rec. X.683 | ISO/IEC 8824-4, 8.3)." */ if (isset($child['explicit']) || $child['type'] == self::TYPE_CHOICE) { $subtag = chr((self::CLASS_CONTEXT_SPECIFIC << 6) | 0x20 | $child['constant']); $temp = $subtag . $this->_encodeLength(strlen($temp)) . $temp; } else { $subtag = chr((self::CLASS_CONTEXT_SPECIFIC << 6) | (ord($temp[0]) & 0x20) | $child['constant']); $temp = $subtag . substr($temp, 1); } } $value.= $temp; } break; case self::TYPE_CHOICE: $temp = false; foreach ($mapping['children'] as $key => $child) { if (!isset($source[$key])) { continue; } $temp = $this->_encode_der($source[$key], $child, $key, $special); if ($temp === false) { return false; } // An empty child encoding means it has been optimized out. // Else we should have at least one tag byte. if ($temp === '') { continue; } $tag = ord($temp[0]); // if isset($child['constant']) is true then isset($child['optional']) should be true as well if (isset($child['constant'])) { if (isset($child['explicit']) || $child['type'] == self::TYPE_CHOICE) { $subtag = chr((self::CLASS_CONTEXT_SPECIFIC << 6) | 0x20 | $child['constant']); $temp = $subtag . $this->_encodeLength(strlen($temp)) . $temp; } else { $subtag = chr((self::CLASS_CONTEXT_SPECIFIC << 6) | (ord($temp[0]) & 0x20) | $child['constant']); $temp = $subtag . substr($temp, 1); } } } if (isset($idx)) { array_pop($this->location); } if ($temp && isset($mapping['cast'])) { $temp[0] = chr(($mapping['class'] << 6) | ($tag & 0x20) | $mapping['cast']); } return $temp; case self::TYPE_INTEGER: case self::TYPE_ENUMERATED: if (!isset($mapping['mapping'])) { if (is_numeric($source)) { $source = new BigInteger($source); } $value = $source->toBytes(true); } else { $value = array_search($source, $mapping['mapping']); if ($value === false) { return false; } $value = new BigInteger($value); $value = $value->toBytes(true); } if (!strlen($value)) { $value = chr(0); } break; case self::TYPE_UTC_TIME: case self::TYPE_GENERALIZED_TIME: $format = $mapping['type'] == self::TYPE_UTC_TIME ? 'y' : 'Y'; $format.= 'mdHis'; $value = @gmdate($format, strtotime($source)) . 'Z'; break; case self::TYPE_BIT_STRING: if (isset($mapping['mapping'])) { $bits = array_fill(0, count($mapping['mapping']), 0); $size = 0; for ($i = 0; $i < count($mapping['mapping']); $i++) { if (in_array($mapping['mapping'][$i], $source)) { $bits[$i] = 1; $size = $i; } } if (isset($mapping['min']) && $mapping['min'] >= 1 && $size < $mapping['min']) { $size = $mapping['min'] - 1; } $offset = 8 - (($size + 1) & 7); $offset = $offset !== 8 ? $offset : 0; $value = chr($offset); for ($i = $size + 1; $i < count($mapping['mapping']); $i++) { unset($bits[$i]); } $bits = implode('', array_pad($bits, $size + $offset + 1, 0)); $bytes = explode(' ', rtrim(chunk_split($bits, 8, ' '))); foreach ($bytes as $byte) { $value.= chr(bindec($byte)); } break; } case self::TYPE_OCTET_STRING: /* The initial octet shall encode, as an unsigned binary integer with bit 1 as the least significant bit, the number of unused bits in the final subsequent octet. The number shall be in the range zero to seven. -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#page=16 */ $value = base64_decode($source); break; case self::TYPE_OBJECT_IDENTIFIER: $oid = preg_match('#(?:\d+\.)+#', $source) ? $source : array_search($source, $this->oids); if ($oid === false) { user_error('Invalid OID'); return false; } $value = ''; $parts = explode('.', $oid); $value = chr(40 * $parts[0] + $parts[1]); for ($i = 2; $i < count($parts); $i++) { $temp = ''; if (!$parts[$i]) { $temp = "\0"; } else { while ($parts[$i]) { $temp = chr(0x80 | ($parts[$i] & 0x7F)) . $temp; $parts[$i] >>= 7; } $temp[strlen($temp) - 1] = $temp[strlen($temp) - 1] & chr(0x7F); } $value.= $temp; } break; case self::TYPE_ANY: $loc = $this->location; if (isset($idx)) { array_pop($this->location); } switch (true) { case !isset($source): return $this->_encode_der(null, array('type' => self::TYPE_NULL) + $mapping, null, $special); case is_int($source): case $source instanceof BigInteger: return $this->_encode_der($source, array('type' => self::TYPE_INTEGER) + $mapping, null, $special); case is_float($source): return $this->_encode_der($source, array('type' => self::TYPE_REAL) + $mapping, null, $special); case is_bool($source): return $this->_encode_der($source, array('type' => self::TYPE_BOOLEAN) + $mapping, null, $special); case is_array($source) && count($source) == 1: $typename = implode('', array_keys($source)); $outtype = array_search($typename, $this->ANYmap, true); if ($outtype !== false) { return $this->_encode_der($source[$typename], array('type' => $outtype) + $mapping, null, $special); } } $filters = $this->filters; foreach ($loc as $part) { if (!isset($filters[$part])) { $filters = false; break; } $filters = $filters[$part]; } if ($filters === false) { user_error('No filters defined for ' . implode('/', $loc)); return false; } return $this->_encode_der($source, $filters + $mapping, null, $special); case self::TYPE_NULL: $value = ''; break; case self::TYPE_NUMERIC_STRING: case self::TYPE_TELETEX_STRING: case self::TYPE_PRINTABLE_STRING: case self::TYPE_UNIVERSAL_STRING: case self::TYPE_UTF8_STRING: case self::TYPE_BMP_STRING: case self::TYPE_IA5_STRING: case self::TYPE_VISIBLE_STRING: case self::TYPE_VIDEOTEX_STRING: case self::TYPE_GRAPHIC_STRING: case self::TYPE_GENERAL_STRING: $value = $source; break; case self::TYPE_BOOLEAN: $value = $source ? "\xFF" : "\x00"; break; default: user_error('Mapping provides no type definition for ' . implode('/', $this->location)); return false; } if (isset($idx)) { array_pop($this->location); } if (isset($mapping['cast'])) { if (isset($mapping['explicit']) || $mapping['type'] == self::TYPE_CHOICE) { $value = chr($tag) . $this->_encodeLength(strlen($value)) . $value; $tag = ($mapping['class'] << 6) | 0x20 | $mapping['cast']; } else { $tag = ($mapping['class'] << 6) | (ord($temp[0]) & 0x20) | $mapping['cast']; } } return chr($tag) . $this->_encodeLength(strlen($value)) . $value; } /** * DER-encode the length * * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information. * * @access private * @param Integer $length * @return String */ function _encodeLength($length) { if ($length <= 0x7F) { return chr($length); } $temp = ltrim(pack('N', $length), chr(0)); return pack('Ca*', 0x80 | strlen($temp), $temp); } /** * BER-decode the time * * Called by _decode_ber() and in the case of implicit tags asn1map(). * * @access private * @param String $content * @param Integer $tag * @return String */ function _decodeTime($content, $tag) { /* UTCTime: http://tools.ietf.org/html/rfc5280#section-4.1.2.5.1 http://www.obj-sys.com/asn1tutorial/node15.html GeneralizedTime: http://tools.ietf.org/html/rfc5280#section-4.1.2.5.2 http://www.obj-sys.com/asn1tutorial/node14.html */ $pattern = $tag == self::TYPE_UTC_TIME ? '#(..)(..)(..)(..)(..)(..)(.*)#' : '#(....)(..)(..)(..)(..)(..).*([Z+-].*)$#'; preg_match($pattern, $content, $matches); list(, $year, $month, $day, $hour, $minute, $second, $timezone) = $matches; if ($tag == self::TYPE_UTC_TIME) { $year = $year >= 50 ? "19$year" : "20$year"; } if ($timezone == 'Z') { $mktime = 'gmmktime'; $timezone = 0; } elseif (preg_match('#([+-])(\d\d)(\d\d)#', $timezone, $matches)) { $mktime = 'gmmktime'; $timezone = 60 * $matches[3] + 3600 * $matches[2]; if ($matches[1] == '-') { $timezone = -$timezone; } } else { $mktime = 'mktime'; $timezone = 0; } return @$mktime($hour, $minute, $second, $month, $day, $year) + $timezone; } /** * Set the time format * * Sets the time / date format for asn1map(). * * @access public * @param String $format */ function setTimeFormat($format) { $this->format = $format; } /** * Load OIDs * * Load the relevant OIDs for a particular ASN.1 semantic mapping. * * @access public * @param Array $oids */ function loadOIDs($oids) { $this->oids = $oids; } /** * Load filters * * See \phpseclib\File\X509, etc, for an example. * * @access public * @param Array $filters */ function loadFilters($filters) { $this->filters = $filters; } /** * String Shift * * Inspired by array_shift * * @param String $string * @param optional Integer $index * @return String * @access private */ function _string_shift(&$string, $index = 1) { $substr = substr($string, 0, $index); $string = substr($string, $index); return $substr; } /** * String type conversion * * This is a lazy conversion, dealing only with character size. * No real conversion table is used. * * @param String $in * @param optional Integer $from * @param optional Integer $to * @return String * @access public */ function convert($in, $from = self::TYPE_UTF8_STRING, $to = self::TYPE_UTF8_STRING) { if (!isset($this->stringTypeSize[$from]) || !isset($this->stringTypeSize[$to])) { return false; } $insize = $this->stringTypeSize[$from]; $outsize = $this->stringTypeSize[$to]; $inlength = strlen($in); $out = ''; for ($i = 0; $i < $inlength;) { if ($inlength - $i < $insize) { return false; } // Get an input character as a 32-bit value. $c = ord($in[$i++]); switch (true) { case $insize == 4: $c = ($c << 8) | ord($in[$i++]); $c = ($c << 8) | ord($in[$i++]); case $insize == 2: $c = ($c << 8) | ord($in[$i++]); case $insize == 1: break; case ($c & 0x80) == 0x00: break; case ($c & 0x40) == 0x00: return false; default: $bit = 6; do { if ($bit > 25 || $i >= $inlength || (ord($in[$i]) & 0xC0) != 0x80) { return false; } $c = ($c << 6) | (ord($in[$i++]) & 0x3F); $bit += 5; $mask = 1 << $bit; } while ($c & $bit); $c &= $mask - 1; break; } // Convert and append the character to output string. $v = ''; switch (true) { case $outsize == 4: $v .= chr($c & 0xFF); $c >>= 8; $v .= chr($c & 0xFF); $c >>= 8; case $outsize == 2: $v .= chr($c & 0xFF); $c >>= 8; case $outsize == 1: $v .= chr($c & 0xFF); $c >>= 8; if ($c) { return false; } break; case ($c & 0x80000000) != 0: return false; case $c >= 0x04000000: $v .= chr(0x80 | ($c & 0x3F)); $c = ($c >> 6) | 0x04000000; case $c >= 0x00200000: $v .= chr(0x80 | ($c & 0x3F)); $c = ($c >> 6) | 0x00200000; case $c >= 0x00010000: $v .= chr(0x80 | ($c & 0x3F)); $c = ($c >> 6) | 0x00010000; case $c >= 0x00000800: $v .= chr(0x80 | ($c & 0x3F)); $c = ($c >> 6) | 0x00000800; case $c >= 0x00000080: $v .= chr(0x80 | ($c & 0x3F)); $c = ($c >> 6) | 0x000000C0; default: $v .= chr($c); break; } $out .= strrev($v); } return $out; } } * @copyright 2012 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\File; use phpseclib\Crypt\Hash; use phpseclib\Crypt\RSA; use phpseclib\File\ASN1; use phpseclib\File\ASN1\Element; use phpseclib\Math\BigInteger; /** * Pure-PHP X.509 Parser * * @package X509 * @author Jim Wigginton * @access public */ class X509 { /** * Flag to only accept signatures signed by certificate authorities * * Not really used anymore but retained all the same to suppress E_NOTICEs from old installs * * @access public */ const VALIDATE_SIGNATURE_BY_CA = 1; /**#@+ * @access public * @see \phpseclib\File\X509::getDN() */ /** * Return internal array representation */ const DN_ARRAY = 0; /** * Return string */ const DN_STRING = 1; /** * Return ASN.1 name string */ const DN_ASN1 = 2; /** * Return OpenSSL compatible array */ const DN_OPENSSL = 3; /** * Return canonical ASN.1 RDNs string */ const DN_CANON = 4; /** * Return name hash for file indexing */ const DN_HASH = 5; /**#@-*/ /**#@+ * @access public * @see \phpseclib\File\X509::saveX509() * @see \phpseclib\File\X509::saveCSR() * @see \phpseclib\File\X509::saveCRL() */ /** * Save as PEM * * ie. a base64-encoded PEM with a header and a footer */ const FORMAT_PEM = 0; /** * Save as DER */ const FORMAT_DER = 1; /** * Save as a SPKAC * * Only works on CSRs. Not currently supported. */ const FORMAT_SPKAC = 2; /**#@-*/ /** * Attribute value disposition. * If disposition is >= 0, this is the index of the target value. */ const ATTR_ALL = -1; // All attribute values (array). const ATTR_APPEND = -2; // Add a value. const ATTR_REPLACE = -3; // Clear first, then add a value. /** * ASN.1 syntax for X.509 certificates * * @var Array * @access private */ var $Certificate; /**#@+ * ASN.1 syntax for various extensions * * @access private */ var $DirectoryString; var $PKCS9String; var $AttributeValue; var $Extensions; var $KeyUsage; var $ExtKeyUsageSyntax; var $BasicConstraints; var $KeyIdentifier; var $CRLDistributionPoints; var $AuthorityKeyIdentifier; var $CertificatePolicies; var $AuthorityInfoAccessSyntax; var $SubjectAltName; var $PrivateKeyUsagePeriod; var $IssuerAltName; var $PolicyMappings; var $NameConstraints; var $CPSuri; var $UserNotice; var $netscape_cert_type; var $netscape_comment; var $netscape_ca_policy_url; var $Name; var $RelativeDistinguishedName; var $CRLNumber; var $CRLReason; var $IssuingDistributionPoint; var $InvalidityDate; var $CertificateIssuer; var $HoldInstructionCode; var $SignedPublicKeyAndChallenge; /**#@-*/ /** * ASN.1 syntax for Certificate Signing Requests (RFC2986) * * @var Array * @access private */ var $CertificationRequest; /** * ASN.1 syntax for Certificate Revocation Lists (RFC5280) * * @var Array * @access private */ var $CertificateList; /** * Distinguished Name * * @var Array * @access private */ var $dn; /** * Public key * * @var String * @access private */ var $publicKey; /** * Private key * * @var String * @access private */ var $privateKey; /** * Object identifiers for X.509 certificates * * @var Array * @access private * @link http://en.wikipedia.org/wiki/Object_identifier */ var $oids; /** * The certificate authorities * * @var Array * @access private */ var $CAs; /** * The currently loaded certificate * * @var Array * @access private */ var $currentCert; /** * The signature subject * * There's no guarantee \phpseclib\File\X509 is going to reencode an X.509 cert in the same way it was originally * encoded so we take save the portion of the original cert that the signature would have made for. * * @var String * @access private */ var $signatureSubject; /** * Certificate Start Date * * @var String * @access private */ var $startDate; /** * Certificate End Date * * @var String * @access private */ var $endDate; /** * Serial Number * * @var String * @access private */ var $serialNumber; /** * Key Identifier * * See {@link http://tools.ietf.org/html/rfc5280#section-4.2.1.1 RFC5280#section-4.2.1.1} and * {@link http://tools.ietf.org/html/rfc5280#section-4.2.1.2 RFC5280#section-4.2.1.2}. * * @var String * @access private */ var $currentKeyIdentifier; /** * CA Flag * * @var Boolean * @access private */ var $caFlag = false; /** * SPKAC Challenge * * @var String * @access private */ var $challenge; /** * Default Constructor. * * @return \phpseclib\File\X509 * @access public */ function __construct() { // Explicitly Tagged Module, 1988 Syntax // http://tools.ietf.org/html/rfc5280#appendix-A.1 $this->DirectoryString = array( 'type' => ASN1::TYPE_CHOICE, 'children' => array( 'teletexString' => array('type' => ASN1::TYPE_TELETEX_STRING), 'printableString' => array('type' => ASN1::TYPE_PRINTABLE_STRING), 'universalString' => array('type' => ASN1::TYPE_UNIVERSAL_STRING), 'utf8String' => array('type' => ASN1::TYPE_UTF8_STRING), 'bmpString' => array('type' => ASN1::TYPE_BMP_STRING) ) ); $this->PKCS9String = array( 'type' => ASN1::TYPE_CHOICE, 'children' => array( 'ia5String' => array('type' => ASN1::TYPE_IA5_STRING), 'directoryString' => $this->DirectoryString ) ); $this->AttributeValue = array('type' => ASN1::TYPE_ANY); $AttributeType = array('type' => ASN1::TYPE_OBJECT_IDENTIFIER); $AttributeTypeAndValue = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'type' => $AttributeType, 'value'=> $this->AttributeValue ) ); /* In practice, RDNs containing multiple name-value pairs (called "multivalued RDNs") are rare, but they can be useful at times when either there is no unique attribute in the entry or you want to ensure that the entry's DN contains some useful identifying information. - https://www.opends.org/wiki/page/DefinitionRelativeDistinguishedName */ $this->RelativeDistinguishedName = array( 'type' => ASN1::TYPE_SET, 'min' => 1, 'max' => -1, 'children' => $AttributeTypeAndValue ); // http://tools.ietf.org/html/rfc5280#section-4.1.2.4 $RDNSequence = array( 'type' => ASN1::TYPE_SEQUENCE, // RDNSequence does not define a min or a max, which means it doesn't have one 'min' => 0, 'max' => -1, 'children' => $this->RelativeDistinguishedName ); $this->Name = array( 'type' => ASN1::TYPE_CHOICE, 'children' => array( 'rdnSequence' => $RDNSequence ) ); // http://tools.ietf.org/html/rfc5280#section-4.1.1.2 $AlgorithmIdentifier = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'algorithm' => array('type' => ASN1::TYPE_OBJECT_IDENTIFIER), 'parameters' => array( 'type' => ASN1::TYPE_ANY, 'optional' => true ) ) ); /* A certificate using system MUST reject the certificate if it encounters a critical extension it does not recognize; however, a non-critical extension may be ignored if it is not recognized. http://tools.ietf.org/html/rfc5280#section-4.2 */ $Extension = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'extnId' => array('type' => ASN1::TYPE_OBJECT_IDENTIFIER), 'critical' => array( 'type' => ASN1::TYPE_BOOLEAN, 'optional' => true, 'default' => false ), 'extnValue' => array('type' => ASN1::TYPE_OCTET_STRING) ) ); $this->Extensions = array( 'type' => ASN1::TYPE_SEQUENCE, 'min' => 1, // technically, it's MAX, but we'll assume anything < 0 is MAX 'max' => -1, // if 'children' isn't an array then 'min' and 'max' must be defined 'children' => $Extension ); $SubjectPublicKeyInfo = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'algorithm' => $AlgorithmIdentifier, 'subjectPublicKey' => array('type' => ASN1::TYPE_BIT_STRING) ) ); $UniqueIdentifier = array('type' => ASN1::TYPE_BIT_STRING); $Time = array( 'type' => ASN1::TYPE_CHOICE, 'children' => array( 'utcTime' => array('type' => ASN1::TYPE_UTC_TIME), 'generalTime' => array('type' => ASN1::TYPE_GENERALIZED_TIME) ) ); // http://tools.ietf.org/html/rfc5280#section-4.1.2.5 $Validity = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'notBefore' => $Time, 'notAfter' => $Time ) ); $CertificateSerialNumber = array('type' => ASN1::TYPE_INTEGER); $Version = array( 'type' => ASN1::TYPE_INTEGER, 'mapping' => array('v1', 'v2', 'v3') ); // assert($TBSCertificate['children']['signature'] == $Certificate['children']['signatureAlgorithm']) $TBSCertificate = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( // technically, default implies optional, but we'll define it as being optional, none-the-less, just to // reenforce that fact 'version' => array( 'constant' => 0, 'optional' => true, 'explicit' => true, 'default' => 'v1' ) + $Version, 'serialNumber' => $CertificateSerialNumber, 'signature' => $AlgorithmIdentifier, 'issuer' => $this->Name, 'validity' => $Validity, 'subject' => $this->Name, 'subjectPublicKeyInfo' => $SubjectPublicKeyInfo, // implicit means that the T in the TLV structure is to be rewritten, regardless of the type 'issuerUniqueID' => array( 'constant' => 1, 'optional' => true, 'implicit' => true ) + $UniqueIdentifier, 'subjectUniqueID' => array( 'constant' => 2, 'optional' => true, 'implicit' => true ) + $UniqueIdentifier, // doesn't use the EXPLICIT keyword but if // it's not IMPLICIT, it's EXPLICIT 'extensions' => array( 'constant' => 3, 'optional' => true, 'explicit' => true ) + $this->Extensions ) ); $this->Certificate = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'tbsCertificate' => $TBSCertificate, 'signatureAlgorithm' => $AlgorithmIdentifier, 'signature' => array('type' => ASN1::TYPE_BIT_STRING) ) ); $this->KeyUsage = array( 'type' => ASN1::TYPE_BIT_STRING, 'mapping' => array( 'digitalSignature', 'nonRepudiation', 'keyEncipherment', 'dataEncipherment', 'keyAgreement', 'keyCertSign', 'cRLSign', 'encipherOnly', 'decipherOnly' ) ); $this->BasicConstraints = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'cA' => array( 'type' => ASN1::TYPE_BOOLEAN, 'optional' => true, 'default' => false ), 'pathLenConstraint' => array( 'type' => ASN1::TYPE_INTEGER, 'optional' => true ) ) ); $this->KeyIdentifier = array('type' => ASN1::TYPE_OCTET_STRING); $OrganizationalUnitNames = array( 'type' => ASN1::TYPE_SEQUENCE, 'min' => 1, 'max' => 4, // ub-organizational-units 'children' => array('type' => ASN1::TYPE_PRINTABLE_STRING) ); $PersonalName = array( 'type' => ASN1::TYPE_SET, 'children' => array( 'surname' => array( 'type' => ASN1::TYPE_PRINTABLE_STRING, 'constant' => 0, 'optional' => true, 'implicit' => true ), 'given-name' => array( 'type' => ASN1::TYPE_PRINTABLE_STRING, 'constant' => 1, 'optional' => true, 'implicit' => true ), 'initials' => array( 'type' => ASN1::TYPE_PRINTABLE_STRING, 'constant' => 2, 'optional' => true, 'implicit' => true ), 'generation-qualifier' => array( 'type' => ASN1::TYPE_PRINTABLE_STRING, 'constant' => 3, 'optional' => true, 'implicit' => true ) ) ); $NumericUserIdentifier = array('type' => ASN1::TYPE_NUMERIC_STRING); $OrganizationName = array('type' => ASN1::TYPE_PRINTABLE_STRING); $PrivateDomainName = array( 'type' => ASN1::TYPE_CHOICE, 'children' => array( 'numeric' => array('type' => ASN1::TYPE_NUMERIC_STRING), 'printable' => array('type' => ASN1::TYPE_PRINTABLE_STRING) ) ); $TerminalIdentifier = array('type' => ASN1::TYPE_PRINTABLE_STRING); $NetworkAddress = array('type' => ASN1::TYPE_NUMERIC_STRING); $AdministrationDomainName = array( 'type' => ASN1::TYPE_CHOICE, // if class isn't present it's assumed to be \phpseclib\File\ASN1::CLASS_UNIVERSAL or // (if constant is present) \phpseclib\File\ASN1::CLASS_CONTEXT_SPECIFIC 'class' => ASN1::CLASS_APPLICATION, 'cast' => 2, 'children' => array( 'numeric' => array('type' => ASN1::TYPE_NUMERIC_STRING), 'printable' => array('type' => ASN1::TYPE_PRINTABLE_STRING) ) ); $CountryName = array( 'type' => ASN1::TYPE_CHOICE, // if class isn't present it's assumed to be \phpseclib\File\ASN1::CLASS_UNIVERSAL or // (if constant is present) \phpseclib\File\ASN1::CLASS_CONTEXT_SPECIFIC 'class' => ASN1::CLASS_APPLICATION, 'cast' => 1, 'children' => array( 'x121-dcc-code' => array('type' => ASN1::TYPE_NUMERIC_STRING), 'iso-3166-alpha2-code' => array('type' => ASN1::TYPE_PRINTABLE_STRING) ) ); $AnotherName = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'type-id' => array('type' => ASN1::TYPE_OBJECT_IDENTIFIER), 'value' => array( 'type' => ASN1::TYPE_ANY, 'constant' => 0, 'optional' => true, 'explicit' => true ) ) ); $ExtensionAttribute = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'extension-attribute-type' => array( 'type' => ASN1::TYPE_PRINTABLE_STRING, 'constant' => 0, 'optional' => true, 'implicit' => true ), 'extension-attribute-value' => array( 'type' => ASN1::TYPE_ANY, 'constant' => 1, 'optional' => true, 'explicit' => true ) ) ); $ExtensionAttributes = array( 'type' => ASN1::TYPE_SET, 'min' => 1, 'max' => 256, // ub-extension-attributes 'children' => $ExtensionAttribute ); $BuiltInDomainDefinedAttribute = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'type' => array('type' => ASN1::TYPE_PRINTABLE_STRING), 'value' => array('type' => ASN1::TYPE_PRINTABLE_STRING) ) ); $BuiltInDomainDefinedAttributes = array( 'type' => ASN1::TYPE_SEQUENCE, 'min' => 1, 'max' => 4, // ub-domain-defined-attributes 'children' => $BuiltInDomainDefinedAttribute ); $BuiltInStandardAttributes = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'country-name' => array('optional' => true) + $CountryName, 'administration-domain-name' => array('optional' => true) + $AdministrationDomainName, 'network-address' => array( 'constant' => 0, 'optional' => true, 'implicit' => true ) + $NetworkAddress, 'terminal-identifier' => array( 'constant' => 1, 'optional' => true, 'implicit' => true ) + $TerminalIdentifier, 'private-domain-name' => array( 'constant' => 2, 'optional' => true, 'explicit' => true ) + $PrivateDomainName, 'organization-name' => array( 'constant' => 3, 'optional' => true, 'implicit' => true ) + $OrganizationName, 'numeric-user-identifier' => array( 'constant' => 4, 'optional' => true, 'implicit' => true ) + $NumericUserIdentifier, 'personal-name' => array( 'constant' => 5, 'optional' => true, 'implicit' => true ) + $PersonalName, 'organizational-unit-names' => array( 'constant' => 6, 'optional' => true, 'implicit' => true ) + $OrganizationalUnitNames ) ); $ORAddress = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'built-in-standard-attributes' => $BuiltInStandardAttributes, 'built-in-domain-defined-attributes' => array('optional' => true) + $BuiltInDomainDefinedAttributes, 'extension-attributes' => array('optional' => true) + $ExtensionAttributes ) ); $EDIPartyName = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'nameAssigner' => array( 'constant' => 0, 'optional' => true, 'implicit' => true ) + $this->DirectoryString, // partyName is technically required but \phpseclib\File\ASN1 doesn't currently support non-optional constants and // setting it to optional gets the job done in any event. 'partyName' => array( 'constant' => 1, 'optional' => true, 'implicit' => true ) + $this->DirectoryString ) ); $GeneralName = array( 'type' => ASN1::TYPE_CHOICE, 'children' => array( 'otherName' => array( 'constant' => 0, 'optional' => true, 'implicit' => true ) + $AnotherName, 'rfc822Name' => array( 'type' => ASN1::TYPE_IA5_STRING, 'constant' => 1, 'optional' => true, 'implicit' => true ), 'dNSName' => array( 'type' => ASN1::TYPE_IA5_STRING, 'constant' => 2, 'optional' => true, 'implicit' => true ), 'x400Address' => array( 'constant' => 3, 'optional' => true, 'implicit' => true ) + $ORAddress, 'directoryName' => array( 'constant' => 4, 'optional' => true, 'explicit' => true ) + $this->Name, 'ediPartyName' => array( 'constant' => 5, 'optional' => true, 'implicit' => true ) + $EDIPartyName, 'uniformResourceIdentifier' => array( 'type' => ASN1::TYPE_IA5_STRING, 'constant' => 6, 'optional' => true, 'implicit' => true ), 'iPAddress' => array( 'type' => ASN1::TYPE_OCTET_STRING, 'constant' => 7, 'optional' => true, 'implicit' => true ), 'registeredID' => array( 'type' => ASN1::TYPE_OBJECT_IDENTIFIER, 'constant' => 8, 'optional' => true, 'implicit' => true ) ) ); $GeneralNames = array( 'type' => ASN1::TYPE_SEQUENCE, 'min' => 1, 'max' => -1, 'children' => $GeneralName ); $this->IssuerAltName = $GeneralNames; $ReasonFlags = array( 'type' => ASN1::TYPE_BIT_STRING, 'mapping' => array( 'unused', 'keyCompromise', 'cACompromise', 'affiliationChanged', 'superseded', 'cessationOfOperation', 'certificateHold', 'privilegeWithdrawn', 'aACompromise' ) ); $DistributionPointName = array( 'type' => ASN1::TYPE_CHOICE, 'children' => array( 'fullName' => array( 'constant' => 0, 'optional' => true, 'implicit' => true ) + $GeneralNames, 'nameRelativeToCRLIssuer' => array( 'constant' => 1, 'optional' => true, 'implicit' => true ) + $this->RelativeDistinguishedName ) ); $DistributionPoint = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'distributionPoint' => array( 'constant' => 0, 'optional' => true, 'explicit' => true ) + $DistributionPointName, 'reasons' => array( 'constant' => 1, 'optional' => true, 'implicit' => true ) + $ReasonFlags, 'cRLIssuer' => array( 'constant' => 2, 'optional' => true, 'implicit' => true ) + $GeneralNames ) ); $this->CRLDistributionPoints = array( 'type' => ASN1::TYPE_SEQUENCE, 'min' => 1, 'max' => -1, 'children' => $DistributionPoint ); $this->AuthorityKeyIdentifier = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'keyIdentifier' => array( 'constant' => 0, 'optional' => true, 'implicit' => true ) + $this->KeyIdentifier, 'authorityCertIssuer' => array( 'constant' => 1, 'optional' => true, 'implicit' => true ) + $GeneralNames, 'authorityCertSerialNumber' => array( 'constant' => 2, 'optional' => true, 'implicit' => true ) + $CertificateSerialNumber ) ); $PolicyQualifierId = array('type' => ASN1::TYPE_OBJECT_IDENTIFIER); $PolicyQualifierInfo = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'policyQualifierId' => $PolicyQualifierId, 'qualifier' => array('type' => ASN1::TYPE_ANY) ) ); $CertPolicyId = array('type' => ASN1::TYPE_OBJECT_IDENTIFIER); $PolicyInformation = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'policyIdentifier' => $CertPolicyId, 'policyQualifiers' => array( 'type' => ASN1::TYPE_SEQUENCE, 'min' => 0, 'max' => -1, 'optional' => true, 'children' => $PolicyQualifierInfo ) ) ); $this->CertificatePolicies = array( 'type' => ASN1::TYPE_SEQUENCE, 'min' => 1, 'max' => -1, 'children' => $PolicyInformation ); $this->PolicyMappings = array( 'type' => ASN1::TYPE_SEQUENCE, 'min' => 1, 'max' => -1, 'children' => array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'issuerDomainPolicy' => $CertPolicyId, 'subjectDomainPolicy' => $CertPolicyId ) ) ); $KeyPurposeId = array('type' => ASN1::TYPE_OBJECT_IDENTIFIER); $this->ExtKeyUsageSyntax = array( 'type' => ASN1::TYPE_SEQUENCE, 'min' => 1, 'max' => -1, 'children' => $KeyPurposeId ); $AccessDescription = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'accessMethod' => array('type' => ASN1::TYPE_OBJECT_IDENTIFIER), 'accessLocation' => $GeneralName ) ); $this->AuthorityInfoAccessSyntax = array( 'type' => ASN1::TYPE_SEQUENCE, 'min' => 1, 'max' => -1, 'children' => $AccessDescription ); $this->SubjectAltName = $GeneralNames; $this->PrivateKeyUsagePeriod = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'notBefore' => array( 'constant' => 0, 'optional' => true, 'implicit' => true, 'type' => ASN1::TYPE_GENERALIZED_TIME), 'notAfter' => array( 'constant' => 1, 'optional' => true, 'implicit' => true, 'type' => ASN1::TYPE_GENERALIZED_TIME) ) ); $BaseDistance = array('type' => ASN1::TYPE_INTEGER); $GeneralSubtree = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'base' => $GeneralName, 'minimum' => array( 'constant' => 0, 'optional' => true, 'implicit' => true, 'default' => new BigInteger(0) ) + $BaseDistance, 'maximum' => array( 'constant' => 1, 'optional' => true, 'implicit' => true, ) + $BaseDistance ) ); $GeneralSubtrees = array( 'type' => ASN1::TYPE_SEQUENCE, 'min' => 1, 'max' => -1, 'children' => $GeneralSubtree ); $this->NameConstraints = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'permittedSubtrees' => array( 'constant' => 0, 'optional' => true, 'implicit' => true ) + $GeneralSubtrees, 'excludedSubtrees' => array( 'constant' => 1, 'optional' => true, 'implicit' => true ) + $GeneralSubtrees ) ); $this->CPSuri = array('type' => ASN1::TYPE_IA5_STRING); $DisplayText = array( 'type' => ASN1::TYPE_CHOICE, 'children' => array( 'ia5String' => array('type' => ASN1::TYPE_IA5_STRING), 'visibleString' => array('type' => ASN1::TYPE_VISIBLE_STRING), 'bmpString' => array('type' => ASN1::TYPE_BMP_STRING), 'utf8String' => array('type' => ASN1::TYPE_UTF8_STRING) ) ); $NoticeReference = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'organization' => $DisplayText, 'noticeNumbers' => array( 'type' => ASN1::TYPE_SEQUENCE, 'min' => 1, 'max' => 200, 'children' => array('type' => ASN1::TYPE_INTEGER) ) ) ); $this->UserNotice = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'noticeRef' => array( 'optional' => true, 'implicit' => true ) + $NoticeReference, 'explicitText' => array( 'optional' => true, 'implicit' => true ) + $DisplayText ) ); // mapping is from $this->netscape_cert_type = array( 'type' => ASN1::TYPE_BIT_STRING, 'mapping' => array( 'SSLClient', 'SSLServer', 'Email', 'ObjectSigning', 'Reserved', 'SSLCA', 'EmailCA', 'ObjectSigningCA' ) ); $this->netscape_comment = array('type' => ASN1::TYPE_IA5_STRING); $this->netscape_ca_policy_url = array('type' => ASN1::TYPE_IA5_STRING); // attribute is used in RFC2986 but we're using the RFC5280 definition $Attribute = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'type' => $AttributeType, 'value'=> array( 'type' => ASN1::TYPE_SET, 'min' => 1, 'max' => -1, 'children' => $this->AttributeValue ) ) ); // adapted from $Attributes = array( 'type' => ASN1::TYPE_SET, 'min' => 1, 'max' => -1, 'children' => $Attribute ); $CertificationRequestInfo = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'version' => array( 'type' => ASN1::TYPE_INTEGER, 'mapping' => array('v1') ), 'subject' => $this->Name, 'subjectPKInfo' => $SubjectPublicKeyInfo, 'attributes' => array( 'constant' => 0, 'optional' => true, 'implicit' => true ) + $Attributes, ) ); $this->CertificationRequest = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'certificationRequestInfo' => $CertificationRequestInfo, 'signatureAlgorithm' => $AlgorithmIdentifier, 'signature' => array('type' => ASN1::TYPE_BIT_STRING) ) ); $RevokedCertificate = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'userCertificate' => $CertificateSerialNumber, 'revocationDate' => $Time, 'crlEntryExtensions' => array( 'optional' => true ) + $this->Extensions ) ); $TBSCertList = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'version' => array( 'optional' => true, 'default' => 'v1' ) + $Version, 'signature' => $AlgorithmIdentifier, 'issuer' => $this->Name, 'thisUpdate' => $Time, 'nextUpdate' => array( 'optional' => true ) + $Time, 'revokedCertificates' => array( 'type' => ASN1::TYPE_SEQUENCE, 'optional' => true, 'min' => 0, 'max' => -1, 'children' => $RevokedCertificate ), 'crlExtensions' => array( 'constant' => 0, 'optional' => true, 'explicit' => true ) + $this->Extensions ) ); $this->CertificateList = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'tbsCertList' => $TBSCertList, 'signatureAlgorithm' => $AlgorithmIdentifier, 'signature' => array('type' => ASN1::TYPE_BIT_STRING) ) ); $this->CRLNumber = array('type' => ASN1::TYPE_INTEGER); $this->CRLReason = array('type' => ASN1::TYPE_ENUMERATED, 'mapping' => array( 'unspecified', 'keyCompromise', 'cACompromise', 'affiliationChanged', 'superseded', 'cessationOfOperation', 'certificateHold', // Value 7 is not used. 8 => 'removeFromCRL', 'privilegeWithdrawn', 'aACompromise' ) ); $this->IssuingDistributionPoint = array('type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'distributionPoint' => array( 'constant' => 0, 'optional' => true, 'explicit' => true ) + $DistributionPointName, 'onlyContainsUserCerts' => array( 'type' => ASN1::TYPE_BOOLEAN, 'constant' => 1, 'optional' => true, 'default' => false, 'implicit' => true ), 'onlyContainsCACerts' => array( 'type' => ASN1::TYPE_BOOLEAN, 'constant' => 2, 'optional' => true, 'default' => false, 'implicit' => true ), 'onlySomeReasons' => array( 'constant' => 3, 'optional' => true, 'implicit' => true ) + $ReasonFlags, 'indirectCRL' => array( 'type' => ASN1::TYPE_BOOLEAN, 'constant' => 4, 'optional' => true, 'default' => false, 'implicit' => true ), 'onlyContainsAttributeCerts' => array( 'type' => ASN1::TYPE_BOOLEAN, 'constant' => 5, 'optional' => true, 'default' => false, 'implicit' => true ) ) ); $this->InvalidityDate = array('type' => ASN1::TYPE_GENERALIZED_TIME); $this->CertificateIssuer = $GeneralNames; $this->HoldInstructionCode = array('type' => ASN1::TYPE_OBJECT_IDENTIFIER); $PublicKeyAndChallenge = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'spki' => $SubjectPublicKeyInfo, 'challenge' => array('type' => ASN1::TYPE_IA5_STRING) ) ); $this->SignedPublicKeyAndChallenge = array( 'type' => ASN1::TYPE_SEQUENCE, 'children' => array( 'publicKeyAndChallenge' => $PublicKeyAndChallenge, 'signatureAlgorithm' => $AlgorithmIdentifier, 'signature' => array('type' => ASN1::TYPE_BIT_STRING) ) ); // OIDs from RFC5280 and those RFCs mentioned in RFC5280#section-4.1.1.2 $this->oids = array( '1.3.6.1.5.5.7' => 'id-pkix', '1.3.6.1.5.5.7.1' => 'id-pe', '1.3.6.1.5.5.7.2' => 'id-qt', '1.3.6.1.5.5.7.3' => 'id-kp', '1.3.6.1.5.5.7.48' => 'id-ad', '1.3.6.1.5.5.7.2.1' => 'id-qt-cps', '1.3.6.1.5.5.7.2.2' => 'id-qt-unotice', '1.3.6.1.5.5.7.48.1' =>'id-ad-ocsp', '1.3.6.1.5.5.7.48.2' => 'id-ad-caIssuers', '1.3.6.1.5.5.7.48.3' => 'id-ad-timeStamping', '1.3.6.1.5.5.7.48.5' => 'id-ad-caRepository', '2.5.4' => 'id-at', '2.5.4.41' => 'id-at-name', '2.5.4.4' => 'id-at-surname', '2.5.4.42' => 'id-at-givenName', '2.5.4.43' => 'id-at-initials', '2.5.4.44' => 'id-at-generationQualifier', '2.5.4.3' => 'id-at-commonName', '2.5.4.7' => 'id-at-localityName', '2.5.4.8' => 'id-at-stateOrProvinceName', '2.5.4.10' => 'id-at-organizationName', '2.5.4.11' => 'id-at-organizationalUnitName', '2.5.4.12' => 'id-at-title', '2.5.4.13' => 'id-at-description', '2.5.4.46' => 'id-at-dnQualifier', '2.5.4.6' => 'id-at-countryName', '2.5.4.5' => 'id-at-serialNumber', '2.5.4.65' => 'id-at-pseudonym', '2.5.4.17' => 'id-at-postalCode', '2.5.4.9' => 'id-at-streetAddress', '2.5.4.45' => 'id-at-uniqueIdentifier', '2.5.4.72' => 'id-at-role', '0.9.2342.19200300.100.1.25' => 'id-domainComponent', '1.2.840.113549.1.9' => 'pkcs-9', '1.2.840.113549.1.9.1' => 'pkcs-9-at-emailAddress', '2.5.29' => 'id-ce', '2.5.29.35' => 'id-ce-authorityKeyIdentifier', '2.5.29.14' => 'id-ce-subjectKeyIdentifier', '2.5.29.15' => 'id-ce-keyUsage', '2.5.29.16' => 'id-ce-privateKeyUsagePeriod', '2.5.29.32' => 'id-ce-certificatePolicies', '2.5.29.32.0' => 'anyPolicy', '2.5.29.33' => 'id-ce-policyMappings', '2.5.29.17' => 'id-ce-subjectAltName', '2.5.29.18' => 'id-ce-issuerAltName', '2.5.29.9' => 'id-ce-subjectDirectoryAttributes', '2.5.29.19' => 'id-ce-basicConstraints', '2.5.29.30' => 'id-ce-nameConstraints', '2.5.29.36' => 'id-ce-policyConstraints', '2.5.29.31' => 'id-ce-cRLDistributionPoints', '2.5.29.37' => 'id-ce-extKeyUsage', '2.5.29.37.0' => 'anyExtendedKeyUsage', '1.3.6.1.5.5.7.3.1' => 'id-kp-serverAuth', '1.3.6.1.5.5.7.3.2' => 'id-kp-clientAuth', '1.3.6.1.5.5.7.3.3' => 'id-kp-codeSigning', '1.3.6.1.5.5.7.3.4' => 'id-kp-emailProtection', '1.3.6.1.5.5.7.3.8' => 'id-kp-timeStamping', '1.3.6.1.5.5.7.3.9' => 'id-kp-OCSPSigning', '2.5.29.54' => 'id-ce-inhibitAnyPolicy', '2.5.29.46' => 'id-ce-freshestCRL', '1.3.6.1.5.5.7.1.1' => 'id-pe-authorityInfoAccess', '1.3.6.1.5.5.7.1.11' => 'id-pe-subjectInfoAccess', '2.5.29.20' => 'id-ce-cRLNumber', '2.5.29.28' => 'id-ce-issuingDistributionPoint', '2.5.29.27' => 'id-ce-deltaCRLIndicator', '2.5.29.21' => 'id-ce-cRLReasons', '2.5.29.29' => 'id-ce-certificateIssuer', '2.5.29.23' => 'id-ce-holdInstructionCode', '1.2.840.10040.2' => 'holdInstruction', '1.2.840.10040.2.1' => 'id-holdinstruction-none', '1.2.840.10040.2.2' => 'id-holdinstruction-callissuer', '1.2.840.10040.2.3' => 'id-holdinstruction-reject', '2.5.29.24' => 'id-ce-invalidityDate', '1.2.840.113549.2.2' => 'md2', '1.2.840.113549.2.5' => 'md5', '1.3.14.3.2.26' => 'id-sha1', '1.2.840.10040.4.1' => 'id-dsa', '1.2.840.10040.4.3' => 'id-dsa-with-sha1', '1.2.840.113549.1.1' => 'pkcs-1', '1.2.840.113549.1.1.1' => 'rsaEncryption', '1.2.840.113549.1.1.2' => 'md2WithRSAEncryption', '1.2.840.113549.1.1.4' => 'md5WithRSAEncryption', '1.2.840.113549.1.1.5' => 'sha1WithRSAEncryption', '1.2.840.10046.2.1' => 'dhpublicnumber', '2.16.840.1.101.2.1.1.22' => 'id-keyExchangeAlgorithm', '1.2.840.10045' => 'ansi-X9-62', '1.2.840.10045.4' => 'id-ecSigType', '1.2.840.10045.4.1' => 'ecdsa-with-SHA1', '1.2.840.10045.1' => 'id-fieldType', '1.2.840.10045.1.1' => 'prime-field', '1.2.840.10045.1.2' => 'characteristic-two-field', '1.2.840.10045.1.2.3' => 'id-characteristic-two-basis', '1.2.840.10045.1.2.3.1' => 'gnBasis', '1.2.840.10045.1.2.3.2' => 'tpBasis', '1.2.840.10045.1.2.3.3' => 'ppBasis', '1.2.840.10045.2' => 'id-publicKeyType', '1.2.840.10045.2.1' => 'id-ecPublicKey', '1.2.840.10045.3' => 'ellipticCurve', '1.2.840.10045.3.0' => 'c-TwoCurve', '1.2.840.10045.3.0.1' => 'c2pnb163v1', '1.2.840.10045.3.0.2' => 'c2pnb163v2', '1.2.840.10045.3.0.3' => 'c2pnb163v3', '1.2.840.10045.3.0.4' => 'c2pnb176w1', '1.2.840.10045.3.0.5' => 'c2pnb191v1', '1.2.840.10045.3.0.6' => 'c2pnb191v2', '1.2.840.10045.3.0.7' => 'c2pnb191v3', '1.2.840.10045.3.0.8' => 'c2pnb191v4', '1.2.840.10045.3.0.9' => 'c2pnb191v5', '1.2.840.10045.3.0.10' => 'c2pnb208w1', '1.2.840.10045.3.0.11' => 'c2pnb239v1', '1.2.840.10045.3.0.12' => 'c2pnb239v2', '1.2.840.10045.3.0.13' => 'c2pnb239v3', '1.2.840.10045.3.0.14' => 'c2pnb239v4', '1.2.840.10045.3.0.15' => 'c2pnb239v5', '1.2.840.10045.3.0.16' => 'c2pnb272w1', '1.2.840.10045.3.0.17' => 'c2pnb304w1', '1.2.840.10045.3.0.18' => 'c2pnb359v1', '1.2.840.10045.3.0.19' => 'c2pnb368w1', '1.2.840.10045.3.0.20' => 'c2pnb431r1', '1.2.840.10045.3.1' => 'primeCurve', '1.2.840.10045.3.1.1' => 'prime192v1', '1.2.840.10045.3.1.2' => 'prime192v2', '1.2.840.10045.3.1.3' => 'prime192v3', '1.2.840.10045.3.1.4' => 'prime239v1', '1.2.840.10045.3.1.5' => 'prime239v2', '1.2.840.10045.3.1.6' => 'prime239v3', '1.2.840.10045.3.1.7' => 'prime256v1', '1.2.840.113549.1.1.7' => 'id-RSAES-OAEP', '1.2.840.113549.1.1.9' => 'id-pSpecified', '1.2.840.113549.1.1.10' => 'id-RSASSA-PSS', '1.2.840.113549.1.1.8' => 'id-mgf1', '1.2.840.113549.1.1.14' => 'sha224WithRSAEncryption', '1.2.840.113549.1.1.11' => 'sha256WithRSAEncryption', '1.2.840.113549.1.1.12' => 'sha384WithRSAEncryption', '1.2.840.113549.1.1.13' => 'sha512WithRSAEncryption', '2.16.840.1.101.3.4.2.4' => 'id-sha224', '2.16.840.1.101.3.4.2.1' => 'id-sha256', '2.16.840.1.101.3.4.2.2' => 'id-sha384', '2.16.840.1.101.3.4.2.3' => 'id-sha512', '1.2.643.2.2.4' => 'id-GostR3411-94-with-GostR3410-94', '1.2.643.2.2.3' => 'id-GostR3411-94-with-GostR3410-2001', '1.2.643.2.2.20' => 'id-GostR3410-2001', '1.2.643.2.2.19' => 'id-GostR3410-94', // Netscape Object Identifiers from "Netscape Certificate Extensions" '2.16.840.1.113730' => 'netscape', '2.16.840.1.113730.1' => 'netscape-cert-extension', '2.16.840.1.113730.1.1' => 'netscape-cert-type', '2.16.840.1.113730.1.13' => 'netscape-comment', '2.16.840.1.113730.1.8' => 'netscape-ca-policy-url', // the following are X.509 extensions not supported by phpseclib '1.3.6.1.5.5.7.1.12' => 'id-pe-logotype', '1.2.840.113533.7.65.0' => 'entrustVersInfo', '2.16.840.1.113733.1.6.9' => 'verisignPrivate', // for Certificate Signing Requests // see http://tools.ietf.org/html/rfc2985 '1.2.840.113549.1.9.2' => 'pkcs-9-at-unstructuredName', // PKCS #9 unstructured name '1.2.840.113549.1.9.7' => 'pkcs-9-at-challengePassword', // Challenge password for certificate revocations '1.2.840.113549.1.9.14' => 'pkcs-9-at-extensionRequest' // Certificate extension request ); } /** * Load X.509 certificate * * Returns an associative array describing the X.509 cert or a false if the cert failed to load * * @param String $cert * @access public * @return Mixed */ function loadX509($cert) { if (is_array($cert) && isset($cert['tbsCertificate'])) { unset($this->currentCert); unset($this->currentKeyIdentifier); $this->dn = $cert['tbsCertificate']['subject']; if (!isset($this->dn)) { return false; } $this->currentCert = $cert; $currentKeyIdentifier = $this->getExtension('id-ce-subjectKeyIdentifier'); $this->currentKeyIdentifier = is_string($currentKeyIdentifier) ? $currentKeyIdentifier : null; unset($this->signatureSubject); return $cert; } $asn1 = new ASN1(); $cert = $this->_extractBER($cert); if ($cert === false) { $this->currentCert = false; return false; } $asn1->loadOIDs($this->oids); $decoded = $asn1->decodeBER($cert); if (!empty($decoded)) { $x509 = $asn1->asn1map($decoded[0], $this->Certificate); } if (!isset($x509) || $x509 === false) { $this->currentCert = false; return false; } $this->signatureSubject = substr($cert, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']); $this->_mapInExtensions($x509, 'tbsCertificate/extensions', $asn1); $key = &$x509['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']; $key = $this->_reformatKey($x509['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['algorithm'], $key); $this->currentCert = $x509; $this->dn = $x509['tbsCertificate']['subject']; $currentKeyIdentifier = $this->getExtension('id-ce-subjectKeyIdentifier'); $this->currentKeyIdentifier = is_string($currentKeyIdentifier) ? $currentKeyIdentifier : null; return $x509; } /** * Save X.509 certificate * * @param Array $cert * @param Integer $format optional * @access public * @return String */ function saveX509($cert, $format = self::FORMAT_PEM) { if (!is_array($cert) || !isset($cert['tbsCertificate'])) { return false; } switch (true) { // "case !$a: case !$b: break; default: whatever();" is the same thing as "if ($a && $b) whatever()" case !($algorithm = $this->_subArray($cert, 'tbsCertificate/subjectPublicKeyInfo/algorithm/algorithm')): case is_object($cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']): break; default: switch ($algorithm) { case 'rsaEncryption': $cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'] = base64_encode("\0" . base64_decode(preg_replace('#-.+-|[\r\n]#', '', $cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']))); } } $asn1 = new ASN1(); $asn1->loadOIDs($this->oids); $filters = array(); $type_utf8_string = array('type' => ASN1::TYPE_UTF8_STRING); $filters['tbsCertificate']['signature']['parameters'] = $type_utf8_string; $filters['tbsCertificate']['signature']['issuer']['rdnSequence']['value'] = $type_utf8_string; $filters['tbsCertificate']['issuer']['rdnSequence']['value'] = $type_utf8_string; $filters['tbsCertificate']['subject']['rdnSequence']['value'] = $type_utf8_string; $filters['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['parameters'] = $type_utf8_string; $filters['signatureAlgorithm']['parameters'] = $type_utf8_string; $filters['authorityCertIssuer']['directoryName']['rdnSequence']['value'] = $type_utf8_string; //$filters['policyQualifiers']['qualifier'] = $type_utf8_string; $filters['distributionPoint']['fullName']['directoryName']['rdnSequence']['value'] = $type_utf8_string; $filters['directoryName']['rdnSequence']['value'] = $type_utf8_string; /* in the case of policyQualifiers/qualifier, the type has to be \phpseclib\File\ASN1::TYPE_IA5_STRING. \phpseclib\File\ASN1::TYPE_PRINTABLE_STRING will cause OpenSSL's X.509 parser to spit out random characters. */ $filters['policyQualifiers']['qualifier'] = array('type' => ASN1::TYPE_IA5_STRING); $asn1->loadFilters($filters); $this->_mapOutExtensions($cert, 'tbsCertificate/extensions', $asn1); $cert = $asn1->encodeDER($cert, $this->Certificate); switch ($format) { case self::FORMAT_DER: return $cert; // case self::FORMAT_PEM: default: return "-----BEGIN CERTIFICATE-----\r\n" . chunk_split(base64_encode($cert), 64) . '-----END CERTIFICATE-----'; } } /** * Map extension values from octet string to extension-specific internal * format. * * @param Array ref $root * @param String $path * @param Object $asn1 * @access private */ function _mapInExtensions(&$root, $path, $asn1) { $extensions = &$this->_subArray($root, $path); if (is_array($extensions)) { for ($i = 0; $i < count($extensions); $i++) { $id = $extensions[$i]['extnId']; $value = &$extensions[$i]['extnValue']; $value = base64_decode($value); $decoded = $asn1->decodeBER($value); /* [extnValue] contains the DER encoding of an ASN.1 value corresponding to the extension type identified by extnID */ $map = $this->_getMapping($id); if (!is_bool($map)) { $mapped = $asn1->asn1map($decoded[0], $map, array('iPAddress' => array($this, '_decodeIP'))); $value = $mapped === false ? $decoded[0] : $mapped; if ($id == 'id-ce-certificatePolicies') { for ($j = 0; $j < count($value); $j++) { if (!isset($value[$j]['policyQualifiers'])) { continue; } for ($k = 0; $k < count($value[$j]['policyQualifiers']); $k++) { $subid = $value[$j]['policyQualifiers'][$k]['policyQualifierId']; $map = $this->_getMapping($subid); $subvalue = &$value[$j]['policyQualifiers'][$k]['qualifier']; if ($map !== false) { $decoded = $asn1->decodeBER($subvalue); $mapped = $asn1->asn1map($decoded[0], $map); $subvalue = $mapped === false ? $decoded[0] : $mapped; } } } } } elseif ($map) { $value = base64_encode($value); } } } } /** * Map extension values from extension-specific internal format to * octet string. * * @param Array ref $root * @param String $path * @param Object $asn1 * @access private */ function _mapOutExtensions(&$root, $path, $asn1) { $extensions = &$this->_subArray($root, $path); if (is_array($extensions)) { $size = count($extensions); for ($i = 0; $i < $size; $i++) { $id = $extensions[$i]['extnId']; $value = &$extensions[$i]['extnValue']; switch ($id) { case 'id-ce-certificatePolicies': for ($j = 0; $j < count($value); $j++) { if (!isset($value[$j]['policyQualifiers'])) { continue; } for ($k = 0; $k < count($value[$j]['policyQualifiers']); $k++) { $subid = $value[$j]['policyQualifiers'][$k]['policyQualifierId']; $map = $this->_getMapping($subid); $subvalue = &$value[$j]['policyQualifiers'][$k]['qualifier']; if ($map !== false) { // by default \phpseclib\File\ASN1 will try to render qualifier as a \phpseclib\File\ASN1::TYPE_IA5_STRING since it's // actual type is \phpseclib\File\ASN1::TYPE_ANY $subvalue = new Element($asn1->encodeDER($subvalue, $map)); } } } break; case 'id-ce-authorityKeyIdentifier': // use 00 as the serial number instead of an empty string if (isset($value['authorityCertSerialNumber'])) { if ($value['authorityCertSerialNumber']->toBytes() == '') { $temp = chr((ASN1::CLASS_CONTEXT_SPECIFIC << 6) | 2) . "\1\0"; $value['authorityCertSerialNumber'] = new Element($temp); } } } /* [extnValue] contains the DER encoding of an ASN.1 value corresponding to the extension type identified by extnID */ $map = $this->_getMapping($id); if (is_bool($map)) { if (!$map) { user_error($id . ' is not a currently supported extension'); unset($extensions[$i]); } } else { $temp = $asn1->encodeDER($value, $map, array('iPAddress' => array($this, '_encodeIP'))); $value = base64_encode($temp); } } } } /** * Map attribute values from ANY type to attribute-specific internal * format. * * @param Array ref $root * @param String $path * @param Object $asn1 * @access private */ function _mapInAttributes(&$root, $path, $asn1) { $attributes = &$this->_subArray($root, $path); if (is_array($attributes)) { for ($i = 0; $i < count($attributes); $i++) { $id = $attributes[$i]['type']; /* $value contains the DER encoding of an ASN.1 value corresponding to the attribute type identified by type */ $map = $this->_getMapping($id); if (is_array($attributes[$i]['value'])) { $values = &$attributes[$i]['value']; for ($j = 0; $j < count($values); $j++) { $value = $asn1->encodeDER($values[$j], $this->AttributeValue); $decoded = $asn1->decodeBER($value); if (!is_bool($map)) { $mapped = $asn1->asn1map($decoded[0], $map); if ($mapped !== false) { $values[$j] = $mapped; } if ($id == 'pkcs-9-at-extensionRequest') { $this->_mapInExtensions($values, $j, $asn1); } } elseif ($map) { $values[$j] = base64_encode($value); } } } } } } /** * Map attribute values from attribute-specific internal format to * ANY type. * * @param Array ref $root * @param String $path * @param Object $asn1 * @access private */ function _mapOutAttributes(&$root, $path, $asn1) { $attributes = &$this->_subArray($root, $path); if (is_array($attributes)) { $size = count($attributes); for ($i = 0; $i < $size; $i++) { /* [value] contains the DER encoding of an ASN.1 value corresponding to the attribute type identified by type */ $id = $attributes[$i]['type']; $map = $this->_getMapping($id); if ($map === false) { user_error($id . ' is not a currently supported attribute', E_USER_NOTICE); unset($attributes[$i]); } elseif (is_array($attributes[$i]['value'])) { $values = &$attributes[$i]['value']; for ($j = 0; $j < count($values); $j++) { switch ($id) { case 'pkcs-9-at-extensionRequest': $this->_mapOutExtensions($values, $j, $asn1); break; } if (!is_bool($map)) { $temp = $asn1->encodeDER($values[$j], $map); $decoded = $asn1->decodeBER($temp); $values[$j] = $asn1->asn1map($decoded[0], $this->AttributeValue); } } } } } } /** * Associate an extension ID to an extension mapping * * @param String $extnId * @access private * @return Mixed */ function _getMapping($extnId) { if (!is_string($extnId)) { // eg. if it's a \phpseclib\File\ASN1\Element object return true; } switch ($extnId) { case 'id-ce-keyUsage': return $this->KeyUsage; case 'id-ce-basicConstraints': return $this->BasicConstraints; case 'id-ce-subjectKeyIdentifier': return $this->KeyIdentifier; case 'id-ce-cRLDistributionPoints': return $this->CRLDistributionPoints; case 'id-ce-authorityKeyIdentifier': return $this->AuthorityKeyIdentifier; case 'id-ce-certificatePolicies': return $this->CertificatePolicies; case 'id-ce-extKeyUsage': return $this->ExtKeyUsageSyntax; case 'id-pe-authorityInfoAccess': return $this->AuthorityInfoAccessSyntax; case 'id-ce-subjectAltName': return $this->SubjectAltName; case 'id-ce-privateKeyUsagePeriod': return $this->PrivateKeyUsagePeriod; case 'id-ce-issuerAltName': return $this->IssuerAltName; case 'id-ce-policyMappings': return $this->PolicyMappings; case 'id-ce-nameConstraints': return $this->NameConstraints; case 'netscape-cert-type': return $this->netscape_cert_type; case 'netscape-comment': return $this->netscape_comment; case 'netscape-ca-policy-url': return $this->netscape_ca_policy_url; // since id-qt-cps isn't a constructed type it will have already been decoded as a string by the time it gets // back around to asn1map() and we don't want it decoded again. //case 'id-qt-cps': // return $this->CPSuri; case 'id-qt-unotice': return $this->UserNotice; // the following OIDs are unsupported but we don't want them to give notices when calling saveX509(). case 'id-pe-logotype': // http://www.ietf.org/rfc/rfc3709.txt case 'entrustVersInfo': // http://support.microsoft.com/kb/287547 case '1.3.6.1.4.1.311.20.2': // szOID_ENROLL_CERTTYPE_EXTENSION case '1.3.6.1.4.1.311.21.1': // szOID_CERTSRV_CA_VERSION // "SET Secure Electronic Transaction Specification" // http://www.maithean.com/docs/set_bk3.pdf case '2.23.42.7.0': // id-set-hashedRootKey return true; // CSR attributes case 'pkcs-9-at-unstructuredName': return $this->PKCS9String; case 'pkcs-9-at-challengePassword': return $this->DirectoryString; case 'pkcs-9-at-extensionRequest': return $this->Extensions; // CRL extensions. case 'id-ce-cRLNumber': return $this->CRLNumber; case 'id-ce-deltaCRLIndicator': return $this->CRLNumber; case 'id-ce-issuingDistributionPoint': return $this->IssuingDistributionPoint; case 'id-ce-freshestCRL': return $this->CRLDistributionPoints; case 'id-ce-cRLReasons': return $this->CRLReason; case 'id-ce-invalidityDate': return $this->InvalidityDate; case 'id-ce-certificateIssuer': return $this->CertificateIssuer; case 'id-ce-holdInstructionCode': return $this->HoldInstructionCode; } return false; } /** * Load an X.509 certificate as a certificate authority * * @param String $cert * @access public * @return Boolean */ function loadCA($cert) { $olddn = $this->dn; $oldcert = $this->currentCert; $oldsigsubj = $this->signatureSubject; $oldkeyid = $this->currentKeyIdentifier; $cert = $this->loadX509($cert); if (!$cert) { $this->dn = $olddn; $this->currentCert = $oldcert; $this->signatureSubject = $oldsigsubj; $this->currentKeyIdentifier = $oldkeyid; return false; } /* From RFC5280 "PKIX Certificate and CRL Profile": If the keyUsage extension is present, then the subject public key MUST NOT be used to verify signatures on certificates or CRLs unless the corresponding keyCertSign or cRLSign bit is set. */ //$keyUsage = $this->getExtension('id-ce-keyUsage'); //if ($keyUsage && !in_array('keyCertSign', $keyUsage)) { // return false; //} /* From RFC5280 "PKIX Certificate and CRL Profile": The cA boolean indicates whether the certified public key may be used to verify certificate signatures. If the cA boolean is not asserted, then the keyCertSign bit in the key usage extension MUST NOT be asserted. If the basic constraints extension is not present in a version 3 certificate, or the extension is present but the cA boolean is not asserted, then the certified public key MUST NOT be used to verify certificate signatures. */ //$basicConstraints = $this->getExtension('id-ce-basicConstraints'); //if (!$basicConstraints || !$basicConstraints['cA']) { // return false; //} $this->CAs[] = $cert; $this->dn = $olddn; $this->currentCert = $oldcert; $this->signatureSubject = $oldsigsubj; return true; } /** * Validate an X.509 certificate against a URL * * From RFC2818 "HTTP over TLS": * * Matching is performed using the matching rules specified by * [RFC2459]. If more than one identity of a given type is present in * the certificate (e.g., more than one dNSName name, a match in any one * of the set is considered acceptable.) Names may contain the wildcard * character * which is considered to match any single domain name * component or component fragment. E.g., *.a.com matches foo.a.com but * not bar.foo.a.com. f*.com matches foo.com but not bar.com. * * @param String $url * @access public * @return Boolean */ function validateURL($url) { if (!is_array($this->currentCert) || !isset($this->currentCert['tbsCertificate'])) { return false; } $components = parse_url($url); if (!isset($components['host'])) { return false; } if ($names = $this->getExtension('id-ce-subjectAltName')) { foreach ($names as $key => $value) { $value = str_replace(array('.', '*'), array('\.', '[^.]*'), $value); switch ($key) { case 'dNSName': /* From RFC2818 "HTTP over TLS": If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead. */ if (preg_match('#^' . $value . '$#', $components['host'])) { return true; } break; case 'iPAddress': /* From RFC2818 "HTTP over TLS": In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI. */ if (preg_match('#(?:\d{1-3}\.){4}#', $components['host'] . '.') && preg_match('#^' . $value . '$#', $components['host'])) { return true; } } } return false; } if ($value = $this->getDNProp('id-at-commonName')) { $value = str_replace(array('.', '*'), array('\.', '[^.]*'), $value[0]); return preg_match('#^' . $value . '$#', $components['host']); } return false; } /** * Validate a date * * If $date isn't defined it is assumed to be the current date. * * @param Integer $date optional * @access public */ function validateDate($date = null) { if (!is_array($this->currentCert) || !isset($this->currentCert['tbsCertificate'])) { return false; } if (!isset($date)) { $date = time(); } $notBefore = $this->currentCert['tbsCertificate']['validity']['notBefore']; $notBefore = isset($notBefore['generalTime']) ? $notBefore['generalTime'] : $notBefore['utcTime']; $notAfter = $this->currentCert['tbsCertificate']['validity']['notAfter']; $notAfter = isset($notAfter['generalTime']) ? $notAfter['generalTime'] : $notAfter['utcTime']; switch (true) { case $date < @strtotime($notBefore): case $date > @strtotime($notAfter): return false; } return true; } /** * Validate a signature * * Works on X.509 certs, CSR's and CRL's. * Returns true if the signature is verified, false if it is not correct or null on error * * By default returns false for self-signed certs. Call validateSignature(false) to make this support * self-signed. * * The behavior of this function is inspired by {@link http://php.net/openssl-verify openssl_verify}. * * @param Boolean $caonly optional * @access public * @return Mixed */ function validateSignature($caonly = true) { if (!is_array($this->currentCert) || !isset($this->signatureSubject)) { return null; } /* TODO: "emailAddress attribute values are not case-sensitive (e.g., "subscriber@example.com" is the same as "SUBSCRIBER@EXAMPLE.COM")." -- http://tools.ietf.org/html/rfc5280#section-4.1.2.6 implement pathLenConstraint in the id-ce-basicConstraints extension */ switch (true) { case isset($this->currentCert['tbsCertificate']): // self-signed cert if ($this->currentCert['tbsCertificate']['issuer'] === $this->currentCert['tbsCertificate']['subject']) { $authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier'); $subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier'); switch (true) { case !is_array($authorityKey): case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID: $signingCert = $this->currentCert; // working cert } } if (!empty($this->CAs)) { for ($i = 0; $i < count($this->CAs); $i++) { // even if the cert is a self-signed one we still want to see if it's a CA; // if not, we'll conditionally return an error $ca = $this->CAs[$i]; if ($this->currentCert['tbsCertificate']['issuer'] === $ca['tbsCertificate']['subject']) { $authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier'); $subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier', $ca); switch (true) { case !is_array($authorityKey): case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID: $signingCert = $ca; // working cert break 2; } } } if (count($this->CAs) == $i && $caonly) { return false; } } elseif (!isset($signingCert) || $caonly) { return false; } return $this->_validateSignature( $signingCert['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['algorithm'], $signingCert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'], $this->currentCert['signatureAlgorithm']['algorithm'], substr(base64_decode($this->currentCert['signature']), 1), $this->signatureSubject ); case isset($this->currentCert['certificationRequestInfo']): return $this->_validateSignature( $this->currentCert['certificationRequestInfo']['subjectPKInfo']['algorithm']['algorithm'], $this->currentCert['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey'], $this->currentCert['signatureAlgorithm']['algorithm'], substr(base64_decode($this->currentCert['signature']), 1), $this->signatureSubject ); case isset($this->currentCert['publicKeyAndChallenge']): return $this->_validateSignature( $this->currentCert['publicKeyAndChallenge']['spki']['algorithm']['algorithm'], $this->currentCert['publicKeyAndChallenge']['spki']['subjectPublicKey'], $this->currentCert['signatureAlgorithm']['algorithm'], substr(base64_decode($this->currentCert['signature']), 1), $this->signatureSubject ); case isset($this->currentCert['tbsCertList']): if (!empty($this->CAs)) { for ($i = 0; $i < count($this->CAs); $i++) { $ca = $this->CAs[$i]; if ($this->currentCert['tbsCertList']['issuer'] === $ca['tbsCertificate']['subject']) { $authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier'); $subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier', $ca); switch (true) { case !is_array($authorityKey): case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID: $signingCert = $ca; // working cert break 2; } } } } if (!isset($signingCert)) { return false; } return $this->_validateSignature( $signingCert['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['algorithm'], $signingCert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'], $this->currentCert['signatureAlgorithm']['algorithm'], substr(base64_decode($this->currentCert['signature']), 1), $this->signatureSubject ); default: return false; } } /** * Validates a signature * * Returns true if the signature is verified, false if it is not correct or null on error * * @param String $publicKeyAlgorithm * @param String $publicKey * @param String $signatureAlgorithm * @param String $signature * @param String $signatureSubject * @access private * @return Integer */ function _validateSignature($publicKeyAlgorithm, $publicKey, $signatureAlgorithm, $signature, $signatureSubject) { switch ($publicKeyAlgorithm) { case 'rsaEncryption': $rsa = new RSA(); $rsa->loadKey($publicKey); switch ($signatureAlgorithm) { case 'md2WithRSAEncryption': case 'md5WithRSAEncryption': case 'sha1WithRSAEncryption': case 'sha224WithRSAEncryption': case 'sha256WithRSAEncryption': case 'sha384WithRSAEncryption': case 'sha512WithRSAEncryption': $rsa->setHash(preg_replace('#WithRSAEncryption$#', '', $signatureAlgorithm)); $rsa->setSignatureMode(RSA::SIGNATURE_PKCS1); if (!@$rsa->verify($signatureSubject, $signature)) { return false; } break; default: return null; } break; default: return null; } return true; } /** * Reformat public keys * * Reformats a public key to a format supported by phpseclib (if applicable) * * @param String $algorithm * @param String $key * @access private * @return String */ function _reformatKey($algorithm, $key) { switch ($algorithm) { case 'rsaEncryption': return "-----BEGIN RSA PUBLIC KEY-----\r\n" . // subjectPublicKey is stored as a bit string in X.509 certs. the first byte of a bit string represents how many bits // in the last byte should be ignored. the following only supports non-zero stuff but as none of the X.509 certs Firefox // uses as a cert authority actually use a non-zero bit I think it's safe to assume that none do. chunk_split(base64_encode(substr(base64_decode($key), 1)), 64) . '-----END RSA PUBLIC KEY-----'; default: return $key; } } /** * Decodes an IP address * * Takes in a base64 encoded "blob" and returns a human readable IP address * * @param String $ip * @access private * @return String */ function _decodeIP($ip) { $ip = base64_decode($ip); list(, $ip) = unpack('N', $ip); return long2ip($ip); } /** * Encodes an IP address * * Takes a human readable IP address into a base64-encoded "blob" * * @param String $ip * @access private * @return String */ function _encodeIP($ip) { return base64_encode(pack('N', ip2long($ip))); } /** * "Normalizes" a Distinguished Name property * * @param String $propName * @access private * @return Mixed */ function _translateDNProp($propName) { switch (strtolower($propName)) { case 'id-at-countryname': case 'countryname': case 'c': return 'id-at-countryName'; case 'id-at-organizationname': case 'organizationname': case 'o': return 'id-at-organizationName'; case 'id-at-dnqualifier': case 'dnqualifier': return 'id-at-dnQualifier'; case 'id-at-commonname': case 'commonname': case 'cn': return 'id-at-commonName'; case 'id-at-stateorprovincename': case 'stateorprovincename': case 'state': case 'province': case 'provincename': case 'st': return 'id-at-stateOrProvinceName'; case 'id-at-localityname': case 'localityname': case 'l': return 'id-at-localityName'; case 'id-emailaddress': case 'emailaddress': return 'pkcs-9-at-emailAddress'; case 'id-at-serialnumber': case 'serialnumber': return 'id-at-serialNumber'; case 'id-at-postalcode': case 'postalcode': return 'id-at-postalCode'; case 'id-at-streetaddress': case 'streetaddress': return 'id-at-streetAddress'; case 'id-at-name': case 'name': return 'id-at-name'; case 'id-at-givenname': case 'givenname': return 'id-at-givenName'; case 'id-at-surname': case 'surname': case 'sn': return 'id-at-surname'; case 'id-at-initials': case 'initials': return 'id-at-initials'; case 'id-at-generationqualifier': case 'generationqualifier': return 'id-at-generationQualifier'; case 'id-at-organizationalunitname': case 'organizationalunitname': case 'ou': return 'id-at-organizationalUnitName'; case 'id-at-pseudonym': case 'pseudonym': return 'id-at-pseudonym'; case 'id-at-title': case 'title': return 'id-at-title'; case 'id-at-description': case 'description': return 'id-at-description'; case 'id-at-role': case 'role': return 'id-at-role'; case 'id-at-uniqueidentifier': case 'uniqueidentifier': case 'x500uniqueidentifier': return 'id-at-uniqueIdentifier'; default: return false; } } /** * Set a Distinguished Name property * * @param String $propName * @param Mixed $propValue * @param String $type optional * @access public * @return Boolean */ function setDNProp($propName, $propValue, $type = 'utf8String') { if (empty($this->dn)) { $this->dn = array('rdnSequence' => array()); } if (($propName = $this->_translateDNProp($propName)) === false) { return false; } foreach ((array) $propValue as $v) { if (!is_array($v) && isset($type)) { $v = array($type => $v); } $this->dn['rdnSequence'][] = array( array( 'type' => $propName, 'value'=> $v ) ); } return true; } /** * Remove Distinguished Name properties * * @param String $propName * @access public */ function removeDNProp($propName) { if (empty($this->dn)) { return; } if (($propName = $this->_translateDNProp($propName)) === false) { return; } $dn = &$this->dn['rdnSequence']; $size = count($dn); for ($i = 0; $i < $size; $i++) { if ($dn[$i][0]['type'] == $propName) { unset($dn[$i]); } } $dn = array_values($dn); } /** * Get Distinguished Name properties * * @param String $propName * @param Array $dn optional * @param Boolean $withType optional * @return Mixed * @access public */ function getDNProp($propName, $dn = null, $withType = false) { if (!isset($dn)) { $dn = $this->dn; } if (empty($dn)) { return false; } if (($propName = $this->_translateDNProp($propName)) === false) { return false; } $dn = $dn['rdnSequence']; $result = array(); $asn1 = new ASN1(); for ($i = 0; $i < count($dn); $i++) { if ($dn[$i][0]['type'] == $propName) { $v = $dn[$i][0]['value']; if (!$withType && is_array($v)) { foreach ($v as $type => $s) { $type = array_search($type, $asn1->ANYmap, true); if ($type !== false && isset($asn1->stringTypeSize[$type])) { $s = $asn1->convert($s, $type); if ($s !== false) { $v = $s; break; } } } if (is_array($v)) { $v = array_pop($v); // Always strip data type. } } $result[] = $v; } } return $result; } /** * Set a Distinguished Name * * @param Mixed $dn * @param Boolean $merge optional * @param String $type optional * @access public * @return Boolean */ function setDN($dn, $merge = false, $type = 'utf8String') { if (!$merge) { $this->dn = null; } if (is_array($dn)) { if (isset($dn['rdnSequence'])) { $this->dn = $dn; // No merge here. return true; } // handles stuff generated by openssl_x509_parse() foreach ($dn as $prop => $value) { if (!$this->setDNProp($prop, $value, $type)) { return false; } } return true; } // handles everything else $results = preg_split('#((?:^|, *|/)(?:C=|O=|OU=|CN=|L=|ST=|SN=|postalCode=|streetAddress=|emailAddress=|serialNumber=|organizationalUnitName=|title=|description=|role=|x500UniqueIdentifier=))#', $dn, -1, PREG_SPLIT_DELIM_CAPTURE); for ($i = 1; $i < count($results); $i+=2) { $prop = trim($results[$i], ', =/'); $value = $results[$i + 1]; if (!$this->setDNProp($prop, $value, $type)) { return false; } } return true; } /** * Get the Distinguished Name for a certificates subject * * @param Mixed $format optional * @param Array $dn optional * @access public * @return Boolean */ function getDN($format = self::DN_ARRAY, $dn = null) { if (!isset($dn)) { $dn = isset($this->currentCert['tbsCertList']) ? $this->currentCert['tbsCertList']['issuer'] : $this->dn; } switch ((int) $format) { case self::DN_ARRAY: return $dn; case self::DN_ASN1: $asn1 = new ASN1(); $asn1->loadOIDs($this->oids); $filters = array(); $filters['rdnSequence']['value'] = array('type' => ASN1::TYPE_UTF8_STRING); $asn1->loadFilters($filters); return $asn1->encodeDER($dn, $this->Name); case self::DN_OPENSSL: $dn = $this->getDN(self::DN_STRING, $dn); if ($dn === false) { return false; } $attrs = preg_split('#((?:^|, *|/)[a-z][a-z0-9]*=)#i', $dn, -1, PREG_SPLIT_DELIM_CAPTURE); $dn = array(); for ($i = 1; $i < count($attrs); $i += 2) { $prop = trim($attrs[$i], ', =/'); $value = $attrs[$i + 1]; if (!isset($dn[$prop])) { $dn[$prop] = $value; } else { $dn[$prop] = array_merge((array) $dn[$prop], array($value)); } } return $dn; case self::DN_CANON: // No SEQUENCE around RDNs and all string values normalized as // trimmed lowercase UTF-8 with all spacing as one blank. $asn1 = new ASN1(); $asn1->loadOIDs($this->oids); $filters = array(); $filters['value'] = array('type' => ASN1::TYPE_UTF8_STRING); $asn1->loadFilters($filters); $result = ''; foreach ($dn['rdnSequence'] as $rdn) { foreach ($rdn as $i=>$attr) { $attr = &$rdn[$i]; if (is_array($attr['value'])) { foreach ($attr['value'] as $type => $v) { $type = array_search($type, $asn1->ANYmap, true); if ($type !== false && isset($asn1->stringTypeSize[$type])) { $v = $asn1->convert($v, $type); if ($v !== false) { $v = preg_replace('/\s+/', ' ', $v); $attr['value'] = strtolower(trim($v)); break; } } } } } $result .= $asn1->encodeDER($rdn, $this->RelativeDistinguishedName); } return $result; case self::DN_HASH: $dn = $this->getDN(self::DN_CANON, $dn); $hash = new Hash('sha1'); $hash = $hash->hash($dn); extract(unpack('Vhash', $hash)); return strtolower(bin2hex(pack('N', $hash))); } // Default is to return a string. $start = true; $output = ''; $asn1 = new ASN1(); foreach ($dn['rdnSequence'] as $field) { $prop = $field[0]['type']; $value = $field[0]['value']; $delim = ', '; switch ($prop) { case 'id-at-countryName': $desc = 'C='; break; case 'id-at-stateOrProvinceName': $desc = 'ST='; break; case 'id-at-organizationName': $desc = 'O='; break; case 'id-at-organizationalUnitName': $desc = 'OU='; break; case 'id-at-commonName': $desc = 'CN='; break; case 'id-at-localityName': $desc = 'L='; break; case 'id-at-surname': $desc = 'SN='; break; case 'id-at-uniqueIdentifier': $delim = '/'; $desc = 'x500UniqueIdentifier='; break; default: $delim = '/'; $desc = preg_replace('#.+-([^-]+)$#', '$1', $prop) . '='; } if (!$start) { $output.= $delim; } if (is_array($value)) { foreach ($value as $type => $v) { $type = array_search($type, $asn1->ANYmap, true); if ($type !== false && isset($asn1->stringTypeSize[$type])) { $v = $asn1->convert($v, $type); if ($v !== false) { $value = $v; break; } } } if (is_array($value)) { $value = array_pop($value); // Always strip data type. } } $output.= $desc . $value; $start = false; } return $output; } /** * Get the Distinguished Name for a certificate/crl issuer * * @param Integer $format optional * @access public * @return Mixed */ function getIssuerDN($format = self::DN_ARRAY) { switch (true) { case !isset($this->currentCert) || !is_array($this->currentCert): break; case isset($this->currentCert['tbsCertificate']): return $this->getDN($format, $this->currentCert['tbsCertificate']['issuer']); case isset($this->currentCert['tbsCertList']): return $this->getDN($format, $this->currentCert['tbsCertList']['issuer']); } return false; } /** * Get the Distinguished Name for a certificate/csr subject * Alias of getDN() * * @param Integer $format optional * @access public * @return Mixed */ function getSubjectDN($format = self::DN_ARRAY) { switch (true) { case !empty($this->dn): return $this->getDN($format); case !isset($this->currentCert) || !is_array($this->currentCert): break; case isset($this->currentCert['tbsCertificate']): return $this->getDN($format, $this->currentCert['tbsCertificate']['subject']); case isset($this->currentCert['certificationRequestInfo']): return $this->getDN($format, $this->currentCert['certificationRequestInfo']['subject']); } return false; } /** * Get an individual Distinguished Name property for a certificate/crl issuer * * @param String $propName * @param Boolean $withType optional * @access public * @return Mixed */ function getIssuerDNProp($propName, $withType = false) { switch (true) { case !isset($this->currentCert) || !is_array($this->currentCert): break; case isset($this->currentCert['tbsCertificate']): return $this->getDNProp($propName, $this->currentCert['tbsCertificate']['issuer'], $withType); case isset($this->currentCert['tbsCertList']): return $this->getDNProp($propName, $this->currentCert['tbsCertList']['issuer'], $withType); } return false; } /** * Get an individual Distinguished Name property for a certificate/csr subject * * @param String $propName * @param Boolean $withType optional * @access public * @return Mixed */ function getSubjectDNProp($propName, $withType = false) { switch (true) { case !empty($this->dn): return $this->getDNProp($propName, null, $withType); case !isset($this->currentCert) || !is_array($this->currentCert): break; case isset($this->currentCert['tbsCertificate']): return $this->getDNProp($propName, $this->currentCert['tbsCertificate']['subject'], $withType); case isset($this->currentCert['certificationRequestInfo']): return $this->getDNProp($propName, $this->currentCert['certificationRequestInfo']['subject'], $withType); } return false; } /** * Get the certificate chain for the current cert * * @access public * @return Mixed */ function getChain() { $chain = array($this->currentCert); if (!is_array($this->currentCert) || !isset($this->currentCert['tbsCertificate'])) { return false; } if (empty($this->CAs)) { return $chain; } while (true) { $currentCert = $chain[count($chain) - 1]; for ($i = 0; $i < count($this->CAs); $i++) { $ca = $this->CAs[$i]; if ($currentCert['tbsCertificate']['issuer'] === $ca['tbsCertificate']['subject']) { $authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier', $currentCert); $subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier', $ca); switch (true) { case !is_array($authorityKey): case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID: if ($currentCert === $ca) { break 3; } $chain[] = $ca; break 2; } } } if ($i == count($this->CAs)) { break; } } foreach ($chain as $key=>$value) { $chain[$key] = new X509(); $chain[$key]->loadX509($value); } return $chain; } /** * Set public key * * Key needs to be a \phpseclib\Crypt\RSA object * * @param Object $key * @access public * @return Boolean */ function setPublicKey($key) { $key->setPublicKey(); $this->publicKey = $key; } /** * Set private key * * Key needs to be a \phpseclib\Crypt\RSA object * * @param Object $key * @access public */ function setPrivateKey($key) { $this->privateKey = $key; } /** * Set challenge * * Used for SPKAC CSR's * * @param String $challenge * @access public */ function setChallenge($challenge) { $this->challenge = $challenge; } /** * Gets the public key * * Returns a \phpseclib\Crypt\RSA object or a false. * * @access public * @return Mixed */ function getPublicKey() { if (isset($this->publicKey)) { return $this->publicKey; } if (isset($this->currentCert) && is_array($this->currentCert)) { foreach (array('tbsCertificate/subjectPublicKeyInfo', 'certificationRequestInfo/subjectPKInfo') as $path) { $keyinfo = $this->_subArray($this->currentCert, $path); if (!empty($keyinfo)) { break; } } } if (empty($keyinfo)) { return false; } $key = $keyinfo['subjectPublicKey']; switch ($keyinfo['algorithm']['algorithm']) { case 'rsaEncryption': $publicKey = new RSA(); $publicKey->loadKey($key); $publicKey->setPublicKey(); break; default: return false; } return $publicKey; } /** * Load a Certificate Signing Request * * @param String $csr * @access public * @return Mixed */ function loadCSR($csr) { if (is_array($csr) && isset($csr['certificationRequestInfo'])) { unset($this->currentCert); unset($this->currentKeyIdentifier); unset($this->signatureSubject); $this->dn = $csr['certificationRequestInfo']['subject']; if (!isset($this->dn)) { return false; } $this->currentCert = $csr; return $csr; } // see http://tools.ietf.org/html/rfc2986 $asn1 = new ASN1(); $csr = $this->_extractBER($csr); $orig = $csr; if ($csr === false) { $this->currentCert = false; return false; } $asn1->loadOIDs($this->oids); $decoded = $asn1->decodeBER($csr); if (empty($decoded)) { $this->currentCert = false; return false; } $csr = $asn1->asn1map($decoded[0], $this->CertificationRequest); if (!isset($csr) || $csr === false) { $this->currentCert = false; return false; } $this->dn = $csr['certificationRequestInfo']['subject']; $this->_mapInAttributes($csr, 'certificationRequestInfo/attributes', $asn1); $this->signatureSubject = substr($orig, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']); $algorithm = &$csr['certificationRequestInfo']['subjectPKInfo']['algorithm']['algorithm']; $key = &$csr['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey']; $key = $this->_reformatKey($algorithm, $key); switch ($algorithm) { case 'rsaEncryption': $this->publicKey = new RSA(); $this->publicKey->loadKey($key); $this->publicKey->setPublicKey(); break; default: $this->publicKey = null; } $this->currentKeyIdentifier = null; $this->currentCert = $csr; return $csr; } /** * Save CSR request * * @param Array $csr * @param Integer $format optional * @access public * @return String */ function saveCSR($csr, $format = self::FORMAT_PEM) { if (!is_array($csr) || !isset($csr['certificationRequestInfo'])) { return false; } switch (true) { case !($algorithm = $this->_subArray($csr, 'certificationRequestInfo/subjectPKInfo/algorithm/algorithm')): case is_object($csr['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey']); break; default: switch ($algorithm) { case 'rsaEncryption': $csr['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey'] = base64_encode("\0" . base64_decode(preg_replace('#-.+-|[\r\n]#', '', $csr['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey']))); } } $asn1 = new ASN1(); $asn1->loadOIDs($this->oids); $filters = array(); $filters['certificationRequestInfo']['subject']['rdnSequence']['value'] = array('type' => ASN1::TYPE_UTF8_STRING); $asn1->loadFilters($filters); $this->_mapOutAttributes($csr, 'certificationRequestInfo/attributes', $asn1); $csr = $asn1->encodeDER($csr, $this->CertificationRequest); switch ($format) { case self::FORMAT_DER: return $csr; // case self::FORMAT_PEM: default: return "-----BEGIN CERTIFICATE REQUEST-----\r\n" . chunk_split(base64_encode($csr), 64) . '-----END CERTIFICATE REQUEST-----'; } } /** * Load a SPKAC CSR * * SPKAC's are produced by the HTML5 keygen element: * * https://developer.mozilla.org/en-US/docs/HTML/Element/keygen * * @param String $csr * @access public * @return Mixed */ function loadSPKAC($spkac) { if (is_array($spkac) && isset($spkac['publicKeyAndChallenge'])) { unset($this->currentCert); unset($this->currentKeyIdentifier); unset($this->signatureSubject); $this->currentCert = $spkac; return $spkac; } // see http://www.w3.org/html/wg/drafts/html/master/forms.html#signedpublickeyandchallenge $asn1 = new ASN1(); // OpenSSL produces SPKAC's that are preceeded by the string SPKAC= $temp = preg_replace('#(?:SPKAC=)|[ \r\n\\\]#', '', $spkac); $temp = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $temp) ? base64_decode($temp) : false; if ($temp != false) { $spkac = $temp; } $orig = $spkac; if ($spkac === false) { $this->currentCert = false; return false; } $asn1->loadOIDs($this->oids); $decoded = $asn1->decodeBER($spkac); if (empty($decoded)) { $this->currentCert = false; return false; } $spkac = $asn1->asn1map($decoded[0], $this->SignedPublicKeyAndChallenge); if (!isset($spkac) || $spkac === false) { $this->currentCert = false; return false; } $this->signatureSubject = substr($orig, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']); $algorithm = &$spkac['publicKeyAndChallenge']['spki']['algorithm']['algorithm']; $key = &$spkac['publicKeyAndChallenge']['spki']['subjectPublicKey']; $key = $this->_reformatKey($algorithm, $key); switch ($algorithm) { case 'rsaEncryption': $this->publicKey = new RSA(); $this->publicKey->loadKey($key); $this->publicKey->setPublicKey(); break; default: $this->publicKey = null; } $this->currentKeyIdentifier = null; $this->currentCert = $spkac; return $spkac; } /** * Save a SPKAC CSR request * * @param Array $csr * @param Integer $format optional * @access public * @return String */ function saveSPKAC($spkac, $format = self::FORMAT_PEM) { if (!is_array($spkac) || !isset($spkac['publicKeyAndChallenge'])) { return false; } $algorithm = $this->_subArray($spkac, 'publicKeyAndChallenge/spki/algorithm/algorithm'); switch (true) { case !$algorithm: case is_object($spkac['publicKeyAndChallenge']['spki']['subjectPublicKey']); break; default: switch ($algorithm) { case 'rsaEncryption': $spkac['publicKeyAndChallenge']['spki']['subjectPublicKey'] = base64_encode("\0" . base64_decode(preg_replace('#-.+-|[\r\n]#', '', $spkac['publicKeyAndChallenge']['spki']['subjectPublicKey']))); } } $asn1 = new ASN1(); $asn1->loadOIDs($this->oids); $spkac = $asn1->encodeDER($spkac, $this->SignedPublicKeyAndChallenge); switch ($format) { case self::FORMAT_DER: return $spkac; // case self::FORMAT_PEM: default: // OpenSSL's implementation of SPKAC requires the SPKAC be preceeded by SPKAC= and since there are pretty much // no other SPKAC decoders phpseclib will use that same format return 'SPKAC=' . base64_encode($spkac); } } /** * Load a Certificate Revocation List * * @param String $crl * @access public * @return Mixed */ function loadCRL($crl) { if (is_array($crl) && isset($crl['tbsCertList'])) { $this->currentCert = $crl; unset($this->signatureSubject); return $crl; } $asn1 = new ASN1(); $crl = $this->_extractBER($crl); $orig = $crl; if ($crl === false) { $this->currentCert = false; return false; } $asn1->loadOIDs($this->oids); $decoded = $asn1->decodeBER($crl); if (empty($decoded)) { $this->currentCert = false; return false; } $crl = $asn1->asn1map($decoded[0], $this->CertificateList); if (!isset($crl) || $crl === false) { $this->currentCert = false; return false; } $this->signatureSubject = substr($orig, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']); $this->_mapInExtensions($crl, 'tbsCertList/crlExtensions', $asn1); $rclist = &$this->_subArray($crl, 'tbsCertList/revokedCertificates'); if (is_array($rclist)) { foreach ($rclist as $i => $extension) { $this->_mapInExtensions($rclist, "$i/crlEntryExtensions", $asn1); } } $this->currentKeyIdentifier = null; $this->currentCert = $crl; return $crl; } /** * Save Certificate Revocation List. * * @param Array $crl * @param Integer $format optional * @access public * @return String */ function saveCRL($crl, $format = self::FORMAT_PEM) { if (!is_array($crl) || !isset($crl['tbsCertList'])) { return false; } $asn1 = new ASN1(); $asn1->loadOIDs($this->oids); $filters = array(); $filters['tbsCertList']['issuer']['rdnSequence']['value'] = array('type' => ASN1::TYPE_UTF8_STRING); $filters['tbsCertList']['signature']['parameters'] = array('type' => ASN1::TYPE_UTF8_STRING); $filters['signatureAlgorithm']['parameters'] = array('type' => ASN1::TYPE_UTF8_STRING); if (empty($crl['tbsCertList']['signature']['parameters'])) { $filters['tbsCertList']['signature']['parameters'] = array('type' => ASN1::TYPE_NULL); } if (empty($crl['signatureAlgorithm']['parameters'])) { $filters['signatureAlgorithm']['parameters'] = array('type' => ASN1::TYPE_NULL); } $asn1->loadFilters($filters); $this->_mapOutExtensions($crl, 'tbsCertList/crlExtensions', $asn1); $rclist = &$this->_subArray($crl, 'tbsCertList/revokedCertificates'); if (is_array($rclist)) { foreach ($rclist as $i => $extension) { $this->_mapOutExtensions($rclist, "$i/crlEntryExtensions", $asn1); } } $crl = $asn1->encodeDER($crl, $this->CertificateList); switch ($format) { case self::FORMAT_DER: return $crl; // case self::FORMAT_PEM: default: return "-----BEGIN X509 CRL-----\r\n" . chunk_split(base64_encode($crl), 64) . '-----END X509 CRL-----'; } } /** * Helper function to build a time field according to RFC 3280 section * - 4.1.2.5 Validity * - 5.1.2.4 This Update * - 5.1.2.5 Next Update * - 5.1.2.6 Revoked Certificates * by choosing utcTime iff year of date given is before 2050 and generalTime else. * * @param String $date in format date('D, d M Y H:i:s O') * @access private * @return Array */ function _timeField($date) { $year = @gmdate("Y", @strtotime($date)); // the same way ASN1.php parses this if ($year < 2050) { return array('utcTime' => $date); } else { return array('generalTime' => $date); } } /** * Sign an X.509 certificate * * $issuer's private key needs to be loaded. * $subject can be either an existing X.509 cert (if you want to resign it), * a CSR or something with the DN and public key explicitly set. * * @param \phpseclib\File\X509 $issuer * @param \phpseclib\File\X509 $subject * @param String $signatureAlgorithm optional * @access public * @return Mixed */ function sign($issuer, $subject, $signatureAlgorithm = 'sha1WithRSAEncryption') { if (!is_object($issuer->privateKey) || empty($issuer->dn)) { return false; } if (isset($subject->publicKey) && !($subjectPublicKey = $subject->_formatSubjectPublicKey())) { return false; } $currentCert = isset($this->currentCert) ? $this->currentCert : null; $signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject: null; if (isset($subject->currentCert) && is_array($subject->currentCert) && isset($subject->currentCert['tbsCertificate'])) { $this->currentCert = $subject->currentCert; $this->currentCert['tbsCertificate']['signature']['algorithm'] = $signatureAlgorithm; $this->currentCert['signatureAlgorithm']['algorithm'] = $signatureAlgorithm; if (!empty($this->startDate)) { $this->currentCert['tbsCertificate']['validity']['notBefore'] = $this->_timeField($this->startDate); } if (!empty($this->endDate)) { $this->currentCert['tbsCertificate']['validity']['notAfter'] = $this->_timeField($this->endDate); } if (!empty($this->serialNumber)) { $this->currentCert['tbsCertificate']['serialNumber'] = $this->serialNumber; } if (!empty($subject->dn)) { $this->currentCert['tbsCertificate']['subject'] = $subject->dn; } if (!empty($subject->publicKey)) { $this->currentCert['tbsCertificate']['subjectPublicKeyInfo'] = $subjectPublicKey; } $this->removeExtension('id-ce-authorityKeyIdentifier'); if (isset($subject->domains)) { $this->removeExtension('id-ce-subjectAltName'); } } else if (isset($subject->currentCert) && is_array($subject->currentCert) && isset($subject->currentCert['tbsCertList'])) { return false; } else { if (!isset($subject->publicKey)) { return false; } $startDate = !empty($this->startDate) ? $this->startDate : @date('D, d M Y H:i:s O'); $endDate = !empty($this->endDate) ? $this->endDate : @date('D, d M Y H:i:s O', strtotime('+1 year')); $serialNumber = !empty($this->serialNumber) ? $this->serialNumber : new BigInteger(); $this->currentCert = array( 'tbsCertificate' => array( 'version' => 'v3', 'serialNumber' => $serialNumber, // $this->setserialNumber() 'signature' => array('algorithm' => $signatureAlgorithm), 'issuer' => false, // this is going to be overwritten later 'validity' => array( 'notBefore' => $this->_timeField($startDate), // $this->setStartDate() 'notAfter' => $this->_timeField($endDate) // $this->setEndDate() ), 'subject' => $subject->dn, 'subjectPublicKeyInfo' => $subjectPublicKey ), 'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm), 'signature' => false // this is going to be overwritten later ); // Copy extensions from CSR. $csrexts = $subject->getAttribute('pkcs-9-at-extensionRequest', 0); if (!empty($csrexts)) { $this->currentCert['tbsCertificate']['extensions'] = $csrexts; } } $this->currentCert['tbsCertificate']['issuer'] = $issuer->dn; if (isset($issuer->currentKeyIdentifier)) { $this->setExtension('id-ce-authorityKeyIdentifier', array( //'authorityCertIssuer' => array( // array( // 'directoryName' => $issuer->dn // ) //), 'keyIdentifier' => $issuer->currentKeyIdentifier ) ); //$extensions = &$this->currentCert['tbsCertificate']['extensions']; //if (isset($issuer->serialNumber)) { // $extensions[count($extensions) - 1]['authorityCertSerialNumber'] = $issuer->serialNumber; //} //unset($extensions); } if (isset($subject->currentKeyIdentifier)) { $this->setExtension('id-ce-subjectKeyIdentifier', $subject->currentKeyIdentifier); } $altName = array(); if (isset($subject->domains) && count($subject->domains) > 1) { $altName = array_map(array('X509', '_dnsName'), $subject->domains); } if (isset($subject->ipAddresses) && count($subject->ipAddresses)) { // should an IP address appear as the CN if no domain name is specified? idk //$ips = count($subject->domains) ? $subject->ipAddresses : array_slice($subject->ipAddresses, 1); $ipAddresses = array(); foreach ($subject->ipAddresses as $ipAddress) { $encoded = $subject->_ipAddress($ipAddress); if ($encoded !== false) { $ipAddresses[] = $encoded; } } if (count($ipAddresses)) { $altName = array_merge($altName, $ipAddresses); } } if (!empty($altName)) { $this->setExtension('id-ce-subjectAltName', $altName); } if ($this->caFlag) { $keyUsage = $this->getExtension('id-ce-keyUsage'); if (!$keyUsage) { $keyUsage = array(); } $this->setExtension('id-ce-keyUsage', array_values(array_unique(array_merge($keyUsage, array('cRLSign', 'keyCertSign')))) ); $basicConstraints = $this->getExtension('id-ce-basicConstraints'); if (!$basicConstraints) { $basicConstraints = array(); } $this->setExtension('id-ce-basicConstraints', array_unique(array_merge(array('cA' => true), $basicConstraints)), true); if (!isset($subject->currentKeyIdentifier)) { $this->setExtension('id-ce-subjectKeyIdentifier', base64_encode($this->computeKeyIdentifier($this->currentCert)), false, false); } } // resync $this->signatureSubject // save $tbsCertificate in case there are any \phpseclib\File\ASN1\Element objects in it $tbsCertificate = $this->currentCert['tbsCertificate']; $this->loadX509($this->saveX509($this->currentCert)); $result = $this->_sign($issuer->privateKey, $signatureAlgorithm); $result['tbsCertificate'] = $tbsCertificate; $this->currentCert = $currentCert; $this->signatureSubject = $signatureSubject; return $result; } /** * Sign a CSR * * @access public * @return Mixed */ function signCSR($signatureAlgorithm = 'sha1WithRSAEncryption') { if (!is_object($this->privateKey) || empty($this->dn)) { return false; } $origPublicKey = $this->publicKey; $class = get_class($this->privateKey); $this->publicKey = new $class(); $this->publicKey->loadKey($this->privateKey->getPublicKey()); $this->publicKey->setPublicKey(); if (!($publicKey = $this->_formatSubjectPublicKey())) { return false; } $this->publicKey = $origPublicKey; $currentCert = isset($this->currentCert) ? $this->currentCert : null; $signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject: null; if (isset($this->currentCert) && is_array($this->currentCert) && isset($this->currentCert['certificationRequestInfo'])) { $this->currentCert['signatureAlgorithm']['algorithm'] = $signatureAlgorithm; if (!empty($this->dn)) { $this->currentCert['certificationRequestInfo']['subject'] = $this->dn; } $this->currentCert['certificationRequestInfo']['subjectPKInfo'] = $publicKey; } else { $this->currentCert = array( 'certificationRequestInfo' => array( 'version' => 'v1', 'subject' => $this->dn, 'subjectPKInfo' => $publicKey ), 'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm), 'signature' => false // this is going to be overwritten later ); } // resync $this->signatureSubject // save $certificationRequestInfo in case there are any \phpseclib\File\ASN1\Element objects in it $certificationRequestInfo = $this->currentCert['certificationRequestInfo']; $this->loadCSR($this->saveCSR($this->currentCert)); $result = $this->_sign($this->privateKey, $signatureAlgorithm); $result['certificationRequestInfo'] = $certificationRequestInfo; $this->currentCert = $currentCert; $this->signatureSubject = $signatureSubject; return $result; } /** * Sign a SPKAC * * @access public * @return Mixed */ function signSPKAC($signatureAlgorithm = 'sha1WithRSAEncryption') { if (!is_object($this->privateKey)) { return false; } $origPublicKey = $this->publicKey; $class = get_class($this->privateKey); $this->publicKey = new $class(); $this->publicKey->loadKey($this->privateKey->getPublicKey()); $this->publicKey->setPublicKey(); $publicKey = $this->_formatSubjectPublicKey(); if (!$publicKey) { return false; } $this->publicKey = $origPublicKey; $currentCert = isset($this->currentCert) ? $this->currentCert : null; $signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject: null; // re-signing a SPKAC seems silly but since everything else supports re-signing why not? if (isset($this->currentCert) && is_array($this->currentCert) && isset($this->currentCert['publicKeyAndChallenge'])) { $this->currentCert['signatureAlgorithm']['algorithm'] = $signatureAlgorithm; $this->currentCert['publicKeyAndChallenge']['spki'] = $publicKey; if (!empty($this->challenge)) { // the bitwise AND ensures that the output is a valid IA5String $this->currentCert['publicKeyAndChallenge']['challenge'] = $this->challenge & str_repeat("\x7F", strlen($this->challenge)); } } else { $this->currentCert = array( 'publicKeyAndChallenge' => array( 'spki' => $publicKey, // quoting , // "A challenge string that is submitted along with the public key. Defaults to an empty string if not specified." // both Firefox and OpenSSL ("openssl spkac -key private.key") behave this way // we could alternatively do this instead if we ignored the specs: // Random::string(8) & str_repeat("\x7F", 8) 'challenge' => !empty($this->challenge) ? $this->challenge : '' ), 'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm), 'signature' => false // this is going to be overwritten later ); } // resync $this->signatureSubject // save $publicKeyAndChallenge in case there are any \phpseclib\File\ASN1\Element objects in it $publicKeyAndChallenge = $this->currentCert['publicKeyAndChallenge']; $this->loadSPKAC($this->saveSPKAC($this->currentCert)); $result = $this->_sign($this->privateKey, $signatureAlgorithm); $result['publicKeyAndChallenge'] = $publicKeyAndChallenge; $this->currentCert = $currentCert; $this->signatureSubject = $signatureSubject; return $result; } /** * Sign a CRL * * $issuer's private key needs to be loaded. * * @param \phpseclib\File\X509 $issuer * @param \phpseclib\File\X509 $crl * @param String $signatureAlgorithm optional * @access public * @return Mixed */ function signCRL($issuer, $crl, $signatureAlgorithm = 'sha1WithRSAEncryption') { if (!is_object($issuer->privateKey) || empty($issuer->dn)) { return false; } $currentCert = isset($this->currentCert) ? $this->currentCert : null; $signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject : null; $thisUpdate = !empty($this->startDate) ? $this->startDate : @date('D, d M Y H:i:s O'); if (isset($crl->currentCert) && is_array($crl->currentCert) && isset($crl->currentCert['tbsCertList'])) { $this->currentCert = $crl->currentCert; $this->currentCert['tbsCertList']['signature']['algorithm'] = $signatureAlgorithm; $this->currentCert['signatureAlgorithm']['algorithm'] = $signatureAlgorithm; } else { $this->currentCert = array( 'tbsCertList' => array( 'version' => 'v2', 'signature' => array('algorithm' => $signatureAlgorithm), 'issuer' => false, // this is going to be overwritten later 'thisUpdate' => $this->_timeField($thisUpdate) // $this->setStartDate() ), 'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm), 'signature' => false // this is going to be overwritten later ); } $tbsCertList = &$this->currentCert['tbsCertList']; $tbsCertList['issuer'] = $issuer->dn; $tbsCertList['thisUpdate'] = $this->_timeField($thisUpdate); if (!empty($this->endDate)) { $tbsCertList['nextUpdate'] = $this->_timeField($this->endDate); // $this->setEndDate() } else { unset($tbsCertList['nextUpdate']); } if (!empty($this->serialNumber)) { $crlNumber = $this->serialNumber; } else { $crlNumber = $this->getExtension('id-ce-cRLNumber'); $crlNumber = $crlNumber !== false ? $crlNumber->add(new BigInteger(1)) : null; } $this->removeExtension('id-ce-authorityKeyIdentifier'); $this->removeExtension('id-ce-issuerAltName'); // Be sure version >= v2 if some extension found. $version = isset($tbsCertList['version']) ? $tbsCertList['version'] : 0; if (!$version) { if (!empty($tbsCertList['crlExtensions'])) { $version = 1; // v2. } elseif (!empty($tbsCertList['revokedCertificates'])) { foreach ($tbsCertList['revokedCertificates'] as $cert) { if (!empty($cert['crlEntryExtensions'])) { $version = 1; // v2. } } } if ($version) { $tbsCertList['version'] = $version; } } // Store additional extensions. if (!empty($tbsCertList['version'])) { // At least v2. if (!empty($crlNumber)) { $this->setExtension('id-ce-cRLNumber', $crlNumber); } if (isset($issuer->currentKeyIdentifier)) { $this->setExtension('id-ce-authorityKeyIdentifier', array( //'authorityCertIssuer' => array( // array( // 'directoryName' => $issuer->dn // ) //), 'keyIdentifier' => $issuer->currentKeyIdentifier ) ); //$extensions = &$tbsCertList['crlExtensions']; //if (isset($issuer->serialNumber)) { // $extensions[count($extensions) - 1]['authorityCertSerialNumber'] = $issuer->serialNumber; //} //unset($extensions); } $issuerAltName = $this->getExtension('id-ce-subjectAltName', $issuer->currentCert); if ($issuerAltName !== false) { $this->setExtension('id-ce-issuerAltName', $issuerAltName); } } if (empty($tbsCertList['revokedCertificates'])) { unset($tbsCertList['revokedCertificates']); } unset($tbsCertList); // resync $this->signatureSubject // save $tbsCertList in case there are any \phpseclib\File\ASN1\Element objects in it $tbsCertList = $this->currentCert['tbsCertList']; $this->loadCRL($this->saveCRL($this->currentCert)); $result = $this->_sign($issuer->privateKey, $signatureAlgorithm); $result['tbsCertList'] = $tbsCertList; $this->currentCert = $currentCert; $this->signatureSubject = $signatureSubject; return $result; } /** * X.509 certificate signing helper function. * * @param Object $key * @param \phpseclib\File\X509 $subject * @param String $signatureAlgorithm * @access public * @return Mixed */ function _sign($key, $signatureAlgorithm) { if ($key instanceof RSA) { switch ($signatureAlgorithm) { case 'md2WithRSAEncryption': case 'md5WithRSAEncryption': case 'sha1WithRSAEncryption': case 'sha224WithRSAEncryption': case 'sha256WithRSAEncryption': case 'sha384WithRSAEncryption': case 'sha512WithRSAEncryption': $key->setHash(preg_replace('#WithRSAEncryption$#', '', $signatureAlgorithm)); $key->setSignatureMode(RSA::SIGNATURE_PKCS1); $this->currentCert['signature'] = base64_encode("\0" . $key->sign($this->signatureSubject)); return $this->currentCert; } } return false; } /** * Set certificate start date * * @param String $date * @access public */ function setStartDate($date) { $this->startDate = @date('D, d M Y H:i:s O', @strtotime($date)); } /** * Set certificate end date * * @param String $date * @access public */ function setEndDate($date) { /* To indicate that a certificate has no well-defined expiration date, the notAfter SHOULD be assigned the GeneralizedTime value of 99991231235959Z. -- http://tools.ietf.org/html/rfc5280#section-4.1.2.5 */ if (strtolower($date) == 'lifetime') { $temp = '99991231235959Z'; $asn1 = new ASN1(); $temp = chr(ASN1::TYPE_GENERALIZED_TIME) . $asn1->_encodeLength(strlen($temp)) . $temp; $this->endDate = new Element($temp); } else { $this->endDate = @date('D, d M Y H:i:s O', @strtotime($date)); } } /** * Set Serial Number * * @param String $serial * @param $base optional * @access public */ function setSerialNumber($serial, $base = -256) { $this->serialNumber = new BigInteger($serial, $base); } /** * Turns the certificate into a certificate authority * * @access public */ function makeCA() { $this->caFlag = true; } /** * Get a reference to a subarray * * @param array $root * @param String $path absolute path with / as component separator * @param Boolean $create optional * @access private * @return array item ref or false */ function &_subArray(&$root, $path, $create = false) { $false = false; if (!is_array($root)) { return $false; } foreach (explode('/', $path) as $i) { if (!is_array($root)) { return $false; } if (!isset($root[$i])) { if (!$create) { return $false; } $root[$i] = array(); } $root = &$root[$i]; } return $root; } /** * Get a reference to an extension subarray * * @param array $root * @param String $path optional absolute path with / as component separator * @param Boolean $create optional * @access private * @return array ref or false */ function &_extensions(&$root, $path = null, $create = false) { if (!isset($root)) { $root = $this->currentCert; } switch (true) { case !empty($path): case !is_array($root): break; case isset($root['tbsCertificate']): $path = 'tbsCertificate/extensions'; break; case isset($root['tbsCertList']): $path = 'tbsCertList/crlExtensions'; break; case isset($root['certificationRequestInfo']): $pth = 'certificationRequestInfo/attributes'; $attributes = &$this->_subArray($root, $pth, $create); if (is_array($attributes)) { foreach ($attributes as $key => $value) { if ($value['type'] == 'pkcs-9-at-extensionRequest') { $path = "$pth/$key/value/0"; break 2; } } if ($create) { $key = count($attributes); $attributes[] = array('type' => 'pkcs-9-at-extensionRequest', 'value' => array()); $path = "$pth/$key/value/0"; } } break; } $extensions = &$this->_subArray($root, $path, $create); if (!is_array($extensions)) { $false = false; return $false; } return $extensions; } /** * Remove an Extension * * @param String $id * @param String $path optional * @access private * @return Boolean */ function _removeExtension($id, $path = null) { $extensions = &$this->_extensions($this->currentCert, $path); if (!is_array($extensions)) { return false; } $result = false; foreach ($extensions as $key => $value) { if ($value['extnId'] == $id) { unset($extensions[$key]); $result = true; } } $extensions = array_values($extensions); return $result; } /** * Get an Extension * * Returns the extension if it exists and false if not * * @param String $id * @param Array $cert optional * @param String $path optional * @access private * @return Mixed */ function _getExtension($id, $cert = null, $path = null) { $extensions = $this->_extensions($cert, $path); if (!is_array($extensions)) { return false; } foreach ($extensions as $key => $value) { if ($value['extnId'] == $id) { return $value['extnValue']; } } return false; } /** * Returns a list of all extensions in use * * @param array $cert optional * @param String $path optional * @access private * @return Array */ function _getExtensions($cert = null, $path = null) { $exts = $this->_extensions($cert, $path); $extensions = array(); if (is_array($exts)) { foreach ($exts as $extension) { $extensions[] = $extension['extnId']; } } return $extensions; } /** * Set an Extension * * @param String $id * @param Mixed $value * @param Boolean $critical optional * @param Boolean $replace optional * @param String $path optional * @access private * @return Boolean */ function _setExtension($id, $value, $critical = false, $replace = true, $path = null) { $extensions = &$this->_extensions($this->currentCert, $path, true); if (!is_array($extensions)) { return false; } $newext = array('extnId' => $id, 'critical' => $critical, 'extnValue' => $value); foreach ($extensions as $key => $value) { if ($value['extnId'] == $id) { if (!$replace) { return false; } $extensions[$key] = $newext; return true; } } $extensions[] = $newext; return true; } /** * Remove a certificate, CSR or CRL Extension * * @param String $id * @access public * @return Boolean */ function removeExtension($id) { return $this->_removeExtension($id); } /** * Get a certificate, CSR or CRL Extension * * Returns the extension if it exists and false if not * * @param String $id * @param Array $cert optional * @access public * @return Mixed */ function getExtension($id, $cert = null) { return $this->_getExtension($id, $cert); } /** * Returns a list of all extensions in use in certificate, CSR or CRL * * @param array $cert optional * @access public * @return Array */ function getExtensions($cert = null) { return $this->_getExtensions($cert); } /** * Set a certificate, CSR or CRL Extension * * @param String $id * @param Mixed $value * @param Boolean $critical optional * @param Boolean $replace optional * @access public * @return Boolean */ function setExtension($id, $value, $critical = false, $replace = true) { return $this->_setExtension($id, $value, $critical, $replace); } /** * Remove a CSR attribute. * * @param String $id * @param Integer $disposition optional * @access public * @return Boolean */ function removeAttribute($id, $disposition = self::ATTR_ALL) { $attributes = &$this->_subArray($this->currentCert, 'certificationRequestInfo/attributes'); if (!is_array($attributes)) { return false; } $result = false; foreach ($attributes as $key => $attribute) { if ($attribute['type'] == $id) { $n = count($attribute['value']); switch (true) { case $disposition == self::ATTR_APPEND: case $disposition == self::ATTR_REPLACE: return false; case $disposition >= $n: $disposition -= $n; break; case $disposition == self::ATTR_ALL: case $n == 1: unset($attributes[$key]); $result = true; break; default: unset($attributes[$key]['value'][$disposition]); $attributes[$key]['value'] = array_values($attributes[$key]['value']); $result = true; break; } if ($result && $disposition != self::ATTR_ALL) { break; } } } $attributes = array_values($attributes); return $result; } /** * Get a CSR attribute * * Returns the attribute if it exists and false if not * * @param String $id * @param Integer $disposition optional * @param Array $csr optional * @access public * @return Mixed */ function getAttribute($id, $disposition = self::ATTR_ALL, $csr = null) { if (empty($csr)) { $csr = $this->currentCert; } $attributes = $this->_subArray($csr, 'certificationRequestInfo/attributes'); if (!is_array($attributes)) { return false; } foreach ($attributes as $key => $attribute) { if ($attribute['type'] == $id) { $n = count($attribute['value']); switch (true) { case $disposition == self::ATTR_APPEND: case $disposition == self::ATTR_REPLACE: return false; case $disposition == self::ATTR_ALL: return $attribute['value']; case $disposition >= $n: $disposition -= $n; break; default: return $attribute['value'][$disposition]; } } } return false; } /** * Returns a list of all CSR attributes in use * * @param array $csr optional * @access public * @return Array */ function getAttributes($csr = null) { if (empty($csr)) { $csr = $this->currentCert; } $attributes = $this->_subArray($csr, 'certificationRequestInfo/attributes'); $attrs = array(); if (is_array($attributes)) { foreach ($attributes as $attribute) { $attrs[] = $attribute['type']; } } return $attrs; } /** * Set a CSR attribute * * @param String $id * @param Mixed $value * @param Boolean $disposition optional * @access public * @return Boolean */ function setAttribute($id, $value, $disposition = self::ATTR_ALL) { $attributes = &$this->_subArray($this->currentCert, 'certificationRequestInfo/attributes', true); if (!is_array($attributes)) { return false; } switch ($disposition) { case self::ATTR_REPLACE: $disposition = self::ATTR_APPEND; case self::ATTR_ALL: $this->removeAttribute($id); break; } foreach ($attributes as $key => $attribute) { if ($attribute['type'] == $id) { $n = count($attribute['value']); switch (true) { case $disposition == self::ATTR_APPEND: $last = $key; break; case $disposition >= $n; $disposition -= $n; break; default: $attributes[$key]['value'][$disposition] = $value; return true; } } } switch (true) { case $disposition >= 0: return false; case isset($last): $attributes[$last]['value'][] = $value; break; default: $attributes[] = array('type' => $id, 'value' => $disposition == self::ATTR_ALL ? $value: array($value)); break; } return true; } /** * Sets the subject key identifier * * This is used by the id-ce-authorityKeyIdentifier and the id-ce-subjectKeyIdentifier extensions. * * @param String $value * @access public */ function setKeyIdentifier($value) { if (empty($value)) { unset($this->currentKeyIdentifier); } else { $this->currentKeyIdentifier = base64_encode($value); } } /** * Compute a public key identifier. * * Although key identifiers may be set to any unique value, this function * computes key identifiers from public key according to the two * recommended methods (4.2.1.2 RFC 3280). * Highly polymorphic: try to accept all possible forms of key: * - Key object * - \phpseclib\File\X509 object with public or private key defined * - Certificate or CSR array * - \phpseclib\File\ASN1\Element object * - PEM or DER string * * @param Mixed $key optional * @param Integer $method optional * @access public * @return String binary key identifier */ function computeKeyIdentifier($key = null, $method = 1) { if (is_null($key)) { $key = $this; } switch (true) { case is_string($key): break; case is_array($key) && isset($key['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']): return $this->computeKeyIdentifier($key['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'], $method); case is_array($key) && isset($key['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey']): return $this->computeKeyIdentifier($key['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey'], $method); case !is_object($key): return false; case $key instanceof Element: // Assume the element is a bitstring-packed key. $asn1 = new ASN1(); $decoded = $asn1->decodeBER($key->element); if (empty($decoded)) { return false; } $raw = $asn1->asn1map($decoded[0], array('type' => ASN1::TYPE_BIT_STRING)); if (empty($raw)) { return false; } $raw = base64_decode($raw); // If the key is private, compute identifier from its corresponding public key. $key = new RSA(); if (!$key->loadKey($raw)) { return false; // Not an unencrypted RSA key. } if ($key->getPrivateKey() !== false) { // If private. return $this->computeKeyIdentifier($key, $method); } $key = $raw; // Is a public key. break; case $key instanceof X509: if (isset($key->publicKey)) { return $this->computeKeyIdentifier($key->publicKey, $method); } if (isset($key->privateKey)) { return $this->computeKeyIdentifier($key->privateKey, $method); } if (isset($key->currentCert['tbsCertificate']) || isset($key->currentCert['certificationRequestInfo'])) { return $this->computeKeyIdentifier($key->currentCert, $method); } return false; default: // Should be a key object (i.e.: \phpseclib\Crypt\RSA). $key = $key->getPublicKey(RSA::PUBLIC_FORMAT_PKCS1); break; } // If in PEM format, convert to binary. $key = $this->_extractBER($key); // Now we have the key string: compute its sha-1 sum. $hash = new Hash('sha1'); $hash = $hash->hash($key); if ($method == 2) { $hash = substr($hash, -8); $hash[0] = chr((ord($hash[0]) & 0x0F) | 0x40); } return $hash; } /** * Format a public key as appropriate * * @access private * @return Array */ function _formatSubjectPublicKey() { if ($this->publicKey instanceof RSA) { // the following two return statements do the same thing. i dunno.. i just prefer the later for some reason. // the former is a good example of how to do fuzzing on the public key //return new Element(base64_decode(preg_replace('#-.+-|[\r\n]#', '', $this->publicKey->getPublicKey()))); return array( 'algorithm' => array('algorithm' => 'rsaEncryption'), 'subjectPublicKey' => $this->publicKey->getPublicKey(RSA::PUBLIC_FORMAT_PKCS1) ); } return false; } /** * Set the domain name's which the cert is to be valid for * * @access public * @return Array */ function setDomain() { $this->domains = func_get_args(); $this->removeDNProp('id-at-commonName'); $this->setDNProp('id-at-commonName', $this->domains[0]); } /** * Set the IP Addresses's which the cert is to be valid for * * @access public * @param String $ipAddress optional */ function setIPAddress() { $this->ipAddresses = func_get_args(); /* if (!isset($this->domains)) { $this->removeDNProp('id-at-commonName'); $this->setDNProp('id-at-commonName', $this->ipAddresses[0]); } */ } /** * Helper function to build domain array * * @access private * @param String $domain * @return Array */ function _dnsName($domain) { return array('dNSName' => $domain); } /** * Helper function to build IP Address array * * (IPv6 is not currently supported) * * @access private * @param String $address * @return Array */ function _iPAddress($address) { return array('iPAddress' => $address); } /** * Get the index of a revoked certificate. * * @param array $rclist * @param String $serial * @param Boolean $create optional * @access private * @return Integer or false */ function _revokedCertificate(&$rclist, $serial, $create = false) { $serial = new BigInteger($serial); foreach ($rclist as $i => $rc) { if (!($serial->compare($rc['userCertificate']))) { return $i; } } if (!$create) { return false; } $i = count($rclist); $rclist[] = array('userCertificate' => $serial, 'revocationDate' => $this->_timeField(@date('D, d M Y H:i:s O'))); return $i; } /** * Revoke a certificate. * * @param String $serial * @param String $date optional * @access public * @return Boolean */ function revoke($serial, $date = null) { if (isset($this->currentCert['tbsCertList'])) { if (is_array($rclist = &$this->_subArray($this->currentCert, 'tbsCertList/revokedCertificates', true))) { if ($this->_revokedCertificate($rclist, $serial) === false) { // If not yet revoked if (($i = $this->_revokedCertificate($rclist, $serial, true)) !== false) { if (!empty($date)) { $rclist[$i]['revocationDate'] = $this->_timeField($date); } return true; } } } } return false; } /** * Unrevoke a certificate. * * @param String $serial * @access public * @return Boolean */ function unrevoke($serial) { if (is_array($rclist = &$this->_subArray($this->currentCert, 'tbsCertList/revokedCertificates'))) { if (($i = $this->_revokedCertificate($rclist, $serial)) !== false) { unset($rclist[$i]); $rclist = array_values($rclist); return true; } } return false; } /** * Get a revoked certificate. * * @param String $serial * @access public * @return Mixed */ function getRevoked($serial) { if (is_array($rclist = $this->_subArray($this->currentCert, 'tbsCertList/revokedCertificates'))) { if (($i = $this->_revokedCertificate($rclist, $serial)) !== false) { return $rclist[$i]; } } return false; } /** * List revoked certificates * * @param array $crl optional * @access public * @return array */ function listRevoked($crl = null) { if (!isset($crl)) { $crl = $this->currentCert; } if (!isset($crl['tbsCertList'])) { return false; } $result = array(); if (is_array($rclist = $this->_subArray($crl, 'tbsCertList/revokedCertificates'))) { foreach ($rclist as $rc) { $result[] = $rc['userCertificate']->toString(); } } return $result; } /** * Remove a Revoked Certificate Extension * * @param String $serial * @param String $id * @access public * @return Boolean */ function removeRevokedCertificateExtension($serial, $id) { if (is_array($rclist = &$this->_subArray($this->currentCert, 'tbsCertList/revokedCertificates'))) { if (($i = $this->_revokedCertificate($rclist, $serial)) !== false) { return $this->_removeExtension($id, "tbsCertList/revokedCertificates/$i/crlEntryExtensions"); } } return false; } /** * Get a Revoked Certificate Extension * * Returns the extension if it exists and false if not * * @param String $serial * @param String $id * @param Array $crl optional * @access public * @return Mixed */ function getRevokedCertificateExtension($serial, $id, $crl = null) { if (!isset($crl)) { $crl = $this->currentCert; } if (is_array($rclist = $this->_subArray($crl, 'tbsCertList/revokedCertificates'))) { if (($i = $this->_revokedCertificate($rclist, $serial)) !== false) { return $this->_getExtension($id, $crl, "tbsCertList/revokedCertificates/$i/crlEntryExtensions"); } } return false; } /** * Returns a list of all extensions in use for a given revoked certificate * * @param String $serial * @param array $crl optional * @access public * @return Array */ function getRevokedCertificateExtensions($serial, $crl = null) { if (!isset($crl)) { $crl = $this->currentCert; } if (is_array($rclist = $this->_subArray($crl, 'tbsCertList/revokedCertificates'))) { if (($i = $this->_revokedCertificate($rclist, $serial)) !== false) { return $this->_getExtensions($crl, "tbsCertList/revokedCertificates/$i/crlEntryExtensions"); } } return false; } /** * Set a Revoked Certificate Extension * * @param String $serial * @param String $id * @param Mixed $value * @param Boolean $critical optional * @param Boolean $replace optional * @access public * @return Boolean */ function setRevokedCertificateExtension($serial, $id, $value, $critical = false, $replace = true) { if (isset($this->currentCert['tbsCertList'])) { if (is_array($rclist = &$this->_subArray($this->currentCert, 'tbsCertList/revokedCertificates', true))) { if (($i = $this->_revokedCertificate($rclist, $serial, true)) !== false) { return $this->_setExtension($id, $value, $critical, $replace, "tbsCertList/revokedCertificates/$i/crlEntryExtensions"); } } } return false; } /** * Extract raw BER from Base64 encoding * * @access private * @param String $str * @return String */ function _extractBER($str) { /* X.509 certs are assumed to be base64 encoded but sometimes they'll have additional things in them * above and beyond the ceritificate. * ie. some may have the following preceding the -----BEGIN CERTIFICATE----- line: * * Bag Attributes * localKeyID: 01 00 00 00 * subject=/O=organization/OU=org unit/CN=common name * issuer=/O=organization/CN=common name */ $temp = preg_replace('#.*?^-+[^-]+-+#ms', '', $str, 1); // remove the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- stuff $temp = preg_replace('#-+[^-]+-+#', '', $temp); // remove new lines $temp = str_replace(array("\r", "\n", ' '), '', $temp); $temp = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $temp) ? base64_decode($temp) : false; return $temp != false ? $temp : $str; } } Copyright 2007-2013 TerraFrost and other contributors http://phpseclib.sourceforge.net/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. > and << cannot be used, nor can the modulo operator %, * which only supports integers. Although this fact will slow this library down, the fact that such a high * base is being used should more than compensate. * * Numbers are stored in {@link http://en.wikipedia.org/wiki/Endianness little endian} format. ie. * (new \phpseclib\Math\BigInteger(pow(2, 26)))->value = array(0, 1) * * Useful resources are as follows: * * - {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf Handbook of Applied Cryptography (HAC)} * - {@link http://math.libtomcrypt.com/files/tommath.pdf Multi-Precision Math (MPM)} * - Java's BigInteger classes. See /j2se/src/share/classes/java/math in jdk-1_5_0-src-jrl.zip * * Here's an example of how to use this library: * * add($b); * * echo $c->toString(); // outputs 5 * ?> * * * @category Math * @package BigInteger * @author Jim Wigginton * @copyright 2006 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://pear.php.net/package/Math_BigInteger */ namespace phpseclib\Math; use phpseclib\Crypt\Random; /** * Pure-PHP arbitrary precision integer arithmetic library. Supports base-2, base-10, base-16, and base-256 * numbers. * * @package BigInteger * @author Jim Wigginton * @access public */ class BigInteger { /**#@+ * Reduction constants * * @access private * @see BigInteger::_reduce() */ /** * @see BigInteger::_montgomery() * @see BigInteger::_prepMontgomery() */ const MONTGOMERY = 0; /** * @see BigInteger::_barrett() */ const BARRETT = 1; /** * @see BigInteger::_mod2() */ const POWEROF2 = 2; /** * @see BigInteger::_remainder() */ const CLASSIC = 3; /** * @see BigInteger::__clone() */ const NONE = 4; /**#@-*/ /**#@+ * Array constants * * Rather than create a thousands and thousands of new BigInteger objects in repeated function calls to add() and * multiply() or whatever, we'll just work directly on arrays, taking them in as parameters and returning them. * * @access private */ /** * $result[self::VALUE] contains the value. */ const VALUE = 0; /** * $result[self::SIGN] contains the sign. */ const SIGN = 1; /**#@-*/ /**#@+ * @access private * @see BigInteger::_montgomery() * @see BigInteger::_barrett() */ /** * Cache constants * * $cache[self::VARIABLE] tells us whether or not the cached data is still valid. */ const VARIABLE = 0; /** * $cache[self::DATA] contains the cached data. */ const DATA = 1; /**#@-*/ /**#@+ * Mode constants. * * @access private * @see BigInteger::__construct() */ /** * To use the pure-PHP implementation */ const MODE_INTERNAL = 1; /** * To use the BCMath library * * (if enabled; otherwise, the internal implementation will be used) */ const MODE_BCMATH = 2; /** * To use the GMP library * * (if present; otherwise, either the BCMath or the internal implementation will be used) */ const MODE_GMP = 3; /**#@-*/ /** * Karatsuba Cutoff * * At what point do we switch between Karatsuba multiplication and schoolbook long multiplication? * * @access private */ const KARATSUBA_CUTOFF = 25; /**#@+ * Static properties used by the pure-PHP implementation. * * @see __construct() */ protected static $base; protected static $baseFull; protected static $maxDigit; protected static $msb; /** * $max10 in greatest $max10Len satisfying * $max10 = 10**$max10Len <= 2**$base. */ protected static $max10; /** * $max10Len in greatest $max10Len satisfying * $max10 = 10**$max10Len <= 2**$base. */ protected static $max10Len; protected static $maxDigit2; /**#@-*/ /** * Holds the BigInteger's value. * * @var Array * @access private */ var $value; /** * Holds the BigInteger's magnitude. * * @var Boolean * @access private */ var $is_negative = false; /** * Random number generator function * * @access private */ var $generator = 'mt_rand'; /** * Precision * * @see setPrecision() * @access private */ var $precision = -1; /** * Precision Bitmask * * @see setPrecision() * @access private */ var $bitmask = false; /** * Mode independent value used for serialization. * * If the bcmath or gmp extensions are installed $this->value will be a non-serializable resource, hence the need for * a variable that'll be serializable regardless of whether or not extensions are being used. Unlike $this->value, * however, $this->hex is only calculated when $this->__sleep() is called. * * @see __sleep() * @see __wakeup() * @var String * @access private */ var $hex; /** * Converts base-2, base-10, base-16, and binary strings (base-256) to BigIntegers. * * If the second parameter - $base - is negative, then it will be assumed that the number's are encoded using * two's compliment. The sole exception to this is -10, which is treated the same as 10 is. * * Here's an example: * * toString(); // outputs 50 * ?> * * * @param optional $x base-10 number or base-$base number if $base set. * @param optional integer $base * @return \phpseclib\Math\BigInteger * @access public */ function __construct($x = 0, $base = 10) { if ( !defined('MATH_BIGINTEGER_MODE') ) { switch (true) { case extension_loaded('gmp'): define('MATH_BIGINTEGER_MODE', self::MODE_GMP); break; case extension_loaded('bcmath'): define('MATH_BIGINTEGER_MODE', self::MODE_BCMATH); break; default: define('MATH_BIGINTEGER_MODE', self::MODE_INTERNAL); } } if (function_exists('openssl_public_encrypt') && !defined('MATH_BIGINTEGER_OPENSSL_DISABLE') && !defined('MATH_BIGINTEGER_OPENSSL_ENABLED')) { // some versions of XAMPP have mismatched versions of OpenSSL which causes it not to work ob_start(); @phpinfo(); $content = ob_get_contents(); ob_end_clean(); preg_match_all('#OpenSSL (Header|Library) Version(.*)#im', $content, $matches); $versions = array(); if (!empty($matches[1])) { for ($i = 0; $i < count($matches[1]); $i++) { $fullVersion = trim(str_replace('=>', '', strip_tags($matches[2][$i]))); // Remove letter part in OpenSSL version if (!preg_match('/(\d+\.\d+\.\d+)/i', $fullVersion, $m)) { $versions[$matches[1][$i]] = $fullVersion; } else { $versions[$matches[1][$i]] = $m[0]; } } } // it doesn't appear that OpenSSL versions were reported upon until PHP 5.3+ switch (true) { case !isset($versions['Header']): case !isset($versions['Library']): case $versions['Header'] == $versions['Library']: define('MATH_BIGINTEGER_OPENSSL_ENABLED', true); break; default: define('MATH_BIGINTEGER_OPENSSL_DISABLE', true); } } if (!defined('PHP_INT_SIZE')) { define('PHP_INT_SIZE', 4); } if (empty(self::$base) && MATH_BIGINTEGER_MODE == self::MODE_INTERNAL) { switch (PHP_INT_SIZE) { case 8: // use 64-bit integers if int size is 8 bytes self::$base = 31; self::$baseFull = 0x80000000; self::$maxDigit = 0x7FFFFFFF; self::$msb = 0x40000000; self::$max10 = 1000000000; self::$max10Len = 9; self::$maxDigit2 = pow(2, 62); break; //case 4: // use 64-bit floats if int size is 4 bytes default: self::$base = 26; self::$baseFull = 0x4000000; self::$maxDigit = 0x3FFFFFF; self::$msb = 0x2000000; self::$max10 = 10000000; self::$max10Len = 7; self::$maxDigit2 = pow(2, 52); // pow() prevents truncation break; } } switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: switch (true) { case is_resource($x) && get_resource_type($x) == 'GMP integer': // PHP 5.6 switched GMP from using resources to objects case $x instanceof \GMP: $this->value = $x; return; } $this->value = gmp_init(0); break; case self::MODE_BCMATH: $this->value = '0'; break; default: $this->value = array(); } // '0' counts as empty() but when the base is 256 '0' is equal to ord('0') or 48 // '0' is the only value like this per http://php.net/empty if (empty($x) && (abs($base) != 256 || $x !== '0')) { return; } switch ($base) { case -256: if (ord($x[0]) & 0x80) { $x = ~$x; $this->is_negative = true; } case 256: switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: $sign = $this->is_negative ? '-' : ''; $this->value = gmp_init($sign . '0x' . bin2hex($x)); break; case self::MODE_BCMATH: // round $len to the nearest 4 (thanks, DavidMJ!) $len = (strlen($x) + 3) & 0xFFFFFFFC; $x = str_pad($x, $len, chr(0), STR_PAD_LEFT); for ($i = 0; $i < $len; $i+= 4) { $this->value = bcmul($this->value, '4294967296', 0); // 4294967296 == 2**32 $this->value = bcadd($this->value, 0x1000000 * ord($x[$i]) + ((ord($x[$i + 1]) << 16) | (ord($x[$i + 2]) << 8) | ord($x[$i + 3])), 0); } if ($this->is_negative) { $this->value = '-' . $this->value; } break; // converts a base-2**8 (big endian / msb) number to base-2**26 (little endian / lsb) default: while (strlen($x)) { $this->value[] = $this->_bytes2int($this->_base256_rshift($x, self::$base)); } } if ($this->is_negative) { if (MATH_BIGINTEGER_MODE != self::MODE_INTERNAL) { $this->is_negative = false; } $temp = $this->add(new static('-1')); $this->value = $temp->value; } break; case 16: case -16: if ($base > 0 && $x[0] == '-') { $this->is_negative = true; $x = substr($x, 1); } $x = preg_replace('#^(?:0x)?([A-Fa-f0-9]*).*#', '$1', $x); $is_negative = false; if ($base < 0 && hexdec($x[0]) >= 8) { $this->is_negative = $is_negative = true; $x = bin2hex(~pack('H*', $x)); } switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: $temp = $this->is_negative ? '-0x' . $x : '0x' . $x; $this->value = gmp_init($temp); $this->is_negative = false; break; case self::MODE_BCMATH: $x = ( strlen($x) & 1 ) ? '0' . $x : $x; $temp = new static(pack('H*', $x), 256); $this->value = $this->is_negative ? '-' . $temp->value : $temp->value; $this->is_negative = false; break; default: $x = ( strlen($x) & 1 ) ? '0' . $x : $x; $temp = new static(pack('H*', $x), 256); $this->value = $temp->value; } if ($is_negative) { $temp = $this->add(new static('-1')); $this->value = $temp->value; } break; case 10: case -10: // (?value = gmp_init($x); break; case self::MODE_BCMATH: // explicitly casting $x to a string is necessary, here, since doing $x[0] on -1 yields different // results then doing it on '-1' does (modInverse does $x[0]) $this->value = $x === '-' ? '0' : (string) $x; break; default: $temp = new static(); $multiplier = new static(); $multiplier->value = array(self::$max10); if ($x[0] == '-') { $this->is_negative = true; $x = substr($x, 1); } $x = str_pad($x, strlen($x) + ((self::$max10Len - 1) * strlen($x)) % self::$max10Len, 0, STR_PAD_LEFT); while (strlen($x)) { $temp = $temp->multiply($multiplier); $temp = $temp->add(new static($this->_int2bytes(substr($x, 0, self::$max10Len)), 256)); $x = substr($x, self::$max10Len); } $this->value = $temp->value; } break; case 2: // base-2 support originally implemented by Lluis Pamies - thanks! case -2: if ($base > 0 && $x[0] == '-') { $this->is_negative = true; $x = substr($x, 1); } $x = preg_replace('#^([01]*).*#', '$1', $x); $x = str_pad($x, strlen($x) + (3 * strlen($x)) % 4, 0, STR_PAD_LEFT); $str = '0x'; while (strlen($x)) { $part = substr($x, 0, 4); $str.= dechex(bindec($part)); $x = substr($x, 4); } if ($this->is_negative) { $str = '-' . $str; } $temp = new static($str, 8 * $base); // ie. either -16 or +16 $this->value = $temp->value; $this->is_negative = $temp->is_negative; break; default: // base not supported, so we'll let $this == 0 } } /** * Converts a BigInteger to a byte string (eg. base-256). * * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're * saved as two's compliment. * * Here's an example: * * toBytes(); // outputs chr(65) * ?> * * * @param Boolean $twos_compliment * @return String * @access public * @internal Converts a base-2**26 number to base-2**8 */ function toBytes($twos_compliment = false) { if ($twos_compliment) { $comparison = $this->compare(new static()); if ($comparison == 0) { return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : ''; } $temp = $comparison < 0 ? $this->add(new static(1)) : $this->copy(); $bytes = $temp->toBytes(); if (empty($bytes)) { // eg. if the number we're trying to convert is -1 $bytes = chr(0); } if (ord($bytes[0]) & 0x80) { $bytes = chr(0) . $bytes; } return $comparison < 0 ? ~$bytes : $bytes; } switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: if (gmp_cmp($this->value, gmp_init(0)) == 0) { return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : ''; } $temp = gmp_strval(gmp_abs($this->value), 16); $temp = ( strlen($temp) & 1 ) ? '0' . $temp : $temp; $temp = pack('H*', $temp); return $this->precision > 0 ? substr(str_pad($temp, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) : ltrim($temp, chr(0)); case self::MODE_BCMATH: if ($this->value === '0') { return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : ''; } $value = ''; $current = $this->value; if ($current[0] == '-') { $current = substr($current, 1); } while (bccomp($current, '0', 0) > 0) { $temp = bcmod($current, '16777216'); $value = chr($temp >> 16) . chr($temp >> 8) . chr($temp) . $value; $current = bcdiv($current, '16777216', 0); } return $this->precision > 0 ? substr(str_pad($value, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) : ltrim($value, chr(0)); } if (!count($this->value)) { return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : ''; } $result = $this->_int2bytes($this->value[count($this->value) - 1]); $temp = $this->copy(); for ($i = count($temp->value) - 2; $i >= 0; --$i) { $temp->_base256_lshift($result, self::$base); $result = $result | str_pad($temp->_int2bytes($temp->value[$i]), strlen($result), chr(0), STR_PAD_LEFT); } return $this->precision > 0 ? str_pad(substr($result, -(($this->precision + 7) >> 3)), ($this->precision + 7) >> 3, chr(0), STR_PAD_LEFT) : $result; } /** * Converts a BigInteger to a hex string (eg. base-16)). * * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're * saved as two's compliment. * * Here's an example: * * toHex(); // outputs '41' * ?> * * * @param Boolean $twos_compliment * @return String * @access public * @internal Converts a base-2**26 number to base-2**8 */ function toHex($twos_compliment = false) { return bin2hex($this->toBytes($twos_compliment)); } /** * Converts a BigInteger to a bit string (eg. base-2). * * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're * saved as two's compliment. * * Here's an example: * * toBits(); // outputs '1000001' * ?> * * * @param Boolean $twos_compliment * @return String * @access public * @internal Converts a base-2**26 number to base-2**2 */ function toBits($twos_compliment = false) { $hex = $this->toHex($twos_compliment); $bits = ''; for ($i = strlen($hex) - 8, $start = strlen($hex) & 7; $i >= $start; $i-=8) { $bits = str_pad(decbin(hexdec(substr($hex, $i, 8))), 32, '0', STR_PAD_LEFT) . $bits; } if ($start) { // hexdec('') == 0 $bits = str_pad(decbin(hexdec(substr($hex, 0, $start))), 8, '0', STR_PAD_LEFT) . $bits; } $result = $this->precision > 0 ? substr($bits, -$this->precision) : ltrim($bits, '0'); if ($twos_compliment && $this->compare(new static()) > 0 && $this->precision <= 0) { return '0' . $result; } return $result; } /** * Converts a BigInteger to a base-10 number. * * Here's an example: * * toString(); // outputs 50 * ?> * * * @return String * @access public * @internal Converts a base-2**26 number to base-10**7 (which is pretty much base-10) */ function toString() { switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: return gmp_strval($this->value); case self::MODE_BCMATH: if ($this->value === '0') { return '0'; } return ltrim($this->value, '0'); } if (!count($this->value)) { return '0'; } $temp = $this->copy(); $temp->is_negative = false; $divisor = new static(); $divisor->value = array(self::$max10); $result = ''; while (count($temp->value)) { list($temp, $mod) = $temp->divide($divisor); $result = str_pad(isset($mod->value[0]) ? $mod->value[0] : '', self::$max10Len, '0', STR_PAD_LEFT) . $result; } $result = ltrim($result, '0'); if (empty($result)) { $result = '0'; } if ($this->is_negative) { $result = '-' . $result; } return $result; } /** * Copy an object * * PHP5 passes objects by reference while PHP4 passes by value. As such, we need a function to guarantee * that all objects are passed by value, when appropriate. More information can be found here: * * {@link http://php.net/language.oop5.basic#51624} * * @access public * @see __clone() * @return \phpseclib\Math\BigInteger */ function copy() { $temp = new static(); $temp->value = $this->value; $temp->is_negative = $this->is_negative; $temp->generator = $this->generator; $temp->precision = $this->precision; $temp->bitmask = $this->bitmask; return $temp; } /** * __toString() magic method * * Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call * toString(). * * @access public * @internal Implemented per a suggestion by Techie-Michael - thanks! */ function __toString() { return $this->toString(); } /** * __clone() magic method * * Although you can call BigInteger::__toString() directly in PHP5, you cannot call BigInteger::__clone() directly * in PHP5. You can in PHP4 since it's not a magic method, but in PHP5, you have to call it by using the PHP5 * only syntax of $y = clone $x. As such, if you're trying to write an application that works on both PHP4 and * PHP5, call BigInteger::copy(), instead. * * @access public * @see copy() * @return \phpseclib\Math\BigInteger */ function __clone() { return $this->copy(); } /** * __sleep() magic method * * Will be called, automatically, when serialize() is called on a BigInteger object. * * @see __wakeup() * @access public */ function __sleep() { $this->hex = $this->toHex(true); $vars = array('hex'); if ($this->generator != 'mt_rand') { $vars[] = 'generator'; } if ($this->precision > 0) { $vars[] = 'precision'; } return $vars; } /** * __wakeup() magic method * * Will be called, automatically, when unserialize() is called on a BigInteger object. * * @see __sleep() * @access public */ function __wakeup() { $temp = new static($this->hex, -16); $this->value = $temp->value; $this->is_negative = $temp->is_negative; if ($this->precision > 0) { // recalculate $this->bitmask $this->setPrecision($this->precision); } } /** * Adds two BigIntegers. * * Here's an example: * * add($b); * * echo $c->toString(); // outputs 30 * ?> * * * @param \phpseclib\Math\BigInteger $y * @return \phpseclib\Math\BigInteger * @access public * @internal Performs base-2**52 addition */ function add($y) { switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: $temp = new static(); $temp->value = gmp_add($this->value, $y->value); return $this->_normalize($temp); case self::MODE_BCMATH: $temp = new static(); $temp->value = bcadd($this->value, $y->value, 0); return $this->_normalize($temp); } $temp = $this->_add($this->value, $this->is_negative, $y->value, $y->is_negative); $result = new static(); $result->value = $temp[self::VALUE]; $result->is_negative = $temp[self::SIGN]; return $this->_normalize($result); } /** * Performs addition. * * @param Array $x_value * @param Boolean $x_negative * @param Array $y_value * @param Boolean $y_negative * @return Array * @access private */ function _add($x_value, $x_negative, $y_value, $y_negative) { $x_size = count($x_value); $y_size = count($y_value); if ($x_size == 0) { return array( self::VALUE => $y_value, self::SIGN => $y_negative ); } else if ($y_size == 0) { return array( self::VALUE => $x_value, self::SIGN => $x_negative ); } // subtract, if appropriate if ( $x_negative != $y_negative ) { if ( $x_value == $y_value ) { return array( self::VALUE => array(), self::SIGN => false ); } $temp = $this->_subtract($x_value, false, $y_value, false); $temp[self::SIGN] = $this->_compare($x_value, false, $y_value, false) > 0 ? $x_negative : $y_negative; return $temp; } if ($x_size < $y_size) { $size = $x_size; $value = $y_value; } else { $size = $y_size; $value = $x_value; } $value[count($value)] = 0; // just in case the carry adds an extra digit $carry = 0; for ($i = 0, $j = 1; $j < $size; $i+=2, $j+=2) { $sum = $x_value[$j] * self::$baseFull + $x_value[$i] + $y_value[$j] * self::$baseFull + $y_value[$i] + $carry; $carry = $sum >= self::$maxDigit2; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1 $sum = $carry ? $sum - self::$maxDigit2 : $sum; $temp = self::$base === 26 ? intval($sum / 0x4000000) : ($sum >> 31); $value[$i] = (int) ($sum - self::$baseFull * $temp); // eg. a faster alternative to fmod($sum, 0x4000000) $value[$j] = $temp; } if ($j == $size) { // ie. if $y_size is odd $sum = $x_value[$i] + $y_value[$i] + $carry; $carry = $sum >= self::$baseFull; $value[$i] = $carry ? $sum - self::$baseFull : $sum; ++$i; // ie. let $i = $j since we've just done $value[$i] } if ($carry) { for (; $value[$i] == self::$maxDigit; ++$i) { $value[$i] = 0; } ++$value[$i]; } return array( self::VALUE => $this->_trim($value), self::SIGN => $x_negative ); } /** * Subtracts two BigIntegers. * * Here's an example: * * subtract($b); * * echo $c->toString(); // outputs -10 * ?> * * * @param \phpseclib\Math\BigInteger $y * @return \phpseclib\Math\BigInteger * @access public * @internal Performs base-2**52 subtraction */ function subtract($y) { switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: $temp = new static(); $temp->value = gmp_sub($this->value, $y->value); return $this->_normalize($temp); case self::MODE_BCMATH: $temp = new static(); $temp->value = bcsub($this->value, $y->value, 0); return $this->_normalize($temp); } $temp = $this->_subtract($this->value, $this->is_negative, $y->value, $y->is_negative); $result = new static(); $result->value = $temp[self::VALUE]; $result->is_negative = $temp[self::SIGN]; return $this->_normalize($result); } /** * Performs subtraction. * * @param Array $x_value * @param Boolean $x_negative * @param Array $y_value * @param Boolean $y_negative * @return Array * @access private */ function _subtract($x_value, $x_negative, $y_value, $y_negative) { $x_size = count($x_value); $y_size = count($y_value); if ($x_size == 0) { return array( self::VALUE => $y_value, self::SIGN => !$y_negative ); } else if ($y_size == 0) { return array( self::VALUE => $x_value, self::SIGN => $x_negative ); } // add, if appropriate (ie. -$x - +$y or +$x - -$y) if ( $x_negative != $y_negative ) { $temp = $this->_add($x_value, false, $y_value, false); $temp[self::SIGN] = $x_negative; return $temp; } $diff = $this->_compare($x_value, $x_negative, $y_value, $y_negative); if ( !$diff ) { return array( self::VALUE => array(), self::SIGN => false ); } // switch $x and $y around, if appropriate. if ( (!$x_negative && $diff < 0) || ($x_negative && $diff > 0) ) { $temp = $x_value; $x_value = $y_value; $y_value = $temp; $x_negative = !$x_negative; $x_size = count($x_value); $y_size = count($y_value); } // at this point, $x_value should be at least as big as - if not bigger than - $y_value $carry = 0; for ($i = 0, $j = 1; $j < $y_size; $i+=2, $j+=2) { $sum = $x_value[$j] * self::$baseFull + $x_value[$i] - $y_value[$j] * self::$baseFull - $y_value[$i] - $carry; $carry = $sum < 0; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1 $sum = $carry ? $sum + self::$maxDigit2 : $sum; $temp = self::$base === 26 ? intval($sum / 0x4000000) : ($sum >> 31); $x_value[$i] = (int) ($sum - self::$baseFull * $temp); $x_value[$j] = $temp; } if ($j == $y_size) { // ie. if $y_size is odd $sum = $x_value[$i] - $y_value[$i] - $carry; $carry = $sum < 0; $x_value[$i] = $carry ? $sum + self::$baseFull : $sum; ++$i; } if ($carry) { for (; !$x_value[$i]; ++$i) { $x_value[$i] = self::$maxDigit; } --$x_value[$i]; } return array( self::VALUE => $this->_trim($x_value), self::SIGN => $x_negative ); } /** * Multiplies two BigIntegers * * Here's an example: * * multiply($b); * * echo $c->toString(); // outputs 200 * ?> * * * @param \phpseclib\Math\BigInteger $x * @return \phpseclib\Math\BigInteger * @access public */ function multiply($x) { switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: $temp = new static(); $temp->value = gmp_mul($this->value, $x->value); return $this->_normalize($temp); case self::MODE_BCMATH: $temp = new static(); $temp->value = bcmul($this->value, $x->value, 0); return $this->_normalize($temp); } $temp = $this->_multiply($this->value, $this->is_negative, $x->value, $x->is_negative); $product = new static(); $product->value = $temp[self::VALUE]; $product->is_negative = $temp[self::SIGN]; return $this->_normalize($product); } /** * Performs multiplication. * * @param Array $x_value * @param Boolean $x_negative * @param Array $y_value * @param Boolean $y_negative * @return Array * @access private */ function _multiply($x_value, $x_negative, $y_value, $y_negative) { //if ( $x_value == $y_value ) { // return array( // self::VALUE => $this->_square($x_value), // self::SIGN => $x_sign != $y_value // ); //} $x_length = count($x_value); $y_length = count($y_value); if ( !$x_length || !$y_length ) { // a 0 is being multiplied return array( self::VALUE => array(), self::SIGN => false ); } return array( self::VALUE => min($x_length, $y_length) < 2 * self::KARATSUBA_CUTOFF ? $this->_trim($this->_regularMultiply($x_value, $y_value)) : $this->_trim($this->_karatsuba($x_value, $y_value)), self::SIGN => $x_negative != $y_negative ); } /** * Performs long multiplication on two BigIntegers * * Modeled after 'multiply' in MutableBigInteger.java. * * @param Array $x_value * @param Array $y_value * @return Array * @access private */ function _regularMultiply($x_value, $y_value) { $x_length = count($x_value); $y_length = count($y_value); if ( !$x_length || !$y_length ) { // a 0 is being multiplied return array(); } if ( $x_length < $y_length ) { $temp = $x_value; $x_value = $y_value; $y_value = $temp; $x_length = count($x_value); $y_length = count($y_value); } $product_value = $this->_array_repeat(0, $x_length + $y_length); // the following for loop could be removed if the for loop following it // (the one with nested for loops) initially set $i to 0, but // doing so would also make the result in one set of unnecessary adds, // since on the outermost loops first pass, $product->value[$k] is going // to always be 0 $carry = 0; for ($j = 0; $j < $x_length; ++$j) { // ie. $i = 0 $temp = $x_value[$j] * $y_value[0] + $carry; // $product_value[$k] == 0 $carry = self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31); $product_value[$j] = (int) ($temp - self::$baseFull * $carry); } $product_value[$j] = $carry; // the above for loop is what the previous comment was talking about. the // following for loop is the "one with nested for loops" for ($i = 1; $i < $y_length; ++$i) { $carry = 0; for ($j = 0, $k = $i; $j < $x_length; ++$j, ++$k) { $temp = $product_value[$k] + $x_value[$j] * $y_value[$i] + $carry; $carry = self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31); $product_value[$k] = (int) ($temp - self::$baseFull * $carry); } $product_value[$k] = $carry; } return $product_value; } /** * Performs Karatsuba multiplication on two BigIntegers * * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=120 MPM 5.2.3}. * * @param Array $x_value * @param Array $y_value * @return Array * @access private */ function _karatsuba($x_value, $y_value) { $m = min(count($x_value) >> 1, count($y_value) >> 1); if ($m < self::KARATSUBA_CUTOFF) { return $this->_regularMultiply($x_value, $y_value); } $x1 = array_slice($x_value, $m); $x0 = array_slice($x_value, 0, $m); $y1 = array_slice($y_value, $m); $y0 = array_slice($y_value, 0, $m); $z2 = $this->_karatsuba($x1, $y1); $z0 = $this->_karatsuba($x0, $y0); $z1 = $this->_add($x1, false, $x0, false); $temp = $this->_add($y1, false, $y0, false); $z1 = $this->_karatsuba($z1[self::VALUE], $temp[self::VALUE]); $temp = $this->_add($z2, false, $z0, false); $z1 = $this->_subtract($z1, false, $temp[self::VALUE], false); $z2 = array_merge(array_fill(0, 2 * $m, 0), $z2); $z1[self::VALUE] = array_merge(array_fill(0, $m, 0), $z1[self::VALUE]); $xy = $this->_add($z2, false, $z1[self::VALUE], $z1[self::SIGN]); $xy = $this->_add($xy[self::VALUE], $xy[self::SIGN], $z0, false); return $xy[self::VALUE]; } /** * Performs squaring * * @param Array $x * @return Array * @access private */ function _square($x = false) { return count($x) < 2 * self::KARATSUBA_CUTOFF ? $this->_trim($this->_baseSquare($x)) : $this->_trim($this->_karatsubaSquare($x)); } /** * Performs traditional squaring on two BigIntegers * * Squaring can be done faster than multiplying a number by itself can be. See * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=7 HAC 14.2.4} / * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=141 MPM 5.3} for more information. * * @param Array $value * @return Array * @access private */ function _baseSquare($value) { if ( empty($value) ) { return array(); } $square_value = $this->_array_repeat(0, 2 * count($value)); for ($i = 0, $max_index = count($value) - 1; $i <= $max_index; ++$i) { $i2 = $i << 1; $temp = $square_value[$i2] + $value[$i] * $value[$i]; $carry = self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31); $square_value[$i2] = (int) ($temp - self::$baseFull * $carry); // note how we start from $i+1 instead of 0 as we do in multiplication. for ($j = $i + 1, $k = $i2 + 1; $j <= $max_index; ++$j, ++$k) { $temp = $square_value[$k] + 2 * $value[$j] * $value[$i] + $carry; $carry = self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31); $square_value[$k] = (int) ($temp - self::$baseFull * $carry); } // the following line can yield values larger 2**15. at this point, PHP should switch // over to floats. $square_value[$i + $max_index + 1] = $carry; } return $square_value; } /** * Performs Karatsuba "squaring" on two BigIntegers * * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=151 MPM 5.3.4}. * * @param Array $value * @return Array * @access private */ function _karatsubaSquare($value) { $m = count($value) >> 1; if ($m < self::KARATSUBA_CUTOFF) { return $this->_baseSquare($value); } $x1 = array_slice($value, $m); $x0 = array_slice($value, 0, $m); $z2 = $this->_karatsubaSquare($x1); $z0 = $this->_karatsubaSquare($x0); $z1 = $this->_add($x1, false, $x0, false); $z1 = $this->_karatsubaSquare($z1[self::VALUE]); $temp = $this->_add($z2, false, $z0, false); $z1 = $this->_subtract($z1, false, $temp[self::VALUE], false); $z2 = array_merge(array_fill(0, 2 * $m, 0), $z2); $z1[self::VALUE] = array_merge(array_fill(0, $m, 0), $z1[self::VALUE]); $xx = $this->_add($z2, false, $z1[self::VALUE], $z1[self::SIGN]); $xx = $this->_add($xx[self::VALUE], $xx[self::SIGN], $z0, false); return $xx[self::VALUE]; } /** * Divides two BigIntegers. * * Returns an array whose first element contains the quotient and whose second element contains the * "common residue". If the remainder would be positive, the "common residue" and the remainder are the * same. If the remainder would be negative, the "common residue" is equal to the sum of the remainder * and the divisor (basically, the "common residue" is the first positive modulo). * * Here's an example: * * divide($b); * * echo $quotient->toString(); // outputs 0 * echo "\r\n"; * echo $remainder->toString(); // outputs 10 * ?> * * * @param \phpseclib\Math\BigInteger $y * @return Array * @access public * @internal This function is based off of {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=9 HAC 14.20}. */ function divide($y) { switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: $quotient = new static(); $remainder = new static(); list($quotient->value, $remainder->value) = gmp_div_qr($this->value, $y->value); if (gmp_sign($remainder->value) < 0) { $remainder->value = gmp_add($remainder->value, gmp_abs($y->value)); } return array($this->_normalize($quotient), $this->_normalize($remainder)); case self::MODE_BCMATH: $quotient = new static(); $remainder = new static(); $quotient->value = bcdiv($this->value, $y->value, 0); $remainder->value = bcmod($this->value, $y->value); if ($remainder->value[0] == '-') { $remainder->value = bcadd($remainder->value, $y->value[0] == '-' ? substr($y->value, 1) : $y->value, 0); } return array($this->_normalize($quotient), $this->_normalize($remainder)); } if (count($y->value) == 1) { list($q, $r) = $this->_divide_digit($this->value, $y->value[0]); $quotient = new static(); $remainder = new static(); $quotient->value = $q; $remainder->value = array($r); $quotient->is_negative = $this->is_negative != $y->is_negative; return array($this->_normalize($quotient), $this->_normalize($remainder)); } static $zero; if ( !isset($zero) ) { $zero = new static(); } $x = $this->copy(); $y = $y->copy(); $x_sign = $x->is_negative; $y_sign = $y->is_negative; $x->is_negative = $y->is_negative = false; $diff = $x->compare($y); if ( !$diff ) { $temp = new static(); $temp->value = array(1); $temp->is_negative = $x_sign != $y_sign; return array($this->_normalize($temp), $this->_normalize(new static())); } if ( $diff < 0 ) { // if $x is negative, "add" $y. if ( $x_sign ) { $x = $y->subtract($x); } return array($this->_normalize(new static()), $this->_normalize($x)); } // normalize $x and $y as described in HAC 14.23 / 14.24 $msb = $y->value[count($y->value) - 1]; for ($shift = 0; !($msb & self::$msb); ++$shift) { $msb <<= 1; } $x->_lshift($shift); $y->_lshift($shift); $y_value = &$y->value; $x_max = count($x->value) - 1; $y_max = count($y->value) - 1; $quotient = new static(); $quotient_value = &$quotient->value; $quotient_value = $this->_array_repeat(0, $x_max - $y_max + 1); static $temp, $lhs, $rhs; if (!isset($temp)) { $temp = new static(); $lhs = new static(); $rhs = new static(); } $temp_value = &$temp->value; $rhs_value = &$rhs->value; // $temp = $y << ($x_max - $y_max-1) in base 2**26 $temp_value = array_merge($this->_array_repeat(0, $x_max - $y_max), $y_value); while ( $x->compare($temp) >= 0 ) { // calculate the "common residue" ++$quotient_value[$x_max - $y_max]; $x = $x->subtract($temp); $x_max = count($x->value) - 1; } for ($i = $x_max; $i >= $y_max + 1; --$i) { $x_value = &$x->value; $x_window = array( isset($x_value[$i]) ? $x_value[$i] : 0, isset($x_value[$i - 1]) ? $x_value[$i - 1] : 0, isset($x_value[$i - 2]) ? $x_value[$i - 2] : 0 ); $y_window = array( $y_value[$y_max], ( $y_max > 0 ) ? $y_value[$y_max - 1] : 0 ); $q_index = $i - $y_max - 1; if ($x_window[0] == $y_window[0]) { $quotient_value[$q_index] = self::$maxDigit; } else { $quotient_value[$q_index] = $this->_safe_divide( $x_window[0] * self::$baseFull + $x_window[1], $y_window[0] ); } $temp_value = array($y_window[1], $y_window[0]); $lhs->value = array($quotient_value[$q_index]); $lhs = $lhs->multiply($temp); $rhs_value = array($x_window[2], $x_window[1], $x_window[0]); while ( $lhs->compare($rhs) > 0 ) { --$quotient_value[$q_index]; $lhs->value = array($quotient_value[$q_index]); $lhs = $lhs->multiply($temp); } $adjust = $this->_array_repeat(0, $q_index); $temp_value = array($quotient_value[$q_index]); $temp = $temp->multiply($y); $temp_value = &$temp->value; $temp_value = array_merge($adjust, $temp_value); $x = $x->subtract($temp); if ($x->compare($zero) < 0) { $temp_value = array_merge($adjust, $y_value); $x = $x->add($temp); --$quotient_value[$q_index]; } $x_max = count($x_value) - 1; } // unnormalize the remainder $x->_rshift($shift); $quotient->is_negative = $x_sign != $y_sign; // calculate the "common residue", if appropriate if ( $x_sign ) { $y->_rshift($shift); $x = $y->subtract($x); } return array($this->_normalize($quotient), $this->_normalize($x)); } /** * Divides a BigInteger by a regular integer * * abc / x = a00 / x + b0 / x + c / x * * @param Array $dividend * @param Array $divisor * @return Array * @access private */ function _divide_digit($dividend, $divisor) { $carry = 0; $result = array(); for ($i = count($dividend) - 1; $i >= 0; --$i) { $temp = self::$baseFull * $carry + $dividend[$i]; $result[$i] = $this->_safe_divide($temp, $divisor); $carry = (int) ($temp - $divisor * $result[$i]); } return array($result, $carry); } /** * Performs modular exponentiation. * * Here's an example: * * modPow($b, $c); * * echo $c->toString(); // outputs 10 * ?> * * * @param \phpseclib\Math\BigInteger $e * @param \phpseclib\Math\BigInteger $n * @return \phpseclib\Math\BigInteger * @access public * @internal The most naive approach to modular exponentiation has very unreasonable requirements, and * and although the approach involving repeated squaring does vastly better, it, too, is impractical * for our purposes. The reason being that division - by far the most complicated and time-consuming * of the basic operations (eg. +,-,*,/) - occurs multiple times within it. * * Modular reductions resolve this issue. Although an individual modular reduction takes more time * then an individual division, when performed in succession (with the same modulo), they're a lot faster. * * The two most commonly used modular reductions are Barrett and Montgomery reduction. Montgomery reduction, * although faster, only works when the gcd of the modulo and of the base being used is 1. In RSA, when the * base is a power of two, the modulo - a product of two primes - is always going to have a gcd of 1 (because * the product of two odd numbers is odd), but what about when RSA isn't used? * * In contrast, Barrett reduction has no such constraint. As such, some bigint implementations perform a * Barrett reduction after every operation in the modpow function. Others perform Barrett reductions when the * modulo is even and Montgomery reductions when the modulo is odd. BigInteger.java's modPow method, however, * uses a trick involving the Chinese Remainder Theorem to factor the even modulo into two numbers - one odd and * the other, a power of two - and recombine them, later. This is the method that this modPow function uses. * {@link http://islab.oregonstate.edu/papers/j34monex.pdf Montgomery Reduction with Even Modulus} elaborates. */ function modPow($e, $n) { $n = $this->bitmask !== false && $this->bitmask->compare($n) < 0 ? $this->bitmask : $n->abs(); if ($e->compare(new static()) < 0) { $e = $e->abs(); $temp = $this->modInverse($n); if ($temp === false) { return false; } return $this->_normalize($temp->modPow($e, $n)); } if ( MATH_BIGINTEGER_MODE == self::MODE_GMP ) { $temp = new static(); $temp->value = gmp_powm($this->value, $e->value, $n->value); return $this->_normalize($temp); } if ($this->compare(new static()) < 0 || $this->compare($n) > 0) { list(, $temp) = $this->divide($n); return $temp->modPow($e, $n); } if (defined('MATH_BIGINTEGER_OPENSSL_ENABLED')) { $components = array( 'modulus' => $n->toBytes(true), 'publicExponent' => $e->toBytes(true) ); $components = array( 'modulus' => pack('Ca*a*', 2, $this->_encodeASN1Length(strlen($components['modulus'])), $components['modulus']), 'publicExponent' => pack('Ca*a*', 2, $this->_encodeASN1Length(strlen($components['publicExponent'])), $components['publicExponent']) ); $RSAPublicKey = pack('Ca*a*a*', 48, $this->_encodeASN1Length(strlen($components['modulus']) + strlen($components['publicExponent'])), $components['modulus'], $components['publicExponent'] ); $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA $RSAPublicKey = chr(0) . $RSAPublicKey; $RSAPublicKey = chr(3) . $this->_encodeASN1Length(strlen($RSAPublicKey)) . $RSAPublicKey; $encapsulated = pack('Ca*a*', 48, $this->_encodeASN1Length(strlen($rsaOID . $RSAPublicKey)), $rsaOID . $RSAPublicKey ); $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" . chunk_split(base64_encode($encapsulated)) . '-----END PUBLIC KEY-----'; $plaintext = str_pad($this->toBytes(), strlen($n->toBytes(true)) - 1, "\0", STR_PAD_LEFT); if (openssl_public_encrypt($plaintext, $result, $RSAPublicKey, OPENSSL_NO_PADDING)) { return new static($result, 256); } } if ( MATH_BIGINTEGER_MODE == self::MODE_BCMATH ) { $temp = new static(); $temp->value = bcpowmod($this->value, $e->value, $n->value, 0); return $this->_normalize($temp); } if ( empty($e->value) ) { $temp = new static(); $temp->value = array(1); return $this->_normalize($temp); } if ( $e->value == array(1) ) { list(, $temp) = $this->divide($n); return $this->_normalize($temp); } if ( $e->value == array(2) ) { $temp = new static(); $temp->value = $this->_square($this->value); list(, $temp) = $temp->divide($n); return $this->_normalize($temp); } return $this->_normalize($this->_slidingWindow($e, $n, self::BARRETT)); // the following code, although not callable, can be run independently of the above code // although the above code performed better in my benchmarks the following could might // perform better under different circumstances. in lieu of deleting it it's just been // made uncallable // is the modulo odd? if ( $n->value[0] & 1 ) { return $this->_normalize($this->_slidingWindow($e, $n, self::MONTGOMERY)); } // if it's not, it's even // find the lowest set bit (eg. the max pow of 2 that divides $n) for ($i = 0; $i < count($n->value); ++$i) { if ( $n->value[$i] ) { $temp = decbin($n->value[$i]); $j = strlen($temp) - strrpos($temp, '1') - 1; $j+= 26 * $i; break; } } // at this point, 2^$j * $n/(2^$j) == $n $mod1 = $n->copy(); $mod1->_rshift($j); $mod2 = new static(); $mod2->value = array(1); $mod2->_lshift($j); $part1 = ( $mod1->value != array(1) ) ? $this->_slidingWindow($e, $mod1, self::MONTGOMERY) : new static(); $part2 = $this->_slidingWindow($e, $mod2, self::POWEROF2); $y1 = $mod2->modInverse($mod1); $y2 = $mod1->modInverse($mod2); $result = $part1->multiply($mod2); $result = $result->multiply($y1); $temp = $part2->multiply($mod1); $temp = $temp->multiply($y2); $result = $result->add($temp); list(, $result) = $result->divide($n); return $this->_normalize($result); } /** * Performs modular exponentiation. * * Alias for modPow(). * * @param \phpseclib\Math\BigInteger $e * @param \phpseclib\Math\BigInteger $n * @return \phpseclib\Math\BigInteger * @access public */ function powMod($e, $n) { return $this->modPow($e, $n); } /** * Sliding Window k-ary Modular Exponentiation * * Based on {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=27 HAC 14.85} / * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=210 MPM 7.7}. In a departure from those algorithims, * however, this function performs a modular reduction after every multiplication and squaring operation. * As such, this function has the same preconditions that the reductions being used do. * * @param \phpseclib\Math\BigInteger $e * @param \phpseclib\Math\BigInteger $n * @param Integer $mode * @return \phpseclib\Math\BigInteger * @access private */ function _slidingWindow($e, $n, $mode) { static $window_ranges = array(7, 25, 81, 241, 673, 1793); // from BigInteger.java's oddModPow function //static $window_ranges = array(0, 7, 36, 140, 450, 1303, 3529); // from MPM 7.3.1 $e_value = $e->value; $e_length = count($e_value) - 1; $e_bits = decbin($e_value[$e_length]); for ($i = $e_length - 1; $i >= 0; --$i) { $e_bits.= str_pad(decbin($e_value[$i]), self::$base, '0', STR_PAD_LEFT); } $e_length = strlen($e_bits); // calculate the appropriate window size. // $window_size == 3 if $window_ranges is between 25 and 81, for example. for ($i = 0, $window_size = 1; $e_length > $window_ranges[$i] && $i < count($window_ranges); ++$window_size, ++$i); $n_value = $n->value; // precompute $this^0 through $this^$window_size $powers = array(); $powers[1] = $this->_prepareReduce($this->value, $n_value, $mode); $powers[2] = $this->_squareReduce($powers[1], $n_value, $mode); // we do every other number since substr($e_bits, $i, $j+1) (see below) is supposed to end // in a 1. ie. it's supposed to be odd. $temp = 1 << ($window_size - 1); for ($i = 1; $i < $temp; ++$i) { $i2 = $i << 1; $powers[$i2 + 1] = $this->_multiplyReduce($powers[$i2 - 1], $powers[2], $n_value, $mode); } $result = array(1); $result = $this->_prepareReduce($result, $n_value, $mode); for ($i = 0; $i < $e_length; ) { if ( !$e_bits[$i] ) { $result = $this->_squareReduce($result, $n_value, $mode); ++$i; } else { for ($j = $window_size - 1; $j > 0; --$j) { if ( !empty($e_bits[$i + $j]) ) { break; } } for ($k = 0; $k <= $j; ++$k) {// eg. the length of substr($e_bits, $i, $j+1) $result = $this->_squareReduce($result, $n_value, $mode); } $result = $this->_multiplyReduce($result, $powers[bindec(substr($e_bits, $i, $j + 1))], $n_value, $mode); $i+=$j + 1; } } $temp = new static(); $temp->value = $this->_reduce($result, $n_value, $mode); return $temp; } /** * Modular reduction * * For most $modes this will return the remainder. * * @see _slidingWindow() * @access private * @param Array $x * @param Array $n * @param Integer $mode * @return Array */ function _reduce($x, $n, $mode) { switch ($mode) { case self::MONTGOMERY: return $this->_montgomery($x, $n); case self::BARRETT: return $this->_barrett($x, $n); case self::POWEROF2: $lhs = new static(); $lhs->value = $x; $rhs = new static(); $rhs->value = $n; return $x->_mod2($n); case self::CLASSIC: $lhs = new static(); $lhs->value = $x; $rhs = new static(); $rhs->value = $n; list(, $temp) = $lhs->divide($rhs); return $temp->value; case self::NONE: return $x; default: // an invalid $mode was provided } } /** * Modular reduction preperation * * @see _slidingWindow() * @access private * @param Array $x * @param Array $n * @param Integer $mode * @return Array */ function _prepareReduce($x, $n, $mode) { if ($mode == self::MONTGOMERY) { return $this->_prepMontgomery($x, $n); } return $this->_reduce($x, $n, $mode); } /** * Modular multiply * * @see _slidingWindow() * @access private * @param Array $x * @param Array $y * @param Array $n * @param Integer $mode * @return Array */ function _multiplyReduce($x, $y, $n, $mode) { if ($mode == self::MONTGOMERY) { return $this->_montgomeryMultiply($x, $y, $n); } $temp = $this->_multiply($x, false, $y, false); return $this->_reduce($temp[self::VALUE], $n, $mode); } /** * Modular square * * @see _slidingWindow() * @access private * @param Array $x * @param Array $n * @param Integer $mode * @return Array */ function _squareReduce($x, $n, $mode) { if ($mode == self::MONTGOMERY) { return $this->_montgomeryMultiply($x, $x, $n); } return $this->_reduce($this->_square($x), $n, $mode); } /** * Modulos for Powers of Two * * Calculates $x%$n, where $n = 2**$e, for some $e. Since this is basically the same as doing $x & ($n-1), * we'll just use this function as a wrapper for doing that. * * @see _slidingWindow() * @access private * @param \phpseclib\Math\BigInteger * @return \phpseclib\Math\BigInteger */ function _mod2($n) { $temp = new static(); $temp->value = array(1); return $this->bitwise_and($n->subtract($temp)); } /** * Barrett Modular Reduction * * See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=14 HAC 14.3.3} / * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=165 MPM 6.2.5} for more information. Modified slightly, * so as not to require negative numbers (initially, this script didn't support negative numbers). * * Employs "folding", as described at * {@link http://www.cosic.esat.kuleuven.be/publications/thesis-149.pdf#page=66 thesis-149.pdf#page=66}. To quote from * it, "the idea [behind folding] is to find a value x' such that x (mod m) = x' (mod m), with x' being smaller than x." * * Unfortunately, the "Barrett Reduction with Folding" algorithm described in thesis-149.pdf is not, as written, all that * usable on account of (1) its not using reasonable radix points as discussed in * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=162 MPM 6.2.2} and (2) the fact that, even with reasonable * radix points, it only works when there are an even number of digits in the denominator. The reason for (2) is that * (x >> 1) + (x >> 1) != x / 2 + x / 2. If x is even, they're the same, but if x is odd, they're not. See the in-line * comments for details. * * @see _slidingWindow() * @access private * @param Array $n * @param Array $m * @return Array */ function _barrett($n, $m) { static $cache = array( self::VARIABLE => array(), self::DATA => array() ); $m_length = count($m); // if ($this->_compare($n, $this->_square($m)) >= 0) { if (count($n) > 2 * $m_length) { $lhs = new static(); $rhs = new static(); $lhs->value = $n; $rhs->value = $m; list(, $temp) = $lhs->divide($rhs); return $temp->value; } // if (m.length >> 1) + 2 <= m.length then m is too small and n can't be reduced if ($m_length < 5) { return $this->_regularBarrett($n, $m); } // n = 2 * m.length if ( ($key = array_search($m, $cache[self::VARIABLE])) === false ) { $key = count($cache[self::VARIABLE]); $cache[self::VARIABLE][] = $m; $lhs = new static(); $lhs_value = &$lhs->value; $lhs_value = $this->_array_repeat(0, $m_length + ($m_length >> 1)); $lhs_value[] = 1; $rhs = new static(); $rhs->value = $m; list($u, $m1) = $lhs->divide($rhs); $u = $u->value; $m1 = $m1->value; $cache[self::DATA][] = array( 'u' => $u, // m.length >> 1 (technically (m.length >> 1) + 1) 'm1'=> $m1 // m.length ); } else { extract($cache[self::DATA][$key]); } $cutoff = $m_length + ($m_length >> 1); $lsd = array_slice($n, 0, $cutoff); // m.length + (m.length >> 1) $msd = array_slice($n, $cutoff); // m.length >> 1 $lsd = $this->_trim($lsd); $temp = $this->_multiply($msd, false, $m1, false); $n = $this->_add($lsd, false, $temp[self::VALUE], false); // m.length + (m.length >> 1) + 1 if ($m_length & 1) { return $this->_regularBarrett($n[self::VALUE], $m); } // (m.length + (m.length >> 1) + 1) - (m.length - 1) == (m.length >> 1) + 2 $temp = array_slice($n[self::VALUE], $m_length - 1); // if even: ((m.length >> 1) + 2) + (m.length >> 1) == m.length + 2 // if odd: ((m.length >> 1) + 2) + (m.length >> 1) == (m.length - 1) + 2 == m.length + 1 $temp = $this->_multiply($temp, false, $u, false); // if even: (m.length + 2) - ((m.length >> 1) + 1) = m.length - (m.length >> 1) + 1 // if odd: (m.length + 1) - ((m.length >> 1) + 1) = m.length - (m.length >> 1) $temp = array_slice($temp[self::VALUE], ($m_length >> 1) + 1); // if even: (m.length - (m.length >> 1) + 1) + m.length = 2 * m.length - (m.length >> 1) + 1 // if odd: (m.length - (m.length >> 1)) + m.length = 2 * m.length - (m.length >> 1) $temp = $this->_multiply($temp, false, $m, false); // at this point, if m had an odd number of digits, we'd be subtracting a 2 * m.length - (m.length >> 1) digit // number from a m.length + (m.length >> 1) + 1 digit number. ie. there'd be an extra digit and the while loop // following this comment would loop a lot (hence our calling _regularBarrett() in that situation). $result = $this->_subtract($n[self::VALUE], false, $temp[self::VALUE], false); while ($this->_compare($result[self::VALUE], $result[self::SIGN], $m, false) >= 0) { $result = $this->_subtract($result[self::VALUE], $result[self::SIGN], $m, false); } return $result[self::VALUE]; } /** * (Regular) Barrett Modular Reduction * * For numbers with more than four digits BigInteger::_barrett() is faster. The difference between that and this * is that this function does not fold the denominator into a smaller form. * * @see _slidingWindow() * @access private * @param Array $x * @param Array $n * @return Array */ function _regularBarrett($x, $n) { static $cache = array( self::VARIABLE => array(), self::DATA => array() ); $n_length = count($n); if (count($x) > 2 * $n_length) { $lhs = new static(); $rhs = new static(); $lhs->value = $x; $rhs->value = $n; list(, $temp) = $lhs->divide($rhs); return $temp->value; } if ( ($key = array_search($n, $cache[self::VARIABLE])) === false ) { $key = count($cache[self::VARIABLE]); $cache[self::VARIABLE][] = $n; $lhs = new static(); $lhs_value = &$lhs->value; $lhs_value = $this->_array_repeat(0, 2 * $n_length); $lhs_value[] = 1; $rhs = new static(); $rhs->value = $n; list($temp, ) = $lhs->divide($rhs); // m.length $cache[self::DATA][] = $temp->value; } // 2 * m.length - (m.length - 1) = m.length + 1 $temp = array_slice($x, $n_length - 1); // (m.length + 1) + m.length = 2 * m.length + 1 $temp = $this->_multiply($temp, false, $cache[self::DATA][$key], false); // (2 * m.length + 1) - (m.length - 1) = m.length + 2 $temp = array_slice($temp[self::VALUE], $n_length + 1); // m.length + 1 $result = array_slice($x, 0, $n_length + 1); // m.length + 1 $temp = $this->_multiplyLower($temp, false, $n, false, $n_length + 1); // $temp == array_slice($temp->_multiply($temp, false, $n, false)->value, 0, $n_length + 1) if ($this->_compare($result, false, $temp[self::VALUE], $temp[self::SIGN]) < 0) { $corrector_value = $this->_array_repeat(0, $n_length + 1); $corrector_value[count($corrector_value)] = 1; $result = $this->_add($result, false, $corrector_value, false); $result = $result[self::VALUE]; } // at this point, we're subtracting a number with m.length + 1 digits from another number with m.length + 1 digits $result = $this->_subtract($result, false, $temp[self::VALUE], $temp[self::SIGN]); while ($this->_compare($result[self::VALUE], $result[self::SIGN], $n, false) > 0) { $result = $this->_subtract($result[self::VALUE], $result[self::SIGN], $n, false); } return $result[self::VALUE]; } /** * Performs long multiplication up to $stop digits * * If you're going to be doing array_slice($product->value, 0, $stop), some cycles can be saved. * * @see _regularBarrett() * @param Array $x_value * @param Boolean $x_negative * @param Array $y_value * @param Boolean $y_negative * @param Integer $stop * @return Array * @access private */ function _multiplyLower($x_value, $x_negative, $y_value, $y_negative, $stop) { $x_length = count($x_value); $y_length = count($y_value); if ( !$x_length || !$y_length ) { // a 0 is being multiplied return array( self::VALUE => array(), self::SIGN => false ); } if ( $x_length < $y_length ) { $temp = $x_value; $x_value = $y_value; $y_value = $temp; $x_length = count($x_value); $y_length = count($y_value); } $product_value = $this->_array_repeat(0, $x_length + $y_length); // the following for loop could be removed if the for loop following it // (the one with nested for loops) initially set $i to 0, but // doing so would also make the result in one set of unnecessary adds, // since on the outermost loops first pass, $product->value[$k] is going // to always be 0 $carry = 0; for ($j = 0; $j < $x_length; ++$j) { // ie. $i = 0, $k = $i $temp = $x_value[$j] * $y_value[0] + $carry; // $product_value[$k] == 0 $carry = self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31); $product_value[$j] = (int) ($temp - self::$baseFull * $carry); } if ($j < $stop) { $product_value[$j] = $carry; } // the above for loop is what the previous comment was talking about. the // following for loop is the "one with nested for loops" for ($i = 1; $i < $y_length; ++$i) { $carry = 0; for ($j = 0, $k = $i; $j < $x_length && $k < $stop; ++$j, ++$k) { $temp = $product_value[$k] + $x_value[$j] * $y_value[$i] + $carry; $carry = self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31); $product_value[$k] = (int) ($temp - self::$baseFull * $carry); } if ($k < $stop) { $product_value[$k] = $carry; } } return array( self::VALUE => $this->_trim($product_value), self::SIGN => $x_negative != $y_negative ); } /** * Montgomery Modular Reduction * * ($x->_prepMontgomery($n))->_montgomery($n) yields $x % $n. * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=170 MPM 6.3} provides insights on how this can be * improved upon (basically, by using the comba method). gcd($n, 2) must be equal to one for this function * to work correctly. * * @see _prepMontgomery() * @see _slidingWindow() * @access private * @param Array $x * @param Array $n * @return Array */ function _montgomery($x, $n) { static $cache = array( self::VARIABLE => array(), self::DATA => array() ); if ( ($key = array_search($n, $cache[self::VARIABLE])) === false ) { $key = count($cache[self::VARIABLE]); $cache[self::VARIABLE][] = $x; $cache[self::DATA][] = $this->_modInverse67108864($n); } $k = count($n); $result = array(self::VALUE => $x); for ($i = 0; $i < $k; ++$i) { $temp = $result[self::VALUE][$i] * $cache[self::DATA][$key]; $temp = $temp - self::$baseFull * (self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31)); $temp = $this->_regularMultiply(array($temp), $n); $temp = array_merge($this->_array_repeat(0, $i), $temp); $result = $this->_add($result[self::VALUE], false, $temp, false); } $result[self::VALUE] = array_slice($result[self::VALUE], $k); if ($this->_compare($result, false, $n, false) >= 0) { $result = $this->_subtract($result[self::VALUE], false, $n, false); } return $result[self::VALUE]; } /** * Montgomery Multiply * * Interleaves the montgomery reduction and long multiplication algorithms together as described in * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=13 HAC 14.36} * * @see _prepMontgomery() * @see _montgomery() * @access private * @param Array $x * @param Array $y * @param Array $m * @return Array */ function _montgomeryMultiply($x, $y, $m) { $temp = $this->_multiply($x, false, $y, false); return $this->_montgomery($temp[self::VALUE], $m); // the following code, although not callable, can be run independently of the above code // although the above code performed better in my benchmarks the following could might // perform better under different circumstances. in lieu of deleting it it's just been // made uncallable static $cache = array( self::VARIABLE => array(), self::DATA => array() ); if ( ($key = array_search($m, $cache[self::VARIABLE])) === false ) { $key = count($cache[self::VARIABLE]); $cache[self::VARIABLE][] = $m; $cache[self::DATA][] = $this->_modInverse67108864($m); } $n = max(count($x), count($y), count($m)); $x = array_pad($x, $n, 0); $y = array_pad($y, $n, 0); $m = array_pad($m, $n, 0); $a = array(self::VALUE => $this->_array_repeat(0, $n + 1)); for ($i = 0; $i < $n; ++$i) { $temp = $a[self::VALUE][0] + $x[$i] * $y[0]; $temp = $temp - self::$baseFull * (self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31)); $temp = $temp * $cache[self::DATA][$key]; $temp = $temp - self::$baseFull * (self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31)); $temp = $this->_add($this->_regularMultiply(array($x[$i]), $y), false, $this->_regularMultiply(array($temp), $m), false); $a = $this->_add($a[self::VALUE], false, $temp[self::VALUE], false); $a[self::VALUE] = array_slice($a[self::VALUE], 1); } if ($this->_compare($a[self::VALUE], false, $m, false) >= 0) { $a = $this->_subtract($a[self::VALUE], false, $m, false); } return $a[self::VALUE]; } /** * Prepare a number for use in Montgomery Modular Reductions * * @see _montgomery() * @see _slidingWindow() * @access private * @param Array $x * @param Array $n * @return Array */ function _prepMontgomery($x, $n) { $lhs = new static(); $lhs->value = array_merge($this->_array_repeat(0, count($n)), $x); $rhs = new static(); $rhs->value = $n; list(, $temp) = $lhs->divide($rhs); return $temp->value; } /** * Modular Inverse of a number mod 2**26 (eg. 67108864) * * Based off of the bnpInvDigit function implemented and justified in the following URL: * * {@link http://www-cs-students.stanford.edu/~tjw/jsbn/jsbn.js} * * The following URL provides more info: * * {@link http://groups.google.com/group/sci.crypt/msg/7a137205c1be7d85} * * As for why we do all the bitmasking... strange things can happen when converting from floats to ints. For * instance, on some computers, var_dump((int) -4294967297) yields int(-1) and on others, it yields * int(-2147483648). To avoid problems stemming from this, we use bitmasks to guarantee that ints aren't * auto-converted to floats. The outermost bitmask is present because without it, there's no guarantee that * the "residue" returned would be the so-called "common residue". We use fmod, in the last step, because the * maximum possible $x is 26 bits and the maximum $result is 16 bits. Thus, we have to be able to handle up to * 40 bits, which only 64-bit floating points will support. * * Thanks to Pedro Gimeno Fortea for input! * * @see _montgomery() * @access private * @param Array $x * @return Integer */ function _modInverse67108864($x) // 2**26 == 67,108,864 { $x = -$x[0]; $result = $x & 0x3; // x**-1 mod 2**2 $result = ($result * (2 - $x * $result)) & 0xF; // x**-1 mod 2**4 $result = ($result * (2 - ($x & 0xFF) * $result)) & 0xFF; // x**-1 mod 2**8 $result = ($result * ((2 - ($x & 0xFFFF) * $result) & 0xFFFF)) & 0xFFFF; // x**-1 mod 2**16 $result = fmod($result * (2 - fmod($x * $result, self::$baseFull)), self::$baseFull); // x**-1 mod 2**26 return $result & self::$maxDigit; } /** * Calculates modular inverses. * * Say you have (30 mod 17 * x mod 17) mod 17 == 1. x can be found using modular inverses. * * Here's an example: * * modInverse($b); * echo $c->toString(); // outputs 4 * * echo "\r\n"; * * $d = $a->multiply($c); * list(, $d) = $d->divide($b); * echo $d; // outputs 1 (as per the definition of modular inverse) * ?> * * * @param \phpseclib\Math\BigInteger $n * @return mixed false, if no modular inverse exists, \phpseclib\Math\BigInteger, otherwise. * @access public * @internal See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=21 HAC 14.64} for more information. */ function modInverse($n) { switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: $temp = new static(); $temp->value = gmp_invert($this->value, $n->value); return ( $temp->value === false ) ? false : $this->_normalize($temp); } static $zero, $one; if (!isset($zero)) { $zero = new static(); $one = new static(1); } // $x mod -$n == $x mod $n. $n = $n->abs(); if ($this->compare($zero) < 0) { $temp = $this->abs(); $temp = $temp->modInverse($n); return $this->_normalize($n->subtract($temp)); } extract($this->extendedGCD($n)); if (!$gcd->equals($one)) { return false; } $x = $x->compare($zero) < 0 ? $x->add($n) : $x; return $this->compare($zero) < 0 ? $this->_normalize($n->subtract($x)) : $this->_normalize($x); } /** * Calculates the greatest common divisor and Bezout's identity. * * Say you have 693 and 609. The GCD is 21. Bezout's identity states that there exist integers x and y such that * 693*x + 609*y == 21. In point of fact, there are actually an infinite number of x and y combinations and which * combination is returned is dependant upon which mode is in use. See * {@link http://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity Bezout's identity - Wikipedia} for more information. * * Here's an example: * * extendedGCD($b)); * * echo $gcd->toString() . "\r\n"; // outputs 21 * echo $a->toString() * $x->toString() + $b->toString() * $y->toString(); // outputs 21 * ?> * * * @param \phpseclib\Math\BigInteger $n * @return \phpseclib\Math\BigInteger * @access public * @internal Calculates the GCD using the binary xGCD algorithim described in * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=19 HAC 14.61}. As the text above 14.61 notes, * the more traditional algorithim requires "relatively costly multiple-precision divisions". */ function extendedGCD($n) { switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: extract(gmp_gcdext($this->value, $n->value)); return array( 'gcd' => $this->_normalize(new static($g)), 'x' => $this->_normalize(new static($s)), 'y' => $this->_normalize(new static($t)) ); case self::MODE_BCMATH: // it might be faster to use the binary xGCD algorithim here, as well, but (1) that algorithim works // best when the base is a power of 2 and (2) i don't think it'd make much difference, anyway. as is, // the basic extended euclidean algorithim is what we're using. $u = $this->value; $v = $n->value; $a = '1'; $b = '0'; $c = '0'; $d = '1'; while (bccomp($v, '0', 0) != 0) { $q = bcdiv($u, $v, 0); $temp = $u; $u = $v; $v = bcsub($temp, bcmul($v, $q, 0), 0); $temp = $a; $a = $c; $c = bcsub($temp, bcmul($a, $q, 0), 0); $temp = $b; $b = $d; $d = bcsub($temp, bcmul($b, $q, 0), 0); } return array( 'gcd' => $this->_normalize(new static($u)), 'x' => $this->_normalize(new static($a)), 'y' => $this->_normalize(new static($b)) ); } $y = $n->copy(); $x = $this->copy(); $g = new static(); $g->value = array(1); while ( !(($x->value[0] & 1)|| ($y->value[0] & 1)) ) { $x->_rshift(1); $y->_rshift(1); $g->_lshift(1); } $u = $x->copy(); $v = $y->copy(); $a = new static(); $b = new static(); $c = new static(); $d = new static(); $a->value = $d->value = $g->value = array(1); $b->value = $c->value = array(); while ( !empty($u->value) ) { while ( !($u->value[0] & 1) ) { $u->_rshift(1); if ( (!empty($a->value) && ($a->value[0] & 1)) || (!empty($b->value) && ($b->value[0] & 1)) ) { $a = $a->add($y); $b = $b->subtract($x); } $a->_rshift(1); $b->_rshift(1); } while ( !($v->value[0] & 1) ) { $v->_rshift(1); if ( (!empty($d->value) && ($d->value[0] & 1)) || (!empty($c->value) && ($c->value[0] & 1)) ) { $c = $c->add($y); $d = $d->subtract($x); } $c->_rshift(1); $d->_rshift(1); } if ($u->compare($v) >= 0) { $u = $u->subtract($v); $a = $a->subtract($c); $b = $b->subtract($d); } else { $v = $v->subtract($u); $c = $c->subtract($a); $d = $d->subtract($b); } } return array( 'gcd' => $this->_normalize($g->multiply($v)), 'x' => $this->_normalize($c), 'y' => $this->_normalize($d) ); } /** * Calculates the greatest common divisor * * Say you have 693 and 609. The GCD is 21. * * Here's an example: * * extendedGCD($b); * * echo $gcd->toString() . "\r\n"; // outputs 21 * ?> * * * @param \phpseclib\Math\BigInteger $n * @return \phpseclib\Math\BigInteger * @access public */ function gcd($n) { extract($this->extendedGCD($n)); return $gcd; } /** * Absolute value. * * @return \phpseclib\Math\BigInteger * @access public */ function abs() { $temp = new static(); switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: $temp->value = gmp_abs($this->value); break; case self::MODE_BCMATH: $temp->value = (bccomp($this->value, '0', 0) < 0) ? substr($this->value, 1) : $this->value; break; default: $temp->value = $this->value; } return $temp; } /** * Compares two numbers. * * Although one might think !$x->compare($y) means $x != $y, it, in fact, means the opposite. The reason for this is * demonstrated thusly: * * $x > $y: $x->compare($y) > 0 * $x < $y: $x->compare($y) < 0 * $x == $y: $x->compare($y) == 0 * * Note how the same comparison operator is used. If you want to test for equality, use $x->equals($y). * * @param \phpseclib\Math\BigInteger $y * @return Integer < 0 if $this is less than $y; > 0 if $this is greater than $y, and 0 if they are equal. * @access public * @see equals() * @internal Could return $this->subtract($x), but that's not as fast as what we do do. */ function compare($y) { switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: return gmp_cmp($this->value, $y->value); case self::MODE_BCMATH: return bccomp($this->value, $y->value, 0); } return $this->_compare($this->value, $this->is_negative, $y->value, $y->is_negative); } /** * Compares two numbers. * * @param Array $x_value * @param Boolean $x_negative * @param Array $y_value * @param Boolean $y_negative * @return Integer * @see compare() * @access private */ function _compare($x_value, $x_negative, $y_value, $y_negative) { if ( $x_negative != $y_negative ) { return ( !$x_negative && $y_negative ) ? 1 : -1; } $result = $x_negative ? -1 : 1; if ( count($x_value) != count($y_value) ) { return ( count($x_value) > count($y_value) ) ? $result : -$result; } $size = max(count($x_value), count($y_value)); $x_value = array_pad($x_value, $size, 0); $y_value = array_pad($y_value, $size, 0); for ($i = count($x_value) - 1; $i >= 0; --$i) { if ($x_value[$i] != $y_value[$i]) { return ( $x_value[$i] > $y_value[$i] ) ? $result : -$result; } } return 0; } /** * Tests the equality of two numbers. * * If you need to see if one number is greater than or less than another number, use BigInteger::compare() * * @param \phpseclib\Math\BigInteger $x * @return Boolean * @access public * @see compare() */ function equals($x) { switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: return gmp_cmp($this->value, $x->value) == 0; default: return $this->value === $x->value && $this->is_negative == $x->is_negative; } } /** * Set Precision * * Some bitwise operations give different results depending on the precision being used. Examples include left * shift, not, and rotates. * * @param Integer $bits * @access public */ function setPrecision($bits) { $this->precision = $bits; if ( MATH_BIGINTEGER_MODE != self::MODE_BCMATH ) { $this->bitmask = new static(chr((1 << ($bits & 0x7)) - 1) . str_repeat(chr(0xFF), $bits >> 3), 256); } else { $this->bitmask = new static(bcpow('2', $bits, 0)); } $temp = $this->_normalize($this); $this->value = $temp->value; } /** * Logical And * * @param \phpseclib\Math\BigInteger $x * @access public * @internal Implemented per a request by Lluis Pamies i Juarez * @return \phpseclib\Math\BigInteger */ function bitwise_and($x) { switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: $temp = new static(); $temp->value = gmp_and($this->value, $x->value); return $this->_normalize($temp); case self::MODE_BCMATH: $left = $this->toBytes(); $right = $x->toBytes(); $length = max(strlen($left), strlen($right)); $left = str_pad($left, $length, chr(0), STR_PAD_LEFT); $right = str_pad($right, $length, chr(0), STR_PAD_LEFT); return $this->_normalize(new static($left & $right, 256)); } $result = $this->copy(); $length = min(count($x->value), count($this->value)); $result->value = array_slice($result->value, 0, $length); for ($i = 0; $i < $length; ++$i) { $result->value[$i]&= $x->value[$i]; } return $this->_normalize($result); } /** * Logical Or * * @param \phpseclib\Math\BigInteger $x * @access public * @internal Implemented per a request by Lluis Pamies i Juarez * @return \phpseclib\Math\BigInteger */ function bitwise_or($x) { switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: $temp = new static(); $temp->value = gmp_or($this->value, $x->value); return $this->_normalize($temp); case self::MODE_BCMATH: $left = $this->toBytes(); $right = $x->toBytes(); $length = max(strlen($left), strlen($right)); $left = str_pad($left, $length, chr(0), STR_PAD_LEFT); $right = str_pad($right, $length, chr(0), STR_PAD_LEFT); return $this->_normalize(new static($left | $right, 256)); } $length = max(count($this->value), count($x->value)); $result = $this->copy(); $result->value = array_pad($result->value, $length, 0); $x->value = array_pad($x->value, $length, 0); for ($i = 0; $i < $length; ++$i) { $result->value[$i]|= $x->value[$i]; } return $this->_normalize($result); } /** * Logical Exclusive-Or * * @param \phpseclib\Math\BigInteger $x * @access public * @internal Implemented per a request by Lluis Pamies i Juarez * @return \phpseclib\Math\BigInteger */ function bitwise_xor($x) { switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: $temp = new static(); $temp->value = gmp_xor($this->value, $x->value); return $this->_normalize($temp); case self::MODE_BCMATH: $left = $this->toBytes(); $right = $x->toBytes(); $length = max(strlen($left), strlen($right)); $left = str_pad($left, $length, chr(0), STR_PAD_LEFT); $right = str_pad($right, $length, chr(0), STR_PAD_LEFT); return $this->_normalize(new static($left ^ $right, 256)); } $length = max(count($this->value), count($x->value)); $result = $this->copy(); $result->value = array_pad($result->value, $length, 0); $x->value = array_pad($x->value, $length, 0); for ($i = 0; $i < $length; ++$i) { $result->value[$i]^= $x->value[$i]; } return $this->_normalize($result); } /** * Logical Not * * @access public * @internal Implemented per a request by Lluis Pamies i Juarez * @return \phpseclib\Math\BigInteger */ function bitwise_not() { // calculuate "not" without regard to $this->precision // (will always result in a smaller number. ie. ~1 isn't 1111 1110 - it's 0) $temp = $this->toBytes(); $pre_msb = decbin(ord($temp[0])); $temp = ~$temp; $msb = decbin(ord($temp[0])); if (strlen($msb) == 8) { $msb = substr($msb, strpos($msb, '0')); } $temp[0] = chr(bindec($msb)); // see if we need to add extra leading 1's $current_bits = strlen($pre_msb) + 8 * strlen($temp) - 8; $new_bits = $this->precision - $current_bits; if ($new_bits <= 0) { return $this->_normalize(new static($temp, 256)); } // generate as many leading 1's as we need to. $leading_ones = chr((1 << ($new_bits & 0x7)) - 1) . str_repeat(chr(0xFF), $new_bits >> 3); $this->_base256_lshift($leading_ones, $current_bits); $temp = str_pad($temp, strlen($leading_ones), chr(0), STR_PAD_LEFT); return $this->_normalize(new static($leading_ones | $temp, 256)); } /** * Logical Right Shift * * Shifts BigInteger's by $shift bits, effectively dividing by 2**$shift. * * @param Integer $shift * @return \phpseclib\Math\BigInteger * @access public * @internal The only version that yields any speed increases is the internal version. */ function bitwise_rightShift($shift) { $temp = new static(); switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: static $two; if (!isset($two)) { $two = gmp_init('2'); } $temp->value = gmp_div_q($this->value, gmp_pow($two, $shift)); break; case self::MODE_BCMATH: $temp->value = bcdiv($this->value, bcpow('2', $shift, 0), 0); break; default: // could just replace _lshift with this, but then all _lshift() calls would need to be rewritten // and I don't want to do that... $temp->value = $this->value; $temp->_rshift($shift); } return $this->_normalize($temp); } /** * Logical Left Shift * * Shifts BigInteger's by $shift bits, effectively multiplying by 2**$shift. * * @param Integer $shift * @return \phpseclib\Math\BigInteger * @access public * @internal The only version that yields any speed increases is the internal version. */ function bitwise_leftShift($shift) { $temp = new static(); switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: static $two; if (!isset($two)) { $two = gmp_init('2'); } $temp->value = gmp_mul($this->value, gmp_pow($two, $shift)); break; case self::MODE_BCMATH: $temp->value = bcmul($this->value, bcpow('2', $shift, 0), 0); break; default: // could just replace _rshift with this, but then all _lshift() calls would need to be rewritten // and I don't want to do that... $temp->value = $this->value; $temp->_lshift($shift); } return $this->_normalize($temp); } /** * Logical Left Rotate * * Instead of the top x bits being dropped they're appended to the shifted bit string. * * @param Integer $shift * @return \phpseclib\Math\BigInteger * @access public */ function bitwise_leftRotate($shift) { $bits = $this->toBytes(); if ($this->precision > 0) { $precision = $this->precision; if ( MATH_BIGINTEGER_MODE == self::MODE_BCMATH ) { $mask = $this->bitmask->subtract(new static(1)); $mask = $mask->toBytes(); } else { $mask = $this->bitmask->toBytes(); } } else { $temp = ord($bits[0]); for ($i = 0; $temp >> $i; ++$i); $precision = 8 * strlen($bits) - 8 + $i; $mask = chr((1 << ($precision & 0x7)) - 1) . str_repeat(chr(0xFF), $precision >> 3); } if ($shift < 0) { $shift+= $precision; } $shift%= $precision; if (!$shift) { return $this->copy(); } $left = $this->bitwise_leftShift($shift); $left = $left->bitwise_and(new static($mask, 256)); $right = $this->bitwise_rightShift($precision - $shift); $result = MATH_BIGINTEGER_MODE != self::MODE_BCMATH ? $left->bitwise_or($right) : $left->add($right); return $this->_normalize($result); } /** * Logical Right Rotate * * Instead of the bottom x bits being dropped they're prepended to the shifted bit string. * * @param Integer $shift * @return \phpseclib\Math\BigInteger * @access public */ function bitwise_rightRotate($shift) { return $this->bitwise_leftRotate(-$shift); } /** * Generates a random BigInteger * * Byte length is equal to $length. Uses \phpseclib\Crypt\Random if it's loaded and mt_rand if it's not. * * @param Integer $length * @return \phpseclib\Math\BigInteger * @access private */ function _random_number_helper($size) { if (class_exists('\phpseclib\Crypt\Random')) { $random = Random::string($size); } else { $random = ''; if ($size & 1) { $random.= chr(mt_rand(0, 255)); } $blocks = $size >> 1; for ($i = 0; $i < $blocks; ++$i) { // mt_rand(-2147483648, 0x7FFFFFFF) always produces -2147483648 on some systems $random.= pack('n', mt_rand(0, 0xFFFF)); } } return new static($random, 256); } /** * Generate a random number * * Returns a random number between $min and $max where $min and $max * can be defined using one of the two methods: * * $min->random($max) * $max->random($min) * * @param \phpseclib\Math\BigInteger $arg1 * @param optional \phpseclib\Math\BigInteger $arg2 * @return \phpseclib\Math\BigInteger * @access public * @internal The API for creating random numbers used to be $a->random($min, $max), where $a was a BigInteger object. * That method is still supported for BC purposes. */ function random($arg1, $arg2 = false) { if ($arg1 === false) { return false; } if ($arg2 === false) { $max = $arg1; $min = $this; } else { $min = $arg1; $max = $arg2; } $compare = $max->compare($min); if (!$compare) { return $this->_normalize($min); } else if ($compare < 0) { // if $min is bigger then $max, swap $min and $max $temp = $max; $max = $min; $min = $temp; } static $one; if (!isset($one)) { $one = new static(1); } $max = $max->subtract($min->subtract($one)); $size = strlen(ltrim($max->toBytes(), chr(0))); /* doing $random % $max doesn't work because some numbers will be more likely to occur than others. eg. if $max is 140 and $random's max is 255 then that'd mean both $random = 5 and $random = 145 would produce 5 whereas the only value of random that could produce 139 would be 139. ie. not all numbers would be equally likely. some would be more likely than others. creating a whole new random number until you find one that is within the range doesn't work because, for sufficiently small ranges, the likelihood that you'd get a number within that range would be pretty small. eg. with $random's max being 255 and if your $max being 1 the probability would be pretty high that $random would be greater than $max. phpseclib works around this using the technique described here: http://crypto.stackexchange.com/questions/5708/creating-a-small-number-from-a-cryptographically-secure-random-string */ $random_max = new static(chr(1) . str_repeat("\0", $size), 256); $random = $this->_random_number_helper($size); list($max_multiple) = $random_max->divide($max); $max_multiple = $max_multiple->multiply($max); while ($random->compare($max_multiple) >= 0) { $random = $random->subtract($max_multiple); $random_max = $random_max->subtract($max_multiple); $random = $random->bitwise_leftShift(8); $random = $random->add($this->_random_number_helper(1)); $random_max = $random_max->bitwise_leftShift(8); list($max_multiple) = $random_max->divide($max); $max_multiple = $max_multiple->multiply($max); } list(, $random) = $random->divide($max); return $this->_normalize($random->add($min)); } /** * Generate a random prime number. * * If there's not a prime within the given range, false will be returned. If more than $timeout seconds have elapsed, * give up and return false. * * @param \phpseclib\Math\BigInteger $arg1 * @param optional \phpseclib\Math\BigInteger $arg2 * @param optional Integer $timeout * @return Mixed * @access public * @internal See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap4.pdf#page=15 HAC 4.44}. */ function randomPrime($arg1, $arg2 = false, $timeout = false) { if ($arg1 === false) { return false; } if ($arg2 === false) { $max = $arg1; $min = $this; } else { $min = $arg1; $max = $arg2; } $compare = $max->compare($min); if (!$compare) { return $min->isPrime() ? $min : false; } else if ($compare < 0) { // if $min is bigger then $max, swap $min and $max $temp = $max; $max = $min; $min = $temp; } static $one, $two; if (!isset($one)) { $one = new static(1); $two = new static(2); } $start = time(); $x = $this->random($min, $max); // gmp_nextprime() requires PHP 5 >= 5.2.0 per . if ( MATH_BIGINTEGER_MODE == self::MODE_GMP && function_exists('gmp_nextprime') ) { $p = new static(); $p->value = gmp_nextprime($x->value); if ($p->compare($max) <= 0) { return $p; } if (!$min->equals($x)) { $x = $x->subtract($one); } return $x->randomPrime($min, $x); } if ($x->equals($two)) { return $x; } $x->_make_odd(); if ($x->compare($max) > 0) { // if $x > $max then $max is even and if $min == $max then no prime number exists between the specified range if ($min->equals($max)) { return false; } $x = $min->copy(); $x->_make_odd(); } $initial_x = $x->copy(); while (true) { if ($timeout !== false && time() - $start > $timeout) { return false; } if ($x->isPrime()) { return $x; } $x = $x->add($two); if ($x->compare($max) > 0) { $x = $min->copy(); if ($x->equals($two)) { return $x; } $x->_make_odd(); } if ($x->equals($initial_x)) { return false; } } } /** * Make the current number odd * * If the current number is odd it'll be unchanged. If it's even, one will be added to it. * * @see randomPrime() * @access private */ function _make_odd() { switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: gmp_setbit($this->value, 0); break; case self::MODE_BCMATH: if ($this->value[strlen($this->value) - 1] % 2 == 0) { $this->value = bcadd($this->value, '1'); } break; default: $this->value[0] |= 1; } } /** * Checks a numer to see if it's prime * * Assuming the $t parameter is not set, this function has an error rate of 2**-80. The main motivation for the * $t parameter is distributability. BigInteger::randomPrime() can be distributed across multiple pageloads * on a website instead of just one. * * @param optional \phpseclib\Math\BigInteger $t * @return Boolean * @access public * @internal Uses the * {@link http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test Miller-Rabin primality test}. See * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap4.pdf#page=8 HAC 4.24}. */ function isPrime($t = false) { $length = strlen($this->toBytes()); if (!$t) { // see HAC 4.49 "Note (controlling the error probability)" // @codingStandardsIgnoreStart if ($length >= 163) { $t = 2; } // floor(1300 / 8) else if ($length >= 106) { $t = 3; } // floor( 850 / 8) else if ($length >= 81 ) { $t = 4; } // floor( 650 / 8) else if ($length >= 68 ) { $t = 5; } // floor( 550 / 8) else if ($length >= 56 ) { $t = 6; } // floor( 450 / 8) else if ($length >= 50 ) { $t = 7; } // floor( 400 / 8) else if ($length >= 43 ) { $t = 8; } // floor( 350 / 8) else if ($length >= 37 ) { $t = 9; } // floor( 300 / 8) else if ($length >= 31 ) { $t = 12; } // floor( 250 / 8) else if ($length >= 25 ) { $t = 15; } // floor( 200 / 8) else if ($length >= 18 ) { $t = 18; } // floor( 150 / 8) else { $t = 27; } // @codingStandardsIgnoreEnd } // ie. gmp_testbit($this, 0) // ie. isEven() or !isOdd() switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: return gmp_prob_prime($this->value, $t) != 0; case self::MODE_BCMATH: if ($this->value === '2') { return true; } if ($this->value[strlen($this->value) - 1] % 2 == 0) { return false; } break; default: if ($this->value == array(2)) { return true; } if (~$this->value[0] & 1) { return false; } } static $primes, $zero, $one, $two; if (!isset($primes)) { $primes = array( 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 ); if ( MATH_BIGINTEGER_MODE != self::MODE_INTERNAL ) { for ($i = 0; $i < count($primes); ++$i) { $primes[$i] = new static($primes[$i]); } } $zero = new static(); $one = new static(1); $two = new static(2); } if ($this->equals($one)) { return false; } // see HAC 4.4.1 "Random search for probable primes" if ( MATH_BIGINTEGER_MODE != self::MODE_INTERNAL ) { foreach ($primes as $prime) { list(, $r) = $this->divide($prime); if ($r->equals($zero)) { return $this->equals($prime); } } } else { $value = $this->value; foreach ($primes as $prime) { list(, $r) = $this->_divide_digit($value, $prime); if (!$r) { return count($value) == 1 && $value[0] == $prime; } } } $n = $this->copy(); $n_1 = $n->subtract($one); $n_2 = $n->subtract($two); $r = $n_1->copy(); $r_value = $r->value; // ie. $s = gmp_scan1($n, 0) and $r = gmp_div_q($n, gmp_pow(gmp_init('2'), $s)); if ( MATH_BIGINTEGER_MODE == self::MODE_BCMATH ) { $s = 0; // if $n was 1, $r would be 0 and this would be an infinite loop, hence our $this->equals($one) check earlier while ($r->value[strlen($r->value) - 1] % 2 == 0) { $r->value = bcdiv($r->value, '2', 0); ++$s; } } else { for ($i = 0, $r_length = count($r_value); $i < $r_length; ++$i) { $temp = ~$r_value[$i] & 0xFFFFFF; for ($j = 1; ($temp >> $j) & 1; ++$j); if ($j != 25) { break; } } $s = 26 * $i + $j - 1; $r->_rshift($s); } for ($i = 0; $i < $t; ++$i) { $a = $this->random($two, $n_2); $y = $a->modPow($r, $n); if (!$y->equals($one) && !$y->equals($n_1)) { for ($j = 1; $j < $s && !$y->equals($n_1); ++$j) { $y = $y->modPow($two, $n); if ($y->equals($one)) { return false; } } if (!$y->equals($n_1)) { return false; } } } return true; } /** * Logical Left Shift * * Shifts BigInteger's by $shift bits. * * @param Integer $shift * @access private */ function _lshift($shift) { if ( $shift == 0 ) { return; } $num_digits = (int) ($shift / self::$base); $shift %= self::$base; $shift = 1 << $shift; $carry = 0; for ($i = 0; $i < count($this->value); ++$i) { $temp = $this->value[$i] * $shift + $carry; $carry = self::$base === 26 ? intval($temp / 0x4000000) : ($temp >> 31); $this->value[$i] = (int) ($temp - $carry * self::$baseFull); } if ( $carry ) { $this->value[count($this->value)] = $carry; } while ($num_digits--) { array_unshift($this->value, 0); } } /** * Logical Right Shift * * Shifts BigInteger's by $shift bits. * * @param Integer $shift * @access private */ function _rshift($shift) { if ($shift == 0) { return; } $num_digits = (int) ($shift / self::$base); $shift %= self::$base; $carry_shift = self::$base - $shift; $carry_mask = (1 << $shift) - 1; if ( $num_digits ) { $this->value = array_slice($this->value, $num_digits); } $carry = 0; for ($i = count($this->value) - 1; $i >= 0; --$i) { $temp = $this->value[$i] >> $shift | $carry; $carry = ($this->value[$i] & $carry_mask) << $carry_shift; $this->value[$i] = $temp; } $this->value = $this->_trim($this->value); } /** * Normalize * * Removes leading zeros and truncates (if necessary) to maintain the appropriate precision * * @param \phpseclib\Math\BigInteger * @return \phpseclib\Math\BigInteger * @see _trim() * @access private */ function _normalize($result) { $result->precision = $this->precision; $result->bitmask = $this->bitmask; switch ( MATH_BIGINTEGER_MODE ) { case self::MODE_GMP: if (!empty($result->bitmask->value)) { $result->value = gmp_and($result->value, $result->bitmask->value); } return $result; case self::MODE_BCMATH: if (!empty($result->bitmask->value)) { $result->value = bcmod($result->value, $result->bitmask->value); } return $result; } $value = &$result->value; if ( !count($value) ) { return $result; } $value = $this->_trim($value); if (!empty($result->bitmask->value)) { $length = min(count($value), count($this->bitmask->value)); $value = array_slice($value, 0, $length); for ($i = 0; $i < $length; ++$i) { $value[$i] = $value[$i] & $this->bitmask->value[$i]; } } return $result; } /** * Trim * * Removes leading zeros * * @param Array $value * @return \phpseclib\Math\BigInteger * @access private */ function _trim($value) { for ($i = count($value) - 1; $i >= 0; --$i) { if ( $value[$i] ) { break; } unset($value[$i]); } return $value; } /** * Array Repeat * * @param $input Array * @param $multiplier mixed * @return Array * @access private */ function _array_repeat($input, $multiplier) { return ($multiplier) ? array_fill(0, $multiplier, $input) : array(); } /** * Logical Left Shift * * Shifts binary strings $shift bits, essentially multiplying by 2**$shift. * * @param $x String * @param $shift Integer * @return String * @access private */ function _base256_lshift(&$x, $shift) { if ($shift == 0) { return; } $num_bytes = $shift >> 3; // eg. floor($shift/8) $shift &= 7; // eg. $shift % 8 $carry = 0; for ($i = strlen($x) - 1; $i >= 0; --$i) { $temp = ord($x[$i]) << $shift | $carry; $x[$i] = chr($temp); $carry = $temp >> 8; } $carry = ($carry != 0) ? chr($carry) : ''; $x = $carry . $x . str_repeat(chr(0), $num_bytes); } /** * Logical Right Shift * * Shifts binary strings $shift bits, essentially dividing by 2**$shift and returning the remainder. * * @param $x String * @param $shift Integer * @return String * @access private */ function _base256_rshift(&$x, $shift) { if ($shift == 0) { $x = ltrim($x, chr(0)); return ''; } $num_bytes = $shift >> 3; // eg. floor($shift/8) $shift &= 7; // eg. $shift % 8 $remainder = ''; if ($num_bytes) { $start = $num_bytes > strlen($x) ? -strlen($x) : -$num_bytes; $remainder = substr($x, $start); $x = substr($x, 0, -$num_bytes); } $carry = 0; $carry_shift = 8 - $shift; for ($i = 0; $i < strlen($x); ++$i) { $temp = (ord($x[$i]) >> $shift) | $carry; $carry = (ord($x[$i]) << $carry_shift) & 0xFF; $x[$i] = chr($temp); } $x = ltrim($x, chr(0)); $remainder = chr($carry >> $carry_shift) . $remainder; return ltrim($remainder, chr(0)); } // one quirk about how the following functions are implemented is that PHP defines N to be an unsigned long // at 32-bits, while java's longs are 64-bits. /** * Converts 32-bit integers to bytes. * * @param Integer $x * @return String * @access private */ function _int2bytes($x) { return ltrim(pack('N', $x), chr(0)); } /** * Converts bytes to 32-bit integers * * @param String $x * @return Integer * @access private */ function _bytes2int($x) { $temp = unpack('Nint', str_pad($x, 4, chr(0), STR_PAD_LEFT)); return $temp['int']; } /** * DER-encode an integer * * The ability to DER-encode integers is needed to create RSA public keys for use with OpenSSL * * @see modPow() * @access private * @param Integer $length * @return String */ function _encodeASN1Length($length) { if ($length <= 0x7F) { return chr($length); } $temp = ltrim(pack('N', $length), chr(0)); return pack('Ca*', 0x80 | strlen($temp), $temp); } /** * Single digit division * * Even if int64 is being used the division operator will return a float64 value * if the dividend is not evenly divisible by the divisor. Since a float64 doesn't * have the precision of int64 this is a problem so, when int64 is being used, * we'll guarantee that the dividend is divisible by first subtracting the remainder. * * @access private * @param Integer $x * @param Integer $y * @return Integer */ function _safe_divide($x, $y) { if (self::$base === 26) { return (int) ($x / $y); } // self::$base === 31 return ($x - ($x % $y)) / $y; } } * login('username', 'password')) { * exit('bad login'); * } * $scp = new \phpseclib\Net\SCP($ssh); * $scp->put('abcd', str_repeat('x', 1024*1024)); * ?> * * * @category Net * @package SCP * @author Jim Wigginton * @copyright 2010 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\Net; use phpseclib\Net\SSH1; use phpseclib\Net\SSH2; /** * Pure-PHP implementations of SCP. * * @package SCP * @author Jim Wigginton * @access public */ class SCP { /**#@+ * @access public * @see \phpseclib\Net\SCP::put() */ /** * Reads data from a local file. */ const SOURCE_LOCAL_FILE = 1; /** * Reads data from a string. */ const SOURCE_STRING = 2; /**#@-*/ /**#@+ * @access private * @see \phpseclib\Net\SCP::_send() * @see \phpseclib\Net\SCP::_receive() */ /** * SSH1 is being used. */ const MODE_SSH1 = 1; /** * SSH2 is being used. */ const MODE_SSH2 = 2; /**#@-*/ /** * SSH Object * * @var Object * @access private */ var $ssh; /** * Packet Size * * @var Integer * @access private */ var $packet_size; /** * Mode * * @var Integer * @access private */ var $mode; /** * Default Constructor. * * Connects to an SSH server * * @param String $host * @param optional Integer $port * @param optional Integer $timeout * @return \phpseclib\Net\SCP * @access public */ function __construct($ssh) { if ($ssh instanceof SSH2) { $this->mode = self::MODE_SSH2; } elseif ($ssh instanceof SSH1) { $this->packet_size = 50000; $this->mode = self::MODE_SSH1; } else { return; } $this->ssh = $ssh; } /** * Uploads a file to the SCP server. * * By default, \phpseclib\Net\SCP::put() does not read from the local filesystem. $data is dumped directly into $remote_file. * So, for example, if you set $data to 'filename.ext' and then do \phpseclib\Net\SCP::get(), you will get a file, twelve bytes * long, containing 'filename.ext' as its contents. * * Setting $mode to self::SOURCE_LOCAL_FILE will change the above behavior. With self::SOURCE_LOCAL_FILE, $remote_file will * contain as many bytes as filename.ext does on your local filesystem. If your filename.ext is 1MB then that is how * large $remote_file will be, as well. * * Currently, only binary mode is supported. As such, if the line endings need to be adjusted, you will need to take * care of that, yourself. * * @param String $remote_file * @param String $data * @param optional Integer $mode * @param optional Callable $callback * @return Boolean * @access public */ function put($remote_file, $data, $mode = self::SOURCE_STRING, $callback = null) { if (!isset($this->ssh)) { return false; } if (!$this->ssh->exec('scp -t ' . escapeshellarg($remote_file), false)) { // -t = to return false; } $temp = $this->_receive(); if ($temp !== chr(0)) { return false; } if ($this->mode == self::MODE_SSH2) { $this->packet_size = $this->ssh->packet_size_client_to_server[SSH2::CHANNEL_EXEC] - 4; } $remote_file = basename($remote_file); if ($mode == self::SOURCE_STRING) { $size = strlen($data); } else { if (!is_file($data)) { user_error("$data is not a valid file", E_USER_NOTICE); return false; } $fp = @fopen($data, 'rb'); if (!$fp) { return false; } $size = filesize($data); } $this->_send('C0644 ' . $size . ' ' . $remote_file . "\n"); $temp = $this->_receive(); if ($temp !== chr(0)) { return false; } $sent = 0; while ($sent < $size) { $temp = $mode & self::SOURCE_STRING ? substr($data, $sent, $this->packet_size) : fread($fp, $this->packet_size); $this->_send($temp); $sent+= strlen($temp); if (is_callable($callback)) { call_user_func($callback, $sent); } } $this->_close(); if ($mode != self::SOURCE_STRING) { fclose($fp); } return true; } /** * Downloads a file from the SCP server. * * Returns a string containing the contents of $remote_file if $local_file is left undefined or a boolean false if * the operation was unsuccessful. If $local_file is defined, returns true or false depending on the success of the * operation * * @param String $remote_file * @param optional String $local_file * @return Mixed * @access public */ function get($remote_file, $local_file = false) { if (!isset($this->ssh)) { return false; } if (!$this->ssh->exec('scp -f ' . escapeshellarg($remote_file), false)) { // -f = from return false; } $this->_send("\0"); if (!preg_match('#(?[^ ]+) (?\d+) (?.+)#', rtrim($this->_receive()), $info)) { return false; } $this->_send("\0"); $size = 0; if ($local_file !== false) { $fp = @fopen($local_file, 'wb'); if (!$fp) { return false; } } $content = ''; while ($size < $info['size']) { $data = $this->_receive(); // SCP usually seems to split stuff out into 16k chunks $size+= strlen($data); if ($local_file === false) { $content.= $data; } else { fputs($fp, $data); } } $this->_close(); if ($local_file !== false) { fclose($fp); return true; } return $content; } /** * Sends a packet to an SSH server * * @param String $data * @access private */ function _send($data) { switch ($this->mode) { case self::MODE_SSH2: $this->ssh->_send_channel_packet(SSH2::CHANNEL_EXEC, $data); break; case self::MODE_SSH1: $data = pack('CNa*', NET_SSH1_CMSG_STDIN_DATA, strlen($data), $data); $this->ssh->_send_binary_packet($data); } } /** * Receives a packet from an SSH server * * @return String * @access private */ function _receive() { switch ($this->mode) { case self::MODE_SSH2: return $this->ssh->_get_channel_packet(SSH2::CHANNEL_EXEC, true); case self::MODE_SSH1: if (!$this->ssh->bitmap) { return false; } while (true) { $response = $this->ssh->_get_binary_packet(); switch ($response[SSH1::RESPONSE_TYPE]) { case NET_SSH1_SMSG_STDOUT_DATA: extract(unpack('Nlength', $response[SSH1::RESPONSE_DATA])); return $this->ssh->_string_shift($response[SSH1::RESPONSE_DATA], $length); case NET_SSH1_SMSG_STDERR_DATA: break; case NET_SSH1_SMSG_EXITSTATUS: $this->ssh->_send_binary_packet(chr(NET_SSH1_CMSG_EXIT_CONFIRMATION)); fclose($this->ssh->fsock); $this->ssh->bitmap = 0; return false; default: user_error('Unknown packet received', E_USER_NOTICE); return false; } } } } /** * Closes the connection to an SSH server * * @access private */ function _close() { switch ($this->mode) { case self::MODE_SSH2: $this->ssh->_close_channel(SSH2::CHANNEL_EXEC, true); break; case self::MODE_SSH1: $this->ssh->disconnect(); } } } * @copyright 2013 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\Net\SFTP; use phpseclib\Crypt\RSA; use phpseclib\Net\SFTP; /** * SFTP Stream Wrapper * * @package SFTP * @author Jim Wigginton * @access public */ class Stream { /** * SFTP instances * * Rather than re-create the connection we re-use instances if possible * * @var Array */ static $instances; /** * SFTP instance * * @var Object * @access private */ var $sftp; /** * Path * * @var String * @access private */ var $path; /** * Mode * * @var String * @access private */ var $mode; /** * Position * * @var Integer * @access private */ var $pos; /** * Size * * @var Integer * @access private */ var $size; /** * Directory entries * * @var Array * @access private */ var $entries; /** * EOF flag * * @var Boolean * @access private */ var $eof; /** * Context resource * * Technically this needs to be publically accessible so PHP can set it directly * * @var Resource * @access public */ var $context; /** * Notification callback function * * @var Callable * @access public */ var $notification; /** * Registers this class as a URL wrapper. * * @param optional String $protocol The wrapper name to be registered. * @return Boolean True on success, false otherwise. * @access public */ static function register($protocol = 'sftp') { if (in_array($protocol, stream_get_wrappers(), true)) { return false; } return stream_wrapper_register($protocol, get_called_class()); } /** * The Constructor * * @access public */ function __construct() { if (defined('NET_SFTP_STREAM_LOGGING')) { echo "__construct()\r\n"; } } /** * Path Parser * * Extract a path from a URI and actually connect to an SSH server if appropriate * * If "notification" is set as a context parameter the message code for successful login is * NET_SSH2_MSG_USERAUTH_SUCCESS. For a failed login it's NET_SSH2_MSG_USERAUTH_FAILURE. * * @param String $path * @return String * @access private */ function _parse_path($path) { extract(parse_url($path) + array('port' => 22)); if (!isset($host)) { return false; } if (isset($this->context)) { $context = stream_context_get_params($this->context); if (isset($context['notification'])) { $this->notification = $context['notification']; } } if ($host[0] == '$') { $host = substr($host, 1); global $$host; if (($$host instanceof SFTP) === false) { return false; } $this->sftp = $$host; } else { if (isset($this->context)) { $context = stream_context_get_options($this->context); } if (isset($context[$scheme]['session'])) { $sftp = $context[$scheme]['session']; } if (isset($context[$scheme]['sftp'])) { $sftp = $context[$scheme]['sftp']; } if (isset($sftp) && $sftp instanceof SFTP) { $this->sftp = $sftp; return $path; } if (isset($context[$scheme]['username'])) { $user = $context[$scheme]['username']; } if (isset($context[$scheme]['password'])) { $pass = $context[$scheme]['password']; } if (isset($context[$scheme]['privkey']) && $context[$scheme]['privkey'] instanceof RSA) { $pass = $context[$scheme]['privkey']; } if (!isset($user) || !isset($pass)) { return false; } // casting $pass to a string is necessary in the event that it's a \phpseclib\Crypt\RSA object if (isset(self::$instances[$host][$port][$user][(string) $pass])) { $this->sftp = self::$instances[$host][$port][$user][(string) $pass]; } else { $this->sftp = new SFTP($host, $port); $this->sftp->disableStatCache(); if (isset($this->notification) && is_callable($this->notification)) { /* if !is_callable($this->notification) we could do this: user_error('fopen(): failed to call user notifier', E_USER_WARNING); the ftp wrapper gives errors like that when the notifier isn't callable. i've opted not to do that, however, since the ftp wrapper gives the line on which the fopen occurred as the line number - not the line that the user_error is on. */ call_user_func($this->notification, STREAM_NOTIFY_CONNECT, STREAM_NOTIFY_SEVERITY_INFO, '', 0, 0, 0); call_user_func($this->notification, STREAM_NOTIFY_AUTH_REQUIRED, STREAM_NOTIFY_SEVERITY_INFO, '', 0, 0, 0); if (!$this->sftp->login($user, $pass)) { call_user_func($this->notification, STREAM_NOTIFY_AUTH_RESULT, STREAM_NOTIFY_SEVERITY_ERR, 'Login Failure', NET_SSH2_MSG_USERAUTH_FAILURE, 0, 0); return false; } call_user_func($this->notification, STREAM_NOTIFY_AUTH_RESULT, STREAM_NOTIFY_SEVERITY_INFO, 'Login Success', NET_SSH2_MSG_USERAUTH_SUCCESS, 0, 0); } else { if (!$this->sftp->login($user, $pass)) { return false; } } self::$instances[$host][$port][$user][(string) $pass] = $this->sftp; } } return $path; } /** * Opens file or URL * * @param String $path * @param String $mode * @param Integer $options * @param String $opened_path * @return Boolean * @access public */ function _stream_open($path, $mode, $options, &$opened_path) { $path = $this->_parse_path($path); if ($path === false) { return false; } $this->path = $path; $this->size = $this->sftp->size($path); $this->mode = preg_replace('#[bt]$#', '', $mode); $this->eof = false; if ($this->size === false) { if ($this->mode[0] == 'r') { return false; } } else { switch ($this->mode[0]) { case 'x': return false; case 'w': case 'c': $this->sftp->truncate($path, 0); } } $this->pos = $this->mode[0] != 'a' ? 0 : $this->size; return true; } /** * Read from stream * * @param Integer $count * @return Mixed * @access public */ function _stream_read($count) { switch ($this->mode) { case 'w': case 'a': case 'x': case 'c': return false; } // commented out because some files - eg. /dev/urandom - will say their size is 0 when in fact it's kinda infinite //if ($this->pos >= $this->size) { // $this->eof = true; // return false; //} $result = $this->sftp->get($this->path, false, $this->pos, $count); if (isset($this->notification) && is_callable($this->notification)) { if ($result === false) { call_user_func($this->notification, STREAM_NOTIFY_FAILURE, STREAM_NOTIFY_SEVERITY_ERR, $this->sftp->getLastSFTPError(), NET_SFTP_OPEN, 0, 0); return 0; } // seems that PHP calls stream_read in 8k chunks call_user_func($this->notification, STREAM_NOTIFY_PROGRESS, STREAM_NOTIFY_SEVERITY_INFO, '', 0, strlen($result), $this->size); } if (empty($result)) { // ie. false or empty string $this->eof = true; return false; } $this->pos+= strlen($result); return $result; } /** * Write to stream * * @param String $data * @return Mixed * @access public */ function _stream_write($data) { switch ($this->mode) { case 'r': return false; } $result = $this->sftp->put($this->path, $data, SFTP::SOURCE_STRING, $this->pos); if (isset($this->notification) && is_callable($this->notification)) { if (!$result) { call_user_func($this->notification, STREAM_NOTIFY_FAILURE, STREAM_NOTIFY_SEVERITY_ERR, $this->sftp->getLastSFTPError(), NET_SFTP_OPEN, 0, 0); return 0; } // seems that PHP splits up strings into 8k blocks before calling stream_write call_user_func($this->notification, STREAM_NOTIFY_PROGRESS, STREAM_NOTIFY_SEVERITY_INFO, '', 0, strlen($data), strlen($data)); } if ($result === false) { return false; } $this->pos+= strlen($data); if ($this->pos > $this->size) { $this->size = $this->pos; } $this->eof = false; return strlen($data); } /** * Retrieve the current position of a stream * * @return Integer * @access public */ function _stream_tell() { return $this->pos; } /** * Tests for end-of-file on a file pointer * * In my testing there are four classes functions that normally effect the pointer: * fseek, fputs / fwrite, fgets / fread and ftruncate. * * Only fgets / fread, however, results in feof() returning true. do fputs($fp, 'aaa') on a blank file and feof() * will return false. do fread($fp, 1) and feof() will then return true. do fseek($fp, 10) on ablank file and feof() * will return false. do fread($fp, 1) and feof() will then return true. * * @return Boolean * @access public */ function _stream_eof() { return $this->eof; } /** * Seeks to specific location in a stream * * @param Integer $offset * @param Integer $whence * @return Boolean * @access public */ function _stream_seek($offset, $whence) { switch ($whence) { case SEEK_SET: if ($offset >= $this->size || $offset < 0) { return false; } break; case SEEK_CUR: $offset+= $this->pos; break; case SEEK_END: $offset+= $this->size; } $this->pos = $offset; $this->eof = false; return true; } /** * Change stream options * * @param String $path * @param Integer $option * @param Mixed $var * @return Boolean * @access public */ function _stream_metadata($path, $option, $var) { $path = $this->_parse_path($path); if ($path === false) { return false; } // stream_metadata was introduced in PHP 5.4.0 but as of 5.4.11 the constants haven't been defined // see http://www.php.net/streamwrapper.stream-metadata and https://bugs.php.net/64246 // and https://github.com/php/php-src/blob/master/main/php_streams.h#L592 switch ($option) { case 1: // PHP_STREAM_META_TOUCH return $this->sftp->touch($path, $var[0], $var[1]); case 2: // PHP_STREAM_OWNER_NAME case 3: // PHP_STREAM_GROUP_NAME return false; case 4: // PHP_STREAM_META_OWNER return $this->sftp->chown($path, $var); case 5: // PHP_STREAM_META_GROUP return $this->sftp->chgrp($path, $var); case 6: // PHP_STREAM_META_ACCESS return $this->sftp->chmod($path, $var) !== false; } } /** * Retrieve the underlaying resource * * @param Integer $cast_as * @return Resource * @access public */ function _stream_cast($cast_as) { return $this->sftp->fsock; } /** * Advisory file locking * * @param Integer $operation * @return Boolean * @access public */ function _stream_lock($operation) { return false; } /** * Renames a file or directory * * Attempts to rename oldname to newname, moving it between directories if necessary. * If newname exists, it will be overwritten. This is a departure from what \phpseclib\Net\SFTP * does. * * @param String $path_from * @param String $path_to * @return Boolean * @access public */ function _rename($path_from, $path_to) { $path1 = parse_url($path_from); $path2 = parse_url($path_to); unset($path1['path'], $path2['path']); if ($path1 != $path2) { return false; } $path_from = $this->_parse_path($path_from); $path_to = parse_url($path_to); if ($path_from == false) { return false; } $path_to = $path_to['path']; // the $component part of parse_url() was added in PHP 5.1.2 // "It is an error if there already exists a file with the name specified by newpath." // -- http://tools.ietf.org/html/draft-ietf-secsh-filexfer-02#section-6.5 if (!$this->sftp->rename($path_from, $path_to)) { if ($this->sftp->stat($path_to)) { return $this->sftp->delete($path_to, true) && $this->sftp->rename($path_from, $path_to); } return false; } return true; } /** * Open directory handle * * The only $options is "whether or not to enforce safe_mode (0x04)". Since safe mode was deprecated in 5.3 and * removed in 5.4 I'm just going to ignore it. * * Also, nlist() is the best that this function is realistically going to be able to do. When an SFTP client * sends a SSH_FXP_READDIR packet you don't generally get info on just one file but on multiple files. Quoting * the SFTP specs: * * The SSH_FXP_NAME response has the following format: * * uint32 id * uint32 count * repeats count times: * string filename * string longname * ATTRS attrs * * @param String $path * @param Integer $options * @return Boolean * @access public */ function _dir_opendir($path, $options) { $path = $this->_parse_path($path); if ($path === false) { return false; } $this->pos = 0; $this->entries = $this->sftp->nlist($path); return $this->entries !== false; } /** * Read entry from directory handle * * @return Mixed * @access public */ function _dir_readdir() { if (isset($this->entries[$this->pos])) { return $this->entries[$this->pos++]; } return false; } /** * Rewind directory handle * * @return Boolean * @access public */ function _dir_rewinddir() { $this->pos = 0; return true; } /** * Close directory handle * * @return Boolean * @access public */ function _dir_closedir() { return true; } /** * Create a directory * * Only valid $options is STREAM_MKDIR_RECURSIVE * * @param String $path * @param Integer $mode * @param Integer $options * @return Boolean * @access public */ function _mkdir($path, $mode, $options) { $path = $this->_parse_path($path); if ($path === false) { return false; } return $this->sftp->mkdir($path, $mode, $options & STREAM_MKDIR_RECURSIVE); } /** * Removes a directory * * Only valid $options is STREAM_MKDIR_RECURSIVE per , however, * does not have a $recursive parameter as mkdir() does so I don't know how * STREAM_MKDIR_RECURSIVE is supposed to be set. Also, when I try it out with rmdir() I get 8 as * $options. What does 8 correspond to? * * @param String $path * @param Integer $mode * @param Integer $options * @return Boolean * @access public */ function _rmdir($path, $options) { $path = $this->_parse_path($path); if ($path === false) { return false; } return $this->sftp->rmdir($path); } /** * Flushes the output * * See . Always returns true because \phpseclib\Net\SFTP doesn't cache stuff before writing * * @return Boolean * @access public */ function _stream_flush() { return true; } /** * Retrieve information about a file resource * * @return Mixed * @access public */ function _stream_stat() { $results = $this->sftp->stat($this->path); if ($results === false) { return false; } return $results; } /** * Delete a file * * @param String $path * @return Boolean * @access public */ function _unlink($path) { $path = $this->_parse_path($path); if ($path === false) { return false; } return $this->sftp->delete($path, false); } /** * Retrieve information about a file * * Ignores the STREAM_URL_STAT_QUIET flag because the entirety of \phpseclib\Net\SFTP\Stream is quiet by default * might be worthwhile to reconstruct bits 12-16 (ie. the file type) if mode doesn't have them but we'll * cross that bridge when and if it's reached * * @param String $path * @param Integer $flags * @return Mixed * @access public */ function _url_stat($path, $flags) { $path = $this->_parse_path($path); if ($path === false) { return false; } $results = $flags & STREAM_URL_STAT_LINK ? $this->sftp->lstat($path) : $this->sftp->stat($path); if ($results === false) { return false; } return $results; } /** * Truncate stream * * @param Integer $new_size * @return Boolean * @access public */ function _stream_truncate($new_size) { if (!$this->sftp->truncate($this->path, $new_size)) { return false; } $this->eof = false; $this->size = $new_size; return true; } /** * Change stream options * * STREAM_OPTION_WRITE_BUFFER isn't supported for the same reason stream_flush isn't. * The other two aren't supported because of limitations in \phpseclib\Net\SFTP. * * @param Integer $option * @param Integer $arg1 * @param Integer $arg2 * @return Boolean * @access public */ function _stream_set_option($option, $arg1, $arg2) { return false; } /** * Close an resource * * @access public */ function _stream_close() { } /** * __call Magic Method * * When you're utilizing an SFTP stream you're not calling the methods in this class directly - PHP is calling them for you. * Which kinda begs the question... what methods is PHP calling and what parameters is it passing to them? This function * lets you figure that out. * * If NET_SFTP_STREAM_LOGGING is defined all calls will be output on the screen and then (regardless of whether or not * NET_SFTP_STREAM_LOGGING is enabled) the parameters will be passed through to the appropriate method. * * @param String * @param Array * @return Mixed * @access public */ function __call($name, $arguments) { if (defined('NET_SFTP_STREAM_LOGGING')) { echo $name . '('; $last = count($arguments) - 1; foreach ($arguments as $i => $argument) { var_export($argument); if ($i != $last) { echo ','; } } echo ")\r\n"; } $name = '_' . $name; if (!method_exists($this, $name)) { return false; } return call_user_func_array(array($this, $name), $arguments); } } * login('username', 'password')) { * exit('Login Failed'); * } * * echo $sftp->pwd() . "\r\n"; * $sftp->put('filename.ext', 'hello, world!'); * print_r($sftp->nlist()); * ?> * * * @category Net * @package SFTP * @author Jim Wigginton * @copyright 2009 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\Net; use phpseclib\Net\SSH2; /** * Pure-PHP implementations of SFTP. * * @package SFTP * @author Jim Wigginton * @access public */ class SFTP extends SSH2 { /** * SFTP channel constant * * \phpseclib\Net\SSH2::exec() uses 0 and \phpseclib\Net\SSH2::read() / \phpseclib\Net\SSH2::write() use 1. * * @see \phpseclib\Net\SSH2::_send_channel_packet() * @see \phpseclib\Net\SSH2::_get_channel_packet() * @access private */ const CHANNEL = 0x100; /**#@+ * @access public * @see \phpseclib\Net\SFTP::put() */ /** * Reads data from a local file. */ const SOURCE_LOCAL_FILE = 1; /** * Reads data from a string. */ // this value isn't really used anymore but i'm keeping it reserved for historical reasons const SOURCE_STRING = 2; /** * Resumes an upload */ const RESUME = 4; /** * Append a local file to an already existing remote file */ const RESUME_START = 8; /**#@-*/ /** * Packet Types * * @see \phpseclib\Net\SFTP::__construct() * @var Array * @access private */ var $packet_types = array(); /** * Status Codes * * @see \phpseclib\Net\SFTP::__construct() * @var Array * @access private */ var $status_codes = array(); /** * The Request ID * * The request ID exists in the off chance that a packet is sent out-of-order. Of course, this library doesn't support * concurrent actions, so it's somewhat academic, here. * * @var Integer * @see \phpseclib\Net\SFTP::_send_sftp_packet() * @access private */ var $request_id = false; /** * The Packet Type * * The request ID exists in the off chance that a packet is sent out-of-order. Of course, this library doesn't support * concurrent actions, so it's somewhat academic, here. * * @var Integer * @see \phpseclib\Net\SFTP::_get_sftp_packet() * @access private */ var $packet_type = -1; /** * Packet Buffer * * @var String * @see \phpseclib\Net\SFTP::_get_sftp_packet() * @access private */ var $packet_buffer = ''; /** * Extensions supported by the server * * @var Array * @see \phpseclib\Net\SFTP::_initChannel() * @access private */ var $extensions = array(); /** * Server SFTP version * * @var Integer * @see \phpseclib\Net\SFTP::_initChannel() * @access private */ var $version; /** * Current working directory * * @var String * @see \phpseclib\Net\SFTP::_realpath() * @see \phpseclib\Net\SFTP::chdir() * @access private */ var $pwd = false; /** * Packet Type Log * * @see \phpseclib\Net\SFTP::getLog() * @var Array * @access private */ var $packet_type_log = array(); /** * Packet Log * * @see \phpseclib\Net\SFTP::getLog() * @var Array * @access private */ var $packet_log = array(); /** * Error information * * @see \phpseclib\Net\SFTP::getSFTPErrors() * @see \phpseclib\Net\SFTP::getLastSFTPError() * @var String * @access private */ var $sftp_errors = array(); /** * Stat Cache * * Rather than always having to open a directory and close it immediately there after to see if a file is a directory * we'll cache the results. * * @see \phpseclib\Net\SFTP::_update_stat_cache() * @see \phpseclib\Net\SFTP::_remove_from_stat_cache() * @see \phpseclib\Net\SFTP::_query_stat_cache() * @var Array * @access private */ var $stat_cache = array(); /** * Max SFTP Packet Size * * @see \phpseclib\Net\SFTP::__construct() * @see \phpseclib\Net\SFTP::get() * @var Array * @access private */ var $max_sftp_packet; /** * Stat Cache Flag * * @see \phpseclib\Net\SFTP::disableStatCache() * @see \phpseclib\Net\SFTP::enableStatCache() * @var Boolean * @access private */ var $use_stat_cache = true; /** * Sort Options * * @see \phpseclib\Net\SFTP::_comparator() * @see \phpseclib\Net\SFTP::setListOrder() * @var Array * @access private */ var $sortOptions = array(); /** * Default Constructor. * * Connects to an SFTP server * * @param String $host * @param optional Integer $port * @param optional Integer $timeout * @return \phpseclib\Net\SFTP * @access public */ function __construct($host, $port = 22, $timeout = 10) { parent::__construct($host, $port, $timeout); $this->max_sftp_packet = 1 << 15; $this->packet_types = array( 1 => 'NET_SFTP_INIT', 2 => 'NET_SFTP_VERSION', /* the format of SSH_FXP_OPEN changed between SFTPv4 and SFTPv5+: SFTPv5+: http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.1 pre-SFTPv5 : http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.3 */ 3 => 'NET_SFTP_OPEN', 4 => 'NET_SFTP_CLOSE', 5 => 'NET_SFTP_READ', 6 => 'NET_SFTP_WRITE', 7 => 'NET_SFTP_LSTAT', 9 => 'NET_SFTP_SETSTAT', 11 => 'NET_SFTP_OPENDIR', 12 => 'NET_SFTP_READDIR', 13 => 'NET_SFTP_REMOVE', 14 => 'NET_SFTP_MKDIR', 15 => 'NET_SFTP_RMDIR', 16 => 'NET_SFTP_REALPATH', 17 => 'NET_SFTP_STAT', /* the format of SSH_FXP_RENAME changed between SFTPv4 and SFTPv5+: SFTPv5+: http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.3 pre-SFTPv5 : http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.5 */ 18 => 'NET_SFTP_RENAME', 19 => 'NET_SFTP_READLINK', 20 => 'NET_SFTP_SYMLINK', 101=> 'NET_SFTP_STATUS', 102=> 'NET_SFTP_HANDLE', /* the format of SSH_FXP_NAME changed between SFTPv3 and SFTPv4+: SFTPv4+: http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-9.4 pre-SFTPv4 : http://tools.ietf.org/html/draft-ietf-secsh-filexfer-02#section-7 */ 103=> 'NET_SFTP_DATA', 104=> 'NET_SFTP_NAME', 105=> 'NET_SFTP_ATTRS', 200=> 'NET_SFTP_EXTENDED' ); $this->status_codes = array( 0 => 'NET_SFTP_STATUS_OK', 1 => 'NET_SFTP_STATUS_EOF', 2 => 'NET_SFTP_STATUS_NO_SUCH_FILE', 3 => 'NET_SFTP_STATUS_PERMISSION_DENIED', 4 => 'NET_SFTP_STATUS_FAILURE', 5 => 'NET_SFTP_STATUS_BAD_MESSAGE', 6 => 'NET_SFTP_STATUS_NO_CONNECTION', 7 => 'NET_SFTP_STATUS_CONNECTION_LOST', 8 => 'NET_SFTP_STATUS_OP_UNSUPPORTED', 9 => 'NET_SFTP_STATUS_INVALID_HANDLE', 10 => 'NET_SFTP_STATUS_NO_SUCH_PATH', 11 => 'NET_SFTP_STATUS_FILE_ALREADY_EXISTS', 12 => 'NET_SFTP_STATUS_WRITE_PROTECT', 13 => 'NET_SFTP_STATUS_NO_MEDIA', 14 => 'NET_SFTP_STATUS_NO_SPACE_ON_FILESYSTEM', 15 => 'NET_SFTP_STATUS_QUOTA_EXCEEDED', 16 => 'NET_SFTP_STATUS_UNKNOWN_PRINCIPAL', 17 => 'NET_SFTP_STATUS_LOCK_CONFLICT', 18 => 'NET_SFTP_STATUS_DIR_NOT_EMPTY', 19 => 'NET_SFTP_STATUS_NOT_A_DIRECTORY', 20 => 'NET_SFTP_STATUS_INVALID_FILENAME', 21 => 'NET_SFTP_STATUS_LINK_LOOP', 22 => 'NET_SFTP_STATUS_CANNOT_DELETE', 23 => 'NET_SFTP_STATUS_INVALID_PARAMETER', 24 => 'NET_SFTP_STATUS_FILE_IS_A_DIRECTORY', 25 => 'NET_SFTP_STATUS_BYTE_RANGE_LOCK_CONFLICT', 26 => 'NET_SFTP_STATUS_BYTE_RANGE_LOCK_REFUSED', 27 => 'NET_SFTP_STATUS_DELETE_PENDING', 28 => 'NET_SFTP_STATUS_FILE_CORRUPT', 29 => 'NET_SFTP_STATUS_OWNER_INVALID', 30 => 'NET_SFTP_STATUS_GROUP_INVALID', 31 => 'NET_SFTP_STATUS_NO_MATCHING_BYTE_RANGE_LOCK' ); // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-7.1 // the order, in this case, matters quite a lot - see \phpseclib\Net\SFTP::_parseAttributes() to understand why $this->attributes = array( 0x00000001 => 'NET_SFTP_ATTR_SIZE', 0x00000002 => 'NET_SFTP_ATTR_UIDGID', // defined in SFTPv3, removed in SFTPv4+ 0x00000004 => 'NET_SFTP_ATTR_PERMISSIONS', 0x00000008 => 'NET_SFTP_ATTR_ACCESSTIME', // 0x80000000 will yield a floating point on 32-bit systems and converting floating points to integers // yields inconsistent behavior depending on how php is compiled. so we left shift -1 (which, in // two's compliment, consists of all 1 bits) by 31. on 64-bit systems this'll yield 0xFFFFFFFF80000000. // that's not a problem, however, and 'anded' and a 32-bit number, as all the leading 1 bits are ignored. -1 << 31 => 'NET_SFTP_ATTR_EXTENDED' ); // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.3 // the flag definitions change somewhat in SFTPv5+. if SFTPv5+ support is added to this library, maybe name // the array for that $this->open5_flags and similarily alter the constant names. $this->open_flags = array( 0x00000001 => 'NET_SFTP_OPEN_READ', 0x00000002 => 'NET_SFTP_OPEN_WRITE', 0x00000004 => 'NET_SFTP_OPEN_APPEND', 0x00000008 => 'NET_SFTP_OPEN_CREATE', 0x00000010 => 'NET_SFTP_OPEN_TRUNCATE', 0x00000020 => 'NET_SFTP_OPEN_EXCL' ); // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-5.2 // see \phpseclib\Net\SFTP::_parseLongname() for an explanation $this->file_types = array( 1 => 'NET_SFTP_TYPE_REGULAR', 2 => 'NET_SFTP_TYPE_DIRECTORY', 3 => 'NET_SFTP_TYPE_SYMLINK', 4 => 'NET_SFTP_TYPE_SPECIAL', 5 => 'NET_SFTP_TYPE_UNKNOWN', // the followin types were first defined for use in SFTPv5+ // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-05#section-5.2 6 => 'NET_SFTP_TYPE_SOCKET', 7 => 'NET_SFTP_TYPE_CHAR_DEVICE', 8 => 'NET_SFTP_TYPE_BLOCK_DEVICE', 9 => 'NET_SFTP_TYPE_FIFO' ); $this->_define_array( $this->packet_types, $this->status_codes, $this->attributes, $this->open_flags, $this->file_types ); if (!defined('NET_SFTP_QUEUE_SIZE')) { define('NET_SFTP_QUEUE_SIZE', 50); } } /** * Login * * @param String $username * @param optional String $password * @return Boolean * @access public */ function login($username) { $args = func_get_args(); if (!call_user_func_array(array(&$this, '_login'), $args)) { return false; } $this->window_size_server_to_client[self::CHANNEL] = $this->window_size; $packet = pack('CNa*N3', NET_SSH2_MSG_CHANNEL_OPEN, strlen('session'), 'session', self::CHANNEL, $this->window_size, 0x4000); if (!$this->_send_binary_packet($packet)) { return false; } $this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_OPEN; $response = $this->_get_channel_packet(self::CHANNEL); if ($response === false) { return false; } $packet = pack('CNNa*CNa*', NET_SSH2_MSG_CHANNEL_REQUEST, $this->server_channels[self::CHANNEL], strlen('subsystem'), 'subsystem', 1, strlen('sftp'), 'sftp'); if (!$this->_send_binary_packet($packet)) { return false; } $this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_REQUEST; $response = $this->_get_channel_packet(self::CHANNEL); if ($response === false) { // from PuTTY's psftp.exe $command = "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n" . "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n" . "exec sftp-server"; // we don't do $this->exec($command, false) because exec() operates on a different channel and plus the SSH_MSG_CHANNEL_OPEN that exec() does // is redundant $packet = pack('CNNa*CNa*', NET_SSH2_MSG_CHANNEL_REQUEST, $this->server_channels[self::CHANNEL], strlen('exec'), 'exec', 1, strlen($command), $command); if (!$this->_send_binary_packet($packet)) { return false; } $this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_REQUEST; $response = $this->_get_channel_packet(self::CHANNEL); if ($response === false) { return false; } } $this->channel_status[self::CHANNEL] = NET_SSH2_MSG_CHANNEL_DATA; if (!$this->_send_sftp_packet(NET_SFTP_INIT, "\0\0\0\3")) { return false; } $response = $this->_get_sftp_packet(); if ($this->packet_type != NET_SFTP_VERSION) { user_error('Expected SSH_FXP_VERSION'); return false; } extract(unpack('Nversion', $this->_string_shift($response, 4))); $this->version = $version; while (!empty($response)) { extract(unpack('Nlength', $this->_string_shift($response, 4))); $key = $this->_string_shift($response, $length); extract(unpack('Nlength', $this->_string_shift($response, 4))); $value = $this->_string_shift($response, $length); $this->extensions[$key] = $value; } /* SFTPv4+ defines a 'newline' extension. SFTPv3 seems to have unofficial support for it via 'newline@vandyke.com', however, I'm not sure what 'newline@vandyke.com' is supposed to do (the fact that it's unofficial means that it's not in the official SFTPv3 specs) and 'newline@vandyke.com' / 'newline' are likely not drop-in substitutes for one another due to the fact that 'newline' comes with a SSH_FXF_TEXT bitmask whereas it seems unlikely that 'newline@vandyke.com' would. */ /* if (isset($this->extensions['newline@vandyke.com'])) { $this->extensions['newline'] = $this->extensions['newline@vandyke.com']; unset($this->extensions['newline@vandyke.com']); } */ $this->request_id = 1; /* A Note on SFTPv4/5/6 support: states the following: "If the client wishes to interoperate with servers that support noncontiguous version numbers it SHOULD send '3'" Given that the server only sends its version number after the client has already done so, the above seems to be suggesting that v3 should be the default version. This makes sense given that v3 is the most popular. states the following; "If the server did not send the "versions" extension, or the version-from-list was not included, the server MAY send a status response describing the failure, but MUST then close the channel without processing any further requests." So what do you do if you have a client whose initial SSH_FXP_INIT packet says it implements v3 and a server whose initial SSH_FXP_VERSION reply says it implements v4 and only v4? If it only implements v4, the "versions" extension is likely not going to have been sent so version re-negotiation as discussed in draft-ietf-secsh-filexfer-13 would be quite impossible. As such, what \phpseclib\Net\SFTP would do is close the channel and reopen it with a new and updated SSH_FXP_INIT packet. */ switch ($this->version) { case 2: case 3: break; default: return false; } $this->pwd = $this->_realpath('.'); $this->_update_stat_cache($this->pwd, array()); return true; } /** * Disable the stat cache * * @access public */ function disableStatCache() { $this->use_stat_cache = false; } /** * Enable the stat cache * * @access public */ function enableStatCache() { $this->use_stat_cache = true; } /** * Clear the stat cache * * @access public */ function clearStatCache() { $this->stat_cache = array(); } /** * Returns the current directory name * * @return Mixed * @access public */ function pwd() { return $this->pwd; } /** * Logs errors * * @param String $response * @param optional Integer $status * @access public */ function _logError($response, $status = -1) { if ($status == -1) { extract(unpack('Nstatus', $this->_string_shift($response, 4))); } $error = $this->status_codes[$status]; if ($this->version > 2) { extract(unpack('Nlength', $this->_string_shift($response, 4))); $this->sftp_errors[] = $error . ': ' . $this->_string_shift($response, $length); } else { $this->sftp_errors[] = $error; } } /** * Canonicalize the Server-Side Path Name * * SFTP doesn't provide a mechanism by which the current working directory can be changed, so we'll emulate it. Returns * the absolute (canonicalized) path. * * @see \phpseclib\Net\SFTP::chdir() * @param String $path * @return Mixed * @access private */ function _realpath($path) { if ($this->pwd === false) { // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.9 if (!$this->_send_sftp_packet(NET_SFTP_REALPATH, pack('Na*', strlen($path), $path))) { return false; } $response = $this->_get_sftp_packet(); switch ($this->packet_type) { case NET_SFTP_NAME: // although SSH_FXP_NAME is implemented differently in SFTPv3 than it is in SFTPv4+, the following // should work on all SFTP versions since the only part of the SSH_FXP_NAME packet the following looks // at is the first part and that part is defined the same in SFTP versions 3 through 6. $this->_string_shift($response, 4); // skip over the count - it should be 1, anyway extract(unpack('Nlength', $this->_string_shift($response, 4))); return $this->_string_shift($response, $length); case NET_SFTP_STATUS: $this->_logError($response); return false; default: user_error('Expected SSH_FXP_NAME or SSH_FXP_STATUS'); return false; } } if ($path[0] != '/') { $path = $this->pwd . '/' . $path; } $path = explode('/', $path); $new = array(); foreach ($path as $dir) { if (!strlen($dir)) { continue; } switch ($dir) { case '..': array_pop($new); case '.': break; default: $new[] = $dir; } } return '/' . implode('/', $new); } /** * Changes the current directory * * @param String $dir * @return Boolean * @access public */ function chdir($dir) { if (!($this->bitmap & SSH2::MASK_LOGIN)) { return false; } // assume current dir if $dir is empty if ($dir === '') { $dir = './'; // suffix a slash if needed } elseif ($dir[strlen($dir) - 1] != '/') { $dir.= '/'; } $dir = $this->_realpath($dir); // confirm that $dir is, in fact, a valid directory if ($this->use_stat_cache && is_array($this->_query_stat_cache($dir))) { $this->pwd = $dir; return true; } // we could do a stat on the alleged $dir to see if it's a directory but that doesn't tell us // the currently logged in user has the appropriate permissions or not. maybe you could see if // the file's uid / gid match the currently logged in user's uid / gid but how there's no easy // way to get those with SFTP if (!$this->_send_sftp_packet(NET_SFTP_OPENDIR, pack('Na*', strlen($dir), $dir))) { return false; } // see \phpseclib\Net\SFTP::nlist() for a more thorough explanation of the following $response = $this->_get_sftp_packet(); switch ($this->packet_type) { case NET_SFTP_HANDLE: $handle = substr($response, 4); break; case NET_SFTP_STATUS: $this->_logError($response); return false; default: user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS'); return false; } if (!$this->_close_handle($handle)) { return false; } $this->_update_stat_cache($dir, array()); $this->pwd = $dir; return true; } /** * Returns a list of files in the given directory * * @param optional String $dir * @param optional Boolean $recursive * @return Mixed * @access public */ function nlist($dir = '.', $recursive = false) { return $this->_nlist_helper($dir, $recursive, ''); } /** * Helper method for nlist * * @param String $dir * @param Boolean $recursive * @param String $relativeDir * @return Mixed * @access private */ function _nlist_helper($dir, $recursive, $relativeDir) { $files = $this->_list($dir, false); if (!$recursive) { return $files; } $result = array(); foreach ($files as $value) { if ($value == '.' || $value == '..') { if ($relativeDir == '') { $result[] = $value; } continue; } if (is_array($this->_query_stat_cache($this->_realpath($dir . '/' . $value)))) { $temp = $this->_nlist_helper($dir . '/' . $value, true, $relativeDir . $value . '/'); $result = array_merge($result, $temp); } else { $result[] = $relativeDir . $value; } } return $result; } /** * Returns a detailed list of files in the given directory * * @param optional String $dir * @param optional Boolean $recursive * @return Mixed * @access public */ function rawlist($dir = '.', $recursive = false) { $files = $this->_list($dir, true); if (!$recursive || $files === false) { return $files; } static $depth = 0; foreach ($files as $key=>$value) { if ($depth != 0 && $key == '..') { unset($files[$key]); continue; } if ($key != '.' && $key != '..' && is_array($this->_query_stat_cache($this->_realpath($dir . '/' . $key)))) { $depth++; $files[$key] = $this->rawlist($dir . '/' . $key, true); $depth--; } else { $files[$key] = (object) $value; } } return $files; } /** * Reads a list, be it detailed or not, of files in the given directory * * @param String $dir * @param optional Boolean $raw * @return Mixed * @access private */ function _list($dir, $raw = true) { if (!($this->bitmap & SSH2::MASK_LOGIN)) { return false; } $dir = $this->_realpath($dir . '/'); if ($dir === false) { return false; } // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.2 if (!$this->_send_sftp_packet(NET_SFTP_OPENDIR, pack('Na*', strlen($dir), $dir))) { return false; } $response = $this->_get_sftp_packet(); switch ($this->packet_type) { case NET_SFTP_HANDLE: // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-9.2 // since 'handle' is the last field in the SSH_FXP_HANDLE packet, we'll just remove the first four bytes that // represent the length of the string and leave it at that $handle = substr($response, 4); break; case NET_SFTP_STATUS: // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED $this->_logError($response); return false; default: user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS'); return false; } $this->_update_stat_cache($dir, array()); $contents = array(); while (true) { // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.2.2 // why multiple SSH_FXP_READDIR packets would be sent when the response to a single one can span arbitrarily many // SSH_MSG_CHANNEL_DATA messages is not known to me. if (!$this->_send_sftp_packet(NET_SFTP_READDIR, pack('Na*', strlen($handle), $handle))) { return false; } $response = $this->_get_sftp_packet(); switch ($this->packet_type) { case NET_SFTP_NAME: extract(unpack('Ncount', $this->_string_shift($response, 4))); for ($i = 0; $i < $count; $i++) { extract(unpack('Nlength', $this->_string_shift($response, 4))); $shortname = $this->_string_shift($response, $length); extract(unpack('Nlength', $this->_string_shift($response, 4))); $longname = $this->_string_shift($response, $length); $attributes = $this->_parseAttributes($response); if (!isset($attributes['type'])) { $fileType = $this->_parseLongname($longname); if ($fileType) { $attributes['type'] = $fileType; } } $contents[$shortname] = $attributes + array('filename' => $shortname); if (isset($attributes['type']) && $attributes['type'] == NET_SFTP_TYPE_DIRECTORY && ($shortname != '.' && $shortname != '..')) { $this->_update_stat_cache($dir . '/' . $shortname, array()); } else { if ($shortname == '..') { $temp = $this->_realpath($dir . '/..') . '/.'; } else { $temp = $dir . '/' . $shortname; } $this->_update_stat_cache($temp, (object) $attributes); } // SFTPv6 has an optional boolean end-of-list field, but we'll ignore that, since the // final SSH_FXP_STATUS packet should tell us that, already. } break; case NET_SFTP_STATUS: extract(unpack('Nstatus', $this->_string_shift($response, 4))); if ($status != NET_SFTP_STATUS_EOF) { $this->_logError($response, $status); return false; } break 2; default: user_error('Expected SSH_FXP_NAME or SSH_FXP_STATUS'); return false; } } if (!$this->_close_handle($handle)) { return false; } if (count($this->sortOptions)) { uasort($contents, array(&$this, '_comparator')); } return $raw ? $contents : array_keys($contents); } /** * Compares two rawlist entries using parameters set by setListOrder() * * Intended for use with uasort() * * @param Array $a * @param Array $b * @return Integer * @access private */ function _comparator($a, $b) { switch (true) { case $a['filename'] === '.' || $b['filename'] === '.': if ($a['filename'] === $b['filename']) { return 0; } return $a['filename'] === '.' ? -1 : 1; case $a['filename'] === '..' || $b['filename'] === '..': if ($a['filename'] === $b['filename']) { return 0; } return $a['filename'] === '..' ? -1 : 1; case isset($a['type']) && $a['type'] === NET_SFTP_TYPE_DIRECTORY: if (!isset($b['type'])) { return 1; } if ($b['type'] !== $a['type']) { return -1; } break; case isset($b['type']) && $b['type'] === NET_SFTP_TYPE_DIRECTORY: return 1; } foreach ($this->sortOptions as $sort => $order) { if (!isset($a[$sort]) || !isset($b[$sort])) { if (isset($a[$sort])) { return -1; } if (isset($b[$sort])) { return 1; } return 0; } switch ($sort) { case 'filename': $result = strcasecmp($a['filename'], $b['filename']); if ($result) { return $order === SORT_DESC ? -$result : $result; } break; case 'permissions': case 'mode': $a[$sort]&= 07777; $b[$sort]&= 07777; default: if ($a[$sort] === $b[$sort]) { break; } return $order === SORT_ASC ? $a[$sort] - $b[$sort] : $b[$sort] - $a[$sort]; } } } /** * Defines how nlist() and rawlist() will be sorted - if at all. * * If sorting is enabled directories and files will be sorted independently with * directories appearing before files in the resultant array that is returned. * * Any parameter returned by stat is a valid sort parameter for this function. * Filename comparisons are case insensitive. * * Examples: * * $sftp->setListOrder('filename', SORT_ASC); * $sftp->setListOrder('size', SORT_DESC, 'filename', SORT_ASC); * $sftp->setListOrder(true); * Separates directories from files but doesn't do any sorting beyond that * $sftp->setListOrder(); * Don't do any sort of sorting * * @access public */ function setListOrder() { $this->sortOptions = array(); $args = func_get_args(); if (empty($args)) { return; } $len = count($args) & 0x7FFFFFFE; for ($i = 0; $i < $len; $i+=2) { $this->sortOptions[$args[$i]] = $args[$i + 1]; } if (!count($this->sortOptions)) { $this->sortOptions = array('bogus' => true); } } /** * Returns the file size, in bytes, or false, on failure * * Files larger than 4GB will show up as being exactly 4GB. * * @param String $filename * @return Mixed * @access public */ function size($filename) { if (!($this->bitmap & SSH2::MASK_LOGIN)) { return false; } $result = $this->stat($filename); if ($result === false) { return false; } return isset($result['size']) ? $result['size'] : -1; } /** * Save files / directories to cache * * @param String $path * @param Mixed $value * @access private */ function _update_stat_cache($path, $value) { // preg_replace('#^/|/(?=/)|/$#', '', $dir) == str_replace('//', '/', trim($path, '/')) $dirs = explode('/', preg_replace('#^/|/(?=/)|/$#', '', $path)); $temp = &$this->stat_cache; $max = count($dirs) - 1; foreach ($dirs as $i=>$dir) { if (!isset($temp[$dir])) { $temp[$dir] = array(); } if ($i === $max) { $temp[$dir] = $value; break; } $temp = &$temp[$dir]; } } /** * Remove files / directories from cache * * @param String $path * @return Boolean * @access private */ function _remove_from_stat_cache($path) { $dirs = explode('/', preg_replace('#^/|/(?=/)|/$#', '', $path)); $temp = &$this->stat_cache; $max = count($dirs) - 1; foreach ($dirs as $i=>$dir) { if ($i === $max) { unset($temp[$dir]); return true; } if (!isset($temp[$dir])) { return false; } $temp = &$temp[$dir]; } } /** * Checks cache for path * * Mainly used by file_exists * * @param String $dir * @return Mixed * @access private */ function _query_stat_cache($path) { $dirs = explode('/', preg_replace('#^/|/(?=/)|/$#', '', $path)); $temp = &$this->stat_cache; foreach ($dirs as $dir) { if (!isset($temp[$dir])) { return null; } $temp = &$temp[$dir]; } return $temp; } /** * Returns general information about a file. * * Returns an array on success and false otherwise. * * @param String $filename * @return Mixed * @access public */ function stat($filename) { if (!($this->bitmap & SSH2::MASK_LOGIN)) { return false; } $filename = $this->_realpath($filename); if ($filename === false) { return false; } if ($this->use_stat_cache) { $result = $this->_query_stat_cache($filename); if (is_array($result) && isset($result['.'])) { return (array) $result['.']; } if (is_object($result)) { return (array) $result; } } $stat = $this->_stat($filename, NET_SFTP_STAT); if ($stat === false) { $this->_remove_from_stat_cache($filename); return false; } if (isset($stat['type'])) { if ($stat['type'] == NET_SFTP_TYPE_DIRECTORY) { $filename.= '/.'; } $this->_update_stat_cache($filename, (object) $stat); return $stat; } $pwd = $this->pwd; $stat['type'] = $this->chdir($filename) ? NET_SFTP_TYPE_DIRECTORY : NET_SFTP_TYPE_REGULAR; $this->pwd = $pwd; if ($stat['type'] == NET_SFTP_TYPE_DIRECTORY) { $filename.= '/.'; } $this->_update_stat_cache($filename, (object) $stat); return $stat; } /** * Returns general information about a file or symbolic link. * * Returns an array on success and false otherwise. * * @param String $filename * @return Mixed * @access public */ function lstat($filename) { if (!($this->bitmap & SSH2::MASK_LOGIN)) { return false; } $filename = $this->_realpath($filename); if ($filename === false) { return false; } if ($this->use_stat_cache) { $result = $this->_query_stat_cache($filename); if (is_array($result) && isset($result['.'])) { return (array) $result['.']; } if (is_object($result)) { return (array) $result; } } $lstat = $this->_stat($filename, NET_SFTP_LSTAT); if ($lstat === false) { $this->_remove_from_stat_cache($filename); return false; } if (isset($lstat['type'])) { if ($lstat['type'] == NET_SFTP_TYPE_DIRECTORY) { $filename.= '/.'; } $this->_update_stat_cache($filename, (object) $lstat); return $lstat; } $stat = $this->_stat($filename, NET_SFTP_STAT); if ($lstat != $stat) { $lstat = array_merge($lstat, array('type' => NET_SFTP_TYPE_SYMLINK)); $this->_update_stat_cache($filename, (object) $lstat); return $stat; } $pwd = $this->pwd; $lstat['type'] = $this->chdir($filename) ? NET_SFTP_TYPE_DIRECTORY : NET_SFTP_TYPE_REGULAR; $this->pwd = $pwd; if ($lstat['type'] == NET_SFTP_TYPE_DIRECTORY) { $filename.= '/.'; } $this->_update_stat_cache($filename, (object) $lstat); return $lstat; } /** * Returns general information about a file or symbolic link * * Determines information without calling \phpseclib\Net\SFTP::_realpath(). * The second parameter can be either NET_SFTP_STAT or NET_SFTP_LSTAT. * * @param String $filename * @param Integer $type * @return Mixed * @access private */ function _stat($filename, $type) { // SFTPv4+ adds an additional 32-bit integer field - flags - to the following: $packet = pack('Na*', strlen($filename), $filename); if (!$this->_send_sftp_packet($type, $packet)) { return false; } $response = $this->_get_sftp_packet(); switch ($this->packet_type) { case NET_SFTP_ATTRS: return $this->_parseAttributes($response); case NET_SFTP_STATUS: $this->_logError($response); return false; } user_error('Expected SSH_FXP_ATTRS or SSH_FXP_STATUS'); return false; } /** * Truncates a file to a given length * * @param String $filename * @param Integer $new_size * @return Boolean * @access public */ function truncate($filename, $new_size) { $attr = pack('N3', NET_SFTP_ATTR_SIZE, $new_size / 4294967296, $new_size); // 4294967296 == 0x100000000 == 1<<32 return $this->_setstat($filename, $attr, false); } /** * Sets access and modification time of file. * * If the file does not exist, it will be created. * * @param String $filename * @param optional Integer $time * @param optional Integer $atime * @return Boolean * @access public */ function touch($filename, $time = null, $atime = null) { if (!($this->bitmap & SSH2::MASK_LOGIN)) { return false; } $filename = $this->_realpath($filename); if ($filename === false) { return false; } if (!isset($time)) { $time = time(); } if (!isset($atime)) { $atime = $time; } $flags = NET_SFTP_OPEN_WRITE | NET_SFTP_OPEN_CREATE | NET_SFTP_OPEN_EXCL; $attr = pack('N3', NET_SFTP_ATTR_ACCESSTIME, $time, $atime); $packet = pack('Na*Na*', strlen($filename), $filename, $flags, $attr); if (!$this->_send_sftp_packet(NET_SFTP_OPEN, $packet)) { return false; } $response = $this->_get_sftp_packet(); switch ($this->packet_type) { case NET_SFTP_HANDLE: return $this->_close_handle(substr($response, 4)); case NET_SFTP_STATUS: $this->_logError($response); break; default: user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS'); return false; } return $this->_setstat($filename, $attr, false); } /** * Changes file or directory owner * * Returns true on success or false on error. * * @param String $filename * @param Integer $uid * @param optional Boolean $recursive * @return Boolean * @access public */ function chown($filename, $uid, $recursive = false) { // quoting from , // "if the owner or group is specified as -1, then that ID is not changed" $attr = pack('N3', NET_SFTP_ATTR_UIDGID, $uid, -1); return $this->_setstat($filename, $attr, $recursive); } /** * Changes file or directory group * * Returns true on success or false on error. * * @param String $filename * @param Integer $gid * @param optional Boolean $recursive * @return Boolean * @access public */ function chgrp($filename, $gid, $recursive = false) { $attr = pack('N3', NET_SFTP_ATTR_UIDGID, -1, $gid); return $this->_setstat($filename, $attr, $recursive); } /** * Set permissions on a file. * * Returns the new file permissions on success or false on error. * If $recursive is true than this just returns true or false. * * @param Integer $mode * @param String $filename * @param optional Boolean $recursive * @return Mixed * @access public */ function chmod($mode, $filename, $recursive = false) { if (is_string($mode) && is_int($filename)) { $temp = $mode; $mode = $filename; $filename = $temp; } $attr = pack('N2', NET_SFTP_ATTR_PERMISSIONS, $mode & 07777); if (!$this->_setstat($filename, $attr, $recursive)) { return false; } if ($recursive) { return true; } // rather than return what the permissions *should* be, we'll return what they actually are. this will also // tell us if the file actually exists. // incidentally, SFTPv4+ adds an additional 32-bit integer field - flags - to the following: $packet = pack('Na*', strlen($filename), $filename); if (!$this->_send_sftp_packet(NET_SFTP_STAT, $packet)) { return false; } $response = $this->_get_sftp_packet(); switch ($this->packet_type) { case NET_SFTP_ATTRS: $attrs = $this->_parseAttributes($response); return $attrs['permissions']; case NET_SFTP_STATUS: $this->_logError($response); return false; } user_error('Expected SSH_FXP_ATTRS or SSH_FXP_STATUS'); return false; } /** * Sets information about a file * * @param String $filename * @param String $attr * @param Boolean $recursive * @return Boolean * @access private */ function _setstat($filename, $attr, $recursive) { if (!($this->bitmap & SSH2::MASK_LOGIN)) { return false; } $filename = $this->_realpath($filename); if ($filename === false) { return false; } $this->_remove_from_stat_cache($filename); if ($recursive) { $i = 0; $result = $this->_setstat_recursive($filename, $attr, $i); $this->_read_put_responses($i); return $result; } // SFTPv4+ has an additional byte field - type - that would need to be sent, as well. setting it to // SSH_FILEXFER_TYPE_UNKNOWN might work. if not, we'd have to do an SSH_FXP_STAT before doing an SSH_FXP_SETSTAT. if (!$this->_send_sftp_packet(NET_SFTP_SETSTAT, pack('Na*a*', strlen($filename), $filename, $attr))) { return false; } /* "Because some systems must use separate system calls to set various attributes, it is possible that a failure response will be returned, but yet some of the attributes may be have been successfully modified. If possible, servers SHOULD avoid this situation; however, clients MUST be aware that this is possible." -- http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.6 */ $response = $this->_get_sftp_packet(); if ($this->packet_type != NET_SFTP_STATUS) { user_error('Expected SSH_FXP_STATUS'); return false; } extract(unpack('Nstatus', $this->_string_shift($response, 4))); if ($status != NET_SFTP_STATUS_OK) { $this->_logError($response, $status); return false; } return true; } /** * Recursively sets information on directories on the SFTP server * * Minimizes directory lookups and SSH_FXP_STATUS requests for speed. * * @param String $path * @param String $attr * @param Integer $i * @return Boolean * @access private */ function _setstat_recursive($path, $attr, &$i) { if (!$this->_read_put_responses($i)) { return false; } $i = 0; $entries = $this->_list($path, true); if ($entries === false) { return $this->_setstat($path, $attr, false); } // normally $entries would have at least . and .. but it might not if the directories // permissions didn't allow reading if (empty($entries)) { return false; } unset($entries['.'], $entries['..']); foreach ($entries as $filename=>$props) { if (!isset($props['type'])) { return false; } $temp = $path . '/' . $filename; if ($props['type'] == NET_SFTP_TYPE_DIRECTORY) { if (!$this->_setstat_recursive($temp, $attr, $i)) { return false; } } else { if (!$this->_send_sftp_packet(NET_SFTP_SETSTAT, pack('Na*a*', strlen($temp), $temp, $attr))) { return false; } $i++; if ($i >= NET_SFTP_QUEUE_SIZE) { if (!$this->_read_put_responses($i)) { return false; } $i = 0; } } } if (!$this->_send_sftp_packet(NET_SFTP_SETSTAT, pack('Na*a*', strlen($path), $path, $attr))) { return false; } $i++; if ($i >= NET_SFTP_QUEUE_SIZE) { if (!$this->_read_put_responses($i)) { return false; } $i = 0; } return true; } /** * Return the target of a symbolic link * * @param String $link * @return Mixed * @access public */ function readlink($link) { if (!($this->bitmap & SSH2::MASK_LOGIN)) { return false; } $link = $this->_realpath($link); if (!$this->_send_sftp_packet(NET_SFTP_READLINK, pack('Na*', strlen($link), $link))) { return false; } $response = $this->_get_sftp_packet(); switch ($this->packet_type) { case NET_SFTP_NAME: break; case NET_SFTP_STATUS: $this->_logError($response); return false; default: user_error('Expected SSH_FXP_NAME or SSH_FXP_STATUS'); return false; } extract(unpack('Ncount', $this->_string_shift($response, 4))); // the file isn't a symlink if (!$count) { return false; } extract(unpack('Nlength', $this->_string_shift($response, 4))); return $this->_string_shift($response, $length); } /** * Create a symlink * * symlink() creates a symbolic link to the existing target with the specified name link. * * @param String $target * @param String $link * @return Boolean * @access public */ function symlink($target, $link) { if (!($this->bitmap & SSH2::MASK_LOGIN)) { return false; } $target = $this->_realpath($target); $link = $this->_realpath($link); $packet = pack('Na*Na*', strlen($target), $target, strlen($link), $link); if (!$this->_send_sftp_packet(NET_SFTP_SYMLINK, $packet)) { return false; } $response = $this->_get_sftp_packet(); if ($this->packet_type != NET_SFTP_STATUS) { user_error('Expected SSH_FXP_STATUS'); return false; } extract(unpack('Nstatus', $this->_string_shift($response, 4))); if ($status != NET_SFTP_STATUS_OK) { $this->_logError($response, $status); return false; } return true; } /** * Creates a directory. * * @param String $dir * @return Boolean * @access public */ function mkdir($dir, $mode = -1, $recursive = false) { if (!($this->bitmap & SSH2::MASK_LOGIN)) { return false; } $dir = $this->_realpath($dir); // by not providing any permissions, hopefully the server will use the logged in users umask - their // default permissions. $attr = $mode == -1 ? "\0\0\0\0" : pack('N2', NET_SFTP_ATTR_PERMISSIONS, $mode & 07777); if ($recursive) { $dirs = explode('/', preg_replace('#/(?=/)|/$#', '', $dir)); if (empty($dirs[0])) { array_shift($dirs); $dirs[0] = '/' . $dirs[0]; } for ($i = 0; $i < count($dirs); $i++) { $temp = array_slice($dirs, 0, $i + 1); $temp = implode('/', $temp); $result = $this->_mkdir_helper($temp, $attr); } return $result; } return $this->_mkdir_helper($dir, $attr); } /** * Helper function for directory creation * * @param String $dir * @return Boolean * @access private */ function _mkdir_helper($dir, $attr) { if (!$this->_send_sftp_packet(NET_SFTP_MKDIR, pack('Na*a*', strlen($dir), $dir, $attr))) { return false; } $response = $this->_get_sftp_packet(); if ($this->packet_type != NET_SFTP_STATUS) { user_error('Expected SSH_FXP_STATUS'); return false; } extract(unpack('Nstatus', $this->_string_shift($response, 4))); if ($status != NET_SFTP_STATUS_OK) { $this->_logError($response, $status); return false; } return true; } /** * Removes a directory. * * @param String $dir * @return Boolean * @access public */ function rmdir($dir) { if (!($this->bitmap & SSH2::MASK_LOGIN)) { return false; } $dir = $this->_realpath($dir); if ($dir === false) { return false; } if (!$this->_send_sftp_packet(NET_SFTP_RMDIR, pack('Na*', strlen($dir), $dir))) { return false; } $response = $this->_get_sftp_packet(); if ($this->packet_type != NET_SFTP_STATUS) { user_error('Expected SSH_FXP_STATUS'); return false; } extract(unpack('Nstatus', $this->_string_shift($response, 4))); if ($status != NET_SFTP_STATUS_OK) { // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED? $this->_logError($response, $status); return false; } $this->_remove_from_stat_cache($dir); // the following will do a soft delete, which would be useful if you deleted a file // and then tried to do a stat on the deleted file. the above, in contrast, does // a hard delete //$this->_update_stat_cache($dir, false); return true; } /** * Uploads a file to the SFTP server. * * By default, \phpseclib\Net\SFTP::put() does not read from the local filesystem. $data is dumped directly into $remote_file. * So, for example, if you set $data to 'filename.ext' and then do \phpseclib\Net\SFTP::get(), you will get a file, twelve bytes * long, containing 'filename.ext' as its contents. * * Setting $mode to self::SOURCE_LOCAL_FILE will change the above behavior. With self::SOURCE_LOCAL_FILE, $remote_file will * contain as many bytes as filename.ext does on your local filesystem. If your filename.ext is 1MB then that is how * large $remote_file will be, as well. * * If $data is a resource then it'll be used as a resource instead. * * Currently, only binary mode is supported. As such, if the line endings need to be adjusted, you will need to take * care of that, yourself. * * $mode can take an additional two parameters - self::RESUME and self::RESUME_START. These are bitwise AND'd with * $mode. So if you want to resume upload of a 300mb file on the local file system you'd set $mode to the following: * * self::SOURCE_LOCAL_FILE | self::RESUME * * If you wanted to simply append the full contents of a local file to the full contents of a remote file you'd replace * self::RESUME with self::RESUME_START. * * If $mode & (self::RESUME | self::RESUME_START) then self::RESUME_START will be assumed. * * $start and $local_start give you more fine grained control over this process and take precident over self::RESUME * when they're non-negative. ie. $start could let you write at the end of a file (like self::RESUME) or in the middle * of one. $local_start could let you start your reading from the end of a file (like self::RESUME_START) or in the * middle of one. * * Setting $local_start to > 0 or $mode | self::RESUME_START doesn't do anything unless $mode | self::SOURCE_LOCAL_FILE. * * @param String $remote_file * @param String|resource $data * @param optional Integer $mode * @param optional Integer $start * @param optional Integer $local_start * @return Boolean * @access public * @internal ASCII mode for SFTPv4/5/6 can be supported by adding a new function - \phpseclib\Net\SFTP::setMode(). */ function put($remote_file, $data, $mode = self::SOURCE_STRING, $start = -1, $local_start = -1) { if (!($this->bitmap & SSH2::MASK_LOGIN)) { return false; } $remote_file = $this->_realpath($remote_file); if ($remote_file === false) { return false; } $this->_remove_from_stat_cache($remote_file); $flags = NET_SFTP_OPEN_WRITE | NET_SFTP_OPEN_CREATE; // according to the SFTP specs, NET_SFTP_OPEN_APPEND should "force all writes to append data at the end of the file." // in practice, it doesn't seem to do that. //$flags|= ($mode & self::RESUME) ? NET_SFTP_OPEN_APPEND : NET_SFTP_OPEN_TRUNCATE; if ($start >= 0) { $offset = $start; } elseif ($mode & self::RESUME) { // if NET_SFTP_OPEN_APPEND worked as it should _size() wouldn't need to be called $size = $this->size($remote_file); $offset = $size !== false ? $size : 0; } else { $offset = 0; $flags|= NET_SFTP_OPEN_TRUNCATE; } $packet = pack('Na*N2', strlen($remote_file), $remote_file, $flags, 0); if (!$this->_send_sftp_packet(NET_SFTP_OPEN, $packet)) { return false; } $response = $this->_get_sftp_packet(); switch ($this->packet_type) { case NET_SFTP_HANDLE: $handle = substr($response, 4); break; case NET_SFTP_STATUS: $this->_logError($response); return false; default: user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS'); return false; } // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.2.3 switch (true) { case is_resource($data): $mode = $mode & ~self::SOURCE_LOCAL_FILE; $fp = $data; break; case $mode & self::SOURCE_LOCAL_FILE: if (!is_file($data)) { user_error("$data is not a valid file"); return false; } $fp = @fopen($data, 'rb'); if (!$fp) { return false; } } if (isset($fp)) { $stat = fstat($fp); $size = $stat['size']; if ($local_start >= 0) { fseek($fp, $local_start); } elseif ($mode & self::RESUME_START) { // do nothing } else { fseek($fp, $offset); } } else { $size = strlen($data); } $sent = 0; $size = $size < 0 ? ($size & 0x7FFFFFFF) + 0x80000000 : $size; $sftp_packet_size = 4096; // PuTTY uses 4096 // make the SFTP packet be exactly 4096 bytes by including the bytes in the NET_SFTP_WRITE packets "header" $sftp_packet_size-= strlen($handle) + 25; $i = 0; while ($sent < $size) { $temp = isset($fp) ? fread($fp, $sftp_packet_size) : substr($data, $sent, $sftp_packet_size); $subtemp = $offset + $sent; $packet = pack('Na*N3a*', strlen($handle), $handle, $subtemp / 4294967296, $subtemp, strlen($temp), $temp); if (!$this->_send_sftp_packet(NET_SFTP_WRITE, $packet)) { if ($mode & self::SOURCE_LOCAL_FILE) { fclose($fp); } return false; } $sent+= strlen($temp); $i++; if ($i == NET_SFTP_QUEUE_SIZE) { if (!$this->_read_put_responses($i)) { $i = 0; break; } $i = 0; } } if (!$this->_read_put_responses($i)) { if ($mode & self::SOURCE_LOCAL_FILE) { fclose($fp); } $this->_close_handle($handle); return false; } if ($mode & self::SOURCE_LOCAL_FILE) { fclose($fp); } return $this->_close_handle($handle); } /** * Reads multiple successive SSH_FXP_WRITE responses * * Sending an SSH_FXP_WRITE packet and immediately reading its response isn't as efficient as blindly sending out $i * SSH_FXP_WRITEs, in succession, and then reading $i responses. * * @param Integer $i * @return Boolean * @access private */ function _read_put_responses($i) { while ($i--) { $response = $this->_get_sftp_packet(); if ($this->packet_type != NET_SFTP_STATUS) { user_error('Expected SSH_FXP_STATUS'); return false; } extract(unpack('Nstatus', $this->_string_shift($response, 4))); if ($status != NET_SFTP_STATUS_OK) { $this->_logError($response, $status); break; } } return $i < 0; } /** * Close handle * * @param String $handle * @return Boolean * @access private */ function _close_handle($handle) { if (!$this->_send_sftp_packet(NET_SFTP_CLOSE, pack('Na*', strlen($handle), $handle))) { return false; } // "The client MUST release all resources associated with the handle regardless of the status." // -- http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.3 $response = $this->_get_sftp_packet(); if ($this->packet_type != NET_SFTP_STATUS) { user_error('Expected SSH_FXP_STATUS'); return false; } extract(unpack('Nstatus', $this->_string_shift($response, 4))); if ($status != NET_SFTP_STATUS_OK) { $this->_logError($response, $status); return false; } return true; } /** * Downloads a file from the SFTP server. * * Returns a string containing the contents of $remote_file if $local_file is left undefined or a boolean false if * the operation was unsuccessful. If $local_file is defined, returns true or false depending on the success of the * operation. * * $offset and $length can be used to download files in chunks. * * @param String $remote_file * @param optional String $local_file * @param optional Integer $offset * @param optional Integer $length * @return Mixed * @access public */ function get($remote_file, $local_file = false, $offset = 0, $length = -1) { if (!($this->bitmap & SSH2::MASK_LOGIN)) { return false; } $remote_file = $this->_realpath($remote_file); if ($remote_file === false) { return false; } $packet = pack('Na*N2', strlen($remote_file), $remote_file, NET_SFTP_OPEN_READ, 0); if (!$this->_send_sftp_packet(NET_SFTP_OPEN, $packet)) { return false; } $response = $this->_get_sftp_packet(); switch ($this->packet_type) { case NET_SFTP_HANDLE: $handle = substr($response, 4); break; case NET_SFTP_STATUS: // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED $this->_logError($response); return false; default: user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS'); return false; } if (is_resource($local_file)) { $fp = $local_file; $stat = fstat($fp); $res_offset = $stat['size']; } else { $res_offset = 0; if ($local_file !== false) { $fp = fopen($local_file, 'wb'); if (!$fp) { return false; } } else { $content = ''; } } $fclose_check = $local_file !== false && !is_resource($local_file); $start = $offset; $size = $this->max_sftp_packet < $length || $length < 0 ? $this->max_sftp_packet : $length; while (true) { $packet = pack('Na*N3', strlen($handle), $handle, $offset / 4294967296, $offset, $size); if (!$this->_send_sftp_packet(NET_SFTP_READ, $packet)) { if ($fclose_check) { fclose($fp); } return false; } $response = $this->_get_sftp_packet(); switch ($this->packet_type) { case NET_SFTP_DATA: $temp = substr($response, 4); $offset+= strlen($temp); if ($local_file === false) { $content.= $temp; } else { fputs($fp, $temp); } break; case NET_SFTP_STATUS: // could, in theory, return false if !strlen($content) but we'll hold off for the time being $this->_logError($response); break 2; default: user_error('Expected SSH_FXP_DATA or SSH_FXP_STATUS'); if ($fclose_check) { fclose($fp); } return false; } if ($length > 0 && $length <= $offset - $start) { break; } } if ($length > 0 && $length <= $offset - $start) { if ($local_file === false) { $content = substr($content, 0, $length); } else { ftruncate($fp, $length + $res_offset); } } if ($fclose_check) { fclose($fp); } if (!$this->_close_handle($handle)) { return false; } // if $content isn't set that means a file was written to return isset($content) ? $content : true; } /** * Deletes a file on the SFTP server. * * @param String $path * @param Boolean $recursive * @return Boolean * @access public */ function delete($path, $recursive = true) { if (!($this->bitmap & SSH2::MASK_LOGIN)) { return false; } $path = $this->_realpath($path); if ($path === false) { return false; } // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.3 if (!$this->_send_sftp_packet(NET_SFTP_REMOVE, pack('Na*', strlen($path), $path))) { return false; } $response = $this->_get_sftp_packet(); if ($this->packet_type != NET_SFTP_STATUS) { user_error('Expected SSH_FXP_STATUS'); return false; } // if $status isn't SSH_FX_OK it's probably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED extract(unpack('Nstatus', $this->_string_shift($response, 4))); if ($status != NET_SFTP_STATUS_OK) { $this->_logError($response, $status); if (!$recursive) { return false; } $i = 0; $result = $this->_delete_recursive($path, $i); $this->_read_put_responses($i); return $result; } $this->_remove_from_stat_cache($path); return true; } /** * Recursively deletes directories on the SFTP server * * Minimizes directory lookups and SSH_FXP_STATUS requests for speed. * * @param String $path * @param Integer $i * @return Boolean * @access private */ function _delete_recursive($path, &$i) { if (!$this->_read_put_responses($i)) { return false; } $i = 0; $entries = $this->_list($path, true); // normally $entries would have at least . and .. but it might not if the directories // permissions didn't allow reading if (empty($entries)) { return false; } unset($entries['.'], $entries['..']); foreach ($entries as $filename=>$props) { if (!isset($props['type'])) { return false; } $temp = $path . '/' . $filename; if ($props['type'] == NET_SFTP_TYPE_DIRECTORY) { if (!$this->_delete_recursive($temp, $i)) { return false; } } else { if (!$this->_send_sftp_packet(NET_SFTP_REMOVE, pack('Na*', strlen($temp), $temp))) { return false; } $i++; if ($i >= NET_SFTP_QUEUE_SIZE) { if (!$this->_read_put_responses($i)) { return false; } $i = 0; } } $this->_remove_from_stat_cache($path); } if (!$this->_send_sftp_packet(NET_SFTP_RMDIR, pack('Na*', strlen($path), $path))) { return false; } $i++; if ($i >= NET_SFTP_QUEUE_SIZE) { if (!$this->_read_put_responses($i)) { return false; } $i = 0; } return true; } /** * Checks whether a file or directory exists * * @param String $path * @return Boolean * @access public */ function file_exists($path) { if ($this->use_stat_cache) { $path = $this->_realpath($path); $result = $this->_query_stat_cache($path); if (isset($result)) { // return true if $result is an array or if it's an stdClass object return $result !== false; } } return $this->stat($path) !== false; } /** * Tells whether the filename is a directory * * @param String $path * @return Boolean * @access public */ function is_dir($path) { $result = $this->_get_stat_cache_prop($path, 'type'); if ($result === false) { return false; } return $result === NET_SFTP_TYPE_DIRECTORY; } /** * Tells whether the filename is a regular file * * @param String $path * @return Boolean * @access public */ function is_file($path) { $result = $this->_get_stat_cache_prop($path, 'type'); if ($result === false) { return false; } return $result === NET_SFTP_TYPE_REGULAR; } /** * Tells whether the filename is a symbolic link * * @param String $path * @return Boolean * @access public */ function is_link($path) { $result = $this->_get_stat_cache_prop($path, 'type'); if ($result === false) { return false; } return $result === NET_SFTP_TYPE_SYMLINK; } /** * Gets last access time of file * * @param String $path * @return Mixed * @access public */ function fileatime($path) { return $this->_get_stat_cache_prop($path, 'atime'); } /** * Gets file modification time * * @param String $path * @return Mixed * @access public */ function filemtime($path) { return $this->_get_stat_cache_prop($path, 'mtime'); } /** * Gets file permissions * * @param String $path * @return Mixed * @access public */ function fileperms($path) { return $this->_get_stat_cache_prop($path, 'permissions'); } /** * Gets file owner * * @param String $path * @return Mixed * @access public */ function fileowner($path) { return $this->_get_stat_cache_prop($path, 'uid'); } /** * Gets file group * * @param String $path * @return Mixed * @access public */ function filegroup($path) { return $this->_get_stat_cache_prop($path, 'gid'); } /** * Gets file size * * @param String $path * @return Mixed * @access public */ function filesize($path) { return $this->_get_stat_cache_prop($path, 'size'); } /** * Gets file type * * @param String $path * @return Mixed * @access public */ function filetype($path) { $type = $this->_get_stat_cache_prop($path, 'type'); if ($type === false) { return false; } switch ($type) { case NET_SFTP_TYPE_BLOCK_DEVICE: return 'block'; case NET_SFTP_TYPE_CHAR_DEVICE: return 'char'; case NET_SFTP_TYPE_DIRECTORY: return 'dir'; case NET_SFTP_TYPE_FIFO: return 'fifo'; case NET_SFTP_TYPE_REGULAR: return 'file'; case NET_SFTP_TYPE_SYMLINK: return 'link'; default: return false; } } /** * Return a stat properity * * Uses cache if appropriate. * * @param String $path * @param String $prop * @return Mixed * @access private */ function _get_stat_cache_prop($path, $prop) { if ($this->use_stat_cache) { $path = $this->_realpath($path); $result = $this->_query_stat_cache($path); if (is_object($result) && isset($result->$prop)) { return $result->$prop; } } $result = $this->stat($path); if ($result === false || !isset($result[$prop])) { return false; } return $result[$prop]; } /** * Renames a file or a directory on the SFTP server * * @param String $oldname * @param String $newname * @return Boolean * @access public */ function rename($oldname, $newname) { if (!($this->bitmap & SSH2::MASK_LOGIN)) { return false; } $oldname = $this->_realpath($oldname); $newname = $this->_realpath($newname); if ($oldname === false || $newname === false) { return false; } // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.3 $packet = pack('Na*Na*', strlen($oldname), $oldname, strlen($newname), $newname); if (!$this->_send_sftp_packet(NET_SFTP_RENAME, $packet)) { return false; } $response = $this->_get_sftp_packet(); if ($this->packet_type != NET_SFTP_STATUS) { user_error('Expected SSH_FXP_STATUS'); return false; } // if $status isn't SSH_FX_OK it's probably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED extract(unpack('Nstatus', $this->_string_shift($response, 4))); if ($status != NET_SFTP_STATUS_OK) { $this->_logError($response, $status); return false; } // don't move the stat cache entry over since this operation could very well change the // atime and mtime attributes //$this->_update_stat_cache($newname, $this->_query_stat_cache($oldname)); $this->_remove_from_stat_cache($oldname); $this->_remove_from_stat_cache($newname); return true; } /** * Parse Attributes * * See '7. File Attributes' of draft-ietf-secsh-filexfer-13 for more info. * * @param String $response * @return Array * @access private */ function _parseAttributes(&$response) { $attr = array(); extract(unpack('Nflags', $this->_string_shift($response, 4))); // SFTPv4+ have a type field (a byte) that follows the above flag field foreach ($this->attributes as $key => $value) { switch ($flags & $key) { case NET_SFTP_ATTR_SIZE: // 0x00000001 // The size attribute is defined as an unsigned 64-bit integer. // The following will use floats on 32-bit platforms, if necessary. // As can be seen in the BigInteger class, floats are generally // IEEE 754 binary64 "double precision" on such platforms and // as such can represent integers of at least 2^50 without loss // of precision. Interpreted in filesize, 2^50 bytes = 1024 TiB. $attr['size'] = hexdec(bin2hex($this->_string_shift($response, 8))); break; case NET_SFTP_ATTR_UIDGID: // 0x00000002 (SFTPv3 only) $attr+= unpack('Nuid/Ngid', $this->_string_shift($response, 8)); break; case NET_SFTP_ATTR_PERMISSIONS: // 0x00000004 $attr+= unpack('Npermissions', $this->_string_shift($response, 4)); // mode == permissions; permissions was the original array key and is retained for bc purposes. // mode was added because that's the more industry standard terminology $attr+= array('mode' => $attr['permissions']); $fileType = $this->_parseMode($attr['permissions']); if ($fileType !== false) { $attr+= array('type' => $fileType); } break; case NET_SFTP_ATTR_ACCESSTIME: // 0x00000008 $attr+= unpack('Natime/Nmtime', $this->_string_shift($response, 8)); break; case NET_SFTP_ATTR_EXTENDED: // 0x80000000 extract(unpack('Ncount', $this->_string_shift($response, 4))); for ($i = 0; $i < $count; $i++) { extract(unpack('Nlength', $this->_string_shift($response, 4))); $key = $this->_string_shift($response, $length); extract(unpack('Nlength', $this->_string_shift($response, 4))); $attr[$key] = $this->_string_shift($response, $length); } } } return $attr; } /** * Attempt to identify the file type * * Quoting the SFTP RFC, "Implementations MUST NOT send bits that are not defined" but they seem to anyway * * @param Integer $mode * @return Integer * @access private */ function _parseMode($mode) { // values come from http://lxr.free-electrons.com/source/include/uapi/linux/stat.h#L12 // see, also, http://linux.die.net/man/2/stat switch ($mode & 0170000) {// ie. 1111 0000 0000 0000 case 0000000: // no file type specified - figure out the file type using alternative means return false; case 0040000: return NET_SFTP_TYPE_DIRECTORY; case 0100000: return NET_SFTP_TYPE_REGULAR; case 0120000: return NET_SFTP_TYPE_SYMLINK; // new types introduced in SFTPv5+ // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-05#section-5.2 case 0010000: // named pipe (fifo) return NET_SFTP_TYPE_FIFO; case 0020000: // character special return NET_SFTP_TYPE_CHAR_DEVICE; case 0060000: // block special return NET_SFTP_TYPE_BLOCK_DEVICE; case 0140000: // socket return NET_SFTP_TYPE_SOCKET; case 0160000: // whiteout // "SPECIAL should be used for files that are of // a known type which cannot be expressed in the protocol" return NET_SFTP_TYPE_SPECIAL; default: return NET_SFTP_TYPE_UNKNOWN; } } /** * Parse Longname * * SFTPv3 doesn't provide any easy way of identifying a file type. You could try to open * a file as a directory and see if an error is returned or you could try to parse the * SFTPv3-specific longname field of the SSH_FXP_NAME packet. That's what this function does. * The result is returned using the * {@link http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-5.2 SFTPv4 type constants}. * * If the longname is in an unrecognized format bool(false) is returned. * * @param String $longname * @return Mixed * @access private */ function _parseLongname($longname) { // http://en.wikipedia.org/wiki/Unix_file_types // http://en.wikipedia.org/wiki/Filesystem_permissions#Notation_of_traditional_Unix_permissions if (preg_match('#^[^/]([r-][w-][xstST-]){3}#', $longname)) { switch ($longname[0]) { case '-': return NET_SFTP_TYPE_REGULAR; case 'd': return NET_SFTP_TYPE_DIRECTORY; case 'l': return NET_SFTP_TYPE_SYMLINK; default: return NET_SFTP_TYPE_SPECIAL; } } return false; } /** * Sends SFTP Packets * * See '6. General Packet Format' of draft-ietf-secsh-filexfer-13 for more info. * * @param Integer $type * @param String $data * @see \phpseclib\Net\SFTP::_get_sftp_packet() * @see \phpseclib\Net\SSH2::_send_channel_packet() * @return Boolean * @access private */ function _send_sftp_packet($type, $data) { $packet = $this->request_id !== false ? pack('NCNa*', strlen($data) + 5, $type, $this->request_id, $data) : pack('NCa*', strlen($data) + 1, $type, $data); $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838 $result = $this->_send_channel_packet(self::CHANNEL, $packet); $stop = strtok(microtime(), ' ') + strtok(''); if (defined('NET_SFTP_LOGGING')) { $packet_type = '-> ' . $this->packet_types[$type] . ' (' . round($stop - $start, 4) . 's)'; if (NET_SFTP_LOGGING == NET_SFTP_LOG_REALTIME) { echo "
\r\n" . $this->_format_log(array($data), array($packet_type)) . "\r\n
\r\n"; flush(); ob_flush(); } else { $this->packet_type_log[] = $packet_type; if (NET_SFTP_LOGGING == NET_SFTP_LOG_COMPLEX) { $this->packet_log[] = $data; } } } return $result; } /** * Receives SFTP Packets * * See '6. General Packet Format' of draft-ietf-secsh-filexfer-13 for more info. * * Incidentally, the number of SSH_MSG_CHANNEL_DATA messages has no bearing on the number of SFTP packets present. * There can be one SSH_MSG_CHANNEL_DATA messages containing two SFTP packets or there can be two SSH_MSG_CHANNEL_DATA * messages containing one SFTP packet. * * @see \phpseclib\Net\SFTP::_send_sftp_packet() * @return String * @access private */ function _get_sftp_packet() { $this->curTimeout = false; $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838 // SFTP packet length while (strlen($this->packet_buffer) < 4) { $temp = $this->_get_channel_packet(self::CHANNEL); if (is_bool($temp)) { $this->packet_type = false; $this->packet_buffer = ''; return false; } $this->packet_buffer.= $temp; } extract(unpack('Nlength', $this->_string_shift($this->packet_buffer, 4))); $tempLength = $length; $tempLength-= strlen($this->packet_buffer); // SFTP packet type and data payload while ($tempLength > 0) { $temp = $this->_get_channel_packet(self::CHANNEL); if (is_bool($temp)) { $this->packet_type = false; $this->packet_buffer = ''; return false; } $this->packet_buffer.= $temp; $tempLength-= strlen($temp); } $stop = strtok(microtime(), ' ') + strtok(''); $this->packet_type = ord($this->_string_shift($this->packet_buffer)); if ($this->request_id !== false) { $this->_string_shift($this->packet_buffer, 4); // remove the request id $length-= 5; // account for the request id and the packet type } else { $length-= 1; // account for the packet type } $packet = $this->_string_shift($this->packet_buffer, $length); if (defined('NET_SFTP_LOGGING')) { $packet_type = '<- ' . $this->packet_types[$this->packet_type] . ' (' . round($stop - $start, 4) . 's)'; if (NET_SFTP_LOGGING == NET_SFTP_LOG_REALTIME) { echo "
\r\n" . $this->_format_log(array($packet), array($packet_type)) . "\r\n
\r\n"; flush(); ob_flush(); } else { $this->packet_type_log[] = $packet_type; if (NET_SFTP_LOGGING == NET_SFTP_LOG_COMPLEX) { $this->packet_log[] = $packet; } } } return $packet; } /** * Returns a log of the packets that have been sent and received. * * Returns a string if NET_SFTP_LOGGING == NET_SFTP_LOG_COMPLEX, an array if NET_SFTP_LOGGING == NET_SFTP_LOG_SIMPLE and false if !defined('NET_SFTP_LOGGING') * * @access public * @return String or Array */ function getSFTPLog() { if (!defined('NET_SFTP_LOGGING')) { return false; } switch (NET_SFTP_LOGGING) { case NET_SFTP_LOG_COMPLEX: return $this->_format_log($this->packet_log, $this->packet_type_log); break; //case NET_SFTP_LOG_SIMPLE: default: return $this->packet_type_log; } } /** * Returns all errors * * @return String * @access public */ function getSFTPErrors() { return $this->sftp_errors; } /** * Returns the last error * * @return String * @access public */ function getLastSFTPError() { return count($this->sftp_errors) ? $this->sftp_errors[count($this->sftp_errors) - 1] : ''; } /** * Get supported SFTP versions * * @return Array * @access public */ function getSupportedVersions() { $temp = array('version' => $this->version); if (isset($this->extensions['versions'])) { $temp['extensions'] = $this->extensions['versions']; } return $temp; } /** * Disconnect * * @param Integer $reason * @return Boolean * @access private */ function _disconnect($reason) { $this->pwd = false; parent::_disconnect($reason); } } * login('username', 'password')) { * exit('Login Failed'); * } * * echo $ssh->exec('ls -la'); * ?> * * * Here's another short example: * * login('username', 'password')) { * exit('Login Failed'); * } * * echo $ssh->read('username@username:~$'); * $ssh->write("ls -la\n"); * echo $ssh->read('username@username:~$'); * ?> * * * More information on the SSHv1 specification can be found by reading * {@link http://www.snailbook.com/docs/protocol-1.5.txt protocol-1.5.txt}. * * @category Net * @package SSH1 * @author Jim Wigginton * @copyright 2007 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\Net; use phpseclib\Crypt\DES; use phpseclib\Crypt\Random; use phpseclib\Crypt\TripleDES; use phpseclib\Math\BigInteger; /** * Pure-PHP implementation of SSHv1. * * @package SSH1 * @author Jim Wigginton * @access public */ class SSH1 { /**#@+ * Encryption Methods * * @see \phpseclib\Net\SSH1::getSupportedCiphers() * @access public */ /** * No encryption * * Not supported. */ const CIPHER_NONE = 0; /** * IDEA in CFB mode * * Not supported. */ const CIPHER_IDEA = 1; /** * DES in CBC mode */ const CIPHER_DES = 2; /** * Triple-DES in CBC mode * * All implementations are required to support this */ const CIPHER_3DES = 3; /** * TRI's Simple Stream encryption CBC * * Not supported nor is it defined in the official SSH1 specs. OpenSSH, however, does define it (see cipher.h), * although it doesn't use it (see cipher.c) */ const CIPHER_BROKEN_TSS = 4; /** * RC4 * * Not supported. * * @internal According to the SSH1 specs: * * "The first 16 bytes of the session key are used as the key for * the server to client direction. The remaining 16 bytes are used * as the key for the client to server direction. This gives * independent 128-bit keys for each direction." * * This library currently only supports encryption when the same key is being used for both directions. This is * because there's only one $crypto object. Two could be added ($encrypt and $decrypt, perhaps). */ const CIPHER_RC4 = 5; /** * Blowfish * * Not supported nor is it defined in the official SSH1 specs. OpenSSH, however, defines it (see cipher.h) and * uses it (see cipher.c) */ const CIPHER_BLOWFISH = 6; /**#@-*/ /**#@+ * Authentication Methods * * @see \phpseclib\Net\SSH1::getSupportedAuthentications() * @access public */ /** * .rhosts or /etc/hosts.equiv */ const AUTH_RHOSTS = 1; /** * pure RSA authentication */ const AUTH_RSA = 2; /** * password authentication * * This is the only method that is supported by this library. */ const AUTH_PASSWORD = 3; /** * .rhosts with RSA host authentication */ const AUTH_RHOSTS_RSA = 4; /**#@-*/ /**#@+ * Terminal Modes * * @link http://3sp.com/content/developer/maverick-net/docs/Maverick.SSH.PseudoTerminalModesMembers.html * @access private */ const TTY_OP_END = 0; /**#@-*/ /** * The Response Type * * @see \phpseclib\Net\SSH1::_get_binary_packet() * @access private */ const RESPONSE_TYPE = 1; /** * The Response Data * * @see \phpseclib\Net\SSH1::_get_binary_packet() * @access private */ const RESPONSE_DATA = 2; /**#@+ * Execution Bitmap Masks * * @see \phpseclib\Net\SSH1::bitmap * @access private */ const MASK_CONSTRUCTOR = 0x00000001; const MASK_CONNECTED = 0x00000002; const MASK_LOGIN = 0x00000004; const MASK_SHELL = 0x00000008; /**#@-*/ /**#@+ * @access public * @see \phpseclib\Net\SSH1::getLog() */ /** * Returns the message numbers */ const LOG_SIMPLE = 1; /** * Returns the message content */ const LOG_COMPLEX = 2; /** * Outputs the content real-time */ const LOG_REALTIME = 3; /** * Dumps the content real-time to a file */ const LOG_REALTIME_FILE = 4; /**#@-*/ /**#@+ * @access public * @see \phpseclib\Net\SSH1::read() */ /** * Returns when a string matching $expect exactly is found */ const READ_SIMPLE = 1; /** * Returns when a string matching the regular expression $expect is found */ const READ_REGEX = 2; /**#@-*/ /** * The SSH identifier * * @var String * @access private */ var $identifier = 'SSH-1.5-phpseclib'; /** * The Socket Object * * @var Object * @access private */ var $fsock; /** * The cryptography object * * @var Object * @access private */ var $crypto = false; /** * Execution Bitmap * * The bits that are set represent functions that have been called already. This is used to determine * if a requisite function has been successfully executed. If not, an error should be thrown. * * @var Integer * @access private */ var $bitmap = 0; /** * The Server Key Public Exponent * * Logged for debug purposes * * @see \phpseclib\Net\SSH1::getServerKeyPublicExponent() * @var String * @access private */ var $server_key_public_exponent; /** * The Server Key Public Modulus * * Logged for debug purposes * * @see \phpseclib\Net\SSH1::getServerKeyPublicModulus() * @var String * @access private */ var $server_key_public_modulus; /** * The Host Key Public Exponent * * Logged for debug purposes * * @see \phpseclib\Net\SSH1::getHostKeyPublicExponent() * @var String * @access private */ var $host_key_public_exponent; /** * The Host Key Public Modulus * * Logged for debug purposes * * @see \phpseclib\Net\SSH1::getHostKeyPublicModulus() * @var String * @access private */ var $host_key_public_modulus; /** * Supported Ciphers * * Logged for debug purposes * * @see \phpseclib\Net\SSH1::getSupportedCiphers() * @var Array * @access private */ var $supported_ciphers = array( self::CIPHER_NONE => 'No encryption', self::CIPHER_IDEA => 'IDEA in CFB mode', self::CIPHER_DES => 'DES in CBC mode', self::CIPHER_3DES => 'Triple-DES in CBC mode', self::CIPHER_BROKEN_TSS => 'TRI\'s Simple Stream encryption CBC', self::CIPHER_RC4 => 'RC4', self::CIPHER_BLOWFISH => 'Blowfish' ); /** * Supported Authentications * * Logged for debug purposes * * @see \phpseclib\Net\SSH1::getSupportedAuthentications() * @var Array * @access private */ var $supported_authentications = array( self::AUTH_RHOSTS => '.rhosts or /etc/hosts.equiv', self::AUTH_RSA => 'pure RSA authentication', self::AUTH_PASSWORD => 'password authentication', self::AUTH_RHOSTS_RSA => '.rhosts with RSA host authentication' ); /** * Server Identification * * @see \phpseclib\Net\SSH1::getServerIdentification() * @var String * @access private */ var $server_identification = ''; /** * Protocol Flags * * @see \phpseclib\Net\SSH1::__construct() * @var Array * @access private */ var $protocol_flags = array(); /** * Protocol Flag Log * * @see \phpseclib\Net\SSH1::getLog() * @var Array * @access private */ var $protocol_flag_log = array(); /** * Message Log * * @see \phpseclib\Net\SSH1::getLog() * @var Array * @access private */ var $message_log = array(); /** * Real-time log file pointer * * @see \phpseclib\Net\SSH1::_append_log() * @var Resource * @access private */ var $realtime_log_file; /** * Real-time log file size * * @see \phpseclib\Net\SSH1::_append_log() * @var Integer * @access private */ var $realtime_log_size; /** * Real-time log file wrap boolean * * @see \phpseclib\Net\SSH1::_append_log() * @var Boolean * @access private */ var $realtime_log_wrap; /** * Interactive Buffer * * @see \phpseclib\Net\SSH1::read() * @var Array * @access private */ var $interactiveBuffer = ''; /** * Timeout * * @see \phpseclib\Net\SSH1::setTimeout() * @access private */ var $timeout; /** * Current Timeout * * @see \phpseclib\Net\SSH1::_get_channel_packet() * @access private */ var $curTimeout; /** * Log Boundary * * @see \phpseclib\Net\SSH1::_format_log * @access private */ var $log_boundary = ':'; /** * Log Long Width * * @see \phpseclib\Net\SSH1::_format_log * @access private */ var $log_long_width = 65; /** * Log Short Width * * @see \phpseclib\Net\SSH1::_format_log * @access private */ var $log_short_width = 16; /** * Hostname * * @see \phpseclib\Net\SSH1::__construct() * @see \phpseclib\Net\SSH1::_connect() * @var String * @access private */ var $host; /** * Port Number * * @see \phpseclib\Net\SSH1::__construct() * @see \phpseclib\Net\SSH1::_connect() * @var Integer * @access private */ var $port; /** * Timeout for initial connection * * Set by the constructor call. Calling setTimeout() is optional. If it's not called functions like * exec() won't timeout unless some PHP setting forces it too. The timeout specified in the constructor, * however, is non-optional. There will be a timeout, whether or not you set it. If you don't it'll be * 10 seconds. It is used by fsockopen() in that function. * * @see \phpseclib\Net\SSH1::__construct() * @see \phpseclib\Net\SSH1::_connect() * @var Integer * @access private */ var $connectionTimeout; /** * Default cipher * * @see \phpseclib\Net\SSH1::__construct() * @see \phpseclib\Net\SSH1::_connect() * @var Integer * @access private */ var $cipher; /** * Default Constructor. * * Connects to an SSHv1 server * * @param String $host * @param optional Integer $port * @param optional Integer $timeout * @param optional Integer $cipher * @return \phpseclib\Net\SSH1 * @access public */ function __construct($host, $port = 22, $timeout = 10, $cipher = self::CIPHER_3DES) { $this->protocol_flags = array( 1 => 'NET_SSH1_MSG_DISCONNECT', 2 => 'NET_SSH1_SMSG_PUBLIC_KEY', 3 => 'NET_SSH1_CMSG_SESSION_KEY', 4 => 'NET_SSH1_CMSG_USER', 9 => 'NET_SSH1_CMSG_AUTH_PASSWORD', 10 => 'NET_SSH1_CMSG_REQUEST_PTY', 12 => 'NET_SSH1_CMSG_EXEC_SHELL', 13 => 'NET_SSH1_CMSG_EXEC_CMD', 14 => 'NET_SSH1_SMSG_SUCCESS', 15 => 'NET_SSH1_SMSG_FAILURE', 16 => 'NET_SSH1_CMSG_STDIN_DATA', 17 => 'NET_SSH1_SMSG_STDOUT_DATA', 18 => 'NET_SSH1_SMSG_STDERR_DATA', 19 => 'NET_SSH1_CMSG_EOF', 20 => 'NET_SSH1_SMSG_EXITSTATUS', 33 => 'NET_SSH1_CMSG_EXIT_CONFIRMATION' ); $this->_define_array($this->protocol_flags); $this->host = $host; $this->port = $port; $this->connectionTimeout = $timeout; $this->cipher = $cipher; } /** * Connect to an SSHv1 server * * @return Boolean * @access private */ function _connect() { $this->fsock = @fsockopen($this->host, $this->port, $errno, $errstr, $this->connectionTimeout); if (!$this->fsock) { user_error(rtrim("Cannot connect to {$this->host}:{$this->port}. Error $errno. $errstr")); return false; } $this->server_identification = $init_line = fgets($this->fsock, 255); if (defined('NET_SSH1_LOGGING')) { $this->_append_log('<-', $this->server_identification); $this->_append_log('->', $this->identifier . "\r\n"); } if (!preg_match('#SSH-([0-9\.]+)-(.+)#', $init_line, $parts)) { user_error('Can only connect to SSH servers'); return false; } if ($parts[1][0] != 1) { user_error("Cannot connect to SSH $parts[1] servers"); return false; } fputs($this->fsock, $this->identifier."\r\n"); $response = $this->_get_binary_packet(); if ($response[self::RESPONSE_TYPE] != NET_SSH1_SMSG_PUBLIC_KEY) { user_error('Expected SSH_SMSG_PUBLIC_KEY'); return false; } $anti_spoofing_cookie = $this->_string_shift($response[self::RESPONSE_DATA], 8); $this->_string_shift($response[self::RESPONSE_DATA], 4); $temp = unpack('nlen', $this->_string_shift($response[self::RESPONSE_DATA], 2)); $server_key_public_exponent = new BigInteger($this->_string_shift($response[self::RESPONSE_DATA], ceil($temp['len'] / 8)), 256); $this->server_key_public_exponent = $server_key_public_exponent; $temp = unpack('nlen', $this->_string_shift($response[self::RESPONSE_DATA], 2)); $server_key_public_modulus = new BigInteger($this->_string_shift($response[self::RESPONSE_DATA], ceil($temp['len'] / 8)), 256); $this->server_key_public_modulus = $server_key_public_modulus; $this->_string_shift($response[self::RESPONSE_DATA], 4); $temp = unpack('nlen', $this->_string_shift($response[self::RESPONSE_DATA], 2)); $host_key_public_exponent = new BigInteger($this->_string_shift($response[self::RESPONSE_DATA], ceil($temp['len'] / 8)), 256); $this->host_key_public_exponent = $host_key_public_exponent; $temp = unpack('nlen', $this->_string_shift($response[self::RESPONSE_DATA], 2)); $host_key_public_modulus = new BigInteger($this->_string_shift($response[self::RESPONSE_DATA], ceil($temp['len'] / 8)), 256); $this->host_key_public_modulus = $host_key_public_modulus; $this->_string_shift($response[self::RESPONSE_DATA], 4); // get a list of the supported ciphers extract(unpack('Nsupported_ciphers_mask', $this->_string_shift($response[self::RESPONSE_DATA], 4))); foreach ($this->supported_ciphers as $mask=>$name) { if (($supported_ciphers_mask & (1 << $mask)) == 0) { unset($this->supported_ciphers[$mask]); } } // get a list of the supported authentications extract(unpack('Nsupported_authentications_mask', $this->_string_shift($response[self::RESPONSE_DATA], 4))); foreach ($this->supported_authentications as $mask=>$name) { if (($supported_authentications_mask & (1 << $mask)) == 0) { unset($this->supported_authentications[$mask]); } } $session_id = pack('H*', md5($host_key_public_modulus->toBytes() . $server_key_public_modulus->toBytes() . $anti_spoofing_cookie)); $session_key = Random::string(32); $double_encrypted_session_key = $session_key ^ str_pad($session_id, 32, chr(0)); if ($server_key_public_modulus->compare($host_key_public_modulus) < 0) { $double_encrypted_session_key = $this->_rsa_crypt( $double_encrypted_session_key, array( $server_key_public_exponent, $server_key_public_modulus ) ); $double_encrypted_session_key = $this->_rsa_crypt( $double_encrypted_session_key, array( $host_key_public_exponent, $host_key_public_modulus ) ); } else { $double_encrypted_session_key = $this->_rsa_crypt( $double_encrypted_session_key, array( $host_key_public_exponent, $host_key_public_modulus ) ); $double_encrypted_session_key = $this->_rsa_crypt( $double_encrypted_session_key, array( $server_key_public_exponent, $server_key_public_modulus ) ); } $cipher = isset($this->supported_ciphers[$this->cipher]) ? $this->cipher : self::CIPHER_3DES; $data = pack('C2a*na*N', NET_SSH1_CMSG_SESSION_KEY, $cipher, $anti_spoofing_cookie, 8 * strlen($double_encrypted_session_key), $double_encrypted_session_key, 0); if (!$this->_send_binary_packet($data)) { user_error('Error sending SSH_CMSG_SESSION_KEY'); return false; } switch ($cipher) { //case self::CIPHER_NONE: // $this->crypto = new \phpseclib\Crypt\Null(); // break; case self::CIPHER_DES: $this->crypto = new DES(); $this->crypto->disablePadding(); $this->crypto->enableContinuousBuffer(); $this->crypto->setKey(substr($session_key, 0, 8)); break; case self::CIPHER_3DES: $this->crypto = new TripleDES(TripleDES::MODE_3CBC); $this->crypto->disablePadding(); $this->crypto->enableContinuousBuffer(); $this->crypto->setKey(substr($session_key, 0, 24)); break; //case self::CIPHER_RC4: // $this->crypto = new RC4(); // $this->crypto->enableContinuousBuffer(); // $this->crypto->setKey(substr($session_key, 0, 16)); // break; } $response = $this->_get_binary_packet(); if ($response[self::RESPONSE_TYPE] != NET_SSH1_SMSG_SUCCESS) { user_error('Expected SSH_SMSG_SUCCESS'); return false; } $this->bitmap = self::MASK_CONNECTED; return true; } /** * Login * * @param String $username * @param optional String $password * @return Boolean * @access public */ function login($username, $password = '') { if (!($this->bitmap & self::MASK_CONSTRUCTOR)) { $this->bitmap |= self::MASK_CONSTRUCTOR; if (!$this->_connect()) { return false; } } if (!($this->bitmap & self::MASK_CONNECTED)) { return false; } $data = pack('CNa*', NET_SSH1_CMSG_USER, strlen($username), $username); if (!$this->_send_binary_packet($data)) { user_error('Error sending SSH_CMSG_USER'); return false; } $response = $this->_get_binary_packet(); if ($response === true) { return false; } if ($response[self::RESPONSE_TYPE] == NET_SSH1_SMSG_SUCCESS) { $this->bitmap |= self::MASK_LOGIN; return true; } else if ($response[self::RESPONSE_TYPE] != NET_SSH1_SMSG_FAILURE) { user_error('Expected SSH_SMSG_SUCCESS or SSH_SMSG_FAILURE'); return false; } $data = pack('CNa*', NET_SSH1_CMSG_AUTH_PASSWORD, strlen($password), $password); if (!$this->_send_binary_packet($data)) { user_error('Error sending SSH_CMSG_AUTH_PASSWORD'); return false; } // remove the username and password from the last logged packet if (defined('NET_SSH1_LOGGING') && NET_SSH1_LOGGING == self::LOG_COMPLEX) { $data = pack('CNa*', NET_SSH1_CMSG_AUTH_PASSWORD, strlen('password'), 'password'); $this->message_log[count($this->message_log) - 1] = $data; } $response = $this->_get_binary_packet(); if ($response === true) { return false; } if ($response[self::RESPONSE_TYPE] == NET_SSH1_SMSG_SUCCESS) { $this->bitmap |= self::MASK_LOGIN; return true; } else if ($response[self::RESPONSE_TYPE] == NET_SSH1_SMSG_FAILURE) { return false; } else { user_error('Expected SSH_SMSG_SUCCESS or SSH_SMSG_FAILURE'); return false; } } /** * Set Timeout * * $ssh->exec('ping 127.0.0.1'); on a Linux host will never return and will run indefinitely. setTimeout() makes it so it'll timeout. * Setting $timeout to false or 0 will mean there is no timeout. * * @param Mixed $timeout */ function setTimeout($timeout) { $this->timeout = $this->curTimeout = $timeout; } /** * Executes a command on a non-interactive shell, returns the output, and quits. * * An SSH1 server will close the connection after a command has been executed on a non-interactive shell. SSH2 * servers don't, however, this isn't an SSH2 client. The way this works, on the server, is by initiating a * shell with the -s option, as discussed in the following links: * * {@link http://www.faqs.org/docs/bashman/bashref_65.html http://www.faqs.org/docs/bashman/bashref_65.html} * {@link http://www.faqs.org/docs/bashman/bashref_62.html http://www.faqs.org/docs/bashman/bashref_62.html} * * To execute further commands, a new \phpseclib\Net\SSH1 object will need to be created. * * Returns false on failure and the output, otherwise. * * @see \phpseclib\Net\SSH1::interactiveRead() * @see \phpseclib\Net\SSH1::interactiveWrite() * @param String $cmd * @return mixed * @access public */ function exec($cmd, $block = true) { if (!($this->bitmap & self::MASK_LOGIN)) { user_error('Operation disallowed prior to login()'); return false; } $data = pack('CNa*', NET_SSH1_CMSG_EXEC_CMD, strlen($cmd), $cmd); if (!$this->_send_binary_packet($data)) { user_error('Error sending SSH_CMSG_EXEC_CMD'); return false; } if (!$block) { return true; } $output = ''; $response = $this->_get_binary_packet(); if ($response !== false) { do { $output.= substr($response[self::RESPONSE_DATA], 4); $response = $this->_get_binary_packet(); } while (is_array($response) && $response[self::RESPONSE_TYPE] != NET_SSH1_SMSG_EXITSTATUS); } $data = pack('C', NET_SSH1_CMSG_EXIT_CONFIRMATION); // i don't think it's really all that important if this packet gets sent or not. $this->_send_binary_packet($data); fclose($this->fsock); // reset the execution bitmap - a new \phpseclib\Net\SSH1 object needs to be created. $this->bitmap = 0; return $output; } /** * Creates an interactive shell * * @see \phpseclib\Net\SSH1::interactiveRead() * @see \phpseclib\Net\SSH1::interactiveWrite() * @return Boolean * @access private */ function _initShell() { // connect using the sample parameters in protocol-1.5.txt. // according to wikipedia.org's entry on text terminals, "the fundamental type of application running on a text // terminal is a command line interpreter or shell". thus, opening a terminal session to run the shell. $data = pack('CNa*N4C', NET_SSH1_CMSG_REQUEST_PTY, strlen('vt100'), 'vt100', 24, 80, 0, 0, self::TTY_OP_END); if (!$this->_send_binary_packet($data)) { user_error('Error sending SSH_CMSG_REQUEST_PTY'); return false; } $response = $this->_get_binary_packet(); if ($response === true) { return false; } if ($response[self::RESPONSE_TYPE] != NET_SSH1_SMSG_SUCCESS) { user_error('Expected SSH_SMSG_SUCCESS'); return false; } $data = pack('C', NET_SSH1_CMSG_EXEC_SHELL); if (!$this->_send_binary_packet($data)) { user_error('Error sending SSH_CMSG_EXEC_SHELL'); return false; } $this->bitmap |= self::MASK_SHELL; //stream_set_blocking($this->fsock, 0); return true; } /** * Inputs a command into an interactive shell. * * @see \phpseclib\Net\SSH1::interactiveWrite() * @param String $cmd * @return Boolean * @access public */ function write($cmd) { return $this->interactiveWrite($cmd); } /** * Returns the output of an interactive shell when there's a match for $expect * * $expect can take the form of a string literal or, if $mode == self::READ__REGEX, * a regular expression. * * @see \phpseclib\Net\SSH1::write() * @param String $expect * @param Integer $mode * @return Boolean * @access public */ function read($expect, $mode = self::READ__SIMPLE) { if (!($this->bitmap & self::MASK_LOGIN)) { user_error('Operation disallowed prior to login()'); return false; } if (!($this->bitmap & self::MASK_SHELL) && !$this->_initShell()) { user_error('Unable to initiate an interactive shell session'); return false; } $match = $expect; while (true) { if ($mode == self::READ__REGEX) { preg_match($expect, $this->interactiveBuffer, $matches); $match = isset($matches[0]) ? $matches[0] : ''; } $pos = strlen($match) ? strpos($this->interactiveBuffer, $match) : false; if ($pos !== false) { return $this->_string_shift($this->interactiveBuffer, $pos + strlen($match)); } $response = $this->_get_binary_packet(); if ($response === true) { return $this->_string_shift($this->interactiveBuffer, strlen($this->interactiveBuffer)); } $this->interactiveBuffer.= substr($response[self::RESPONSE_DATA], 4); } } /** * Inputs a command into an interactive shell. * * @see \phpseclib\Net\SSH1::interactiveRead() * @param String $cmd * @return Boolean * @access public */ function interactiveWrite($cmd) { if (!($this->bitmap & self::MASK_LOGIN)) { user_error('Operation disallowed prior to login()'); return false; } if (!($this->bitmap & self::MASK_SHELL) && !$this->_initShell()) { user_error('Unable to initiate an interactive shell session'); return false; } $data = pack('CNa*', NET_SSH1_CMSG_STDIN_DATA, strlen($cmd), $cmd); if (!$this->_send_binary_packet($data)) { user_error('Error sending SSH_CMSG_STDIN'); return false; } return true; } /** * Returns the output of an interactive shell when no more output is available. * * Requires PHP 4.3.0 or later due to the use of the stream_select() function. If you see stuff like * "^[[00m", you're seeing ANSI escape codes. According to * {@link http://support.microsoft.com/kb/101875 How to Enable ANSI.SYS in a Command Window}, "Windows NT * does not support ANSI escape sequences in Win32 Console applications", so if you're a Windows user, * there's not going to be much recourse. * * @see \phpseclib\Net\SSH1::interactiveRead() * @return String * @access public */ function interactiveRead() { if (!($this->bitmap & self::MASK_LOGIN)) { user_error('Operation disallowed prior to login()'); return false; } if (!($this->bitmap & self::MASK_SHELL) && !$this->_initShell()) { user_error('Unable to initiate an interactive shell session'); return false; } $read = array($this->fsock); $write = $except = null; if (stream_select($read, $write, $except, 0)) { $response = $this->_get_binary_packet(); return substr($response[self::RESPONSE_DATA], 4); } else { return ''; } } /** * Disconnect * * @access public */ function disconnect() { $this->_disconnect(); } /** * Destructor. * * Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call * disconnect(). * * @access public */ function __destruct() { $this->_disconnect(); } /** * Disconnect * * @param String $msg * @access private */ function _disconnect($msg = 'Client Quit') { if ($this->bitmap) { $data = pack('C', NET_SSH1_CMSG_EOF); $this->_send_binary_packet($data); /* $response = $this->_get_binary_packet(); if ($response === true) { $response = array(self::RESPONSE_TYPE => -1); } switch ($response[self::RESPONSE_TYPE]) { case NET_SSH1_SMSG_EXITSTATUS: $data = pack('C', NET_SSH1_CMSG_EXIT_CONFIRMATION); break; default: $data = pack('CNa*', NET_SSH1_MSG_DISCONNECT, strlen($msg), $msg); } */ $data = pack('CNa*', NET_SSH1_MSG_DISCONNECT, strlen($msg), $msg); $this->_send_binary_packet($data); fclose($this->fsock); $this->bitmap = 0; } } /** * Gets Binary Packets * * See 'The Binary Packet Protocol' of protocol-1.5.txt for more info. * * Also, this function could be improved upon by adding detection for the following exploit: * http://www.securiteam.com/securitynews/5LP042K3FY.html * * @see \phpseclib\Net\SSH1::_send_binary_packet() * @return Array * @access private */ function _get_binary_packet() { if (feof($this->fsock)) { //user_error('connection closed prematurely'); return false; } if ($this->curTimeout) { $read = array($this->fsock); $write = $except = null; $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838 $sec = floor($this->curTimeout); $usec = 1000000 * ($this->curTimeout - $sec); // on windows this returns a "Warning: Invalid CRT parameters detected" error if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) { //$this->_disconnect('Timeout'); return true; } $elapsed = strtok(microtime(), ' ') + strtok('') - $start; $this->curTimeout-= $elapsed; } $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838 $temp = unpack('Nlength', fread($this->fsock, 4)); $padding_length = 8 - ($temp['length'] & 7); $length = $temp['length'] + $padding_length; $raw = ''; while ($length > 0) { $temp = fread($this->fsock, $length); $raw.= $temp; $length-= strlen($temp); } $stop = strtok(microtime(), ' ') + strtok(''); if (strlen($raw) && $this->crypto !== false) { $raw = $this->crypto->decrypt($raw); } $padding = substr($raw, 0, $padding_length); $type = $raw[$padding_length]; $data = substr($raw, $padding_length + 1, -4); $temp = unpack('Ncrc', substr($raw, -4)); //if ( $temp['crc'] != $this->_crc($padding . $type . $data) ) { // user_error('Bad CRC in packet from server'); // return false; //} $type = ord($type); if (defined('NET_SSH1_LOGGING')) { $temp = isset($this->protocol_flags[$type]) ? $this->protocol_flags[$type] : 'UNKNOWN'; $temp = '<- ' . $temp . ' (' . round($stop - $start, 4) . 's)'; $this->_append_log($temp, $data); } return array( self::RESPONSE_TYPE => $type, self::RESPONSE_DATA => $data ); } /** * Sends Binary Packets * * Returns true on success, false on failure. * * @see \phpseclib\Net\SSH1::_get_binary_packet() * @param String $data * @return Boolean * @access private */ function _send_binary_packet($data) { if (feof($this->fsock)) { //user_error('connection closed prematurely'); return false; } $length = strlen($data) + 4; $padding = Random::string(8 - ($length & 7)); $orig = $data; $data = $padding . $data; $data.= pack('N', $this->_crc($data)); if ($this->crypto !== false) { $data = $this->crypto->encrypt($data); } $packet = pack('Na*', $length, $data); $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838 $result = strlen($packet) == fputs($this->fsock, $packet); $stop = strtok(microtime(), ' ') + strtok(''); if (defined('NET_SSH1_LOGGING')) { $temp = isset($this->protocol_flags[ord($orig[0])]) ? $this->protocol_flags[ord($orig[0])] : 'UNKNOWN'; $temp = '-> ' . $temp . ' (' . round($stop - $start, 4) . 's)'; $this->_append_log($temp, $orig); } return $result; } /** * Cyclic Redundancy Check (CRC) * * PHP's crc32 function is implemented slightly differently than the one that SSH v1 uses, so * we've reimplemented it. A more detailed discussion of the differences can be found after * $crc_lookup_table's initialization. * * @see \phpseclib\Net\SSH1::_get_binary_packet() * @see \phpseclib\Net\SSH1::_send_binary_packet() * @param String $data * @return Integer * @access private */ function _crc($data) { static $crc_lookup_table = array( 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D ); // For this function to yield the same output as PHP's crc32 function, $crc would have to be // set to 0xFFFFFFFF, initially - not 0x00000000 as it currently is. $crc = 0x00000000; $length = strlen($data); for ($i=0;$i<$length;$i++) { // We AND $crc >> 8 with 0x00FFFFFF because we want the eight newly added bits to all // be zero. PHP, unfortunately, doesn't always do this. 0x80000000 >> 8, as an example, // yields 0xFF800000 - not 0x00800000. The following link elaborates: // http://www.php.net/manual/en/language.operators.bitwise.php#57281 $crc = (($crc >> 8) & 0x00FFFFFF) ^ $crc_lookup_table[($crc & 0xFF) ^ ord($data[$i])]; } // In addition to having to set $crc to 0xFFFFFFFF, initially, the return value must be XOR'd with // 0xFFFFFFFF for this function to return the same thing that PHP's crc32 function would. return $crc; } /** * String Shift * * Inspired by array_shift * * @param String $string * @param optional Integer $index * @return String * @access private */ function _string_shift(&$string, $index = 1) { $substr = substr($string, 0, $index); $string = substr($string, $index); return $substr; } /** * RSA Encrypt * * Returns mod(pow($m, $e), $n), where $n should be the product of two (large) primes $p and $q and where $e * should be a number with the property that gcd($e, ($p - 1) * ($q - 1)) == 1. Could just make anything that * calls this call modexp, instead, but I think this makes things clearer, maybe... * * @see \phpseclib\Net\SSH1::__construct() * @param BigInteger $m * @param Array $key * @return BigInteger * @access private */ function _rsa_crypt($m, $key) { /* $rsa = new RSA(); $rsa->loadKey($key, RSA::PUBLIC_FORMAT_RAW); $rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1); return $rsa->encrypt($m); */ // To quote from protocol-1.5.txt: // The most significant byte (which is only partial as the value must be // less than the public modulus, which is never a power of two) is zero. // // The next byte contains the value 2 (which stands for public-key // encrypted data in the PKCS standard [PKCS#1]). Then, there are non- // zero random bytes to fill any unused space, a zero byte, and the data // to be encrypted in the least significant bytes, the last byte of the // data in the least significant byte. // Presumably the part of PKCS#1 they're refering to is "Section 7.2.1 Encryption Operation", // under "7.2 RSAES-PKCS1-v1.5" and "7 Encryption schemes" of the following URL: // ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1.pdf $modulus = $key[1]->toBytes(); $length = strlen($modulus) - strlen($m) - 3; $random = ''; while (strlen($random) != $length) { $block = Random::string($length - strlen($random)); $block = str_replace("\x00", '', $block); $random.= $block; } $temp = chr(0) . chr(2) . $random . chr(0) . $m; $m = new BigInteger($temp, 256); $m = $m->modPow($key[0], $key[1]); return $m->toBytes(); } /** * Define Array * * Takes any number of arrays whose indices are integers and whose values are strings and defines a bunch of * named constants from it, using the value as the name of the constant and the index as the value of the constant. * If any of the constants that would be defined already exists, none of the constants will be defined. * * @param Array $array * @access private */ function _define_array() { $args = func_get_args(); foreach ($args as $arg) { foreach ($arg as $key=>$value) { if (!defined($value)) { define($value, $key); } else { break 2; } } } } /** * Returns a log of the packets that have been sent and received. * * Returns a string if NET_SSH1_LOGGING == self::LOG_COMPLEX, an array if NET_SSH1_LOGGING == self::LOG_SIMPLE and false if !defined('NET_SSH1_LOGGING') * * @access public * @return String or Array */ function getLog() { if (!defined('NET_SSH1_LOGGING')) { return false; } switch (NET_SSH1_LOGGING) { case self::LOG_SIMPLE: return $this->message_number_log; break; case self::LOG_COMPLEX: return $this->_format_log($this->message_log, $this->protocol_flags_log); break; default: return false; } } /** * Formats a log for printing * * @param Array $message_log * @param Array $message_number_log * @access private * @return String */ function _format_log($message_log, $message_number_log) { $output = ''; for ($i = 0; $i < count($message_log); $i++) { $output.= $message_number_log[$i] . "\r\n"; $current_log = $message_log[$i]; $j = 0; do { if (strlen($current_log)) { $output.= str_pad(dechex($j), 7, '0', STR_PAD_LEFT) . '0 '; } $fragment = $this->_string_shift($current_log, $this->log_short_width); $hex = substr(preg_replace_callback('#.#s', array($this, '_format_log_helper'), $fragment), strlen($this->log_boundary)); // replace non ASCII printable characters with dots // http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters // also replace < with a . since < messes up the output on web browsers $raw = preg_replace('#[^\x20-\x7E]|<#', '.', $fragment); $output.= str_pad($hex, $this->log_long_width - $this->log_short_width, ' ') . $raw . "\r\n"; $j++; } while (strlen($current_log)); $output.= "\r\n"; } return $output; } /** * Helper function for _format_log * * For use with preg_replace_callback() * * @param Array $matches * @access private * @return String */ function _format_log_helper($matches) { return $this->log_boundary . str_pad(dechex(ord($matches[0])), 2, '0', STR_PAD_LEFT); } /** * Return the server key public exponent * * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead, * the raw bytes. This behavior is similar to PHP's md5() function. * * @param optional Boolean $raw_output * @return String * @access public */ function getServerKeyPublicExponent($raw_output = false) { return $raw_output ? $this->server_key_public_exponent->toBytes() : $this->server_key_public_exponent->toString(); } /** * Return the server key public modulus * * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead, * the raw bytes. This behavior is similar to PHP's md5() function. * * @param optional Boolean $raw_output * @return String * @access public */ function getServerKeyPublicModulus($raw_output = false) { return $raw_output ? $this->server_key_public_modulus->toBytes() : $this->server_key_public_modulus->toString(); } /** * Return the host key public exponent * * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead, * the raw bytes. This behavior is similar to PHP's md5() function. * * @param optional Boolean $raw_output * @return String * @access public */ function getHostKeyPublicExponent($raw_output = false) { return $raw_output ? $this->host_key_public_exponent->toBytes() : $this->host_key_public_exponent->toString(); } /** * Return the host key public modulus * * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead, * the raw bytes. This behavior is similar to PHP's md5() function. * * @param optional Boolean $raw_output * @return String * @access public */ function getHostKeyPublicModulus($raw_output = false) { return $raw_output ? $this->host_key_public_modulus->toBytes() : $this->host_key_public_modulus->toString(); } /** * Return a list of ciphers supported by SSH1 server. * * Just because a cipher is supported by an SSH1 server doesn't mean it's supported by this library. If $raw_output * is set to true, returns, instead, an array of constants. ie. instead of array('Triple-DES in CBC mode'), you'll * get array(self::CIPHER_3DES). * * @param optional Boolean $raw_output * @return Array * @access public */ function getSupportedCiphers($raw_output = false) { return $raw_output ? array_keys($this->supported_ciphers) : array_values($this->supported_ciphers); } /** * Return a list of authentications supported by SSH1 server. * * Just because a cipher is supported by an SSH1 server doesn't mean it's supported by this library. If $raw_output * is set to true, returns, instead, an array of constants. ie. instead of array('password authentication'), you'll * get array(self::AUTH_PASSWORD). * * @param optional Boolean $raw_output * @return Array * @access public */ function getSupportedAuthentications($raw_output = false) { return $raw_output ? array_keys($this->supported_authentications) : array_values($this->supported_authentications); } /** * Return the server identification. * * @return String * @access public */ function getServerIdentification() { return rtrim($this->server_identification); } /** * Logs data packets * * Makes sure that only the last 1MB worth of packets will be logged * * @param String $data * @access private */ function _append_log($protocol_flags, $message) { switch (NET_SSH1_LOGGING) { // useful for benchmarks case self::LOG_SIMPLE: $this->protocol_flags_log[] = $protocol_flags; break; // the most useful log for SSH1 case self::LOG_COMPLEX: $this->protocol_flags_log[] = $protocol_flags; $this->_string_shift($message); $this->log_size+= strlen($message); $this->message_log[] = $message; while ($this->log_size > self::LOG_MAX_SIZE) { $this->log_size-= strlen(array_shift($this->message_log)); array_shift($this->protocol_flags_log); } break; // dump the output out realtime; packets may be interspersed with non packets, // passwords won't be filtered out and select other packets may not be correctly // identified case self::LOG_REALTIME: echo "
\r\n" . $this->_format_log(array($message), array($protocol_flags)) . "\r\n
\r\n"; @flush(); @ob_flush(); break; // basically the same thing as self::LOG_REALTIME with the caveat that self::LOG_REALTIME_FILE // needs to be defined and that the resultant log file will be capped out at self::LOG_MAX_SIZE. // the earliest part of the log file is denoted by the first <<< START >>> and is not going to necessarily // at the beginning of the file case self::LOG_REALTIME_FILE: if (!isset($this->realtime_log_file)) { // PHP doesn't seem to like using constants in fopen() $filename = self::LOG_REALTIME_FILE; $fp = fopen($filename, 'w'); $this->realtime_log_file = $fp; } if (!is_resource($this->realtime_log_file)) { break; } $entry = $this->_format_log(array($message), array($protocol_flags)); if ($this->realtime_log_wrap) { $temp = "<<< START >>>\r\n"; $entry.= $temp; fseek($this->realtime_log_file, ftell($this->realtime_log_file) - strlen($temp)); } $this->realtime_log_size+= strlen($entry); if ($this->realtime_log_size > self::LOG_MAX_SIZE) { fseek($this->realtime_log_file, 0); $this->realtime_log_size = strlen($entry); $this->realtime_log_wrap = true; } fputs($this->realtime_log_file, $entry); } } } * login('username', 'password')) { * exit('Login Failed'); * } * * echo $ssh->exec('pwd'); * echo $ssh->exec('ls -la'); * ?> * * * * setPassword('whatever'); * $key->loadKey(file_get_contents('privatekey')); * * $ssh = new \phpseclib\Net\SSH2('www.domain.tld'); * if (!$ssh->login('username', $key)) { * exit('Login Failed'); * } * * echo $ssh->read('username@username:~$'); * $ssh->write("ls -la\n"); * echo $ssh->read('username@username:~$'); * ?> * * * @category Net * @package SSH2 * @author Jim Wigginton * @copyright 2007 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net */ namespace phpseclib\Net; use phpseclib\Crypt\Base; use phpseclib\Crypt\Blowfish; use phpseclib\Crypt\Hash; use phpseclib\Crypt\Random; use phpseclib\Crypt\RC4; use phpseclib\Crypt\Rijndael; use phpseclib\Crypt\RSA; use phpseclib\Crypt\TripleDES; use phpseclib\Crypt\Twofish; use phpseclib\Math\BigInteger; // Used to do Diffie-Hellman key exchange and DSA/RSA signature verification. use phpseclib\System\SSH\Agent; /** * Pure-PHP implementation of SSHv2. * * @package SSH2 * @author Jim Wigginton * @access public */ class SSH2 { /**#@+ * Execution Bitmap Masks * * @see \phpseclib\Net\SSH2::bitmap * @access private */ const MASK_CONSTRUCTOR = 0x00000001; const MASK_CONNECTED = 0x00000002; const MASK_LOGIN_REQ = 0x00000004; const MASK_LOGIN = 0x00000008; const MASK_SHELL = 0x00000010; const MASK_WINDOW_ADJUST = 0x00000020; /**#@-*/ /**#@+ * Channel constants * * RFC4254 refers not to client and server channels but rather to sender and recipient channels. we don't refer * to them in that way because RFC4254 toggles the meaning. the client sends a SSH_MSG_CHANNEL_OPEN message with * a sender channel and the server sends a SSH_MSG_CHANNEL_OPEN_CONFIRMATION in response, with a sender and a * recepient channel. at first glance, you might conclude that SSH_MSG_CHANNEL_OPEN_CONFIRMATION's sender channel * would be the same thing as SSH_MSG_CHANNEL_OPEN's sender channel, but it's not, per this snipet: * The 'recipient channel' is the channel number given in the original * open request, and 'sender channel' is the channel number allocated by * the other side. * * @see \phpseclib\Net\SSH2::_send_channel_packet() * @see \phpseclib\Net\SSH2::_get_channel_packet() * @access private */ const CHANNEL_EXEC = 0; // PuTTy uses 0x100 const CHANNEL_SHELL = 1; const CHANNEL_SUBSYSTEM = 2; /**#@-*/ /**#@+ * @access public * @see \phpseclib\Net\SSH2::getLog() */ /** * Returns the message numbers */ const LOG_SIMPLE = 1; /** * Returns the message content */ const LOG_COMPLEX = 2; /** * Outputs the content real-time */ const LOG_REALTIME = 3; /** * Dumps the content real-time to a file */ const LOG_REALTIME_FILE = 4; /**#@-*/ /**#@+ * @access public * @see \phpseclib\Net\SSH2::read() */ /** * Returns when a string matching $expect exactly is found */ const READ_SIMPLE = 1; /** * Returns when a string matching the regular expression $expect is found */ const READ_REGEX = 2; /** * Make sure that the log never gets larger than this */ const LOG_MAX_SIZE = 1048576; // 1024 * 1024 /**#@-*/ /** * The SSH identifier * * @var String * @access private */ var $identifier; /** * The Socket Object * * @var Object * @access private */ var $fsock; /** * Execution Bitmap * * The bits that are set represent functions that have been called already. This is used to determine * if a requisite function has been successfully executed. If not, an error should be thrown. * * @var Integer * @access private */ var $bitmap = 0; /** * Error information * * @see \phpseclib\Net\SSH2::getErrors() * @see \phpseclib\Net\SSH2::getLastError() * @var String * @access private */ var $errors = array(); /** * Server Identifier * * @see \phpseclib\Net\SSH2::getServerIdentification() * @var mixed false or Array * @access private */ var $server_identifier = false; /** * Key Exchange Algorithms * * @see \phpseclib\Net\SSH2::getKexAlgorithims() * @var mixed false or Array * @access private */ var $kex_algorithms = false; /** * Server Host Key Algorithms * * @see \phpseclib\Net\SSH2::getServerHostKeyAlgorithms() * @var mixed false or Array * @access private */ var $server_host_key_algorithms = false; /** * Encryption Algorithms: Client to Server * * @see \phpseclib\Net\SSH2::getEncryptionAlgorithmsClient2Server() * @var mixed false or Array * @access private */ var $encryption_algorithms_client_to_server = false; /** * Encryption Algorithms: Server to Client * * @see \phpseclib\Net\SSH2::getEncryptionAlgorithmsServer2Client() * @var mixed false or Array * @access private */ var $encryption_algorithms_server_to_client = false; /** * MAC Algorithms: Client to Server * * @see \phpseclib\Net\SSH2::getMACAlgorithmsClient2Server() * @var mixed false or Array * @access private */ var $mac_algorithms_client_to_server = false; /** * MAC Algorithms: Server to Client * * @see \phpseclib\Net\SSH2::getMACAlgorithmsServer2Client() * @var mixed false or Array * @access private */ var $mac_algorithms_server_to_client = false; /** * Compression Algorithms: Client to Server * * @see \phpseclib\Net\SSH2::getCompressionAlgorithmsClient2Server() * @var mixed false or Array * @access private */ var $compression_algorithms_client_to_server = false; /** * Compression Algorithms: Server to Client * * @see \phpseclib\Net\SSH2::getCompressionAlgorithmsServer2Client() * @var mixed false or Array * @access private */ var $compression_algorithms_server_to_client = false; /** * Languages: Server to Client * * @see \phpseclib\Net\SSH2::getLanguagesServer2Client() * @var mixed false or Array * @access private */ var $languages_server_to_client = false; /** * Languages: Client to Server * * @see \phpseclib\Net\SSH2::getLanguagesClient2Server() * @var mixed false or Array * @access private */ var $languages_client_to_server = false; /** * Block Size for Server to Client Encryption * * "Note that the length of the concatenation of 'packet_length', * 'padding_length', 'payload', and 'random padding' MUST be a multiple * of the cipher block size or 8, whichever is larger. This constraint * MUST be enforced, even when using stream ciphers." * * -- http://tools.ietf.org/html/rfc4253#section-6 * * @see \phpseclib\Net\SSH2::__construct() * @see \phpseclib\Net\SSH2::_send_binary_packet() * @var Integer * @access private */ var $encrypt_block_size = 8; /** * Block Size for Client to Server Encryption * * @see \phpseclib\Net\SSH2::__construct() * @see \phpseclib\Net\SSH2::_get_binary_packet() * @var Integer * @access private */ var $decrypt_block_size = 8; /** * Server to Client Encryption Object * * @see \phpseclib\Net\SSH2::_get_binary_packet() * @var Object * @access private */ var $decrypt = false; /** * Client to Server Encryption Object * * @see \phpseclib\Net\SSH2::_send_binary_packet() * @var Object * @access private */ var $encrypt = false; /** * Client to Server HMAC Object * * @see \phpseclib\Net\SSH2::_send_binary_packet() * @var Object * @access private */ var $hmac_create = false; /** * Server to Client HMAC Object * * @see \phpseclib\Net\SSH2::_get_binary_packet() * @var Object * @access private */ var $hmac_check = false; /** * Size of server to client HMAC * * We need to know how big the HMAC will be for the server to client direction so that we know how many bytes to read. * For the client to server side, the HMAC object will make the HMAC as long as it needs to be. All we need to do is * append it. * * @see \phpseclib\Net\SSH2::_get_binary_packet() * @var Integer * @access private */ var $hmac_size = false; /** * Server Public Host Key * * @see \phpseclib\Net\SSH2::getServerPublicHostKey() * @var String * @access private */ var $server_public_host_key; /** * Session identifer * * "The exchange hash H from the first key exchange is additionally * used as the session identifier, which is a unique identifier for * this connection." * * -- http://tools.ietf.org/html/rfc4253#section-7.2 * * @see \phpseclib\Net\SSH2::_key_exchange() * @var String * @access private */ var $session_id = false; /** * Exchange hash * * The current exchange hash * * @see \phpseclib\Net\SSH2::_key_exchange() * @var String * @access private */ var $exchange_hash = false; /** * Message Numbers * * @see \phpseclib\Net\SSH2::__construct() * @var Array * @access private */ var $message_numbers = array(); /** * Disconnection Message 'reason codes' defined in RFC4253 * * @see \phpseclib\Net\SSH2::__construct() * @var Array * @access private */ var $disconnect_reasons = array(); /** * SSH_MSG_CHANNEL_OPEN_FAILURE 'reason codes', defined in RFC4254 * * @see \phpseclib\Net\SSH2::__construct() * @var Array * @access private */ var $channel_open_failure_reasons = array(); /** * Terminal Modes * * @link http://tools.ietf.org/html/rfc4254#section-8 * @see \phpseclib\Net\SSH2::__construct() * @var Array * @access private */ var $terminal_modes = array(); /** * SSH_MSG_CHANNEL_EXTENDED_DATA's data_type_codes * * @link http://tools.ietf.org/html/rfc4254#section-5.2 * @see \phpseclib\Net\SSH2::__construct() * @var Array * @access private */ var $channel_extended_data_type_codes = array(); /** * Send Sequence Number * * See 'Section 6.4. Data Integrity' of rfc4253 for more info. * * @see \phpseclib\Net\SSH2::_send_binary_packet() * @var Integer * @access private */ var $send_seq_no = 0; /** * Get Sequence Number * * See 'Section 6.4. Data Integrity' of rfc4253 for more info. * * @see \phpseclib\Net\SSH2::_get_binary_packet() * @var Integer * @access private */ var $get_seq_no = 0; /** * Server Channels * * Maps client channels to server channels * * @see \phpseclib\Net\SSH2::_get_channel_packet() * @see \phpseclib\Net\SSH2::exec() * @var Array * @access private */ var $server_channels = array(); /** * Channel Buffers * * If a client requests a packet from one channel but receives two packets from another those packets should * be placed in a buffer * * @see \phpseclib\Net\SSH2::_get_channel_packet() * @see \phpseclib\Net\SSH2::exec() * @var Array * @access private */ var $channel_buffers = array(); /** * Channel Status * * Contains the type of the last sent message * * @see \phpseclib\Net\SSH2::_get_channel_packet() * @var Array * @access private */ var $channel_status = array(); /** * Packet Size * * Maximum packet size indexed by channel * * @see \phpseclib\Net\SSH2::_send_channel_packet() * @var Array * @access private */ var $packet_size_client_to_server = array(); /** * Message Number Log * * @see \phpseclib\Net\SSH2::getLog() * @var Array * @access private */ var $message_number_log = array(); /** * Message Log * * @see \phpseclib\Net\SSH2::getLog() * @var Array * @access private */ var $message_log = array(); /** * The Window Size * * Bytes the other party can send before it must wait for the window to be adjusted (0x7FFFFFFF = 2GB) * * @var Integer * @see \phpseclib\Net\SSH2::_send_channel_packet() * @see \phpseclib\Net\SSH2::exec() * @access private */ var $window_size = 0x7FFFFFFF; /** * Window size, server to client * * Window size indexed by channel * * @see \phpseclib\Net\SSH2::_send_channel_packet() * @var Array * @access private */ var $window_size_server_to_client = array(); /** * Window size, client to server * * Window size indexed by channel * * @see \phpseclib\Net\SSH2::_get_channel_packet() * @var Array * @access private */ var $window_size_client_to_server = array(); /** * Server signature * * Verified against $this->session_id * * @see \phpseclib\Net\SSH2::getServerPublicHostKey() * @var String * @access private */ var $signature = ''; /** * Server signature format * * ssh-rsa or ssh-dss. * * @see \phpseclib\Net\SSH2::getServerPublicHostKey() * @var String * @access private */ var $signature_format = ''; /** * Interactive Buffer * * @see \phpseclib\Net\SSH2::read() * @var Array * @access private */ var $interactiveBuffer = ''; /** * Current log size * * Should never exceed self::LOG_MAX_SIZE * * @see \phpseclib\Net\SSH2::_send_binary_packet() * @see \phpseclib\Net\SSH2::_get_binary_packet() * @var Integer * @access private */ var $log_size; /** * Timeout * * @see \phpseclib\Net\SSH2::setTimeout() * @access private */ var $timeout; /** * Current Timeout * * @see \phpseclib\Net\SSH2::_get_channel_packet() * @access private */ var $curTimeout; /** * Real-time log file pointer * * @see \phpseclib\Net\SSH2::_append_log() * @var Resource * @access private */ var $realtime_log_file; /** * Real-time log file size * * @see \phpseclib\Net\SSH2::_append_log() * @var Integer * @access private */ var $realtime_log_size; /** * Has the signature been validated? * * @see \phpseclib\Net\SSH2::getServerPublicHostKey() * @var Boolean * @access private */ var $signature_validated = false; /** * Real-time log file wrap boolean * * @see \phpseclib\Net\SSH2::_append_log() * @access private */ var $realtime_log_wrap; /** * Flag to suppress stderr from output * * @see \phpseclib\Net\SSH2::enableQuietMode() * @access private */ var $quiet_mode = false; /** * Time of first network activity * * @var Integer * @access private */ var $last_packet; /** * Exit status returned from ssh if any * * @var Integer * @access private */ var $exit_status; /** * Flag to request a PTY when using exec() * * @var Boolean * @see \phpseclib\Net\SSH2::enablePTY() * @access private */ var $request_pty = false; /** * Flag set while exec() is running when using enablePTY() * * @var Boolean * @access private */ var $in_request_pty_exec = false; /** * Flag set after startSubsystem() is called * * @var Boolean * @access private */ var $in_subsystem; /** * Contents of stdError * * @var String * @access private */ var $stdErrorLog; /** * The Last Interactive Response * * @see \phpseclib\Net\SSH2::_keyboard_interactive_process() * @var String * @access private */ var $last_interactive_response = ''; /** * Keyboard Interactive Request / Responses * * @see \phpseclib\Net\SSH2::_keyboard_interactive_process() * @var Array * @access private */ var $keyboard_requests_responses = array(); /** * Banner Message * * Quoting from the RFC, "in some jurisdictions, sending a warning message before * authentication may be relevant for getting legal protection." * * @see \phpseclib\Net\SSH2::_filter() * @see \phpseclib\Net\SSH2::getBannerMessage() * @var String * @access private */ var $banner_message = ''; /** * Did read() timeout or return normally? * * @see \phpseclib\Net\SSH2::isTimeout() * @var Boolean * @access private */ var $is_timeout = false; /** * Log Boundary * * @see \phpseclib\Net\SSH2::_format_log() * @var String * @access private */ var $log_boundary = ':'; /** * Log Long Width * * @see \phpseclib\Net\SSH2::_format_log() * @var Integer * @access private */ var $log_long_width = 65; /** * Log Short Width * * @see \phpseclib\Net\SSH2::_format_log() * @var Integer * @access private */ var $log_short_width = 16; /** * Hostname * * @see \phpseclib\Net\SSH2::__construct() * @see \phpseclib\Net\SSH2::_connect() * @var String * @access private */ var $host; /** * Port Number * * @see \phpseclib\Net\SSH2::__construct() * @see \phpseclib\Net\SSH2::_connect() * @var Integer * @access private */ var $port; /** * Timeout for initial connection * * Set by the constructor call. Calling setTimeout() is optional. If it's not called functions like * exec() won't timeout unless some PHP setting forces it too. The timeout specified in the constructor, * however, is non-optional. There will be a timeout, whether or not you set it. If you don't it'll be * 10 seconds. It is used by fsockopen() and the initial stream_select in that function. * * @see \phpseclib\Net\SSH2::__construct() * @see \phpseclib\Net\SSH2::_connect() * @var Integer * @access private */ var $connectionTimeout; /** * Number of columns for terminal window size * * @see \phpseclib\Net\SSH2::getWindowColumns() * @see \phpseclib\Net\SSH2::setWindowColumns() * @see \phpseclib\Net\SSH2::setWindowSize() * @var Integer * @access private */ var $windowColumns = 80; /** * Number of columns for terminal window size * * @see \phpseclib\Net\SSH2::getWindowRows() * @see \phpseclib\Net\SSH2::setWindowRows() * @see \phpseclib\Net\SSH2::setWindowSize() * @var Integer * @access private */ var $windowRows = 24; /** * Default Constructor. * * @param String $host * @param optional Integer $port * @param optional Integer $timeout * @see \phpseclib\Net\SSH2::login() * @return \phpseclib\Net\SSH2 * @access public */ function __construct($host, $port = 22, $timeout = 10) { $this->message_numbers = array( 1 => 'NET_SSH2_MSG_DISCONNECT', 2 => 'NET_SSH2_MSG_IGNORE', 3 => 'NET_SSH2_MSG_UNIMPLEMENTED', 4 => 'NET_SSH2_MSG_DEBUG', 5 => 'NET_SSH2_MSG_SERVICE_REQUEST', 6 => 'NET_SSH2_MSG_SERVICE_ACCEPT', 20 => 'NET_SSH2_MSG_KEXINIT', 21 => 'NET_SSH2_MSG_NEWKEYS', 30 => 'NET_SSH2_MSG_KEXDH_INIT', 31 => 'NET_SSH2_MSG_KEXDH_REPLY', 50 => 'NET_SSH2_MSG_USERAUTH_REQUEST', 51 => 'NET_SSH2_MSG_USERAUTH_FAILURE', 52 => 'NET_SSH2_MSG_USERAUTH_SUCCESS', 53 => 'NET_SSH2_MSG_USERAUTH_BANNER', 80 => 'NET_SSH2_MSG_GLOBAL_REQUEST', 81 => 'NET_SSH2_MSG_REQUEST_SUCCESS', 82 => 'NET_SSH2_MSG_REQUEST_FAILURE', 90 => 'NET_SSH2_MSG_CHANNEL_OPEN', 91 => 'NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION', 92 => 'NET_SSH2_MSG_CHANNEL_OPEN_FAILURE', 93 => 'NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST', 94 => 'NET_SSH2_MSG_CHANNEL_DATA', 95 => 'NET_SSH2_MSG_CHANNEL_EXTENDED_DATA', 96 => 'NET_SSH2_MSG_CHANNEL_EOF', 97 => 'NET_SSH2_MSG_CHANNEL_CLOSE', 98 => 'NET_SSH2_MSG_CHANNEL_REQUEST', 99 => 'NET_SSH2_MSG_CHANNEL_SUCCESS', 100 => 'NET_SSH2_MSG_CHANNEL_FAILURE' ); $this->disconnect_reasons = array( 1 => 'NET_SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT', 2 => 'NET_SSH2_DISCONNECT_PROTOCOL_ERROR', 3 => 'NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED', 4 => 'NET_SSH2_DISCONNECT_RESERVED', 5 => 'NET_SSH2_DISCONNECT_MAC_ERROR', 6 => 'NET_SSH2_DISCONNECT_COMPRESSION_ERROR', 7 => 'NET_SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE', 8 => 'NET_SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED', 9 => 'NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE', 10 => 'NET_SSH2_DISCONNECT_CONNECTION_LOST', 11 => 'NET_SSH2_DISCONNECT_BY_APPLICATION', 12 => 'NET_SSH2_DISCONNECT_TOO_MANY_CONNECTIONS', 13 => 'NET_SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER', 14 => 'NET_SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE', 15 => 'NET_SSH2_DISCONNECT_ILLEGAL_USER_NAME' ); $this->channel_open_failure_reasons = array( 1 => 'NET_SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED' ); $this->terminal_modes = array( 0 => 'NET_SSH2_TTY_OP_END' ); $this->channel_extended_data_type_codes = array( 1 => 'NET_SSH2_EXTENDED_DATA_STDERR' ); $this->_define_array( $this->message_numbers, $this->disconnect_reasons, $this->channel_open_failure_reasons, $this->terminal_modes, $this->channel_extended_data_type_codes, array(60 => 'NET_SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ'), array(60 => 'NET_SSH2_MSG_USERAUTH_PK_OK'), array(60 => 'NET_SSH2_MSG_USERAUTH_INFO_REQUEST', 61 => 'NET_SSH2_MSG_USERAUTH_INFO_RESPONSE') ); $this->host = $host; $this->port = $port; $this->connectionTimeout = $timeout; } /** * Connect to an SSHv2 server * * @return Boolean * @access private */ function _connect() { if ($this->bitmap & self::MASK_CONSTRUCTOR) { return false; } $this->bitmap |= self::MASK_CONSTRUCTOR; $timeout = $this->connectionTimeout; $host = $this->host . ':' . $this->port; $this->last_packet = microtime(true); $start = microtime(true); $this->fsock = @fsockopen($this->host, $this->port, $errno, $errstr, $timeout); if (!$this->fsock) { user_error(rtrim("Cannot connect to $host. Error $errno. $errstr")); return false; } $elapsed = microtime(true) - $start; $timeout-= $elapsed; if ($timeout <= 0) { user_error("Cannot connect to $host. Timeout error"); return false; } $read = array($this->fsock); $write = $except = null; $sec = floor($timeout); $usec = 1000000 * ($timeout - $sec); // on windows this returns a "Warning: Invalid CRT parameters detected" error // the !count() is done as a workaround for if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) { user_error("Cannot connect to $host. Banner timeout"); return false; } /* According to the SSH2 specs, "The server MAY send other lines of data before sending the version string. Each line SHOULD be terminated by a Carriage Return and Line Feed. Such lines MUST NOT begin with "SSH-", and SHOULD be encoded in ISO-10646 UTF-8 [RFC3629] (language is not specified). Clients MUST be able to process such lines." */ $temp = ''; $extra = ''; while (!feof($this->fsock) && !preg_match('#^SSH-(\d\.\d+)#', $temp, $matches)) { if (substr($temp, -2) == "\r\n") { $extra.= $temp; $temp = ''; } $temp.= fgets($this->fsock, 255); } if (feof($this->fsock)) { user_error('Connection closed by server'); return false; } $this->identifier = $this->_generate_identifier(); if (defined('NET_SSH2_LOGGING')) { $this->_append_log('<-', $extra . $temp); $this->_append_log('->', $this->identifier . "\r\n"); } $this->server_identifier = trim($temp, "\r\n"); if (strlen($extra)) { $this->errors[] = utf8_decode($extra); } if ($matches[1] != '1.99' && $matches[1] != '2.0') { user_error("Cannot connect to SSH $matches[1] servers"); return false; } fputs($this->fsock, $this->identifier . "\r\n"); $response = $this->_get_binary_packet(); if ($response === false) { user_error('Connection closed by server'); return false; } if (ord($response[0]) != NET_SSH2_MSG_KEXINIT) { user_error('Expected SSH_MSG_KEXINIT'); return false; } if (!$this->_key_exchange($response)) { return false; } $this->bitmap|= self::MASK_CONNECTED; return true; } /** * Generates the SSH identifier * * You should overwrite this method in your own class if you want to use another identifier * * @access protected * @return String */ function _generate_identifier() { $identifier = 'SSH-2.0-phpseclib_0.3'; $ext = array(); if (extension_loaded('mcrypt')) { $ext[] = 'mcrypt'; } if (extension_loaded('gmp')) { $ext[] = 'gmp'; } elseif (extension_loaded('bcmath')) { $ext[] = 'bcmath'; } if (!empty($ext)) { $identifier .= ' (' . implode(', ', $ext) . ')'; } return $identifier; } /** * Key Exchange * * @param String $kexinit_payload_server * @access private */ function _key_exchange($kexinit_payload_server) { static $kex_algorithms = array( 'diffie-hellman-group1-sha1', // REQUIRED 'diffie-hellman-group14-sha1' // REQUIRED ); static $server_host_key_algorithms = array( 'ssh-rsa', // RECOMMENDED sign Raw RSA Key 'ssh-dss' // REQUIRED sign Raw DSS Key ); static $encryption_algorithms = false; if ($encryption_algorithms === false) { $encryption_algorithms = array( // from : 'arcfour256', 'arcfour128', //'arcfour', // OPTIONAL the ARCFOUR stream cipher with a 128-bit key // CTR modes from : 'aes128-ctr', // RECOMMENDED AES (Rijndael) in SDCTR mode, with 128-bit key 'aes192-ctr', // RECOMMENDED AES with 192-bit key 'aes256-ctr', // RECOMMENDED AES with 256-bit key 'twofish128-ctr', // OPTIONAL Twofish in SDCTR mode, with 128-bit key 'twofish192-ctr', // OPTIONAL Twofish with 192-bit key 'twofish256-ctr', // OPTIONAL Twofish with 256-bit key 'aes128-cbc', // RECOMMENDED AES with a 128-bit key 'aes192-cbc', // OPTIONAL AES with a 192-bit key 'aes256-cbc', // OPTIONAL AES in CBC mode, with a 256-bit key 'twofish128-cbc', // OPTIONAL Twofish with a 128-bit key 'twofish192-cbc', // OPTIONAL Twofish with a 192-bit key 'twofish256-cbc', 'twofish-cbc', // OPTIONAL alias for "twofish256-cbc" // (this is being retained for historical reasons) 'blowfish-ctr', // OPTIONAL Blowfish in SDCTR mode 'blowfish-cbc', // OPTIONAL Blowfish in CBC mode '3des-ctr', // RECOMMENDED Three-key 3DES in SDCTR mode '3des-cbc', // REQUIRED three-key 3DES in CBC mode //'none' // OPTIONAL no encryption; NOT RECOMMENDED ); if (class_exists('\phpseclib\Crypt\RC4') === false) { $encryption_algorithms = array_diff( $encryption_algorithms, array('arcfour256', 'arcfour128', 'arcfour') ); } if (class_exists('\phpseclib\Crypt\Rijndael') === false) { $encryption_algorithms = array_diff( $encryption_algorithms, array('aes128-ctr', 'aes192-ctr', 'aes256-ctr', 'aes128-cbc', 'aes192-cbc', 'aes256-cbc') ); } if (class_exists('\phpseclib\Crypt\Twofish') === false) { $encryption_algorithms = array_diff( $encryption_algorithms, array('twofish128-ctr', 'twofish192-ctr', 'twofish256-ctr', 'twofish128-cbc', 'twofish192-cbc', 'twofish256-cbc', 'twofish-cbc') ); } if (class_exists('\phpseclib\Crypt\Blowfish') === false) { $encryption_algorithms = array_diff( $encryption_algorithms, array('blowfish-ctr', 'blowfish-cbc') ); } if (class_exists('\phpseclib\Crypt\TripleDES') === false) { $encryption_algorithms = array_diff( $encryption_algorithms, array('3des-ctr', '3des-cbc') ); } $encryption_algorithms = array_values($encryption_algorithms); } $mac_algorithms = array( // from : 'hmac-sha2-256',// RECOMMENDED HMAC-SHA256 (digest length = key length = 32) 'hmac-sha1-96', // RECOMMENDED first 96 bits of HMAC-SHA1 (digest length = 12, key length = 20) 'hmac-sha1', // REQUIRED HMAC-SHA1 (digest length = key length = 20) 'hmac-md5-96', // OPTIONAL first 96 bits of HMAC-MD5 (digest length = 12, key length = 16) 'hmac-md5', // OPTIONAL HMAC-MD5 (digest length = key length = 16) //'none' // OPTIONAL no MAC; NOT RECOMMENDED ); static $compression_algorithms = array( 'none' // REQUIRED no compression //'zlib' // OPTIONAL ZLIB (LZ77) compression ); // some SSH servers have buggy implementations of some of the above algorithms switch ($this->server_identifier) { case 'SSH-2.0-SSHD': $mac_algorithms = array_values(array_diff( $mac_algorithms, array('hmac-sha1-96', 'hmac-md5-96') )); } static $str_kex_algorithms, $str_server_host_key_algorithms, $encryption_algorithms_server_to_client, $mac_algorithms_server_to_client, $compression_algorithms_server_to_client, $encryption_algorithms_client_to_server, $mac_algorithms_client_to_server, $compression_algorithms_client_to_server; if (empty($str_kex_algorithms)) { $str_kex_algorithms = implode(',', $kex_algorithms); $str_server_host_key_algorithms = implode(',', $server_host_key_algorithms); $encryption_algorithms_server_to_client = $encryption_algorithms_client_to_server = implode(',', $encryption_algorithms); $mac_algorithms_server_to_client = $mac_algorithms_client_to_server = implode(',', $mac_algorithms); $compression_algorithms_server_to_client = $compression_algorithms_client_to_server = implode(',', $compression_algorithms); } $client_cookie = Random::string(16); $response = $kexinit_payload_server; $this->_string_shift($response, 1); // skip past the message number (it should be SSH_MSG_KEXINIT) $server_cookie = $this->_string_shift($response, 16); $temp = unpack('Nlength', $this->_string_shift($response, 4)); $this->kex_algorithms = explode(',', $this->_string_shift($response, $temp['length'])); $temp = unpack('Nlength', $this->_string_shift($response, 4)); $this->server_host_key_algorithms = explode(',', $this->_string_shift($response, $temp['length'])); $temp = unpack('Nlength', $this->_string_shift($response, 4)); $this->encryption_algorithms_client_to_server = explode(',', $this->_string_shift($response, $temp['length'])); $temp = unpack('Nlength', $this->_string_shift($response, 4)); $this->encryption_algorithms_server_to_client = explode(',', $this->_string_shift($response, $temp['length'])); $temp = unpack('Nlength', $this->_string_shift($response, 4)); $this->mac_algorithms_client_to_server = explode(',', $this->_string_shift($response, $temp['length'])); $temp = unpack('Nlength', $this->_string_shift($response, 4)); $this->mac_algorithms_server_to_client = explode(',', $this->_string_shift($response, $temp['length'])); $temp = unpack('Nlength', $this->_string_shift($response, 4)); $this->compression_algorithms_client_to_server = explode(',', $this->_string_shift($response, $temp['length'])); $temp = unpack('Nlength', $this->_string_shift($response, 4)); $this->compression_algorithms_server_to_client = explode(',', $this->_string_shift($response, $temp['length'])); $temp = unpack('Nlength', $this->_string_shift($response, 4)); $this->languages_client_to_server = explode(',', $this->_string_shift($response, $temp['length'])); $temp = unpack('Nlength', $this->_string_shift($response, 4)); $this->languages_server_to_client = explode(',', $this->_string_shift($response, $temp['length'])); extract(unpack('Cfirst_kex_packet_follows', $this->_string_shift($response, 1))); $first_kex_packet_follows = $first_kex_packet_follows != 0; // the sending of SSH2_MSG_KEXINIT could go in one of two places. this is the second place. $kexinit_payload_client = pack('Ca*Na*Na*Na*Na*Na*Na*Na*Na*Na*Na*CN', NET_SSH2_MSG_KEXINIT, $client_cookie, strlen($str_kex_algorithms), $str_kex_algorithms, strlen($str_server_host_key_algorithms), $str_server_host_key_algorithms, strlen($encryption_algorithms_client_to_server), $encryption_algorithms_client_to_server, strlen($encryption_algorithms_server_to_client), $encryption_algorithms_server_to_client, strlen($mac_algorithms_client_to_server), $mac_algorithms_client_to_server, strlen($mac_algorithms_server_to_client), $mac_algorithms_server_to_client, strlen($compression_algorithms_client_to_server), $compression_algorithms_client_to_server, strlen($compression_algorithms_server_to_client), $compression_algorithms_server_to_client, 0, '', 0, '', 0, 0 ); if (!$this->_send_binary_packet($kexinit_payload_client)) { return false; } // here ends the second place. // we need to decide upon the symmetric encryption algorithms before we do the diffie-hellman key exchange for ($i = 0; $i < count($encryption_algorithms) && !in_array($encryption_algorithms[$i], $this->encryption_algorithms_server_to_client); $i++); if ($i == count($encryption_algorithms)) { user_error('No compatible server to client encryption algorithms found'); return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); } // we don't initialize any crypto-objects, yet - we do that, later. for now, we need the lengths to make the // diffie-hellman key exchange as fast as possible $decrypt = $encryption_algorithms[$i]; switch ($decrypt) { case '3des-cbc': case '3des-ctr': $decryptKeyLength = 24; // eg. 192 / 8 break; case 'aes256-cbc': case 'aes256-ctr': case 'twofish-cbc': case 'twofish256-cbc': case 'twofish256-ctr': $decryptKeyLength = 32; // eg. 256 / 8 break; case 'aes192-cbc': case 'aes192-ctr': case 'twofish192-cbc': case 'twofish192-ctr': $decryptKeyLength = 24; // eg. 192 / 8 break; case 'aes128-cbc': case 'aes128-ctr': case 'twofish128-cbc': case 'twofish128-ctr': case 'blowfish-cbc': case 'blowfish-ctr': $decryptKeyLength = 16; // eg. 128 / 8 break; case 'arcfour': case 'arcfour128': $decryptKeyLength = 16; // eg. 128 / 8 break; case 'arcfour256': $decryptKeyLength = 32; // eg. 128 / 8 break; case 'none'; $decryptKeyLength = 0; } for ($i = 0; $i < count($encryption_algorithms) && !in_array($encryption_algorithms[$i], $this->encryption_algorithms_client_to_server); $i++); if ($i == count($encryption_algorithms)) { user_error('No compatible client to server encryption algorithms found'); return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); } $encrypt = $encryption_algorithms[$i]; switch ($encrypt) { case '3des-cbc': case '3des-ctr': $encryptKeyLength = 24; break; case 'aes256-cbc': case 'aes256-ctr': case 'twofish-cbc': case 'twofish256-cbc': case 'twofish256-ctr': $encryptKeyLength = 32; break; case 'aes192-cbc': case 'aes192-ctr': case 'twofish192-cbc': case 'twofish192-ctr': $encryptKeyLength = 24; break; case 'aes128-cbc': case 'aes128-ctr': case 'twofish128-cbc': case 'twofish128-ctr': case 'blowfish-cbc': case 'blowfish-ctr': $encryptKeyLength = 16; break; case 'arcfour': case 'arcfour128': $encryptKeyLength = 16; break; case 'arcfour256': $encryptKeyLength = 32; break; case 'none'; $encryptKeyLength = 0; } $keyLength = $decryptKeyLength > $encryptKeyLength ? $decryptKeyLength : $encryptKeyLength; // through diffie-hellman key exchange a symmetric key is obtained for ($i = 0; $i < count($kex_algorithms) && !in_array($kex_algorithms[$i], $this->kex_algorithms); $i++); if ($i == count($kex_algorithms)) { user_error('No compatible key exchange algorithms found'); return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); } switch ($kex_algorithms[$i]) { // see http://tools.ietf.org/html/rfc2409#section-6.2 and // http://tools.ietf.org/html/rfc2412, appendex E case 'diffie-hellman-group1-sha1': $prime = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' . '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' . '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' . 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; break; // see http://tools.ietf.org/html/rfc3526#section-3 case 'diffie-hellman-group14-sha1': $prime = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' . '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' . '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' . 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF05' . '98DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB' . '9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' . 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718' . '3995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF'; break; } // For both diffie-hellman-group1-sha1 and diffie-hellman-group14-sha1 // the generator field element is 2 (decimal) and the hash function is sha1. $g = new BigInteger(2); $prime = new BigInteger($prime, 16); $kexHash = new Hash('sha1'); //$q = $p->bitwise_rightShift(1); /* To increase the speed of the key exchange, both client and server may reduce the size of their private exponents. It should be at least twice as long as the key material that is generated from the shared secret. For more details, see the paper by van Oorschot and Wiener [VAN-OORSCHOT]. -- http://tools.ietf.org/html/rfc4419#section-6.2 */ $one = new BigInteger(1); $keyLength = min($keyLength, $kexHash->getLength()); $max = $one->bitwise_leftShift(16 * $keyLength); // 2 * 8 * $keyLength $max = $max->subtract($one); $x = $one->random($one, $max); $e = $g->modPow($x, $prime); $eBytes = $e->toBytes(true); $data = pack('CNa*', NET_SSH2_MSG_KEXDH_INIT, strlen($eBytes), $eBytes); if (!$this->_send_binary_packet($data)) { user_error('Connection closed by server'); return false; } $response = $this->_get_binary_packet(); if ($response === false) { user_error('Connection closed by server'); return false; } extract(unpack('Ctype', $this->_string_shift($response, 1))); if ($type != NET_SSH2_MSG_KEXDH_REPLY) { user_error('Expected SSH_MSG_KEXDH_REPLY'); return false; } $temp = unpack('Nlength', $this->_string_shift($response, 4)); $this->server_public_host_key = $server_public_host_key = $this->_string_shift($response, $temp['length']); $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $public_key_format = $this->_string_shift($server_public_host_key, $temp['length']); $temp = unpack('Nlength', $this->_string_shift($response, 4)); $fBytes = $this->_string_shift($response, $temp['length']); $f = new BigInteger($fBytes, -256); $temp = unpack('Nlength', $this->_string_shift($response, 4)); $this->signature = $this->_string_shift($response, $temp['length']); $temp = unpack('Nlength', $this->_string_shift($this->signature, 4)); $this->signature_format = $this->_string_shift($this->signature, $temp['length']); $key = $f->modPow($x, $prime); $keyBytes = $key->toBytes(true); $this->exchange_hash = pack('Na*Na*Na*Na*Na*Na*Na*Na*', strlen($this->identifier), $this->identifier, strlen($this->server_identifier), $this->server_identifier, strlen($kexinit_payload_client), $kexinit_payload_client, strlen($kexinit_payload_server), $kexinit_payload_server, strlen($this->server_public_host_key), $this->server_public_host_key, strlen($eBytes), $eBytes, strlen($fBytes), $fBytes, strlen($keyBytes), $keyBytes ); $this->exchange_hash = $kexHash->hash($this->exchange_hash); if ($this->session_id === false) { $this->session_id = $this->exchange_hash; } for ($i = 0; $i < count($server_host_key_algorithms) && !in_array($server_host_key_algorithms[$i], $this->server_host_key_algorithms); $i++); if ($i == count($server_host_key_algorithms)) { user_error('No compatible server host key algorithms found'); return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); } if ($public_key_format != $server_host_key_algorithms[$i] || $this->signature_format != $server_host_key_algorithms[$i]) { user_error('Server Host Key Algorithm Mismatch'); return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); } $packet = pack('C', NET_SSH2_MSG_NEWKEYS ); if (!$this->_send_binary_packet($packet)) { return false; } $response = $this->_get_binary_packet(); if ($response === false) { user_error('Connection closed by server'); return false; } extract(unpack('Ctype', $this->_string_shift($response, 1))); if ($type != NET_SSH2_MSG_NEWKEYS) { user_error('Expected SSH_MSG_NEWKEYS'); return false; } switch ($encrypt) { case '3des-cbc': $this->encrypt = new TripleDES(); // $this->encrypt_block_size = 64 / 8 == the default break; case '3des-ctr': $this->encrypt = new TripleDES(Base::MODE_CTR); // $this->encrypt_block_size = 64 / 8 == the default break; case 'aes256-cbc': case 'aes192-cbc': case 'aes128-cbc': $this->encrypt = new Rijndael(); $this->encrypt_block_size = 16; // eg. 128 / 8 break; case 'aes256-ctr': case 'aes192-ctr': case 'aes128-ctr': $this->encrypt = new Rijndael(Base::MODE_CTR); $this->encrypt_block_size = 16; // eg. 128 / 8 break; case 'blowfish-cbc': $this->encrypt = new Blowfish(); $this->encrypt_block_size = 8; break; case 'blowfish-ctr': $this->encrypt = new Blowfish(Base::MODE_CTR); $this->encrypt_block_size = 8; break; case 'twofish128-cbc': case 'twofish192-cbc': case 'twofish256-cbc': case 'twofish-cbc': $this->encrypt = new Twofish(); $this->encrypt_block_size = 16; break; case 'twofish128-ctr': case 'twofish192-ctr': case 'twofish256-ctr': $this->encrypt = new Twofish(Base::MODE_CTR); $this->encrypt_block_size = 16; break; case 'arcfour': case 'arcfour128': case 'arcfour256': $this->encrypt = new RC4(); break; case 'none'; //$this->encrypt = new Null(); } switch ($decrypt) { case '3des-cbc': $this->decrypt = new TripleDES(); break; case '3des-ctr': $this->decrypt = new TripleDES(Base::MODE_CTR); break; case 'aes256-cbc': case 'aes192-cbc': case 'aes128-cbc': $this->decrypt = new Rijndael(); $this->decrypt_block_size = 16; break; case 'aes256-ctr': case 'aes192-ctr': case 'aes128-ctr': $this->decrypt = new Rijndael(Base::MODE_CTR); $this->decrypt_block_size = 16; break; case 'blowfish-cbc': $this->decrypt = new Blowfish(); $this->decrypt_block_size = 8; break; case 'blowfish-ctr': $this->decrypt = new Blowfish(Base::MODE_CTR); $this->decrypt_block_size = 8; break; case 'twofish128-cbc': case 'twofish192-cbc': case 'twofish256-cbc': case 'twofish-cbc': $this->decrypt = new Twofish(); $this->decrypt_block_size = 16; break; case 'twofish128-ctr': case 'twofish192-ctr': case 'twofish256-ctr': $this->decrypt = new Twofish(Base::MODE_CTR); $this->decrypt_block_size = 16; break; case 'arcfour': case 'arcfour128': case 'arcfour256': $this->decrypt = new RC4(); break; case 'none'; //$this->decrypt = new Null(); } $keyBytes = pack('Na*', strlen($keyBytes), $keyBytes); if ($this->encrypt) { $this->encrypt->enableContinuousBuffer(); $this->encrypt->disablePadding(); $iv = $kexHash->hash($keyBytes . $this->exchange_hash . 'A' . $this->session_id); while ($this->encrypt_block_size > strlen($iv)) { $iv.= $kexHash->hash($keyBytes . $this->exchange_hash . $iv); } $this->encrypt->setIV(substr($iv, 0, $this->encrypt_block_size)); $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'C' . $this->session_id); while ($encryptKeyLength > strlen($key)) { $key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key); } $this->encrypt->setKey(substr($key, 0, $encryptKeyLength)); } if ($this->decrypt) { $this->decrypt->enableContinuousBuffer(); $this->decrypt->disablePadding(); $iv = $kexHash->hash($keyBytes . $this->exchange_hash . 'B' . $this->session_id); while ($this->decrypt_block_size > strlen($iv)) { $iv.= $kexHash->hash($keyBytes . $this->exchange_hash . $iv); } $this->decrypt->setIV(substr($iv, 0, $this->decrypt_block_size)); $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'D' . $this->session_id); while ($decryptKeyLength > strlen($key)) { $key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key); } $this->decrypt->setKey(substr($key, 0, $decryptKeyLength)); } /* The "arcfour128" algorithm is the RC4 cipher, as described in [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream generated by the cipher MUST be discarded, and the first byte of the first encrypted packet MUST be encrypted using the 1537th byte of keystream. -- http://tools.ietf.org/html/rfc4345#section-4 */ if ($encrypt == 'arcfour128' || $encrypt == 'arcfour256') { $this->encrypt->encrypt(str_repeat("\0", 1536)); } if ($decrypt == 'arcfour128' || $decrypt == 'arcfour256') { $this->decrypt->decrypt(str_repeat("\0", 1536)); } for ($i = 0; $i < count($mac_algorithms) && !in_array($mac_algorithms[$i], $this->mac_algorithms_client_to_server); $i++); if ($i == count($mac_algorithms)) { user_error('No compatible client to server message authentication algorithms found'); return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); } $createKeyLength = 0; // ie. $mac_algorithms[$i] == 'none' switch ($mac_algorithms[$i]) { case 'hmac-sha2-256': $this->hmac_create = new Hash('sha256'); $createKeyLength = 32; break; case 'hmac-sha1': $this->hmac_create = new Hash('sha1'); $createKeyLength = 20; break; case 'hmac-sha1-96': $this->hmac_create = new Hash('sha1-96'); $createKeyLength = 20; break; case 'hmac-md5': $this->hmac_create = new Hash('md5'); $createKeyLength = 16; break; case 'hmac-md5-96': $this->hmac_create = new Hash('md5-96'); $createKeyLength = 16; } for ($i = 0; $i < count($mac_algorithms) && !in_array($mac_algorithms[$i], $this->mac_algorithms_server_to_client); $i++); if ($i == count($mac_algorithms)) { user_error('No compatible server to client message authentication algorithms found'); return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); } $checkKeyLength = 0; $this->hmac_size = 0; switch ($mac_algorithms[$i]) { case 'hmac-sha2-256': $this->hmac_check = new Hash('sha256'); $checkKeyLength = 32; $this->hmac_size = 32; break; case 'hmac-sha1': $this->hmac_check = new Hash('sha1'); $checkKeyLength = 20; $this->hmac_size = 20; break; case 'hmac-sha1-96': $this->hmac_check = new Hash('sha1-96'); $checkKeyLength = 20; $this->hmac_size = 12; break; case 'hmac-md5': $this->hmac_check = new Hash('md5'); $checkKeyLength = 16; $this->hmac_size = 16; break; case 'hmac-md5-96': $this->hmac_check = new Hash('md5-96'); $checkKeyLength = 16; $this->hmac_size = 12; } $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'E' . $this->session_id); while ($createKeyLength > strlen($key)) { $key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key); } $this->hmac_create->setKey(substr($key, 0, $createKeyLength)); $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'F' . $this->session_id); while ($checkKeyLength > strlen($key)) { $key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key); } $this->hmac_check->setKey(substr($key, 0, $checkKeyLength)); for ($i = 0; $i < count($compression_algorithms) && !in_array($compression_algorithms[$i], $this->compression_algorithms_server_to_client); $i++); if ($i == count($compression_algorithms)) { user_error('No compatible server to client compression algorithms found'); return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); } $this->decompress = $compression_algorithms[$i] == 'zlib'; for ($i = 0; $i < count($compression_algorithms) && !in_array($compression_algorithms[$i], $this->compression_algorithms_client_to_server); $i++); if ($i == count($compression_algorithms)) { user_error('No compatible client to server compression algorithms found'); return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); } $this->compress = $compression_algorithms[$i] == 'zlib'; return true; } /** * Login * * The $password parameter can be a plaintext password, a \phpseclib\Crypt\RSA object or an array * * @param String $username * @param Mixed $password * @param Mixed $... * @return Boolean * @see _login * @access public */ function login($username) { $args = func_get_args(); return call_user_func_array(array(&$this, '_login'), $args); } /** * Login Helper * * @param String $username * @param Mixed $password * @param Mixed $... * @return Boolean * @see _login_helper * @access private */ function _login($username) { if (!($this->bitmap & self::MASK_CONSTRUCTOR)) { if (!$this->_connect()) { return false; } } $args = array_slice(func_get_args(), 1); if (empty($args)) { return $this->_login_helper($username); } foreach ($args as $arg) { if ($this->_login_helper($username, $arg)) { return true; } } return false; } /** * Login Helper * * @param String $username * @param optional String $password * @return Boolean * @access private * @internal It might be worthwhile, at some point, to protect against {@link http://tools.ietf.org/html/rfc4251#section-9.3.9 traffic analysis} * by sending dummy SSH_MSG_IGNORE messages. */ function _login_helper($username, $password = null) { if (!($this->bitmap & self::MASK_CONNECTED)) { return false; } if (!($this->bitmap & self::MASK_LOGIN_REQ)) { $packet = pack('CNa*', NET_SSH2_MSG_SERVICE_REQUEST, strlen('ssh-userauth'), 'ssh-userauth' ); if (!$this->_send_binary_packet($packet)) { return false; } $response = $this->_get_binary_packet(); if ($response === false) { user_error('Connection closed by server'); return false; } extract(unpack('Ctype', $this->_string_shift($response, 1))); if ($type != NET_SSH2_MSG_SERVICE_ACCEPT) { user_error('Expected SSH_MSG_SERVICE_ACCEPT'); return false; } $this->bitmap |= self::MASK_LOGIN_REQ; } if (strlen($this->last_interactive_response)) { return !is_string($password) && !is_array($password) ? false : $this->_keyboard_interactive_process($password); } if ($password instanceof RSA) { return $this->_privatekey_login($username, $password); } elseif ($password instanceof Agent) { return $this->_ssh_agent_login($username, $password); } if (is_array($password)) { if ($this->_keyboard_interactive_login($username, $password)) { $this->bitmap |= self::MASK_LOGIN; return true; } return false; } if (!isset($password)) { $packet = pack('CNa*Na*Na*', NET_SSH2_MSG_USERAUTH_REQUEST, strlen($username), $username, strlen('ssh-connection'), 'ssh-connection', strlen('none'), 'none' ); if (!$this->_send_binary_packet($packet)) { return false; } $response = $this->_get_binary_packet(); if ($response === false) { user_error('Connection closed by server'); return false; } extract(unpack('Ctype', $this->_string_shift($response, 1))); switch ($type) { case NET_SSH2_MSG_USERAUTH_SUCCESS: $this->bitmap |= self::MASK_LOGIN; return true; //case NET_SSH2_MSG_USERAUTH_FAILURE: default: return false; } } $packet = pack('CNa*Na*Na*CNa*', NET_SSH2_MSG_USERAUTH_REQUEST, strlen($username), $username, strlen('ssh-connection'), 'ssh-connection', strlen('password'), 'password', 0, strlen($password), $password ); // remove the username and password from the logged packet if (!defined('NET_SSH2_LOGGING')) { $logged = null; } else { $logged = pack('CNa*Na*Na*CNa*', NET_SSH2_MSG_USERAUTH_REQUEST, strlen('username'), 'username', strlen('ssh-connection'), 'ssh-connection', strlen('password'), 'password', 0, strlen('password'), 'password' ); } if (!$this->_send_binary_packet($packet, $logged)) { return false; } $response = $this->_get_binary_packet(); if ($response === false) { user_error('Connection closed by server'); return false; } extract(unpack('Ctype', $this->_string_shift($response, 1))); switch ($type) { case NET_SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: // in theory, the password can be changed if (defined('NET_SSH2_LOGGING')) { $this->message_number_log[count($this->message_number_log) - 1] = 'NET_SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ'; } extract(unpack('Nlength', $this->_string_shift($response, 4))); $this->errors[] = 'SSH_MSG_USERAUTH_PASSWD_CHANGEREQ: ' . utf8_decode($this->_string_shift($response, $length)); return $this->_disconnect(NET_SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER); case NET_SSH2_MSG_USERAUTH_FAILURE: // can we use keyboard-interactive authentication? if not then either the login is bad or the server employees // multi-factor authentication extract(unpack('Nlength', $this->_string_shift($response, 4))); $auth_methods = explode(',', $this->_string_shift($response, $length)); extract(unpack('Cpartial_success', $this->_string_shift($response, 1))); $partial_success = $partial_success != 0; if (!$partial_success && in_array('keyboard-interactive', $auth_methods)) { if ($this->_keyboard_interactive_login($username, $password)) { $this->bitmap |= self::MASK_LOGIN; return true; } return false; } return false; case NET_SSH2_MSG_USERAUTH_SUCCESS: $this->bitmap |= self::MASK_LOGIN; return true; } return false; } /** * Login via keyboard-interactive authentication * * See {@link http://tools.ietf.org/html/rfc4256 RFC4256} for details. This is not a full-featured keyboard-interactive authenticator. * * @param String $username * @param String $password * @return Boolean * @access private */ function _keyboard_interactive_login($username, $password) { $packet = pack('CNa*Na*Na*Na*Na*', NET_SSH2_MSG_USERAUTH_REQUEST, strlen($username), $username, strlen('ssh-connection'), 'ssh-connection', strlen('keyboard-interactive'), 'keyboard-interactive', 0, '', 0, '' ); if (!$this->_send_binary_packet($packet)) { return false; } return $this->_keyboard_interactive_process($password); } /** * Handle the keyboard-interactive requests / responses. * * @param String $responses... * @return Boolean * @access private */ function _keyboard_interactive_process() { $responses = func_get_args(); if (strlen($this->last_interactive_response)) { $response = $this->last_interactive_response; } else { $orig = $response = $this->_get_binary_packet(); if ($response === false) { user_error('Connection closed by server'); return false; } } extract(unpack('Ctype', $this->_string_shift($response, 1))); switch ($type) { case NET_SSH2_MSG_USERAUTH_INFO_REQUEST: extract(unpack('Nlength', $this->_string_shift($response, 4))); $this->_string_shift($response, $length); // name; may be empty extract(unpack('Nlength', $this->_string_shift($response, 4))); $this->_string_shift($response, $length); // instruction; may be empty extract(unpack('Nlength', $this->_string_shift($response, 4))); $this->_string_shift($response, $length); // language tag; may be empty extract(unpack('Nnum_prompts', $this->_string_shift($response, 4))); for ($i = 0; $i < count($responses); $i++) { if (is_array($responses[$i])) { foreach ($responses[$i] as $key => $value) { $this->keyboard_requests_responses[$key] = $value; } unset($responses[$i]); } } $responses = array_values($responses); if (isset($this->keyboard_requests_responses)) { for ($i = 0; $i < $num_prompts; $i++) { extract(unpack('Nlength', $this->_string_shift($response, 4))); // prompt - ie. "Password: "; must not be empty $prompt = $this->_string_shift($response, $length); //$echo = $this->_string_shift($response) != chr(0); foreach ($this->keyboard_requests_responses as $key => $value) { if (substr($prompt, 0, strlen($key)) == $key) { $responses[] = $value; break; } } } } // see http://tools.ietf.org/html/rfc4256#section-3.2 if (strlen($this->last_interactive_response)) { $this->last_interactive_response = ''; } else if (defined('NET_SSH2_LOGGING')) { $this->message_number_log[count($this->message_number_log) - 1] = str_replace( 'UNKNOWN', 'NET_SSH2_MSG_USERAUTH_INFO_REQUEST', $this->message_number_log[count($this->message_number_log) - 1] ); } if (!count($responses) && $num_prompts) { $this->last_interactive_response = $orig; return false; } /* After obtaining the requested information from the user, the client MUST respond with an SSH_MSG_USERAUTH_INFO_RESPONSE message. */ // see http://tools.ietf.org/html/rfc4256#section-3.4 $packet = $logged = pack('CN', NET_SSH2_MSG_USERAUTH_INFO_RESPONSE, count($responses)); for ($i = 0; $i < count($responses); $i++) { $packet.= pack('Na*', strlen($responses[$i]), $responses[$i]); $logged.= pack('Na*', strlen('dummy-answer'), 'dummy-answer'); } if (!$this->_send_binary_packet($packet, $logged)) { return false; } if (defined('NET_SSH2_LOGGING') && NET_SSH2_LOGGING == self::LOG_COMPLEX) { $this->message_number_log[count($this->message_number_log) - 1] = str_replace( 'UNKNOWN', 'NET_SSH2_MSG_USERAUTH_INFO_RESPONSE', $this->message_number_log[count($this->message_number_log) - 1] ); } /* After receiving the response, the server MUST send either an SSH_MSG_USERAUTH_SUCCESS, SSH_MSG_USERAUTH_FAILURE, or another SSH_MSG_USERAUTH_INFO_REQUEST message. */ // maybe phpseclib should force close the connection after x request / responses? unless something like that is done // there could be an infinite loop of request / responses. return $this->_keyboard_interactive_process(); case NET_SSH2_MSG_USERAUTH_SUCCESS: return true; case NET_SSH2_MSG_USERAUTH_FAILURE: return false; } return false; } /** * Login with an ssh-agent provided key * * @param String $username * @param \phpseclib\System\SSH\Agent $agent * @return Boolean * @access private */ function _ssh_agent_login($username, $agent) { $keys = $agent->requestIdentities(); foreach ($keys as $key) { if ($this->_privatekey_login($username, $key)) { return true; } } return false; } /** * Login with an RSA private key * * @param String $username * @param \phpseclib\Crypt\RSA $password * @return Boolean * @access private * @internal It might be worthwhile, at some point, to protect against {@link http://tools.ietf.org/html/rfc4251#section-9.3.9 traffic analysis} * by sending dummy SSH_MSG_IGNORE messages. */ function _privatekey_login($username, $privatekey) { // see http://tools.ietf.org/html/rfc4253#page-15 $publickey = $privatekey->getPublicKey(RSA::PUBLIC_FORMAT_RAW); if ($publickey === false) { return false; } $publickey = array( 'e' => $publickey['e']->toBytes(true), 'n' => $publickey['n']->toBytes(true) ); $publickey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publickey['e']), $publickey['e'], strlen($publickey['n']), $publickey['n'] ); $part1 = pack('CNa*Na*Na*', NET_SSH2_MSG_USERAUTH_REQUEST, strlen($username), $username, strlen('ssh-connection'), 'ssh-connection', strlen('publickey'), 'publickey' ); $part2 = pack('Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publickey), $publickey); $packet = $part1 . chr(0) . $part2; if (!$this->_send_binary_packet($packet)) { return false; } $response = $this->_get_binary_packet(); if ($response === false) { user_error('Connection closed by server'); return false; } extract(unpack('Ctype', $this->_string_shift($response, 1))); switch ($type) { case NET_SSH2_MSG_USERAUTH_FAILURE: extract(unpack('Nlength', $this->_string_shift($response, 4))); $this->errors[] = 'SSH_MSG_USERAUTH_FAILURE: ' . $this->_string_shift($response, $length); return false; case NET_SSH2_MSG_USERAUTH_PK_OK: // we'll just take it on faith that the public key blob and the public key algorithm name are as // they should be if (defined('NET_SSH2_LOGGING') && NET_SSH2_LOGGING == self::LOG_COMPLEX) { $this->message_number_log[count($this->message_number_log) - 1] = str_replace( 'UNKNOWN', 'NET_SSH2_MSG_USERAUTH_PK_OK', $this->message_number_log[count($this->message_number_log) - 1] ); } } $packet = $part1 . chr(1) . $part2; $privatekey->setSignatureMode(RSA::SIGNATURE_PKCS1); $signature = $privatekey->sign(pack('Na*a*', strlen($this->session_id), $this->session_id, $packet)); $signature = pack('Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($signature), $signature); $packet.= pack('Na*', strlen($signature), $signature); if (!$this->_send_binary_packet($packet)) { return false; } $response = $this->_get_binary_packet(); if ($response === false) { user_error('Connection closed by server'); return false; } extract(unpack('Ctype', $this->_string_shift($response, 1))); switch ($type) { case NET_SSH2_MSG_USERAUTH_FAILURE: // either the login is bad or the server employs multi-factor authentication return false; case NET_SSH2_MSG_USERAUTH_SUCCESS: $this->bitmap |= self::MASK_LOGIN; return true; } return false; } /** * Set Timeout * * $ssh->exec('ping 127.0.0.1'); on a Linux host will never return and will run indefinitely. setTimeout() makes it so it'll timeout. * Setting $timeout to false or 0 will mean there is no timeout. * * @param Mixed $timeout * @access public */ function setTimeout($timeout) { $this->timeout = $this->curTimeout = $timeout; } /** * Get the output from stdError * * @access public */ function getStdError() { return $this->stdErrorLog; } /** * Execute Command * * If $callback is set to false then \phpseclib\Net\SSH2::_get_channel_packet(self::CHANNEL_EXEC) will need to be called manually. * In all likelihood, this is not a feature you want to be taking advantage of. * * @param String $command * @param optional Callback $callback * @return String * @access public */ function exec($command, $callback = null) { $this->curTimeout = $this->timeout; $this->is_timeout = false; $this->stdErrorLog = ''; if (!($this->bitmap & self::MASK_LOGIN)) { return false; } // RFC4254 defines the (client) window size as "bytes the other party can send before it must wait for the window to // be adjusted". 0x7FFFFFFF is, at 2GB, the max size. technically, it should probably be decremented, but, // honestly, if you're transfering more than 2GB, you probably shouldn't be using phpseclib, anyway. // see http://tools.ietf.org/html/rfc4254#section-5.2 for more info $this->window_size_server_to_client[self::CHANNEL_EXEC] = $this->window_size; // 0x8000 is the maximum max packet size, per http://tools.ietf.org/html/rfc4253#section-6.1, although since PuTTy // uses 0x4000, that's what will be used here, as well. $packet_size = 0x4000; $packet = pack('CNa*N3', NET_SSH2_MSG_CHANNEL_OPEN, strlen('session'), 'session', self::CHANNEL_EXEC, $this->window_size_server_to_client[self::CHANNEL_EXEC], $packet_size); if (!$this->_send_binary_packet($packet)) { return false; } $this->channel_status[self::CHANNEL_EXEC] = NET_SSH2_MSG_CHANNEL_OPEN; $response = $this->_get_channel_packet(self::CHANNEL_EXEC); if ($response === false) { return false; } if ($this->request_pty === true) { $terminal_modes = pack('C', NET_SSH2_TTY_OP_END); $packet = pack('CNNa*CNa*N5a*', NET_SSH2_MSG_CHANNEL_REQUEST, $this->server_channels[self::CHANNEL_EXEC], strlen('pty-req'), 'pty-req', 1, strlen('vt100'), 'vt100', $this->windowColumns, $this->windowRows, 0, 0, strlen($terminal_modes), $terminal_modes); if (!$this->_send_binary_packet($packet)) { return false; } $response = $this->_get_binary_packet(); if ($response === false) { user_error('Connection closed by server'); return false; } list(, $type) = unpack('C', $this->_string_shift($response, 1)); switch ($type) { case NET_SSH2_MSG_CHANNEL_SUCCESS: break; case NET_SSH2_MSG_CHANNEL_FAILURE: default: user_error('Unable to request pseudo-terminal'); return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION); } $this->in_request_pty_exec = true; } // sending a pty-req SSH_MSG_CHANNEL_REQUEST message is unnecessary and, in fact, in most cases, slows things // down. the one place where it might be desirable is if you're doing something like \phpseclib\Net\SSH2::exec('ping localhost &'). // with a pty-req SSH_MSG_CHANNEL_REQUEST, exec() will return immediately and the ping process will then // then immediately terminate. without such a request exec() will loop indefinitely. the ping process won't end but // neither will your script. // although, in theory, the size of SSH_MSG_CHANNEL_REQUEST could exceed the maximum packet size established by // SSH_MSG_CHANNEL_OPEN_CONFIRMATION, RFC4254#section-5.1 states that the "maximum packet size" refers to the // "maximum size of an individual data packet". ie. SSH_MSG_CHANNEL_DATA. RFC4254#section-5.2 corroborates. $packet = pack('CNNa*CNa*', NET_SSH2_MSG_CHANNEL_REQUEST, $this->server_channels[self::CHANNEL_EXEC], strlen('exec'), 'exec', 1, strlen($command), $command); if (!$this->_send_binary_packet($packet)) { return false; } $this->channel_status[self::CHANNEL_EXEC] = NET_SSH2_MSG_CHANNEL_REQUEST; $response = $this->_get_channel_packet(self::CHANNEL_EXEC); if ($response === false) { return false; } $this->channel_status[self::CHANNEL_EXEC] = NET_SSH2_MSG_CHANNEL_DATA; if ($callback === false || $this->in_request_pty_exec) { return true; } $output = ''; while (true) { $temp = $this->_get_channel_packet(self::CHANNEL_EXEC); switch (true) { case $temp === true: return is_callable($callback) ? true : $output; case $temp === false: return false; default: if (is_callable($callback)) { if (call_user_func($callback, $temp) === true) { $this->_close_channel(self::CHANNEL_EXEC); return true; } } else { $output.= $temp; } } } } /** * Creates an interactive shell * * @see \phpseclib\Net\SSH2::read() * @see \phpseclib\Net\SSH2::write() * @return Boolean * @access private */ function _initShell() { if ($this->in_request_pty_exec === true) { return true; } $this->window_size_server_to_client[self::CHANNEL_SHELL] = $this->window_size; $packet_size = 0x4000; $packet = pack('CNa*N3', NET_SSH2_MSG_CHANNEL_OPEN, strlen('session'), 'session', self::CHANNEL_SHELL, $this->window_size_server_to_client[self::CHANNEL_SHELL], $packet_size); if (!$this->_send_binary_packet($packet)) { return false; } $this->channel_status[self::CHANNEL_SHELL] = NET_SSH2_MSG_CHANNEL_OPEN; $response = $this->_get_channel_packet(self::CHANNEL_SHELL); if ($response === false) { return false; } $terminal_modes = pack('C', NET_SSH2_TTY_OP_END); $packet = pack('CNNa*CNa*N5a*', NET_SSH2_MSG_CHANNEL_REQUEST, $this->server_channels[self::CHANNEL_SHELL], strlen('pty-req'), 'pty-req', 1, strlen('vt100'), 'vt100', $this->windowColumns, $this->windowRows, 0, 0, strlen($terminal_modes), $terminal_modes); if (!$this->_send_binary_packet($packet)) { return false; } $response = $this->_get_binary_packet(); if ($response === false) { user_error('Connection closed by server'); return false; } list(, $type) = unpack('C', $this->_string_shift($response, 1)); switch ($type) { case NET_SSH2_MSG_CHANNEL_SUCCESS: // if a pty can't be opened maybe commands can still be executed case NET_SSH2_MSG_CHANNEL_FAILURE: break; default: user_error('Unable to request pseudo-terminal'); return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION); } $packet = pack('CNNa*C', NET_SSH2_MSG_CHANNEL_REQUEST, $this->server_channels[self::CHANNEL_SHELL], strlen('shell'), 'shell', 1); if (!$this->_send_binary_packet($packet)) { return false; } $this->channel_status[self::CHANNEL_SHELL] = NET_SSH2_MSG_CHANNEL_REQUEST; $response = $this->_get_channel_packet(self::CHANNEL_SHELL); if ($response === false) { return false; } $this->channel_status[self::CHANNEL_SHELL] = NET_SSH2_MSG_CHANNEL_DATA; $this->bitmap |= self::MASK_SHELL; return true; } /** * Return the channel to be used with read() / write() * * @see \phpseclib\Net\SSH2::read() * @see \phpseclib\Net\SSH2::write() * @return Integer * @access public */ function _get_interactive_channel() { switch (true) { case $this->in_subsystem: return self::CHANNEL_SUBSYSTEM; case $this->in_request_pty_exec: return self::CHANNEL_EXEC; default: return self::CHANNEL_SHELL; } } /** * Returns the output of an interactive shell * * Returns when there's a match for $expect, which can take the form of a string literal or, * if $mode == self::READ_REGEX, a regular expression. * * @see \phpseclib\Net\SSH2::write() * @param String $expect * @param Integer $mode * @return String * @access public */ function read($expect = '', $mode = self::READ_SIMPLE) { $this->curTimeout = $this->timeout; $this->is_timeout = false; if (!($this->bitmap & self::MASK_LOGIN)) { user_error('Operation disallowed prior to login()'); return false; } if (!($this->bitmap & self::MASK_SHELL) && !$this->_initShell()) { user_error('Unable to initiate an interactive shell session'); return false; } $channel = $this->_get_interactive_channel(); $match = $expect; while (true) { if ($mode == self::READ_REGEX) { preg_match($expect, $this->interactiveBuffer, $matches); $match = isset($matches[0]) ? $matches[0] : ''; } $pos = strlen($match) ? strpos($this->interactiveBuffer, $match) : false; if ($pos !== false) { return $this->_string_shift($this->interactiveBuffer, $pos + strlen($match)); } $response = $this->_get_channel_packet($channel); if (is_bool($response)) { $this->in_request_pty_exec = false; return $response ? $this->_string_shift($this->interactiveBuffer, strlen($this->interactiveBuffer)) : false; } $this->interactiveBuffer.= $response; } } /** * Inputs a command into an interactive shell. * * @see \phpseclib\Net\SSH2::read() * @param String $cmd * @return Boolean * @access public */ function write($cmd) { if (!($this->bitmap & self::MASK_LOGIN)) { user_error('Operation disallowed prior to login()'); return false; } if (!($this->bitmap & self::MASK_SHELL) && !$this->_initShell()) { user_error('Unable to initiate an interactive shell session'); return false; } return $this->_send_channel_packet($this->_get_interactive_channel(), $cmd); } /** * Start a subsystem. * * Right now only one subsystem at a time is supported. To support multiple subsystem's stopSubsystem() could accept * a string that contained the name of the subsystem, but at that point, only one subsystem of each type could be opened. * To support multiple subsystem's of the same name maybe it'd be best if startSubsystem() generated a new channel id and * returns that and then that that was passed into stopSubsystem() but that'll be saved for a future date and implemented * if there's sufficient demand for such a feature. * * @see \phpseclib\Net\SSH2::stopSubsystem() * @param String $subsystem * @return Boolean * @access public */ function startSubsystem($subsystem) { $this->window_size_server_to_client[self::CHANNEL_SUBSYSTEM] = $this->window_size; $packet = pack('CNa*N3', NET_SSH2_MSG_CHANNEL_OPEN, strlen('session'), 'session', self::CHANNEL_SUBSYSTEM, $this->window_size, 0x4000); if (!$this->_send_binary_packet($packet)) { return false; } $this->channel_status[self::CHANNEL_SUBSYSTEM] = NET_SSH2_MSG_CHANNEL_OPEN; $response = $this->_get_channel_packet(self::CHANNEL_SUBSYSTEM); if ($response === false) { return false; } $packet = pack('CNNa*CNa*', NET_SSH2_MSG_CHANNEL_REQUEST, $this->server_channels[self::CHANNEL_SUBSYSTEM], strlen('subsystem'), 'subsystem', 1, strlen($subsystem), $subsystem); if (!$this->_send_binary_packet($packet)) { return false; } $this->channel_status[self::CHANNEL_SUBSYSTEM] = NET_SSH2_MSG_CHANNEL_REQUEST; $response = $this->_get_channel_packet(self::CHANNEL_SUBSYSTEM); if ($response === false) { return false; } $this->channel_status[self::CHANNEL_SUBSYSTEM] = NET_SSH2_MSG_CHANNEL_DATA; $this->bitmap |= self::MASK_SHELL; $this->in_subsystem = true; return true; } /** * Stops a subsystem. * * @see \phpseclib\Net\SSH2::startSubsystem() * @return Boolean * @access public */ function stopSubsystem() { $this->in_subsystem = false; $this->_close_channel(self::CHANNEL_SUBSYSTEM); return true; } /** * Closes a channel * * If read() timed out you might want to just close the channel and have it auto-restart on the next read() call * * @access public */ function reset() { $this->_close_channel($this->_get_interactive_channel()); } /** * Is timeout? * * Did exec() or read() return because they timed out or because they encountered the end? * * @access public */ function isTimeout() { return $this->is_timeout; } /** * Disconnect * * @access public */ function disconnect() { $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION); if (isset($this->realtime_log_file) && is_resource($this->realtime_log_file)) { fclose($this->realtime_log_file); } } /** * Destructor. * * Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call * disconnect(). * * @access public */ function __destruct() { $this->disconnect(); } /** * Is the connection still active? * * @return boolean * @access public */ function isConnected() { return (bool) ($this->bitmap & self::MASK_CONNECTED); } /** * Gets Binary Packets * * See '6. Binary Packet Protocol' of rfc4253 for more info. * * @see \phpseclib\Net\SSH2::_send_binary_packet() * @return String * @access private */ function _get_binary_packet() { if (!is_resource($this->fsock) || feof($this->fsock)) { user_error('Connection closed prematurely'); $this->bitmap = 0; return false; } $start = microtime(true); $raw = fread($this->fsock, $this->decrypt_block_size); if (!strlen($raw)) { return ''; } if ($this->decrypt !== false) { $raw = $this->decrypt->decrypt($raw); } if ($raw === false) { user_error('Unable to decrypt content'); return false; } extract(unpack('Npacket_length/Cpadding_length', $this->_string_shift($raw, 5))); $remaining_length = $packet_length + 4 - $this->decrypt_block_size; // quoting , // "implementations SHOULD check that the packet length is reasonable" // PuTTY uses 0x9000 as the actual max packet size and so to shall we if ($remaining_length < -$this->decrypt_block_size || $remaining_length > 0x9000 || $remaining_length % $this->decrypt_block_size != 0) { user_error('Invalid size'); return false; } $buffer = ''; while ($remaining_length > 0) { $temp = fread($this->fsock, $remaining_length); if ($temp === false || feof($this->fsock)) { user_error('Error reading from socket'); $this->bitmap = 0; return false; } $buffer.= $temp; $remaining_length-= strlen($temp); } $stop = microtime(true); if (strlen($buffer)) { $raw.= $this->decrypt !== false ? $this->decrypt->decrypt($buffer) : $buffer; } $payload = $this->_string_shift($raw, $packet_length - $padding_length - 1); $padding = $this->_string_shift($raw, $padding_length); // should leave $raw empty if ($this->hmac_check !== false) { $hmac = fread($this->fsock, $this->hmac_size); if ($hmac === false || strlen($hmac) != $this->hmac_size) { user_error('Error reading socket'); $this->bitmap = 0; return false; } elseif ($hmac != $this->hmac_check->hash(pack('NNCa*', $this->get_seq_no, $packet_length, $padding_length, $payload . $padding))) { user_error('Invalid HMAC'); return false; } } //if ($this->decompress) { // $payload = gzinflate(substr($payload, 2)); //} $this->get_seq_no++; if (defined('NET_SSH2_LOGGING')) { $current = microtime(true); $message_number = isset($this->message_numbers[ord($payload[0])]) ? $this->message_numbers[ord($payload[0])] : 'UNKNOWN (' . ord($payload[0]) . ')'; $message_number = '<- ' . $message_number . ' (since last: ' . round($current - $this->last_packet, 4) . ', network: ' . round($stop - $start, 4) . 's)'; $this->_append_log($message_number, $payload); $this->last_packet = $current; } return $this->_filter($payload); } /** * Filter Binary Packets * * Because some binary packets need to be ignored... * * @see \phpseclib\Net\SSH2::_get_binary_packet() * @return String * @access private */ function _filter($payload) { switch (ord($payload[0])) { case NET_SSH2_MSG_DISCONNECT: $this->_string_shift($payload, 1); extract(unpack('Nreason_code/Nlength', $this->_string_shift($payload, 8))); $this->errors[] = 'SSH_MSG_DISCONNECT: ' . $this->disconnect_reasons[$reason_code] . "\r\n" . utf8_decode($this->_string_shift($payload, $length)); $this->bitmap = 0; return false; case NET_SSH2_MSG_IGNORE: $payload = $this->_get_binary_packet(); break; case NET_SSH2_MSG_DEBUG: $this->_string_shift($payload, 2); extract(unpack('Nlength', $this->_string_shift($payload, 4))); $this->errors[] = 'SSH_MSG_DEBUG: ' . utf8_decode($this->_string_shift($payload, $length)); $payload = $this->_get_binary_packet(); break; case NET_SSH2_MSG_UNIMPLEMENTED: return false; case NET_SSH2_MSG_KEXINIT: if ($this->session_id !== false) { if (!$this->_key_exchange($payload)) { $this->bitmap = 0; return false; } $payload = $this->_get_binary_packet(); } } // see http://tools.ietf.org/html/rfc4252#section-5.4; only called when the encryption has been activated and when we haven't already logged in if (($this->bitmap & self::MASK_CONNECTED) && !($this->bitmap & self::MASK_LOGIN) && ord($payload[0]) == NET_SSH2_MSG_USERAUTH_BANNER) { $this->_string_shift($payload, 1); extract(unpack('Nlength', $this->_string_shift($payload, 4))); $this->banner_message = utf8_decode($this->_string_shift($payload, $length)); $payload = $this->_get_binary_packet(); } // only called when we've already logged in if (($this->bitmap & self::MASK_CONNECTED) && ($this->bitmap & self::MASK_LOGIN)) { switch (ord($payload[0])) { case NET_SSH2_MSG_GLOBAL_REQUEST: // see http://tools.ietf.org/html/rfc4254#section-4 $this->_string_shift($payload, 1); extract(unpack('Nlength', $this->_string_shift($payload))); $this->errors[] = 'SSH_MSG_GLOBAL_REQUEST: ' . utf8_decode($this->_string_shift($payload, $length)); if (!$this->_send_binary_packet(pack('C', NET_SSH2_MSG_REQUEST_FAILURE))) { return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION); } $payload = $this->_get_binary_packet(); break; case NET_SSH2_MSG_CHANNEL_OPEN: // see http://tools.ietf.org/html/rfc4254#section-5.1 $this->_string_shift($payload, 1); extract(unpack('Nlength', $this->_string_shift($payload, 4))); $this->errors[] = 'SSH_MSG_CHANNEL_OPEN: ' . utf8_decode($this->_string_shift($payload, $length)); $this->_string_shift($payload, 4); // skip over client channel extract(unpack('Nserver_channel', $this->_string_shift($payload, 4))); $packet = pack('CN3a*Na*', NET_SSH2_MSG_REQUEST_FAILURE, $server_channel, NET_SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED, 0, '', 0, ''); if (!$this->_send_binary_packet($packet)) { return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION); } $payload = $this->_get_binary_packet(); break; case NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST: $this->_string_shift($payload, 1); extract(unpack('Nchannel', $this->_string_shift($payload, 4))); extract(unpack('Nwindow_size', $this->_string_shift($payload, 4))); $this->window_size_client_to_server[$channel]+= $window_size; $payload = ($this->bitmap & self::MASK_WINDOW_ADJUST) ? true : $this->_get_binary_packet(); } } return $payload; } /** * Enable Quiet Mode * * Suppress stderr from output * * @access public */ function enableQuietMode() { $this->quiet_mode = true; } /** * Disable Quiet Mode * * Show stderr in output * * @access public */ function disableQuietMode() { $this->quiet_mode = false; } /** * Returns whether Quiet Mode is enabled or not * * @see \phpseclib\Net\SSH2::enableQuietMode() * @see \phpseclib\Net\SSH2::disableQuietMode() * * @access public * @return boolean */ function isQuietModeEnabled() { return $this->quiet_mode; } /** * Enable request-pty when using exec() * * @access public */ function enablePTY() { $this->request_pty = true; } /** * Disable request-pty when using exec() * * @access public */ function disablePTY() { $this->request_pty = false; } /** * Returns whether request-pty is enabled or not * * @see \phpseclib\Net\SSH2::enablePTY() * @see \phpseclib\Net\SSH2::disablePTY() * * @access public * @return boolean */ function isPTYEnabled() { return $this->request_pty; } /** * Gets channel data * * Returns the data as a string if it's available and false if not. * * @param $client_channel * @return Mixed * @access private */ function _get_channel_packet($client_channel, $skip_extended = false) { if (!empty($this->channel_buffers[$client_channel])) { return array_shift($this->channel_buffers[$client_channel]); } while (true) { if ($this->curTimeout) { if ($this->curTimeout < 0) { $this->is_timeout = true; return true; } $read = array($this->fsock); $write = $except = null; $start = microtime(true); $sec = floor($this->curTimeout); $usec = 1000000 * ($this->curTimeout - $sec); // on windows this returns a "Warning: Invalid CRT parameters detected" error if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) { $this->is_timeout = true; return true; } $elapsed = microtime(true) - $start; $this->curTimeout-= $elapsed; } $response = $this->_get_binary_packet(); if ($response === false) { user_error('Connection closed by server'); return false; } if ($client_channel == -1 && $response === true) { return true; } if (!strlen($response)) { return ''; } extract(unpack('Ctype/Nchannel', $this->_string_shift($response, 5))); $this->window_size_server_to_client[$channel]-= strlen($response); // resize the window, if appropriate if ($this->window_size_server_to_client[$channel] < 0) { $packet = pack('CNN', NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST, $this->server_channels[$channel], $this->window_size); if (!$this->_send_binary_packet($packet)) { return false; } $this->window_size_server_to_client[$channel]+= $this->window_size; } switch ($this->channel_status[$channel]) { case NET_SSH2_MSG_CHANNEL_OPEN: switch ($type) { case NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION: extract(unpack('Nserver_channel', $this->_string_shift($response, 4))); $this->server_channels[$channel] = $server_channel; extract(unpack('Nwindow_size', $this->_string_shift($response, 4))); $this->window_size_client_to_server[$channel] = $window_size; $temp = unpack('Npacket_size_client_to_server', $this->_string_shift($response, 4)); $this->packet_size_client_to_server[$channel] = $temp['packet_size_client_to_server']; return $client_channel == $channel ? true : $this->_get_channel_packet($client_channel, $skip_extended); //case NET_SSH2_MSG_CHANNEL_OPEN_FAILURE: default: user_error('Unable to open channel'); return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION); } break; case NET_SSH2_MSG_CHANNEL_REQUEST: switch ($type) { case NET_SSH2_MSG_CHANNEL_SUCCESS: return true; case NET_SSH2_MSG_CHANNEL_FAILURE: return false; default: user_error('Unable to fulfill channel request'); return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION); } case NET_SSH2_MSG_CHANNEL_CLOSE: return $type == NET_SSH2_MSG_CHANNEL_CLOSE ? true : $this->_get_channel_packet($client_channel, $skip_extended); } // ie. $this->channel_status[$channel] == NET_SSH2_MSG_CHANNEL_DATA switch ($type) { case NET_SSH2_MSG_CHANNEL_DATA: /* if ($channel == self::CHANNEL_EXEC) { // SCP requires null packets, such as this, be sent. further, in the case of the ssh.com SSH server // this actually seems to make things twice as fast. more to the point, the message right after // SSH_MSG_CHANNEL_DATA (usually SSH_MSG_IGNORE) won't block for as long as it would have otherwise. // in OpenSSH it slows things down but only by a couple thousandths of a second. $this->_send_channel_packet($channel, chr(0)); } */ extract(unpack('Nlength', $this->_string_shift($response, 4))); $data = $this->_string_shift($response, $length); if ($client_channel == $channel) { return $data; } if (!isset($this->channel_buffers[$channel])) { $this->channel_buffers[$channel] = array(); } $this->channel_buffers[$channel][] = $data; break; case NET_SSH2_MSG_CHANNEL_EXTENDED_DATA: /* if ($client_channel == self::CHANNEL_EXEC) { $this->_send_channel_packet($client_channel, chr(0)); } */ // currently, there's only one possible value for $data_type_code: NET_SSH2_EXTENDED_DATA_STDERR extract(unpack('Ndata_type_code/Nlength', $this->_string_shift($response, 8))); $data = $this->_string_shift($response, $length); $this->stdErrorLog.= $data; if ($skip_extended || $this->quiet_mode) { break; } if ($client_channel == $channel) { return $data; } if (!isset($this->channel_buffers[$channel])) { $this->channel_buffers[$channel] = array(); } $this->channel_buffers[$channel][] = $data; break; case NET_SSH2_MSG_CHANNEL_REQUEST: extract(unpack('Nlength', $this->_string_shift($response, 4))); $value = $this->_string_shift($response, $length); switch ($value) { case 'exit-signal': $this->_string_shift($response, 1); extract(unpack('Nlength', $this->_string_shift($response, 4))); $this->errors[] = 'SSH_MSG_CHANNEL_REQUEST (exit-signal): ' . $this->_string_shift($response, $length); $this->_string_shift($response, 1); extract(unpack('Nlength', $this->_string_shift($response, 4))); if ($length) { $this->errors[count($this->errors)].= "\r\n" . $this->_string_shift($response, $length); } $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_EOF, $this->server_channels[$client_channel])); $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_CLOSE, $this->server_channels[$channel])); $this->channel_status[$channel] = NET_SSH2_MSG_CHANNEL_EOF; break; case 'exit-status': extract(unpack('Cfalse/Nexit_status', $this->_string_shift($response, 5))); $this->exit_status = $exit_status; // "The client MAY ignore these messages." // -- http://tools.ietf.org/html/rfc4254#section-6.10 break; default: // "Some systems may not implement signals, in which case they SHOULD ignore this message." // -- http://tools.ietf.org/html/rfc4254#section-6.9 break; } break; case NET_SSH2_MSG_CHANNEL_CLOSE: $this->curTimeout = 0; if ($this->bitmap & self::MASK_SHELL) { $this->bitmap&= ~self::MASK_SHELL; } if ($this->channel_status[$channel] != NET_SSH2_MSG_CHANNEL_EOF) { $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_CLOSE, $this->server_channels[$channel])); } $this->channel_status[$channel] = NET_SSH2_MSG_CHANNEL_CLOSE; return true; case NET_SSH2_MSG_CHANNEL_EOF: break; default: user_error('Error reading channel data'); return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION); } } } /** * Sends Binary Packets * * See '6. Binary Packet Protocol' of rfc4253 for more info. * * @param String $data * @param optional String $logged * @see \phpseclib\Net\SSH2::_get_binary_packet() * @return Boolean * @access private */ function _send_binary_packet($data, $logged = null) { if (!is_resource($this->fsock) || feof($this->fsock)) { user_error('Connection closed prematurely'); $this->bitmap = 0; return false; } //if ($this->compress) { // // the -4 removes the checksum: // // http://php.net/function.gzcompress#57710 // $data = substr(gzcompress($data), 0, -4); //} // 4 (packet length) + 1 (padding length) + 4 (minimal padding amount) == 9 $packet_length = strlen($data) + 9; // round up to the nearest $this->encrypt_block_size $packet_length+= (($this->encrypt_block_size - 1) * $packet_length) % $this->encrypt_block_size; // subtracting strlen($data) is obvious - subtracting 5 is necessary because of packet_length and padding_length $padding_length = $packet_length - strlen($data) - 5; $padding = Random::string($padding_length); // we subtract 4 from packet_length because the packet_length field isn't supposed to include itself $packet = pack('NCa*', $packet_length - 4, $padding_length, $data . $padding); $hmac = $this->hmac_create !== false ? $this->hmac_create->hash(pack('Na*', $this->send_seq_no, $packet)) : ''; $this->send_seq_no++; if ($this->encrypt !== false) { $packet = $this->encrypt->encrypt($packet); } $packet.= $hmac; $start = microtime(true); $result = strlen($packet) == fputs($this->fsock, $packet); $stop = microtime(true); if (defined('NET_SSH2_LOGGING')) { $current = microtime(true); $message_number = isset($this->message_numbers[ord($data[0])]) ? $this->message_numbers[ord($data[0])] : 'UNKNOWN (' . ord($data[0]) . ')'; $message_number = '-> ' . $message_number . ' (since last: ' . round($current - $this->last_packet, 4) . ', network: ' . round($stop - $start, 4) . 's)'; $this->_append_log($message_number, isset($logged) ? $logged : $data); $this->last_packet = $current; } return $result; } /** * Logs data packets * * Makes sure that only the last 1MB worth of packets will be logged * * @param String $data * @access private */ function _append_log($message_number, $message) { // remove the byte identifying the message type from all but the first two messages (ie. the identification strings) if (strlen($message_number) > 2) { $this->_string_shift($message); } switch (NET_SSH2_LOGGING) { // useful for benchmarks case self::LOG_SIMPLE: $this->message_number_log[] = $message_number; break; // the most useful log for SSH2 case self::LOG_COMPLEX: $this->message_number_log[] = $message_number; $this->log_size+= strlen($message); $this->message_log[] = $message; while ($this->log_size > self::LOG_MAX_SIZE) { $this->log_size-= strlen(array_shift($this->message_log)); array_shift($this->message_number_log); } break; // dump the output out realtime; packets may be interspersed with non packets, // passwords won't be filtered out and select other packets may not be correctly // identified case self::LOG_REALTIME: switch (PHP_SAPI) { case 'cli': $start = $stop = "\r\n"; break; default: $start = '
';
                        $stop = '
'; } echo $start . $this->_format_log(array($message), array($message_number)) . $stop; @flush(); @ob_flush(); break; // basically the same thing as self::LOG_REALTIME with the caveat that self::LOG_REALTIME_FILE // needs to be defined and that the resultant log file will be capped out at self::LOG_MAX_SIZE. // the earliest part of the log file is denoted by the first <<< START >>> and is not going to necessarily // at the beginning of the file case self::LOG_REALTIME_FILE: if (!isset($this->realtime_log_file)) { // PHP doesn't seem to like using constants in fopen() $filename = self::LOG_REALTIME_FILENAME; $fp = fopen($filename, 'w'); $this->realtime_log_file = $fp; } if (!is_resource($this->realtime_log_file)) { break; } $entry = $this->_format_log(array($message), array($message_number)); if ($this->realtime_log_wrap) { $temp = "<<< START >>>\r\n"; $entry.= $temp; fseek($this->realtime_log_file, ftell($this->realtime_log_file) - strlen($temp)); } $this->realtime_log_size+= strlen($entry); if ($this->realtime_log_size > self::LOG_MAX_SIZE) { fseek($this->realtime_log_file, 0); $this->realtime_log_size = strlen($entry); $this->realtime_log_wrap = true; } fputs($this->realtime_log_file, $entry); } } /** * Sends channel data * * Spans multiple SSH_MSG_CHANNEL_DATAs if appropriate * * @param Integer $client_channel * @param String $data * @return Boolean * @access private */ function _send_channel_packet($client_channel, $data) { while (strlen($data)) { if (!$this->window_size_client_to_server[$client_channel]) { $this->bitmap^= self::MASK_WINDOW_ADJUST; // using an invalid channel will let the buffers be built up for the valid channels $this->_get_channel_packet(-1); $this->bitmap^= NET_SSH2_MASK_WINDOW_ADJUST; } /* The maximum amount of data allowed is determined by the maximum packet size for the channel, and the current window size, whichever is smaller. -- http://tools.ietf.org/html/rfc4254#section-5.2 */ $max_size = min( $this->packet_size_client_to_server[$client_channel], $this->window_size_client_to_server[$client_channel] ); $temp = $this->_string_shift($data, $max_size); $packet = pack('CN2a*', NET_SSH2_MSG_CHANNEL_DATA, $this->server_channels[$client_channel], strlen($temp), $temp ); $this->window_size_client_to_server[$client_channel]-= strlen($temp); if (!$this->_send_binary_packet($packet)) { return false; } } return true; } /** * Closes and flushes a channel * * \phpseclib\Net\SSH2 doesn't properly close most channels. For exec() channels are normally closed by the server * and for SFTP channels are presumably closed when the client disconnects. This functions is intended * for SCP more than anything. * * @param Integer $client_channel * @param Boolean $want_reply * @return Boolean * @access private */ function _close_channel($client_channel, $want_reply = false) { // see http://tools.ietf.org/html/rfc4254#section-5.3 $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_EOF, $this->server_channels[$client_channel])); if (!$want_reply) { $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_CLOSE, $this->server_channels[$client_channel])); } $this->channel_status[$client_channel] = NET_SSH2_MSG_CHANNEL_CLOSE; $this->curTimeout = 0; while (!is_bool($this->_get_channel_packet($client_channel))); if ($want_reply) { $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_CLOSE, $this->server_channels[$client_channel])); } if ($this->bitmap & self::MASK_SHELL) { $this->bitmap&= ~self::MASK_SHELL; } } /** * Disconnect * * @param Integer $reason * @return Boolean * @access private */ function _disconnect($reason) { if ($this->bitmap & self::MASK_CONNECTED) { $data = pack('CNNa*Na*', NET_SSH2_MSG_DISCONNECT, $reason, 0, '', 0, ''); $this->_send_binary_packet($data); $this->bitmap = 0; fclose($this->fsock); return false; } } /** * String Shift * * Inspired by array_shift * * @param String $string * @param optional Integer $index * @return String * @access private */ function _string_shift(&$string, $index = 1) { $substr = substr($string, 0, $index); $string = substr($string, $index); return $substr; } /** * Define Array * * Takes any number of arrays whose indices are integers and whose values are strings and defines a bunch of * named constants from it, using the value as the name of the constant and the index as the value of the constant. * If any of the constants that would be defined already exists, none of the constants will be defined. * * @param Array $array * @access private */ function _define_array() { $args = func_get_args(); foreach ($args as $arg) { foreach ($arg as $key=>$value) { if (!defined($value)) { define($value, $key); } else { break 2; } } } } /** * Returns a log of the packets that have been sent and received. * * Returns a string if NET_SSH2_LOGGING == self::LOG_COMPLEX, an array if NET_SSH2_LOGGING == self::LOG_SIMPLE and false if !defined('NET_SSH2_LOGGING') * * @access public * @return String or Array */ function getLog() { if (!defined('NET_SSH2_LOGGING')) { return false; } switch (NET_SSH2_LOGGING) { case self::LOG_SIMPLE: return $this->message_number_log; break; case self::LOG_COMPLEX: return $this->_format_log($this->message_log, $this->message_number_log); break; default: return false; } } /** * Formats a log for printing * * @param Array $message_log * @param Array $message_number_log * @access private * @return String */ function _format_log($message_log, $message_number_log) { $output = ''; for ($i = 0; $i < count($message_log); $i++) { $output.= $message_number_log[$i] . "\r\n"; $current_log = $message_log[$i]; $j = 0; do { if (strlen($current_log)) { $output.= str_pad(dechex($j), 7, '0', STR_PAD_LEFT) . '0 '; } $fragment = $this->_string_shift($current_log, $this->log_short_width); $hex = substr(preg_replace_callback('#.#s', array($this, '_format_log_helper'), $fragment), strlen($this->log_boundary)); // replace non ASCII printable characters with dots // http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters // also replace < with a . since < messes up the output on web browsers $raw = preg_replace('#[^\x20-\x7E]|<#', '.', $fragment); $output.= str_pad($hex, $this->log_long_width - $this->log_short_width, ' ') . $raw . "\r\n"; $j++; } while (strlen($current_log)); $output.= "\r\n"; } return $output; } /** * Helper function for _format_log * * For use with preg_replace_callback() * * @param Array $matches * @access private * @return String */ function _format_log_helper($matches) { return $this->log_boundary . str_pad(dechex(ord($matches[0])), 2, '0', STR_PAD_LEFT); } /** * Returns all errors * * @return String * @access public */ function getErrors() { return $this->errors; } /** * Returns the last error * * @return String * @access public */ function getLastError() { return $this->errors[count($this->errors) - 1]; } /** * Return the server identification. * * @return String * @access public */ function getServerIdentification() { $this->_connect(); return $this->server_identifier; } /** * Return a list of the key exchange algorithms the server supports. * * @return Array * @access public */ function getKexAlgorithms() { $this->_connect(); return $this->kex_algorithms; } /** * Return a list of the host key (public key) algorithms the server supports. * * @return Array * @access public */ function getServerHostKeyAlgorithms() { $this->_connect(); return $this->server_host_key_algorithms; } /** * Return a list of the (symmetric key) encryption algorithms the server supports, when receiving stuff from the client. * * @return Array * @access public */ function getEncryptionAlgorithmsClient2Server() { $this->_connect(); return $this->encryption_algorithms_client_to_server; } /** * Return a list of the (symmetric key) encryption algorithms the server supports, when sending stuff to the client. * * @return Array * @access public */ function getEncryptionAlgorithmsServer2Client() { $this->_connect(); return $this->encryption_algorithms_server_to_client; } /** * Return a list of the MAC algorithms the server supports, when receiving stuff from the client. * * @return Array * @access public */ function getMACAlgorithmsClient2Server() { $this->_connect(); return $this->mac_algorithms_client_to_server; } /** * Return a list of the MAC algorithms the server supports, when sending stuff to the client. * * @return Array * @access public */ function getMACAlgorithmsServer2Client() { $this->_connect(); return $this->mac_algorithms_server_to_client; } /** * Return a list of the compression algorithms the server supports, when receiving stuff from the client. * * @return Array * @access public */ function getCompressionAlgorithmsClient2Server() { $this->_connect(); return $this->compression_algorithms_client_to_server; } /** * Return a list of the compression algorithms the server supports, when sending stuff to the client. * * @return Array * @access public */ function getCompressionAlgorithmsServer2Client() { $this->_connect(); return $this->compression_algorithms_server_to_client; } /** * Return a list of the languages the server supports, when sending stuff to the client. * * @return Array * @access public */ function getLanguagesServer2Client() { $this->_connect(); return $this->languages_server_to_client; } /** * Return a list of the languages the server supports, when receiving stuff from the client. * * @return Array * @access public */ function getLanguagesClient2Server() { $this->_connect(); return $this->languages_client_to_server; } /** * Returns the banner message. * * Quoting from the RFC, "in some jurisdictions, sending a warning message before * authentication may be relevant for getting legal protection." * * @return String * @access public */ function getBannerMessage() { return $this->banner_message; } /** * Returns the server public host key. * * Caching this the first time you connect to a server and checking the result on subsequent connections * is recommended. Returns false if the server signature is not signed correctly with the public host key. * * @return Mixed * @access public */ function getServerPublicHostKey() { if (!($this->bitmap & self::MASK_CONSTRUCTOR)) { if (!$this->_connect()) { return false; } } $signature = $this->signature; $server_public_host_key = $this->server_public_host_key; extract(unpack('Nlength', $this->_string_shift($server_public_host_key, 4))); $this->_string_shift($server_public_host_key, $length); if ($this->signature_validated) { return $this->bitmap ? $this->signature_format . ' ' . base64_encode($this->server_public_host_key) : false; } $this->signature_validated = true; switch ($this->signature_format) { case 'ssh-dss': $zero = new BigInteger(); $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $p = new BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $q = new BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $g = new BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $y = new BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); /* The value for 'dss_signature_blob' is encoded as a string containing r, followed by s (which are 160-bit integers, without lengths or padding, unsigned, and in network byte order). */ $temp = unpack('Nlength', $this->_string_shift($signature, 4)); if ($temp['length'] != 40) { user_error('Invalid signature'); return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); } $r = new BigInteger($this->_string_shift($signature, 20), 256); $s = new BigInteger($this->_string_shift($signature, 20), 256); switch (true) { case $r->equals($zero): case $r->compare($q) >= 0: case $s->equals($zero): case $s->compare($q) >= 0: user_error('Invalid signature'); return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); } $w = $s->modInverse($q); $u1 = $w->multiply(new BigInteger(sha1($this->exchange_hash), 16)); list(, $u1) = $u1->divide($q); $u2 = $w->multiply($r); list(, $u2) = $u2->divide($q); $g = $g->modPow($u1, $p); $y = $y->modPow($u2, $p); $v = $g->multiply($y); list(, $v) = $v->divide($p); list(, $v) = $v->divide($q); if (!$v->equals($r)) { user_error('Bad server signature'); return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE); } break; case 'ssh-rsa': $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $e = new BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); $rawN = $this->_string_shift($server_public_host_key, $temp['length']); $n = new BigInteger($rawN, -256); $nLength = strlen(ltrim($rawN, "\0")); /* $temp = unpack('Nlength', $this->_string_shift($signature, 4)); $signature = $this->_string_shift($signature, $temp['length']); $rsa = new RSA(); $rsa->setSignatureMode(RSA::SIGNATURE_PKCS1); $rsa->loadKey(array('e' => $e, 'n' => $n), RSA::PUBLIC_FORMAT_RAW); if (!$rsa->verify($this->exchange_hash, $signature)) { user_error('Bad server signature'); return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE); } */ $temp = unpack('Nlength', $this->_string_shift($signature, 4)); $s = new BigInteger($this->_string_shift($signature, $temp['length']), 256); // validate an RSA signature per "8.2 RSASSA-PKCS1-v1_5", "5.2.2 RSAVP1", and "9.1 EMSA-PSS" in the // following URL: // ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1.pdf // also, see SSHRSA.c (rsa2_verifysig) in PuTTy's source. if ($s->compare(new BigInteger()) < 0 || $s->compare($n->subtract(new BigInteger(1))) > 0) { user_error('Invalid signature'); return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); } $s = $s->modPow($e, $n); $s = $s->toBytes(); $h = pack('N4H*', 0x00302130, 0x0906052B, 0x0E03021A, 0x05000414, sha1($this->exchange_hash)); $h = chr(0x01) . str_repeat(chr(0xFF), $nLength - 2 - strlen($h)) . $h; if ($s != $h) { user_error('Bad server signature'); return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE); } break; default: user_error('Unsupported signature format'); return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE); } return $this->signature_format . ' ' . base64_encode($this->server_public_host_key); } /** * Returns the exit status of an SSH command or false. * * @return Integer or false * @access public */ function getExitStatus() { if (is_null($this->exit_status)) { return false; } return $this->exit_status; } /** * Returns the number of columns for the terminal window size. * * @return Integer * @access public */ function getWindowColumns() { return $this->windowColumns; } /** * Returns the number of rows for the terminal window size. * * @return Integer * @access public */ function getWindowRows() { return $this->windowRows; } /** * Sets the number of columns for the terminal window size. * * @param Integer $value * @access public */ function setWindowColumns($value) { $this->windowColumns = $value; } /** * Sets the number of rows for the terminal window size. * * @param Integer $value * @access public */ function setWindowRows($value) { $this->windowRows = $value; } /** * Sets the number of columns and rows for the terminal window size. * * @param Integer $columns * @param Integer $rows * @access public */ function setWindowSize($columns = 80, $rows = 24) { $this->windowColumns = $columns; $this->windowRows = $rows; } } # minimalist openssl.cnf file for use with phpseclib HOME = . RANDFILE = $ENV::HOME/.rnd [ v3_ca ] * @copyright 2009 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net * @internal See http://api.libssh.org/rfc/PROTOCOL.agent */ namespace phpseclib\System\SSH\Agent; use phpseclib\System\SSH\Agent; /** * Pure-PHP ssh-agent client identity object * * Instantiation should only be performed by \phpseclib\System\SSH\Agent class. * This could be thought of as implementing an interface that phpseclib\Crypt\RSA * implements. ie. maybe a Net_SSH_Auth_PublicKey interface or something. * The methods in this interface would be getPublicKey, setSignatureMode * and sign since those are the methods phpseclib looks for to perform * public key authentication. * * @package SSH\Agent * @author Jim Wigginton * @access internal */ class Identity { /** * Key Object * * @var \phpseclib\Crypt\RSA * @access private * @see \phpseclib\System\SSH\Agent\Identity::getPublicKey() */ var $key; /** * Key Blob * * @var String * @access private * @see \phpseclib\System\SSH\Agent\Identity::sign() */ var $key_blob; /** * Socket Resource * * @var Resource * @access private * @see \phpseclib\System\SSH\Agent\Identity::sign() */ var $fsock; /** * Default Constructor. * * @param Resource $fsock * @return \phpseclib\System\SSH\Agent\Identity * @access private */ function __construct($fsock) { $this->fsock = $fsock; } /** * Set Public Key * * Called by \phpseclib\System\SSH\Agent::requestIdentities() * * @param \phpseclib\Crypt\RSA $key * @access private */ function setPublicKey($key) { $this->key = $key; $this->key->setPublicKey(); } /** * Set Public Key * * Called by \phpseclib\System\SSH\Agent::requestIdentities(). The key blob could be extracted from $this->key * but this saves a small amount of computation. * * @param String $key_blob * @access private */ function setPublicKeyBlob($key_blob) { $this->key_blob = $key_blob; } /** * Get Public Key * * Wrapper for $this->key->getPublicKey() * * @param Integer $format optional * @return Mixed * @access public */ function getPublicKey($format = null) { return !isset($format) ? $this->key->getPublicKey() : $this->key->getPublicKey($format); } /** * Set Signature Mode * * Doesn't do anything as ssh-agent doesn't let you pick and choose the signature mode. ie. * ssh-agent's only supported mode is \phpseclib\Crypt\RSA::SIGNATURE_PKCS1 * * @param Integer $mode * @access public */ function setSignatureMode($mode) { } /** * Create a signature * * See "2.6.2 Protocol 2 private key signature request" * * @param String $message * @return String * @access public */ function sign($message) { // the last parameter (currently 0) is for flags and ssh-agent only defines one flag (for ssh-dss): SSH_AGENT_OLD_SIGNATURE $packet = pack('CNa*Na*N', Agent::SSH_AGENTC_SIGN_REQUEST, strlen($this->key_blob), $this->key_blob, strlen($message), $message, 0); $packet = pack('Na*', strlen($packet), $packet); if (strlen($packet) != fputs($this->fsock, $packet)) { user_error('Connection closed during signing'); } $length = current(unpack('N', fread($this->fsock, 4))); $type = ord(fread($this->fsock, 1)); if ($type != Agent::SSH_AGENT_SIGN_RESPONSE) { user_error('Unable to retreive signature'); } $signature_blob = fread($this->fsock, $length - 1); // the only other signature format defined - ssh-dss - is the same length as ssh-rsa // the + 12 is for the other various SSH added length fields return substr($signature_blob, strlen('ssh-rsa') + 12); } } * login('username', $agent)) { * exit('Login Failed'); * } * * echo $ssh->exec('pwd'); * echo $ssh->exec('ls -la'); * ?> * * * @category System * @package SSH\Agent * @author Jim Wigginton * @copyright 2014 Jim Wigginton * @license http://www.opensource.org/licenses/mit-license.html MIT License * @link http://phpseclib.sourceforge.net * @internal See http://api.libssh.org/rfc/PROTOCOL.agent */ namespace phpseclib\System\SSH; use phpseclib\Crypt\RSA; use phpseclib\System\SSH\Agent\Identity; /** * Pure-PHP ssh-agent client identity factory * * requestIdentities() method pumps out \phpseclib\System\SSH\Agent\Identity objects * * @package SSH\Agent * @author Jim Wigginton * @access internal */ class Agent { /**#@+ * Message numbers * * @access private */ // to request SSH1 keys you have to use SSH_AGENTC_REQUEST_RSA_IDENTITIES (1) const SSH_AGENTC_REQUEST_IDENTITIES = 11; // this is the SSH2 response; the SSH1 response is SSH_AGENT_RSA_IDENTITIES_ANSWER (2). const SSH_AGENT_IDENTITIES_ANSWER = 12; // the SSH1 request is SSH_AGENTC_RSA_CHALLENGE (3) const SSH_AGENTC_SIGN_REQUEST = 13; // the SSH1 response is SSH_AGENT_RSA_RESPONSE (4) const SSH_AGENT_SIGN_RESPONSE = 14; /**#@-*/ /** * Unused */ const SSH_AGENT_FAILURE = 5; /** * Socket Resource * * @var Resource * @access private */ var $fsock; /** * Default Constructor * * @return \phpseclib\System\SSH\Agent * @access public */ function __construct() { switch (true) { case isset($_SERVER['SSH_AUTH_SOCK']): $address = $_SERVER['SSH_AUTH_SOCK']; break; case isset($_ENV['SSH_AUTH_SOCK']): $address = $_ENV['SSH_AUTH_SOCK']; break; default: user_error('SSH_AUTH_SOCK not found'); return false; } $this->fsock = fsockopen('unix://' . $address, 0, $errno, $errstr); if (!$this->fsock) { user_error("Unable to connect to ssh-agent (Error $errno: $errstr)"); } } /** * Request Identities * * See "2.5.2 Requesting a list of protocol 2 keys" * Returns an array containing zero or more \phpseclib\System\SSH\Agent\Identity objects * * @return Array * @access public */ function requestIdentities() { if (!$this->fsock) { return array(); } $packet = pack('NC', 1, self::SSH_AGENTC_REQUEST_IDENTITIES); if (strlen($packet) != fputs($this->fsock, $packet)) { user_error('Connection closed while requesting identities'); } $length = current(unpack('N', fread($this->fsock, 4))); $type = ord(fread($this->fsock, 1)); if ($type != self::SSH_AGENT_IDENTITIES_ANSWER) { user_error('Unable to request identities'); } $identities = array(); $keyCount = current(unpack('N', fread($this->fsock, 4))); for ($i = 0; $i < $keyCount; $i++) { $length = current(unpack('N', fread($this->fsock, 4))); $key_blob = fread($this->fsock, $length); $length = current(unpack('N', fread($this->fsock, 4))); $key_comment = fread($this->fsock, $length); $length = current(unpack('N', substr($key_blob, 0, 4))); $key_type = substr($key_blob, 4, $length); switch ($key_type) { case 'ssh-rsa': $key = new RSA(); $key->loadKey('ssh-rsa ' . base64_encode($key_blob) . ' ' . $key_comment); break; case 'ssh-dss': // not currently supported break; } // resources are passed by reference by default if (isset($key)) { $identity = new Identity($this->fsock); $identity->setPublicKey($key); $identity->setPublicKeyBlob($key_blob); $identities[] = $identity; unset($key); } } return $identities; } } . * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Sebastian Bergmann nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package Environment * @author Sebastian Bergmann * @copyright 2014 Sebastian Bergmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://www.github.com/sebastianbergmann/environment */ namespace SebastianBergmann\Environment; /** * @package Environment * @author Sebastian Bergmann * @copyright 2014 Sebastian Bergmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://www.github.com/sebastianbergmann/environment */ class Console { /** * Returns true if STDOUT supports colorization. * * This code has been copied and adapted from * Symfony\Component\Console\Output\OutputStream. * * @return boolean */ public function hasColorSupport() { if (DIRECTORY_SEPARATOR == '\\') { return false !== getenv('ANSICON') || 'ON' === getenv('ConEmuANSI'); } if (!defined('STDOUT')) { return false; } return $this->isTty(STDOUT); } /** * Returns the number of columns of the terminal. * * @return integer */ public function getNumberOfColumns() { // Windows terminals have a fixed size of 80 // but one column is used for the cursor. if (DIRECTORY_SEPARATOR == '\\') { return 79; } if (!defined('STDIN') || !$this->isTty(STDIN)) { return 80; } if (preg_match('#\d+ (\d+)#', shell_exec('stty size'), $match) === 1) { return (int) $match[1]; } if (preg_match('#columns = (\d+);#', shell_exec('stty'), $match) === 1) { return (int) $match[1]; } return 80; } /** * @param resource $fd * @return boolean */ private function isTty($fd) { return function_exists('posix_isatty') && @posix_isatty($fd); } } Environment Copyright (c) 2014, Sebastian Bergmann . All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Sebastian Bergmann nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. . * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Sebastian Bergmann nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package Environment * @author Sebastian Bergmann * @copyright 2014 Sebastian Bergmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://www.github.com/sebastianbergmann/environment */ namespace SebastianBergmann\Environment; /** * Utility class for HHVM/PHP environment handling. * * @package Environment * @author Sebastian Bergmann * @copyright 2014 Sebastian Bergmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://www.github.com/sebastianbergmann/environment */ class Runtime { /** * @var string */ private static $binary; /** * Returns true when the runtime used is HHVM or * the runtime used is PHP + Xdebug. * * @return boolean */ public function canCollectCodeCoverage() { return $this->isHHVM() || $this->hasXdebug(); } /** * Returns the path to the binary of the current runtime. * Appends ' --php' to the path when the runtime is HHVM. * * @return string */ public function getBinary() { // HHVM if (self::$binary === null && $this->isHHVM()) { if ((self::$binary = getenv('PHP_BINARY')) === false) { self::$binary = PHP_BINARY; } self::$binary = escapeshellarg(self::$binary) . ' --php'; } // PHP >= 5.4.0 if (self::$binary === null && defined('PHP_BINARY')) { self::$binary = escapeshellarg(PHP_BINARY); } // PHP < 5.4.0 if (self::$binary === null) { if (PHP_SAPI == 'cli' && isset($_SERVER['_'])) { if (strpos($_SERVER['_'], 'phpunit') !== false) { $file = file($_SERVER['_']); if (strpos($file[0], ' ') !== false) { $tmp = explode(' ', $file[0]); self::$binary = escapeshellarg(trim($tmp[1])); } else { self::$binary = escapeshellarg(ltrim(trim($file[0]), '#!')); } } elseif (strpos(basename($_SERVER['_']), 'php') !== false) { self::$binary = escapeshellarg($_SERVER['_']); } } } if (self::$binary === null) { $possibleBinaryLocations = array( PHP_BINDIR . '/php', PHP_BINDIR . '/php-cli.exe', PHP_BINDIR . '/php.exe' ); foreach ($possibleBinaryLocations as $binary) { if (is_readable($binary)) { self::$binary = escapeshellarg($binary); break; } } } if (self::$binary === null) { self::$binary = 'php'; } return self::$binary; } /** * @return string */ public function getNameWithVersion() { return $this->getName() . ' ' . $this->getVersion(); } /** * @return string */ public function getName() { if ($this->isHHVM()) { return 'HHVM'; } else { return 'PHP'; } } /** * @return string */ public function getVendorUrl() { if ($this->isHHVM()) { return 'http://hhvm.com/'; } else { return 'http://php.net/'; } } /** * @return string */ public function getVersion() { if ($this->isHHVM()) { return HHVM_VERSION; } else { return PHP_VERSION; } } /** * Returns true when the runtime used is PHP and Xdebug is loaded. * * @return boolean */ public function hasXdebug() { return $this->isPHP() && extension_loaded('xdebug'); } /** * Returns true when the runtime used is HHVM. * * @return boolean */ public function isHHVM() { return defined('HHVM_VERSION'); } /** * Returns true when the runtime used is PHP. * * @return boolean */ public function isPHP() { return !$this->isHHVM(); } } Version Copyright (c) 2013-2014, Sebastian Bergmann . All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Sebastian Bergmann nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. . * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of Sebastian Bergmann nor the names of his * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package Version * @author Sebastian Bergmann * @copyright 2013-2014 Sebastian Bergmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://github.com/sebastianbergmann/version * @since File available since Release 1.0.0 */ namespace SebastianBergmann; /** * @package Version * @author Sebastian Bergmann * @copyright 2013-2014 Sebastian Bergmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://github.com/sebastianbergmann/version * @since Class available since Release 1.0.0 */ class Version { private $path; private $release; private $version; /** * @param string $release * @param string $path */ public function __construct($release, $path) { $this->release = $release; $this->path = $path; } /** * @return string */ public function getVersion() { if ($this->version === null) { if (count(explode('.', $this->release)) == 3) { $this->version = $this->release; } else { $this->version = $this->release . '-dev'; } $git = $this->getGitInformation($this->path); if ($git) { if (count(explode('.', $this->release)) == 3) { $this->version = $git; } else { $git = explode('-', $git); $this->version = $this->release . '-' . end($git); } } } return $this->version; } /** * @param string $path * @return boolean|string */ private function getGitInformation($path) { if (!is_dir($path . DIRECTORY_SEPARATOR . '.git')) { return false; } $dir = getcwd(); chdir($path); $result = @exec('git describe --tags 2>&1', $output, $returnCode); chdir($dir); if ($returnCode !== 0) { return false; } return $result; } } Unless otherwise noted, all files are released under the MIT license, exceptions contain licensing information in them. Copyright (C) 2014 SoftLayer Technologies, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of SoftLayer Technologies, Inc. shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from SoftLayer Technologies, Inc. Portions Copyright © 2008 Rackspace US, Inc. * $objectStorageDallas = new ObjectStorage($objectStorageHost, $username, $password, $options); * * $newContainer = $objectStorageDallas->with('example_container')->create(); * * $updatedContainer = $newContainer->setMeta('Description', 'Adding a meta data')->update(); * * $reloadedContainer = $newContainer->get(); * * $result = $newContainer->delete(); * * // If you wanted, you can do this all one line. * // Most functions return itself so you can chain method calls except detele method which returns a boolean value. * $result = $objectStorageDallas05->with('example_container')->create()->setMeta('Description', 'Adding a meta data')->update()->get()->delete(); * * // When you create a new container or an object, ObjectStorage_Abstract will return itself, not the newly created conainer or object. * // If you wish to reload the the data from ObjectStorage cluster, use ObjectStorage_Abstract::get or ObjectStorage_Abstract::reload methods. * $newContainer = $objectStorageDallas->with('example_container')->create(); * * // It will fetch the container info from ObjectStorage and reload $newContainer object with it. * $newContainer->reload(); * * * ObjectStorage_Abstract tries to postpone the actual interaction with ObjectStorage as late as it can. * Authentication to ObjectStorage or any CRUD operation happens when you invoke these method: * * create * * get * * getInfo (Equivalent to HEAD request) * * update * * delete * * getCdnUrls * * purgeCache (only applicable to a ObjectStorage_Object in a public container) * * loadCache (only applicable to a ObjectStorage_Object in a public container) * * In order to make objects available via CDN, you will need to make a container public. See the example below: * * // To create a CDN enabled container * $objectStorageDallas->with('cdn_container')->enableCdn()->create(); * * // To update an existing container to a CDN enabled container * $objectStorageDallas->with('another_container')->enableCdn()->update(); * * // Likewise, you can change a container private this way. * $objectStorageDallas->with('another_container')->disableCdn()->update(); * * * You can iterate through container or object using $containers or $objects property * * if (count($container->objects) > 0) { * foreach ($results->objects as $shallowObject) { * $object = $shallowObject->get(); * * echo $object->getUrl(); * echo $object->getResponse()->getBody(); * } * } * * You can copy a container or an object to another ObjectStorage cluster this way: * * $objectStorageDallas = new ObjectStorage($objectStorageHost01, $username01, $password01, $options); * $objectStorageSeattle = new ObjectStorage($objectStorageHost02, $username02, $password02, $options); * * $object = $objectStorageDallas->with('path/object')->get(); * $objectStorageSeattle->create($object); * * * @package ObjectStorage-Client * @copyright Copyright (c) 2012 SoftLayer Technologies Inc. (http://www.softlayer.com) */ abstract class ObjectStorage_Abstract { public $containers = array(); public $objects = array(); public $limit = 0; public $marker = ''; public $searchFilters = array(); public $queryString = array(); protected $path; protected $mime; protected $request; protected $response; protected $objectStorage; protected $context = ''; protected $containerCount = null; protected $objectCount = null; protected static $httpClient; const CONTEXT_CDN = 'CDN'; const CONTEXT_SEARCH = 'SEARCH'; /** * Constructor. * * @param string $path ObjectStorage path delimited by slash. * @param ObjectStorage $objectStorage */ public function __construct($path, ObjectStorage $objectStorage) { $this->path = $path; $this->objectStorage = $objectStorage; $this->request = new ObjectStorage_Http_Request(); $this->response = new ObjectStorage_Http_Response(); } /** * Returns the ObjectStorage path * * @return string */ public function getPath() { return $this->path; } /** * Returns response HTTP status code * * @return int */ public function getStatusCode() { return $this->response->getStatusCode(); } /** * Sets a meta data * "Meta data" is an optional custom header and it is a part of the ObjectStorage response headers * * @param string $metaKey * @param string $value * * @return ObjectStorage_Abstract */ public function setMeta($metaKey = '', $value = '') { $this->request->setHeader($this->getMetaPrefix() . strtolower($metaKey), (string) $value); return $this; } /** * Gets a meta data by key in the response * * @param string $metaKey * * @return string */ public function getMeta($metaKey = '') { return $this->response->getHeader($this->getMetaPrefix() . strtolower($metaKey)); } /** * Sets a meta data * * @param string $metaKey * @param string $value * * @return ObjectStorage_Abstract */ public function setAccountMeta($metaKey = '', $value = '') { $this->request->setHeader('X-Account-Meta-' . strtolower($metaKey), (string) $value); return $this; } /** * Sets an array of meta data * * @param array $metaData * * @return ObjectStorage_Abstract */ public function setMetaList($metaData = array()) { if (is_array($metaData) && count($metaData) > 0) { foreach ($metaData as $key => $value) { $this->setMeta($key, $value); } } return $this; } /** * Sets a request header * Use this when you need to add special request headers such as X-CDN-CNAME and so on. * * @param string $headerKey * @param string $value * * @return ObjectStorage_Abstract */ public function setHeader($headerKey = '', $value = '') { $this->request->setHeader(ucfirst(strtolower($headerKey)), (string) $value); return $this; } /** * Sets an array of ObjectStorage headers * * @param array $headerData * * @return ObjectStorage_Abstract */ public function setHeaders($headerData = array()) { if (is_array($headerData) && count($headerData) > 0) { foreach ($headerData as $key => $value) { $this->setHeader($key, $value); } } return $this; } /** * Gets a response header by key * * @param string $headerKey * * @return string */ public function getHeader($headerKey = '') { return $this->response->getHeader($headerKey); } /** * Gets an array of response headers * * @return array */ public function getHeaders() { return $this->response->getHeaders(); } /** * Sets request body * * @param mixed $body * * @return ObjectStorage_Abstract */ public function setBody($body) { $this->request->setBody($body); return $this; } /** * Gets body data from response object * * @return mixed */ public function getBody() { return $this->response->getBody(); } /** * Sets a location to copy from for an object * * @param string $location * * @return ObjectStorage_Abstract */ public function copyFrom($location) { $this->setHeader('X-Copy-From', $location); return $this; } /** * Return ObjectStorage_Http_Request object * * @return ObjectStorage_Http_Request */ public function getRequest() { return $this->request; } /** * Returns ObjectStorage_Http_Response object * * @return ObjectStorage_Http_Response */ public function getResponse() { return $this->response; } /** * Sets response object * * @param ObjectStorage_Http_Response $response */ public function setResponse(ObjectStorage_Http_Response $response) { if ($response->getHeader('X-cdn-enabled-item-count') != null) { $this->containerCount = $response->getHeader('X-cdn-enabled-item-count'); } else if ($response->getHeader('X-account-container-count') != null) { $this->containerCount = $response->getHeader('X-account-container-count'); } if ($response->getHeader('X-container-object-count') != null) { $this->objectCount = $response->getHeader('X-container-object-count'); } $this->response = $response; } /** * Sets a ObjectStorage response format. Available values are: json, xml, text * * @param string $mime * * @return ObjectStorage_Abstract */ public function setMime($mime) { switch (strtoupper($mime)) { case ObjectStorage::MIME_JSON: $this->setHeader('Accept', 'application/json; charset=utf-8'); break; case ObjectStorage::MIME_XML: $this->setHeader('Accept', 'application/xml; charset=utf-8'); break; case ObjectStorage::MIME_TEXT: $this->setHeader('Accept', 'plain/text; charset=utf-8'); break; default: throw new ObjectStorage_Exception(null, 'Invalid MIME type is provided.'); } $this->mime = strtoupper($mime); return $this; } /** * Sets a TTL value for a container or an object * * @param int $ttlValue * * @return ObjectStorage_Abstract */ public function setTtl($ttlValue = 3600) { $this->setHeader('X-Cdn-Ttl', (int) $ttlValue); return $this; } /** * Gets a TTL value for a container or an object from HTTP response * * @return int */ public function getTtl() { $this->getHeader('X-Cdn-Ttl'); } /** * Sets a search filter. This method is used when you are working in "search" context. * * @param string $key * @param string $value * * @throws ObjectStorage_Exception * * @return ObjectStorage_Abstract */ public function setFilter($key, $value) { if ($this->context != ObjectStorage_Abstract::CONTEXT_SEARCH) { throw new ObjectStorage_Exception('Filter can be set within the "search" contenxt.'); } // @todo Validate $key $this->searchFilters[$key] = (string) $value; return $this; } /** * Sets a query parameter. This method is used to set a URL parameter. * * @param string $key * @param string $value * * @return ObjectStorage_Abstract */ public function setParam($key, $value) { // @todo Validate $key $this->queryString[$key] = (string) $value; return $this; } /** * Returns the ObjectStorage context value * * @return string */ public function getContext() { return $this->context; } /** * Sets the ObjectStorage context. Valid context values are: cdn, search * * @param string $name * @return ObjectStorage_Abstract */ public function setContext($name = '') { $name = strtoupper($name); if (in_array($name, array(self::CONTEXT_CDN, self::CONTEXT_SEARCH))) { $this->context = $name; $this->setHeader('X-Context', strtolower($name)); } return $this; } /** * Removes the ObjectStorage context if any. It reset the context back to the default ObjectStorage context. * * @return ObjectStorage_Abstract */ public function removeContext() { $this->context = ''; $this->request->deleteHeader('X-Context'); return $this; } /** * Returns the full ObjectStorage URL * * @return string */ public function getUrl() { $url = $this->objectStorage->getUrl($this); $queryString = array(); if ($this->marker != '') { $queryString[] = 'marker=' . $this->marker; } if (count($this->searchFilters) > 0) { foreach ($this->searchFilters as $key => $value) { $queryString[] = $key . '=' . $value; } } if (count($this->queryString) > 0) { foreach ($this->queryString as $key => $value) { $queryString[] = $key . '=' . $value; } } if (count($queryString) > 0) { $url .= '?' . implode('&', $queryString); } return $url; } /** * Returns total number of containers * * @return array */ public function getContainerCount() { return $this->containerCount; } /** * Returns total number of objects within the current container * * @return array */ public function getObjectCount() { return $this->objectCount; } /** * Returns all CDN URLs * * @return array */ public function getCdnUrls() { try { return $this->objectStorage->getCdnUrls($this); } catch (Exception $e) { $this->objectStorage->reloadAuthenticationData(); return $this->objectStorage->getCdnUrls($this); } } /** * Retrieves the container or object data from ObjectStorage * $limit and $marker will not be taken into consideration when dealing with an object. * * @param int $limit * @param string $marker * * @return ObjectStorage_Abstract */ public function get($limit = 100, $marker = '') { $this->limit = $limit; $this->marker = $marker; try { return $this->objectStorage->get($this); } catch (ObjectStorage_Exception_Http_NotFound $e) { throw $e; } catch (Exception $e) { $this->objectStorage->reloadAuthenticationData(); return $this->objectStorage->get($this); } } /** * Returns the header and meta data of a container or an object. * * @return ObjectStorage_Abstract */ public function getInfo() { try { return $this->objectStorage->get($this, false); } catch (ObjectStorage_Exception_Http_NotFound $e) { throw $e; } catch (Exception $e) { $this->objectStorage->reloadAuthenticationData(); return $this->objectStorage->get($this, false); } } /** * Creates a container or an object on ObjectStorage * * @return ObjectStorage_Abstract */ public function create() { try { return $this->objectStorage->create($this); } catch (Exception $e) { $this->objectStorage->reloadAuthenticationData(); return $this->objectStorage->create($this); } } /** * Updates a container or an object on ObjectStorage * * @return ObjectStorage_Abstract */ public function update() { try { return $this->objectStorage->update($this); } catch (Exception $e) { $this->objectStorage->reloadAuthenticationData(); return $this->objectStorage->update($this); } } /** * Deletes a container or an object on ObjectStorage * * @return bool */ public function delete() { try { return $this->objectStorage->delete($this); } catch (ObjectStorage_Exception_Http_NotFound $e) { throw $e; } catch (Exception $e) { $this->objectStorage->reloadAuthenticationData(); return $this->objectStorage->delete($this); } } /** * Reloads the current object with the newly retrieved data from ObjectStorage. * Synonym of ObjectStorage_Abstract::get method * * @return ObjectStorage_Abstract */ public function reload() { return $this->get(); } }request->setHeader('X-CONTAINER-READ', '.r:*'); return $this; } /** * Disables CDN. This method removes a "public read" meta data. * You have to call ObjectStorage_Abstract::create or ObjectStorage_Abstract_update method in order for this to take affect. * * @return ObjectStorage_Container */ public function disableCdn() { $this->request->setHeader('X-CONTAINER-READ', ''); return $this; } /** * Adds CNAME. This method sets a CNAME on the container. * You have to call ObjectStorage_Abstract::create or ObjectStorage_Abstract_update method in order for this to take affect. * * @return ObjectStorage_Container */ public function addCname($cnameUrl, $type='HTTP') { $this->setContext(self::CONTEXT_CDN); $this->request->setHeader('X-CDN-CNAME', $cnameUrl); $this->request->setHeader('X-CDN-CNAME-TYPE', $type); $this->request->setHeader('X-CDN-CNAME-ACTION', 'add'); return $this; } /** * Removes CNAME. This method removes the CNAME from the container. * You have to call ObjectStorage_Abstract::create or ObjectStorage_Abstract_update method in order for this to take affect. * * @return ObjectStorage_Container */ public function removeCname($cnameUrl) { $this->setContext(self::CONTEXT_CDN); $this->request->setHeader('X-CDN-CNAME', $cnameUrl); $this->request->setHeader('X-CDN-CNAME-ACTION', 'delete'); return $this; } /** * (non-PHPdoc) * @see ObjectStorage_Abstract::update() */ public function update() { $headers = $this->request->getHeaders(); if (count($headers) > 0) { foreach ($headers as $key => $value) { if (in_array(strtoupper($key), self::$skipOverwriteHeaders)) { $this->request->deleteHeader($key); } } } return parent::update(); } /** * (non-PHPdoc) * @see ObjectStorage_Abstract::get() */ public function get($limit = 100, $marker = '') { parent::get($limit, $marker); if ($this->response->getBody() == '') { return $this; } switch (strtoupper($this->mime)) { case ObjectStorage::MIME_JSON: $objects = json_decode($this->response->getBody()); if (count($objects) > 0) { foreach ($objects as $object) { if ($this->context == ObjectStorage_Abstract::CONTEXT_SEARCH) { $path = $object->type == 'container' ? $object->container : $object->container . '/' . $object->name; } else { $path = $this->path . '/' . (isset($object->name) ? $object->name : (isset($object->subdir) ? $object->subdir : '')); } $this->appendData($this->objectStorage->with($path)); } } break; case ObjectStorage::MIME_XML: // @todo implement this $data = simplexml_load_string($this->response->getBody()); $loopData = count($data->object) > 0 ? $data->object : (count($data->container) > 0 ? $data->container : array()); if (count($loopData) > 0) { if ($this->context == ObjectStorage_Abstract::CONTEXT_SEARCH) { foreach ($loopData as $object) { $path = (string) $object->type == 'container' ? $object->container : $object->container . '/' . $object->name; $this->appendData($this->objectStorage->with($path)); } } else { foreach ($loopData as $object) { $this->appendData($this->objectStorage->with($this->path . '/' . (string) $object->name)); } } } break; default: // plain/text $objects = explode("\n", trim($this->response->getBody(), "\n")); if (count($objects) > 0) { $path = ($this->path == '') ? '' : trim($this->path, '/') . '/'; foreach ($objects as $object) { $this->appendData($this->objectStorage->with($path . $object)); } } } if ($this->context == ObjectStorage_Abstract::CONTEXT_SEARCH) { $this->containerCount = count($this->containers); $this->objectCount = count($this->objects); } return $this; } protected function appendData(ObjectStorage_Abstract $objectStorageObject) { if ($objectStorageObject instanceof ObjectStorage_Container) { $this->containers[] = $objectStorageObject; } else { $this->objects[] = $objectStorageObject; } } public function __toString() { return 'ObjectStorage Container'; } }setFile($stackTrace[0]['file']); $newException->setLine($stackTrace[0]['line']); return $newException; } }file = $file; } /** * Sets the line number of which an exception is thrown * * @param int $line */ public function setLine($line) { $this->line = $line; } }cleanHeaderKey($headerKey); if (isset($this->headers[$key])) { return $this->headers[$key]; } return null; } /** * Returns header array * * @return array */ public function getHeaders() { return $this->headers; } /** * Sets header * * @param string $headerKey * @param string $value */ public function setHeader($headerKey = '', $value = '') { $this->headers[$this->cleanHeaderKey($headerKey)] = $value; } /** * Deletes a header by key * * @param string $headerKey */ public function deleteHeader($headerKey = '') { if (isset($this->headers[$this->cleanHeaderKey($headerKey)])) { unset($this->headers[$this->cleanHeaderKey($headerKey)]); } } /** * Sets header array * * @param array $headerArray */ public function setHeaders($headerArray = array()) { if (! is_array($headerArray)) { throw new ObjectStorage_Exception('HTTP headers must be an array.'); } foreach ($headerArray as $headerKey => $value) { $this->setHeader($headerKey, $value); } } /** * Returns HTTP body * * @return mixed */ public function getBody() { return $this->body; } /** * Sets HTTP body * * @param mixed $body */ public function setBody($body) { $this->body = $body; } protected function cleanHeaderKey($headerKey) { return ucfirst(strtolower($headerKey)); } }timeout = $options['timeout']; } } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::setUri() */ public function setUri($uri) { $this->uri = $uri; } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::setHeaders() */ public function setHeaders($name, $value) { $this->headers[$name] = $name . ': ' . $value; } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::setBody() */ public function setBody($body) { $this->body = $body; } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::setFileHandler() */ public function setFileHandler($handler) { $this->fileHandler = $handler; } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::setMethod() */ public function setMethod($method) { $this->method = $method; } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::reset() */ public function reset() { $this->headers = array(); $this->body = ''; $this->method = ''; $this->fileHandler = null; return true; } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::request() */ public function request() { $curl = curl_init(); $urlInfo = parse_url($this->uri); $requiredHeaders[] = 'Host: ' . $urlInfo['host']; $requiredHeaders[] = 'Connection: close'; $requiredHeaders[] = 'Expect:'; $this->requestHeaders = array_merge($requiredHeaders, $this->headers); // To get around CURL issue. http://curl.haxx.se/mail/lib-2010-08/0171.html $requestHeaders = implode("\r\n", $this->requestHeaders); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_URL, $this->uri); curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout); curl_setopt($curl, CURLOPT_HTTPHEADER, array($requestHeaders)); $method = strtoupper($this->method); switch($method) { case 'HEAD': curl_setopt($curl, CURLOPT_NOBODY, true); break; case 'PUT': curl_setopt($curl, CURLOPT_PUT, true); break; case 'POST': curl_setopt($curl, CURLOPT_POST, true); break; case 'DELETE': curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); break; } if (in_array($method, array('PUT', 'POST'))) { if ($this->fileHandler != null) { curl_setopt($curl, CURLOPT_BINARYTRANSFER, true); curl_setopt($curl, CURLOPT_INFILE, $this->fileHandler); curl_setopt($curl, CURLOPT_READFUNCTION, array(&$this, 'readFileCallback')); } else if ($this->body != '') { $filePointer = fopen('php://temp/maxmemory:256000', 'w'); if (! $filePointer) { throw new ObjectStorage_Exception('could not open temp memory data'); } fwrite($filePointer, $this->body); fseek($filePointer, 0); curl_setopt($curl, CURLOPT_BINARYTRANSFER, true); curl_setopt($curl, CURLOPT_INFILE, $filePointer); curl_setopt($curl, CURLOPT_INFILESIZE, strlen($this->body)); } } $rawResponse = curl_exec($curl); if ($rawResponse === false) { throw new ObjectStorage_Exception(curl_error($curl)); } $curlInfo = curl_getinfo($curl); $rawHeaders = substr($rawResponse, 0, $curlInfo['header_size']); $headers = array(); if ($rawHeaders != '') { $headerLines = explode("\n", $rawHeaders); foreach ($headerLines as $line) { $headerChunk = explode(': ', $line); if (count($headerChunk) == 2) { $headers[ucfirst(strtolower($headerChunk[0]))] = trim($headerChunk[1]); } } } $body = substr($rawResponse, $curlInfo['header_size']); $statusCode = $curlInfo['http_code']; curl_close($curl); $response = new ObjectStorage_Http_Response(); $response->setStatusCode($statusCode); $response->setHeaders($headers); $response->setBody($body); return $response; } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::getLastRequestHeaders() */ public function getLastRequestHeaders() { return $this->requestHeaders; } protected function readFileCallback($curl, $fileHandler, $length = 1000) { $data = fread($fileHandler, $length); $len = strlen($data); return $data; } }timeout = $options['timeout']; } } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::setUri() */ public function setUri($uri) { $this->uri = $uri; } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::setHeaders() */ public function setHeaders($name, $value) { $this->headers[$name] = $name . ': ' . $value; } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::setBody() */ public function setBody($body) { $this->body = $body; } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::setFileHandler() */ public function setFileHandler($handler) { $this->fileHander = $handler; } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::setMethod() */ public function setMethod($method) { $this->method = $method; } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::reset() */ public function reset() { $this->headers = array(); $this->body = ''; $this->method = ''; return true; } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::request() */ public function request() { $urlInfo = parse_url($this->uri); if (! isset($urlInfo['port'])) { $urlInfo['port'] = $urlInfo['scheme'] == 'https' ? 443 : 80; } $scheme = $urlInfo['scheme'] == 'https' ? 'ssl://' : ''; if (($socket = @fsockopen($scheme . $urlInfo['host'], $urlInfo['port'], $errno, $errstr, $this->timeout)) == false) { throw new ObjectStorage_Exception($errstr); } stream_set_timeout($socket, 0, $this->timeout * 1000); $statusCode = 0; $this->requestHeaders = array(); $lineBreak = "\r\n"; $doubleLineBreaks = $lineBreak . $lineBreak; $requestData = $responseData = ''; $this->requestHeaders[] = $this->method . ' ' . $urlInfo['path'] . (isset($urlInfo['query']) ? '?' . $urlInfo['query'] : '') . ' HTTP/1.1'; $this->requestHeaders[] = 'Host: ' . $urlInfo['host']; $this->requestHeaders[] = 'Connection: Close'; if (count($this->headers) > 0) { $this->requestHeaders = array_merge($this->requestHeaders, $this->headers); } $requestData = implode($lineBreak, $this->requestHeaders) . $doubleLineBreaks; fputs($socket, $requestData); if (in_array($this->method, array('PUT', 'POST'))) { if (is_resource($this->fileHander)) { $fseek = 0; // Used for debugging purposes $readSize = 1024; while (! feof($this->fileHander)) { $contents = fread($this->fileHander, $readSize); if (@fwrite($socket, $contents) === false) { throw new ObjectStorage_Exception('Failed to write data to socket when writing about ' . $fseek . ' bytes.'); } $fseek += $readSize; } fclose($this->fileHander); } else if ($this->body != '') { fputs($socket, $this->body); } } while(!feof($socket)) { $responseData .= fgets($socket, 128); } fclose($socket); $headerEndingPosition = strpos($responseData, $doubleLineBreaks); $rawHeaders = substr($responseData, 0, $headerEndingPosition); $headers = array(); if ($rawHeaders != '') { $headerLines = explode("\n", $rawHeaders); $isFirst = true; foreach ($headerLines as $line) { if ($isFirst == true) { $statusChunks = explode(' ', $line); $statusCode = (int) $statusChunks[1]; $isFirst = false; } $headerChunk = explode(': ', $line); if (count($headerChunk) == 2) { $headers[ucfirst(strtolower($headerChunk[0]))] = trim($headerChunk[1]); } } } $body = substr($responseData, $headerEndingPosition + strlen($doubleLineBreaks)); $response = new ObjectStorage_Http_Response(); $response->setStatusCode($statusCode); $response->setHeaders($headers); $response->setBody($body); return $response; } public function getLastRequestHeaders() { return $this->requestHeaders; } }client = new Zend_Http_Client(); if (isset($options['timeout']) && is_numeric($options['timeout'])) { $this->timeout = $options['timeout']; } } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::setUri() */ public function setUri($uri) { $this->client->setUri($uri); } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::setHeaders() */ public function setHeaders($name, $value) { $this->headers[$name] = $name . ': ' . $value; $this->client->setHeaders($name, $value); } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::setBody() */ public function setBody($body) { $this->client->setRawData($body); } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::setFileHandler() */ public function setFileHandler($handler) { $requiredVersion = '1.10'; if (Zend_Version::compareVersion($requiredVersion) >= 1) { throw new ObjectStorage_Exception('Zend HTTP clien\'s data streaming upload requires Zend framework version ' . $requiredVersion . ' or greater.'); } $this->client->setRawData($handler); } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::setMethod() */ public function setMethod($method) { $this->client->setMethod($method); } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::reset() */ public function reset() { if (count($this->headers) > 0) { foreach ($this->headers as $key => $val) { $this->client->setHeaders($key, null); } } $this->headers = array(); $this->client->resetParameters(); return true; } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::request() */ public function request() { $this->requestHeaders = $this->headers; $this->client->setConfig(array('timeout', $this->timeout)); $result = $this->client->request(); $response = new ObjectStorage_Http_Response(); $response->setStatusCode($result->getStatus()); $response->setHeaders($result->getHeaders()); $response->setBody($result->getBody()); return $response; } /** * (non-PHPdoc) * @see ObjectStorage_Http_Adapter_Interface::getLastRequestHeaders() */ public function getLastRequestHeaders() { return $this->requestHeaders; } }statusCode; } /** * Sets HTTP status code * * @param int $statusCode */ public function setStatusCode($statusCode) { if (! is_int($statusCode)) { throw new ObjectStorage_Exception('HTTP status code must be an integer.'); } $this->statusCode = $statusCode; } }request->getHeader('Content-Length') == null || $this->request->getHeader('Content-Length') == 0) { $this->request->setHeader('Content-Length', strlen($this->request->getBody())); } return parent::create(); } /** * (non-PHPdoc) * @see ObjectStorage_Abstract::update() */ public function update() { $headers = $this->request->getHeaders(); if (count($headers) > 0) { foreach ($headers as $key => $value) { if (in_array(strtoupper($key), self::$skipOverwriteHeaders)) { $this->request->deleteHeader($key); } } } $this->request->setHeader('Content-Length', strlen($this->request->getBody())); return parent::update(); } /** * Removes CDN cache. This method is only applicable to objects in CDN enabled containers * * @return bool */ public function purgeCache() { $this->setContext(self::CONTEXT_CDN); try { $this->request->setHeader('X-Cdn-Purge', 'true'); $this->objectStorage->update($this); } catch (Exception $e) { $this->objectStorage->reloadAuthenticationData(); $this->objectStorage->update($this); } return true; } /** * Load object to CDN. This method is only applicable to objects in CDN enabled containers * * @return bool */ public function loadCache() { $this->setContext(self::CONTEXT_CDN); try { $this->request->setHeader('X-Cdn-Load', 'true'); $this->objectStorage->update($this); } catch (Exception $e) { $this->objectStorage->reloadAuthenticationData(); $this->objectStorage->update($this); } return true; } /** * Returns the path to a local file that you will be used as object content * If you a local file is set, it will proceed the body data set by setBody() method. * * @return string */ public function getLocalFile() { return $this->localFile; } /** * Sets a local file that will be used as object body * If you set the local file, it will proceed the body data set by setBody() method. * * @param string $path * * @return ObjectStorage_Abstract */ public function setLocalFile($path) { $this->localFile = $path; return $this; } /** * Sets a deletion timestamp for an object * Send an $epochTimestamp of "null" to remove the attribute * * @param int $epochTimestamp * * @return ObjectStorage_Abstract */ public function deleteAt($epochTimestamp) { $this->request->setHeader('X-Delete-At', $epochTimestamp); return $this; } /** * Sets the number of seconds to wait before deleting an object * (This is converted into an 'X-Delete-At' header in the container * * @param int $seconds * * @return ObjectStorage_Abstract */ public function deleteAfter($seconds) { $this->request->setHeader('X-Delete-After', $seconds); return $this; } }filePath = $config['path'] . '/objectStorage_key_'; } else { $this->filePath = '/tmp/objectStorage_key_'; } $this->ttl = isset($config['ttl']) && (int) $config['ttl'] > 60 ? (int) $config['ttl'] : 3600; } /** * (non-PHPdoc) * @see ObjectStorage_TokenStore_Interface::get() */ public function get($key) { $filePath = $this->getFilePath($key); if (file_exists($filePath)) { if (! is_readable($filePath)) { throw new ObjectStorage_Exception_TokenStore('Failed to retrieve data from file store.'); } $data = file_get_contents($filePath); $delimiterPosition = strpos($data, self::TIMESTAMP_DELIMITER); $delimiterLength = strlen(self::TIMESTAMP_DELIMITER); $expirationTime = substr($data, 0, $delimiterPosition); if ($expirationTime > time()) { return unserialize(substr($data, $delimiterPosition + $delimiterLength)); } else { $this->delete($key); return null; } } else { return null; } } /** * (non-PHPdoc) * @see ObjectStorage_TokenStore_Interface::set() */ public function set($key, $data) { $filePath = $this->getFilePath($key); $expirationTime = time() + $this->ttl; $result = file_put_contents($filePath, $expirationTime . self::TIMESTAMP_DELIMITER . serialize($data)); if ($result === false || ! is_readable($filePath)) { throw new ObjectStorage_Exception_TokenStore('Failed to set the data to file store.'); } return true; } /** * (non-PHPdoc) * @see ObjectStorage_TokenStore_Interface::delete() */ public function delete($key) { $filePath = $this->getFilePath($key); return unlink($filePath); } private function getFilePath($key) { $encryptedKey = str_replace('=', '', sha1($key)); return $this->filePath . substr($encryptedKey, 0, 64); } }data[$key])) { return unserialize($this->data[$key]); } return null; } /** * (non-PHPdoc) * @see ObjectStorage_TokenStore_Interface::set() */ public function set($key, $data) { $this->data[$key] = serialize($data); return true; } /** * (non-PHPdoc) * @see ObjectStorage_TokenStore_Interface::delete() */ public function delete($key) { if (isset($this->data[$key])) { unset($this->data[$key]); } return true; } } * $tokenStore = ObjectStorage_TokenStore::factory('file', array('ttl' => 3600, 'path' => '/tmp/objectStorage')); * ObjectStorage::setTokenStore($tokenStore); * * $objectStorageDallas = new ObjectStorage($objectStorageHost01, $username01, $password01); * * * @param string $type * @param array $config * * @throws ObjectStorage_Exception_TokenStore * * @return ObjectStorage_TokenStore_Interface */ public static function factory($type, $config = array()) { switch(strtoupper($type)) { case 'FILE': return new ObjectStorage_TokenStore_File($config); case 'MEMORY': return new ObjectStorage_TokenStore_Memory($config); default: throw new ObjectStorage_Exception_TokenStore("Token store type '{$type}' is not implemented."); } } } = 5.3.0 $mimeTypes = array( 'ai' => 'application/postscript', 'atom' => 'application/atom+xml', 'avi' => 'video/x-msvideo', 'bin' => 'application/octet-stream', 'bmp' => 'image/bmp', 'cab' => 'application/vnd.ms-cab-compressed', 'css' => 'text/css', 'dmg' => 'application/octet-stream', 'doc' => 'application/msword', 'dtd' => 'application/xml-dtd', 'eps' => 'application/postscript', 'exe' => 'application/x-msdownload', 'flv' => 'video/x-flv', 'gif' => 'image/gif', 'htm' => 'text/html', 'html' => 'text/html', 'ico' => 'image/vnd.microsoft.icon', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'js' => 'application/javascript', 'json' => 'application/json', 'mov' => 'video/quicktime', 'mp3' => 'audio/mpeg', 'mp4' => 'video/mp4', 'msi' => 'application/x-msdownload', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', 'odt' => 'application/vnd.oasis.opendocument.text', 'pdf' => 'application/pdf', 'php' => 'text/html', 'png' => 'image/png', 'ppt' => 'application/vnd.ms-powerpoint', 'ps' => 'application/postscript', 'psd' => 'image/vnd.adobe.photoshop', 'qt' => 'video/quicktime', 'rar' => 'application/x-rar-compressed', 'rtf' => 'application/rtf', 'svg' => 'image/svg+xml', 'svgz' => 'image/svg+xml', 'swf' => 'application/x-shockwave-flash', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'txt' => 'text/plain', 'xls' => 'application/vnd.ms-excel', 'xml' => 'application/xml', 'zip' => 'application/zip' ); $chunks = explode('.', $fileName); $extension = ''; if (count($chunks) > 1) { $extension = array_pop($chunks); } if ($extension == '') { return 'application/directory'; } else if (isset($mimeTypes[$extension])) { return $mimeTypes[$extension]; } else if (function_exists('mime_content_type')) { return mime_content_type($fileName); } else { return 'application/octet-stream'; } } } * $options = array('adapter' => ObjectStorage_Http_Client::CURL, 'timeout' => 10); * * $objectStorageDallas = new ObjectStorage($objectStorageHost01, $username01, $password01, $options); * * $objectStorageSeattle = new ObjectStorage($objectStorageHost02, $username02, $password02, $options); * * * @param string $objectStorageHost * @param string $username * @param string $password * @param array $options * * @throws ObjectStorage_Exception_Authentication */ public function __construct($objectStorageHost = null, $username = null, $password = null, $options = array()) { if ($objectStorageHost == null || $username == null || $password == null) { throw new ObjectStorage_Exception_Authentication('You must provide ObjectStorage host, username and password.'); } $this->objectStorageHost = $objectStorageHost; $this->username = $username; $this->password = $password; if (isset($options['adapter']) && ObjectStorage_Http_Client::validateAdapter($options['adapter'])) { $this->httpClientAdapterIdendifier = $options['adapter']; } else { $this->httpClientAdapterIdendifier = ObjectStorage_Http_Client::CURL; } if (isset($options['timeout'])) { $this->httpClientAdapterTimeout = $options['timeout']; } } /** * Returns an object with ObjectStorage URL and authentication token * * @return ObjectStorage_AuthData */ public function getAuthenticationData() { if ($this->objectStorageAuthData != null) { return $this->objectStorageAuthData; } $cacheKey = $this->getAuthenticationCacheKey(); $authData = self::getTokenStore()->get($cacheKey); if ($authData == null) { $response = $this->authenticate(); $authData = new ObjectStorage_AuthData(); $authData->objectStorageUrl = $response->getHeader('X-storage-url'); $authData->authToken = $response->getHeader('X-auth-token'); $this->objectStorageAuthData = $authData; self::getTokenStore()->set($cacheKey, $authData); } else { $this->objectStorageAuthData = $authData; } return $this->objectStorageAuthData; } protected function getAuthenticationCacheKey() { return $this->objectStorageHost . $this->username; } /** * Sets the persistent ObjectStorage authentication token storage * * * // ObjectStorage auth token can be reused in subsequent requests instead of each request attempts to authenticate again and again. * $tokenStore = ObjectStorage_TokenStore::factory('file', array('ttl' => 3600, 'path' => '/tmp/objectStorage')); * ObjectStorage::setTokenStore($tokenStore); * * $options = array('adapter' => ObjectStorage_Http_Client::CURL, 'timeout' => 10); * $objectStorageDallas = new ObjectStorage($objectStorageHost, $username, $password, $options); * * * @param ObjectStorage_TokenStore_Interface $tokenStore */ public static function setTokenStore(ObjectStorage_TokenStore_Interface $tokenStore) { self::$tokenStore = $tokenStore; } protected static function getTokenStore() { if (! self::$tokenStore instanceof ObjectStorage_TokenStore_Interface) { self::$tokenStore = ObjectStorage_TokenStore::factory('memory'); } return self::$tokenStore; } /** * Returns authentication token and ObjectStorage account URL * * @return ObjectStorage_Http_Response */ protected function authenticate() { $client = $this->getHttpClient(); $client->setUri($this->objectStorageHost . '/auth/v1.0'); $client->setHeaders('X-Auth-User', $this->username); $client->setHeaders('X-Auth-Key', $this->password); $client->setMethod('GET'); try { $response = $client->request(); } catch (Exception $e) { throw new ObjectStorage_Exception_Authentication($e->getMessage()); } if ($this->isAcceptableResponse($response->getStatusCode())) { return $response; } else { throw ObjectStorage_Exception_Http::factory(null, $response->getStatusCode()); } } /** * ObjectStorage object stores an authentication token in a Token Store if configured. * If you changed your ObjectStorage password and you need to delete the old token, use this method to remove the cached token. * * @return boolean */ public function reloadAuthenticationData() { $cacheKey = $this->getAuthenticationCacheKey(); $response = $this->authenticate(); $authData = new stdClass(); $authData->objectStorageUrl = $response->getHeader('X-storage-url'); $authData->authToken = $response->getHeader('X-auth-token'); $this->objectStorageAuthData = $authData; self::getTokenStore()->set($cacheKey, $authData); return true; } protected function getHttpClient() { if (! isset($this->httpClient)) { $this->httpClient = ObjectStorage_Http_Client::factory($this->httpClientAdapterIdendifier, array('timeout' => $this->httpClientAdapterTimeout)); } // Remove previous request headers and other trails $this->httpClient->reset(); return $this->httpClient; } /** * Returns an instance of a ObjectStorage_Abstract sub-class which can be ObjectStorage_Container or ObjectStorage_Object. * A ObjectStorage_Abstract instance returned from this method will have the link to the ObjectStorage object. * * @see ObjectStorage_Abstract * * @param string $path * * @return ObjectStorage_Abstract */ public function with($path) { return $this->getResponseWrapper($path); } protected function getResponseWrapper($path) { $path = trim($path, '/'); list($container, $object) = $this->parseUri($path); if ($object != null) { return new ObjectStorage_Object($path, $this); } else { return new ObjectStorage_Container($path, $this); } } protected function parseUri($path) { $fragments = explode('/', $path); $fragCount = count($fragments); if ($fragCount >= 1) { $container = array_shift($fragments); return array($container, implode('/', $fragments)); } else if ($fragCount == 1) { return array($fragments[0], null); } else { return array('/', null); } } /** * Returns a ObjectStorage container or an object. * You will less likely use this method directly from ObjectStorage object. This method is used by ObjectStorage_Abstract object. * * @param ObjectStorage_Abstract $objectStorageObject * @param bool $retrieveBody * * @return ObjectStorage_Abstract */ public function get(ObjectStorage_Abstract $objectStorageObject, $retrieveBody = true) { $authData = $this->getAuthenticationData(); $client = $this->getHttpClient(); $client->setHeaders('X-Auth-Token', $authData->authToken); $httpMethod = $retrieveBody == true ? 'GET' : 'HEAD'; $client->setMethod($httpMethod); $uri = $authData->objectStorageUrl . '/' . rawurlencode(ltrim($objectStorageObject->getPath(), '/')); $queryParams = array(); if ($objectStorageObject->marker != '') { $queryParams[] = 'marker=' . urlencode($objectStorageObject->marker); } if (count($objectStorageObject->queryString) > 0) { foreach ($objectStorageObject->queryString as $key => $value) { $queryParams[] = $key . '=' . urlencode($value); } } if ($objectStorageObject->limit) { $queryParams[] = 'limit=' . urlencode($objectStorageObject->limit); } if ($objectStorageObject->getContext() == ObjectStorage_Abstract::CONTEXT_SEARCH && count($objectStorageObject->searchFilters) > 0) { foreach ($objectStorageObject->searchFilters as $key => $val) { $queryParams[] = urlencode($key) . '=' . urlencode($val); } } if (count($queryParams) > 0) { $uri .= '?' . implode('&', $queryParams); } $client->setUri($uri); $headers = $objectStorageObject->getRequest()->getHeaders(); if (count($headers) > 0) { foreach ($headers as $key => $value) { $client->setHeaders($key, $value); } } $response = $client->request(); if ($this->isAcceptableResponse($response->getStatusCode())) { $objectStorageObject->setResponse($response); return $objectStorageObject; } else { throw ObjectStorage_Exception_Http::factory('Failed to retrieve "' . $objectStorageObject->getPath() . '".', $response->getStatusCode()); } } /** * Returns ObjectStorage user list and cluster information in JSON format. * This will only work with users with admin privileges. * * @return string json data * * @throws ObjectStorage_Exception_Http */ public function getClusterInfo() { $client = $this->getHttpClient(); $client->setMethod('GET'); list($account, $username) = explode(':', $this->username); $client->setUri($this->objectStorageHost . '/auth/v2/' . $account); $client->setHeaders('X-Auth-Admin-User', $this->username); $client->setHeaders('X-Auth-Admin-Key', $this->password); try { $response = $client->request(); } catch (Exception $e) { throw ObjectStorage_Exception_Http::factory('Failed to retrieve users.'); } if ($this->isAcceptableResponse($response->getStatusCode())) { return $response->getBody(); } else { throw ObjectStorage_Exception_Http::factory('Failed to retrieve users.', $response->getStatusCode()); } } /** * Adds an Object Storage user. Only works with administrative privileges. * * @param string $username * @param string $password * @param bool $isAdminUser Indicates if the new user is an admin or not * * @return bool * * @throws ObjectStorage_Exception_Http */ public function addUser($username, $password, $isAdminUser = false) { $newUsername = trim($username); $password = trim($password); if (empty($newUsername)) { throw new ObjectStorage_Exception('Username cannot be empty.'); } if (empty($password)) { throw new ObjectStorage_Exception('Password cannot be empty.'); } $client = $this->getHttpClient(); $client->setMethod('PUT'); list($account, $username) = explode(':', $this->username); $client->setUri($this->objectStorageHost . '/auth/v2/' . $account . '/' . $newUsername); $client->setHeaders('X-Auth-Admin-User', $this->username); $client->setHeaders('X-Auth-Admin-Key', $this->password); $client->setHeaders('X-Auth-User-Key', $password); if ($isAdminUser == true) { $client->setHeaders('X-Auth-User-Admin', 'true'); } try { $response = $client->request(); } catch (Exception $e) { throw ObjectStorage_Exception_Http::factory('Failed to create user.'); } if ($this->isAcceptableResponse($response->getStatusCode())) { return true; } else { throw ObjectStorage_Exception_Http::factory('Failed to create user.', $response->getStatusCode()); } } /** * Deletes an Object Storage user * * @param string $username * * @return bool * * @throws ObjectStorage_Exception_Http */ public function deleteUser($username) { $existingUsername = trim($username); if (empty($existingUsername)) { throw new ObjectStorage_Exception('Username cannot be empty.'); } $client = $this->getHttpClient(); $client->setMethod('DELETE'); list($account, $username) = explode(':', $this->username); $client->setUri($this->objectStorageHost . '/auth/v2/' . $account . '/' . $existingUsername); $client->setHeaders('X-Auth-Admin-User', $this->username); $client->setHeaders('X-Auth-Admin-Key', $this->password); try { $response = $client->request(); } catch (Exception $e) { throw ObjectStorage_Exception_Http::factory('Failed to delete user.'); } if ($this->isAcceptableResponse($response->getStatusCode())) { return true; } else { throw ObjectStorage_Exception_Http::factory('Failed to delete user.', $response->getStatusCode()); } } /** * Returns ObjectStorage URL. * You will less likely use this method directly from ObjectStorage object. This method is used by ObjectStorage_Abstract object. * * @param string */ public function getUrl(ObjectStorage_Abstract $objectStorageObject) { $authData = $this->getAuthenticationData(); return $authData->objectStorageUrl . '/' . ltrim($objectStorageObject->getPath(), '/'); } /** * Returns ObjectStorage CDN URLs. * You will less likely use this method directly from ObjectStorage object. This method is used by ObjectStorage_Abstract object. * * @param array */ public function getCdnUrls(ObjectStorage_Abstract $objectStorageObject) { $authData = $this->getAuthenticationData(); $cdnUrls = array(); $headers = $objectStorageObject->getHeaders(); if (count($headers) == 0 || $objectStorageObject->getContext() != ObjectStorage_Abstract::CONTEXT_CDN) { $authData = $this->getAuthenticationData(); $client = $this->getHttpClient(); $client->setHeaders('X-Auth-Token', $authData->authToken); $client->setHeaders('X-Context', 'cdn'); $client->setMethod('HEAD'); $client->setUri($authData->objectStorageUrl . '/' . rawurlencode(ltrim($objectStorageObject->getPath(), '/'))); $response = $client->request(); if ($this->isAcceptableResponse($response->getStatusCode())) { $objectStorageObject->setResponse($response); } else { throw ObjectStorage_Exception_Http::factory('Failed to retrieve "' . $objectStorageObject->getPath() . '".', $response->getStatusCode()); } } $path = '/' . ltrim($objectStorageObject->getPath(), '/'); foreach ($objectStorageObject->getResponse()->getHeaders() as $key => $val) { if (in_array(strtoupper($key), array('X-CDN-URL', 'X-CDN-STREAM-HTTP-URL', 'X-CDN-STREAM-FLASH-URL', 'X-CDN-CUSTOM-URL', 'X-CDN-CUSTOM-STREAM-HTTP-URL', 'X-CDN-CUSTOM-STREAM-FLASH-URL'))) { $cdnUrls[] = $val; } } return $cdnUrls; } /** * Creates a ObjectStorage container or an object * * @param ObjectStorage_Abstract $objectStorageObject * * @return ObjectStorage_Abstract */ public function create(ObjectStorage_Abstract $objectStorageObject) { $authData = $this->getAuthenticationData(); $client = $this->getHttpClient(); $client->setUri($authData->objectStorageUrl . '/' . rawurlencode(ltrim($objectStorageObject->getPath(), '/'))); $client->setHeaders('X-Auth-Token', $authData->authToken); $client->setMethod('PUT'); $request = $objectStorageObject->getRequest(); if ($objectStorageObject instanceof ObjectStorage_Object) { $localFile = $objectStorageObject->getLocalFile(); if ($localFile != '') { if (! is_readable($localFile)) { throw new ObjectStorage_Exception('Local file ' . $localFile . ' is not readable.'); } $fileHander = fopen($localFile, 'r'); if ($fileHander == false) { throw new ObjectStorage_Exception('Failed to open local file ' . $localFile); } $client->setFileHandler($fileHander); // Override the content-length $request->setHeader('Content-Length', filesize($localFile)); } else { $client->setBody($objectStorageObject->getRequest()->getBody()); } if ($request->getHeader('Content-type') == '') { $request->setHeader('Content-type', ObjectStorage_Util::getMimeByName($objectStorageObject->getPath())); } } $headers = $request->getHeaders(); if (count($headers) > 0) { foreach ($headers as $key => $value) { $client->setHeaders($key, $value); } } $response = $client->request(); if ($this->isAcceptableResponse($response->getStatusCode())) { $objectStorageObject->setResponse($response); return $objectStorageObject; } else { throw ObjectStorage_Exception_Http::factory('Failed to create ' . $objectStorageObject . '.', $response->getStatusCode()); } } /** * Modifies a ObjectStorage container or an object * * @param ObjectStorage_Abstract $objectStorageObject * * @return ObjectStorage_Abstract */ public function update(ObjectStorage_Abstract $objectStorageObject) { $authData = $this->getAuthenticationData(); $client = $this->getHttpClient(); $client->setUri($authData->objectStorageUrl . '/' . rawurlencode(ltrim($objectStorageObject->getPath(), '/'))); $client->setHeaders('X-Auth-Token', $authData->authToken); $client->setMethod('POST'); $request = $objectStorageObject->getRequest(); $headers = $request->getHeaders(); if (count($headers) > 0) { foreach ($headers as $key => $value) { $client->setHeaders($key, $value); } } if ($objectStorageObject instanceof ObjectStorage_Object) { $client->setBody($request->getBody()); } $response = $client->request(); if ($this->isAcceptableResponse($response->getStatusCode())) { $objectStorageObject->setResponse($response); return $objectStorageObject; } else { throw ObjectStorage_Exception_Http::factory('Failed to save ' . $objectStorageObject . '. ' . $response->getBody(), $response->getStatusCode()); } } /** * Deletes a ObjectStorage container or an object * * @param ObjectStorage_Abstract $objectStorageObject * * @return bool */ public function delete(ObjectStorage_Abstract $objectStorageObject) { $authData = $this->getAuthenticationData(); $uri = $authData->objectStorageUrl . '/' . rawurlencode($objectStorageObject->getPath()); $queryParams = array(); if (count($objectStorageObject->queryString) > 0) { foreach ($objectStorageObject->queryString as $key => $value) { $queryParams[] = $key . '=' . urlencode($value); } $uri .= '?' . implode('&', $queryParams); } $client = $this->getHttpClient(); $client->setHeaders('X-Auth-Token', $authData->authToken); $client->setMethod('DELETE'); $client->setUri($uri); $response = $client->request(); if ($this->isAcceptableResponse($response->getStatusCode())) { $objectStorageObject->setResponse($response); return true; } else { throw ObjectStorage_Exception_Http::factory(null, $response->getStatusCode()); } } protected function isAcceptableResponse($responseCode = 0) { return intval($responseCode / 200) == 1 ? true : false; } } createDependenciesFor('mime.attachment') ); $this->setBody($data); $this->setFilename($filename); if ($contentType) { $this->setContentType($contentType); } } /** * Create a new Attachment. * * @param string|Swift_OutputByteStream $data * @param string $filename * @param string $contentType * * @return Swift_Mime_Attachment */ public static function newInstance($data = null, $filename = null, $contentType = null) { return new self($data, $filename, $contentType); } /** * Create a new Attachment from a filesystem path. * * @param string $path * @param string $contentType optional * * @return Swift_Mime_Attachment */ public static function fromPath($path, $contentType = null) { return self::newInstance()->setFile( new Swift_ByteStream_FileByteStream($path), $contentType ); } } _filters[$key] = $filter; } /** * Remove an already present StreamFilter based on its $key. * * @param string $key */ public function removeFilter($key) { unset($this->_filters[$key]); } /** * Writes $bytes to the end of the stream. * * @param string $bytes * * @return int * * @throws Swift_IoException */ public function write($bytes) { $this->_writeBuffer .= $bytes; foreach ($this->_filters as $filter) { if ($filter->shouldBuffer($this->_writeBuffer)) { return; } } $this->_doWrite($this->_writeBuffer); return ++$this->_sequence; } /** * For any bytes that are currently buffered inside the stream, force them * off the buffer. * * @throws Swift_IoException */ public function commit() { $this->_doWrite($this->_writeBuffer); } /** * Attach $is to this stream. * * The stream acts as an observer, receiving all data that is written. * All {@link write()} and {@link flushBuffers()} operations will be mirrored. * * @param Swift_InputByteStream $is */ public function bind(Swift_InputByteStream $is) { $this->_mirrors[] = $is; } /** * Remove an already bound stream. * * If $is is not bound, no errors will be raised. * If the stream currently has any buffered data it will be written to $is * before unbinding occurs. * * @param Swift_InputByteStream $is */ public function unbind(Swift_InputByteStream $is) { foreach ($this->_mirrors as $k => $stream) { if ($is === $stream) { if ($this->_writeBuffer !== '') { $stream->write($this->_writeBuffer); } unset($this->_mirrors[$k]); } } } /** * Flush the contents of the stream (empty it) and set the internal pointer * to the beginning. * * @throws Swift_IoException */ public function flushBuffers() { if ($this->_writeBuffer !== '') { $this->_doWrite($this->_writeBuffer); } $this->_flush(); foreach ($this->_mirrors as $stream) { $stream->flushBuffers(); } } /** Run $bytes through all filters */ private function _filter($bytes) { foreach ($this->_filters as $filter) { $bytes = $filter->filter($bytes); } return $bytes; } /** Just write the bytes to the stream */ private function _doWrite($bytes) { $this->_commit($this->_filter($bytes)); foreach ($this->_mirrors as $stream) { $stream->write($bytes); } $this->_writeBuffer = ''; } } _array = $stack; $this->_arraySize = count($stack); } elseif (is_string($stack)) { $this->write($stack); } else { $this->_array = array(); } } /** * Reads $length bytes from the stream into a string and moves the pointer * through the stream by $length. * * If less bytes exist than are requested the * remaining bytes are given instead. If no bytes are remaining at all, boolean * false is returned. * * @param int $length * * @return string */ public function read($length) { if ($this->_offset == $this->_arraySize) { return false; } // Don't use array slice $end = $length + $this->_offset; $end = $this->_arraySize<$end ? $this->_arraySize : $end; $ret = ''; for (; $this->_offset < $end; ++$this->_offset) { $ret .= $this->_array[$this->_offset]; } return $ret; } /** * Writes $bytes to the end of the stream. * * @param string $bytes */ public function write($bytes) { $to_add = str_split($bytes); foreach ($to_add as $value) { $this->_array[] = $value; } $this->_arraySize = count($this->_array); foreach ($this->_mirrors as $stream) { $stream->write($bytes); } } /** * Not used. */ public function commit() { } /** * Attach $is to this stream. * * The stream acts as an observer, receiving all data that is written. * All {@link write()} and {@link flushBuffers()} operations will be mirrored. * * @param Swift_InputByteStream $is */ public function bind(Swift_InputByteStream $is) { $this->_mirrors[] = $is; } /** * Remove an already bound stream. * * If $is is not bound, no errors will be raised. * If the stream currently has any buffered data it will be written to $is * before unbinding occurs. * * @param Swift_InputByteStream $is */ public function unbind(Swift_InputByteStream $is) { foreach ($this->_mirrors as $k => $stream) { if ($is === $stream) { unset($this->_mirrors[$k]); } } } /** * Move the internal read pointer to $byteOffset in the stream. * * @param int $byteOffset * * @return bool */ public function setReadPointer($byteOffset) { if ($byteOffset > $this->_arraySize) { $byteOffset = $this->_arraySize; } elseif ($byteOffset < 0) { $byteOffset = 0; } $this->_offset = $byteOffset; } /** * Flush the contents of the stream (empty it) and set the internal pointer * to the beginning. */ public function flushBuffers() { $this->_offset = 0; $this->_array = array(); $this->_arraySize = 0; foreach ($this->_mirrors as $stream) { $stream->flushBuffers(); } } } _path = $path; $this->_mode = $writable ? 'w+b' : 'rb'; if (function_exists('get_magic_quotes_runtime') && @get_magic_quotes_runtime() == 1) { $this->_quotes = true; } } /** * Get the complete path to the file. * * @return string */ public function getPath() { return $this->_path; } /** * Reads $length bytes from the stream into a string and moves the pointer * through the stream by $length. * * If less bytes exist than are requested the * remaining bytes are given instead. If no bytes are remaining at all, boolean * false is returned. * * @param int $length * * @return string|bool * * @throws Swift_IoException */ public function read($length) { $fp = $this->_getReadHandle(); if (!feof($fp)) { if ($this->_quotes) { ini_set('magic_quotes_runtime', 0); } $bytes = fread($fp, $length); if ($this->_quotes) { ini_set('magic_quotes_runtime', 1); } $this->_offset = ftell($fp); // If we read one byte after reaching the end of the file // feof() will return false and an empty string is returned if ($bytes === '' && feof($fp)) { $this->_resetReadHandle(); return false; } return $bytes; } $this->_resetReadHandle(); return false; } /** * Move the internal read pointer to $byteOffset in the stream. * * @param int $byteOffset * * @return bool */ public function setReadPointer($byteOffset) { if (isset($this->_reader)) { $this->_seekReadStreamToPosition($byteOffset); } $this->_offset = $byteOffset; } /** Just write the bytes to the file */ protected function _commit($bytes) { fwrite($this->_getWriteHandle(), $bytes); $this->_resetReadHandle(); } /** Not used */ protected function _flush() { } /** Get the resource for reading */ private function _getReadHandle() { if (!isset($this->_reader)) { if (!$this->_reader = fopen($this->_path, 'rb')) { throw new Swift_IoException( 'Unable to open file for reading ['.$this->_path.']' ); } if ($this->_offset != 0) { $this->_getReadStreamSeekableStatus(); $this->_seekReadStreamToPosition($this->_offset); } } return $this->_reader; } /** Get the resource for writing */ private function _getWriteHandle() { if (!isset($this->_writer)) { if (!$this->_writer = fopen($this->_path, $this->_mode)) { throw new Swift_IoException( 'Unable to open file for writing ['.$this->_path.']' ); } } return $this->_writer; } /** Force a reload of the resource for reading */ private function _resetReadHandle() { if (isset($this->_reader)) { fclose($this->_reader); $this->_reader = null; } } /** Check if ReadOnly Stream is seekable */ private function _getReadStreamSeekableStatus() { $metas = stream_get_meta_data($this->_reader); $this->_seekable = $metas['seekable']; } /** Streams in a readOnly stream ensuring copy if needed */ private function _seekReadStreamToPosition($offset) { if ($this->_seekable === null) { $this->_getReadStreamSeekableStatus(); } if ($this->_seekable === false) { $currentPos = ftell($this->_reader); if ($currentPos<$offset) { $toDiscard = $offset-$currentPos; fread($this->_reader, $toDiscard); return; } $this->_copyReadStream(); } fseek($this->_reader, $offset, SEEK_SET); } /** Copy a readOnly Stream to ensure seekability */ private function _copyReadStream() { if ($tmpFile = fopen('php://temp/maxmemory:4096', 'w+b')) { /* We have opened a php:// Stream Should work without problem */ } elseif (function_exists('sys_get_temp_dir') && is_writable(sys_get_temp_dir()) && ($tmpFile = tmpfile())) { /* We have opened a tmpfile */ } else { throw new Swift_IoException('Unable to copy the file to make it seekable, sys_temp_dir is not writable, php://memory not available'); } $currentPos = ftell($this->_reader); fclose($this->_reader); $source = fopen($this->_path, 'rb'); if (!$source) { throw new Swift_IoException('Unable to open file for copying ['.$this->_path.']'); } fseek($tmpFile, 0, SEEK_SET); while (!feof($source)) { fwrite($tmpFile, fread($source, 4096)); } fseek($tmpFile, $currentPos, SEEK_SET); fclose($source); $this->_reader = $tmpFile; } } getPath())) === false) { throw new Swift_IoException('Failed to get temporary file content.'); } return $content; } public function __destruct() { if (file_exists($this->getPath())) { @unlink($this->getPath()); } } } */ class Swift_CharacterReader_GenericFixedWidthReader implements Swift_CharacterReader { /** * The number of bytes in a single character. * * @var int */ private $_width; /** * Creates a new GenericFixedWidthReader using $width bytes per character. * * @param int $width */ public function __construct($width) { $this->_width = $width; } /** * Returns the complete character map. * * @param string $string * @param int $startOffset * @param array $currentMap * @param mixed $ignoredChars * * @return int */ public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars) { $strlen = strlen($string); // % and / are CPU intensive, so, maybe find a better way $ignored = $strlen % $this->_width; $ignoredChars = substr($string, - $ignored); $currentMap = $this->_width; return ($strlen - $ignored) / $this->_width; } /** * Returns the mapType. * * @return int */ public function getMapType() { return self::MAP_TYPE_FIXED_LEN; } /** * Returns an integer which specifies how many more bytes to read. * * A positive integer indicates the number of more bytes to fetch before invoking * this method again. * * A value of zero means this is already a valid character. * A value of -1 means this cannot possibly be a valid character. * * @param string $bytes * @param int $size * * @return int */ public function validateByteSequence($bytes, $size) { $needed = $this->_width - $size; return ($needed > -1) ? $needed : -1; } /** * Returns the number of bytes which should be read to start each character. * * @return int */ public function getInitialByteSize() { return $this->_width; } } "\x07F") { // Invalid char $currentMap[$i+$startOffset] = $string[$i]; } } return $strlen; } /** * Returns mapType * * @return int mapType */ public function getMapType() { return self::MAP_TYPE_INVALID; } /** * Returns an integer which specifies how many more bytes to read. * * A positive integer indicates the number of more bytes to fetch before invoking * this method again. * A value of zero means this is already a valid character. * A value of -1 means this cannot possibly be a valid character. * * @param string $bytes * @param int $size * * @return int */ public function validateByteSequence($bytes, $size) { $byte = reset($bytes); if (1 == count($bytes) && $byte >= 0x00 && $byte <= 0x7F) { return 0; } else { return -1; } } /** * Returns the number of bytes which should be read to start each character. * * @return int */ public function getInitialByteSize() { return 1; } } */ class Swift_CharacterReader_Utf8Reader implements Swift_CharacterReader { /** Pre-computed for optimization */ private static $length_map = array( // N=0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x0N 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1N 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x2N 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3N 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x4N 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5N 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x6N 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7N 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x8N 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9N 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xAN 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBN 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xCN 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDN 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEN 4,4,4,4,4,4,4,4,5,5,5,5,6,6,0,0, // 0xFN ); private static $s_length_map = array( "\x00" => 1, "\x01" => 1, "\x02" => 1, "\x03" => 1, "\x04" => 1, "\x05" => 1, "\x06" => 1, "\x07" => 1, "\x08" => 1, "\x09" => 1, "\x0a" => 1, "\x0b" => 1, "\x0c" => 1, "\x0d" => 1, "\x0e" => 1, "\x0f" => 1, "\x10" => 1, "\x11" => 1, "\x12" => 1, "\x13" => 1, "\x14" => 1, "\x15" => 1, "\x16" => 1, "\x17" => 1, "\x18" => 1, "\x19" => 1, "\x1a" => 1, "\x1b" => 1, "\x1c" => 1, "\x1d" => 1, "\x1e" => 1, "\x1f" => 1, "\x20" => 1, "\x21" => 1, "\x22" => 1, "\x23" => 1, "\x24" => 1, "\x25" => 1, "\x26" => 1, "\x27" => 1, "\x28" => 1, "\x29" => 1, "\x2a" => 1, "\x2b" => 1, "\x2c" => 1, "\x2d" => 1, "\x2e" => 1, "\x2f" => 1, "\x30" => 1, "\x31" => 1, "\x32" => 1, "\x33" => 1, "\x34" => 1, "\x35" => 1, "\x36" => 1, "\x37" => 1, "\x38" => 1, "\x39" => 1, "\x3a" => 1, "\x3b" => 1, "\x3c" => 1, "\x3d" => 1, "\x3e" => 1, "\x3f" => 1, "\x40" => 1, "\x41" => 1, "\x42" => 1, "\x43" => 1, "\x44" => 1, "\x45" => 1, "\x46" => 1, "\x47" => 1, "\x48" => 1, "\x49" => 1, "\x4a" => 1, "\x4b" => 1, "\x4c" => 1, "\x4d" => 1, "\x4e" => 1, "\x4f" => 1, "\x50" => 1, "\x51" => 1, "\x52" => 1, "\x53" => 1, "\x54" => 1, "\x55" => 1, "\x56" => 1, "\x57" => 1, "\x58" => 1, "\x59" => 1, "\x5a" => 1, "\x5b" => 1, "\x5c" => 1, "\x5d" => 1, "\x5e" => 1, "\x5f" => 1, "\x60" => 1, "\x61" => 1, "\x62" => 1, "\x63" => 1, "\x64" => 1, "\x65" => 1, "\x66" => 1, "\x67" => 1, "\x68" => 1, "\x69" => 1, "\x6a" => 1, "\x6b" => 1, "\x6c" => 1, "\x6d" => 1, "\x6e" => 1, "\x6f" => 1, "\x70" => 1, "\x71" => 1, "\x72" => 1, "\x73" => 1, "\x74" => 1, "\x75" => 1, "\x76" => 1, "\x77" => 1, "\x78" => 1, "\x79" => 1, "\x7a" => 1, "\x7b" => 1, "\x7c" => 1, "\x7d" => 1, "\x7e" => 1, "\x7f" => 1, "\x80" => 0, "\x81" => 0, "\x82" => 0, "\x83" => 0, "\x84" => 0, "\x85" => 0, "\x86" => 0, "\x87" => 0, "\x88" => 0, "\x89" => 0, "\x8a" => 0, "\x8b" => 0, "\x8c" => 0, "\x8d" => 0, "\x8e" => 0, "\x8f" => 0, "\x90" => 0, "\x91" => 0, "\x92" => 0, "\x93" => 0, "\x94" => 0, "\x95" => 0, "\x96" => 0, "\x97" => 0, "\x98" => 0, "\x99" => 0, "\x9a" => 0, "\x9b" => 0, "\x9c" => 0, "\x9d" => 0, "\x9e" => 0, "\x9f" => 0, "\xa0" => 0, "\xa1" => 0, "\xa2" => 0, "\xa3" => 0, "\xa4" => 0, "\xa5" => 0, "\xa6" => 0, "\xa7" => 0, "\xa8" => 0, "\xa9" => 0, "\xaa" => 0, "\xab" => 0, "\xac" => 0, "\xad" => 0, "\xae" => 0, "\xaf" => 0, "\xb0" => 0, "\xb1" => 0, "\xb2" => 0, "\xb3" => 0, "\xb4" => 0, "\xb5" => 0, "\xb6" => 0, "\xb7" => 0, "\xb8" => 0, "\xb9" => 0, "\xba" => 0, "\xbb" => 0, "\xbc" => 0, "\xbd" => 0, "\xbe" => 0, "\xbf" => 0, "\xc0" => 2, "\xc1" => 2, "\xc2" => 2, "\xc3" => 2, "\xc4" => 2, "\xc5" => 2, "\xc6" => 2, "\xc7" => 2, "\xc8" => 2, "\xc9" => 2, "\xca" => 2, "\xcb" => 2, "\xcc" => 2, "\xcd" => 2, "\xce" => 2, "\xcf" => 2, "\xd0" => 2, "\xd1" => 2, "\xd2" => 2, "\xd3" => 2, "\xd4" => 2, "\xd5" => 2, "\xd6" => 2, "\xd7" => 2, "\xd8" => 2, "\xd9" => 2, "\xda" => 2, "\xdb" => 2, "\xdc" => 2, "\xdd" => 2, "\xde" => 2, "\xdf" => 2, "\xe0" => 3, "\xe1" => 3, "\xe2" => 3, "\xe3" => 3, "\xe4" => 3, "\xe5" => 3, "\xe6" => 3, "\xe7" => 3, "\xe8" => 3, "\xe9" => 3, "\xea" => 3, "\xeb" => 3, "\xec" => 3, "\xed" => 3, "\xee" => 3, "\xef" => 3, "\xf0" => 4, "\xf1" => 4, "\xf2" => 4, "\xf3" => 4, "\xf4" => 4, "\xf5" => 4, "\xf6" => 4, "\xf7" => 4, "\xf8" => 5, "\xf9" => 5, "\xfa" => 5, "\xfb" => 5, "\xfc" => 6, "\xfd" => 6, "\xfe" => 0, "\xff" => 0, ); /** * Returns the complete character map. * * @param string $string * @param int $startOffset * @param array $currentMap * @param mixed $ignoredChars * * @return int */ public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars) { if (!isset($currentMap['i']) || ! isset($currentMap['p'])) { $currentMap['p'] = $currentMap['i'] = array(); } $strlen = strlen($string); $charPos = count($currentMap['p']); $foundChars = 0; $invalid = false; for ($i = 0; $i < $strlen; ++$i) { $char = $string[$i]; $size = self::$s_length_map[$char]; if ($size == 0) { /* char is invalid, we must wait for a resync */ $invalid = true; continue; } else { if ($invalid == true) { /* We mark the chars as invalid and start a new char */ $currentMap['p'][$charPos + $foundChars] = $startOffset + $i; $currentMap['i'][$charPos + $foundChars] = true; ++$foundChars; $invalid = false; } if (($i + $size) > $strlen) { $ignoredChars = substr($string, $i); break; } for ($j = 1; $j < $size; ++$j) { $char = $string[$i + $j]; if ($char > "\x7F" && $char < "\xC0") { // Valid - continue parsing } else { /* char is invalid, we must wait for a resync */ $invalid = true; continue 2; } } /* Ok we got a complete char here */ $currentMap['p'][$charPos + $foundChars] = $startOffset + $i + $size; $i += $j - 1; ++$foundChars; } } return $foundChars; } /** * Returns mapType. * * @return int mapType */ public function getMapType() { return self::MAP_TYPE_POSITIONS; } /** * Returns an integer which specifies how many more bytes to read. * * A positive integer indicates the number of more bytes to fetch before invoking * this method again. * A value of zero means this is already a valid character. * A value of -1 means this cannot possibly be a valid character. * * @param string $bytes * @param int $size * * @return int */ public function validateByteSequence($bytes, $size) { if ($size<1) { return -1; } $needed = self::$length_map[$bytes[0]] - $size; return ($needed > -1) ? $needed : -1 ; } /** * Returns the number of bytes which should be read to start each character. * * @return int */ public function getInitialByteSize() { return 1; } } */ interface Swift_CharacterReader { const MAP_TYPE_INVALID = 0x01; const MAP_TYPE_FIXED_LEN = 0x02; const MAP_TYPE_POSITIONS = 0x03; /** * Returns the complete character map * * @param string $string * @param int $startOffset * @param array $currentMap * @param mixed $ignoredChars * * @return int */ public function getCharPositions($string, $startOffset, &$currentMap, &$ignoredChars); /** * Returns the mapType, see constants. * * @return int */ public function getMapType(); /** * Returns an integer which specifies how many more bytes to read. * * A positive integer indicates the number of more bytes to fetch before invoking * this method again. * * A value of zero means this is already a valid character. * A value of -1 means this cannot possibly be a valid character. * * @param integer[] $bytes * @param int $size * * @return int */ public function validateByteSequence($bytes, $size); /** * Returns the number of bytes which should be read to start each character. * * For fixed width character sets this should be the number of octets-per-character. * For multibyte character sets this will probably be 1. * * @return int */ public function getInitialByteSize(); } init(); } public function __wakeup() { $this->init(); } public function init() { if (count(self::$_map) > 0) { return; } $prefix = 'Swift_CharacterReader_'; $singleByte = array( 'class' => $prefix.'GenericFixedWidthReader', 'constructor' => array(1), ); $doubleByte = array( 'class' => $prefix.'GenericFixedWidthReader', 'constructor' => array(2), ); $fourBytes = array( 'class' => $prefix.'GenericFixedWidthReader', 'constructor' => array(4), ); // Utf-8 self::$_map['utf-?8'] = array( 'class' => $prefix.'Utf8Reader', 'constructor' => array(), ); //7-8 bit charsets self::$_map['(us-)?ascii'] = $singleByte; self::$_map['(iso|iec)-?8859-?[0-9]+'] = $singleByte; self::$_map['windows-?125[0-9]'] = $singleByte; self::$_map['cp-?[0-9]+'] = $singleByte; self::$_map['ansi'] = $singleByte; self::$_map['macintosh'] = $singleByte; self::$_map['koi-?7'] = $singleByte; self::$_map['koi-?8-?.+'] = $singleByte; self::$_map['mik'] = $singleByte; self::$_map['(cork|t1)'] = $singleByte; self::$_map['v?iscii'] = $singleByte; //16 bits self::$_map['(ucs-?2|utf-?16)'] = $doubleByte; //32 bits self::$_map['(ucs-?4|utf-?32)'] = $fourBytes; // Fallback self::$_map['.*'] = $singleByte; } /** * Returns a CharacterReader suitable for the charset applied. * * @param string $charset * * @return Swift_CharacterReader */ public function getReaderFor($charset) { $charset = trim(strtolower($charset)); foreach (self::$_map as $pattern => $spec) { $re = '/^'.$pattern.'$/D'; if (preg_match($re, $charset)) { if (!array_key_exists($pattern, self::$_loaded)) { $reflector = new ReflectionClass($spec['class']); if ($reflector->getConstructor()) { $reader = $reflector->newInstanceArgs($spec['constructor']); } else { $reader = $reflector->newInstance(); } self::$_loaded[$pattern] = $reader; } return self::$_loaded[$pattern]; } } } } setCharacterReaderFactory($factory); $this->setCharacterSet($charset); } /** * Set the character set used in this CharacterStream. * * @param string $charset */ public function setCharacterSet($charset) { $this->_charset = $charset; $this->_charReader = null; } /** * Set the CharacterReaderFactory for multi charset support. * * @param Swift_CharacterReaderFactory $factory */ public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory) { $this->_charReaderFactory = $factory; } /** * Overwrite this character stream using the byte sequence in the byte stream. * * @param Swift_OutputByteStream $os output stream to read from */ public function importByteStream(Swift_OutputByteStream $os) { if (!isset($this->_charReader)) { $this->_charReader = $this->_charReaderFactory ->getReaderFor($this->_charset); } $startLength = $this->_charReader->getInitialByteSize(); while (false !== $bytes = $os->read($startLength)) { $c = array(); for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) { $c[] = self::$_byteMap[$bytes[$i]]; } $size = count($c); $need = $this->_charReader ->validateByteSequence($c, $size); if ($need > 0 && false !== $bytes = $os->read($need)) { for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) { $c[] = self::$_byteMap[$bytes[$i]]; } } $this->_array[] = $c; ++$this->_array_size; } } /** * Import a string a bytes into this CharacterStream, overwriting any existing * data in the stream. * * @param string $string */ public function importString($string) { $this->flushContents(); $this->write($string); } /** * Read $length characters from the stream and move the internal pointer * $length further into the stream. * * @param int $length * * @return string */ public function read($length) { if ($this->_offset == $this->_array_size) { return false; } // Don't use array slice $arrays = array(); $end = $length + $this->_offset; for ($i = $this->_offset; $i < $end; ++$i) { if (!isset($this->_array[$i])) { break; } $arrays[] = $this->_array[$i]; } $this->_offset += $i - $this->_offset; // Limit function calls $chars = false; foreach ($arrays as $array) { $chars .= implode('', array_map('chr', $array)); } return $chars; } /** * Read $length characters from the stream and return a 1-dimensional array * containing there octet values. * * @param int $length * * @return integer[] */ public function readBytes($length) { if ($this->_offset == $this->_array_size) { return false; } $arrays = array(); $end = $length + $this->_offset; for ($i = $this->_offset; $i < $end; ++$i) { if (!isset($this->_array[$i])) { break; } $arrays[] = $this->_array[$i]; } $this->_offset += ($i - $this->_offset); // Limit function calls return call_user_func_array('array_merge', $arrays); } /** * Write $chars to the end of the stream. * * @param string $chars */ public function write($chars) { if (!isset($this->_charReader)) { $this->_charReader = $this->_charReaderFactory->getReaderFor( $this->_charset); } $startLength = $this->_charReader->getInitialByteSize(); $fp = fopen('php://memory', 'w+b'); fwrite($fp, $chars); unset($chars); fseek($fp, 0, SEEK_SET); $buffer = array(0); $buf_pos = 1; $buf_len = 1; $has_datas = true; do { $bytes = array(); // Buffer Filing if ($buf_len - $buf_pos < $startLength) { $buf = array_splice($buffer, $buf_pos); $new = $this->_reloadBuffer($fp, 100); if ($new) { $buffer = array_merge($buf, $new); $buf_len = count($buffer); $buf_pos = 0; } else { $has_datas = false; } } if ($buf_len - $buf_pos > 0) { $size = 0; for ($i = 0; $i < $startLength && isset($buffer[$buf_pos]); ++$i) { ++$size; $bytes[] = $buffer[$buf_pos++]; } $need = $this->_charReader->validateByteSequence( $bytes, $size); if ($need > 0) { if ($buf_len - $buf_pos < $need) { $new = $this->_reloadBuffer($fp, $need); if ($new) { $buffer = array_merge($buffer, $new); $buf_len = count($buffer); } } for ($i = 0; $i < $need && isset($buffer[$buf_pos]); ++$i) { $bytes[] = $buffer[$buf_pos++]; } } $this->_array[] = $bytes; ++$this->_array_size; } } while ($has_datas); fclose($fp); } /** * Move the internal pointer to $charOffset in the stream. * * @param int $charOffset */ public function setPointer($charOffset) { if ($charOffset > $this->_array_size) { $charOffset = $this->_array_size; } elseif ($charOffset < 0) { $charOffset = 0; } $this->_offset = $charOffset; } /** * Empty the stream and reset the internal pointer. */ public function flushContents() { $this->_offset = 0; $this->_array = array(); $this->_array_size = 0; } private function _reloadBuffer($fp, $len) { if (!feof($fp) && ($bytes = fread($fp, $len)) !== false) { $buf = array(); for ($i = 0, $len = strlen($bytes); $i < $len; ++$i) { $buf[] = self::$_byteMap[$bytes[$i]]; } return $buf; } return false; } private static function _initializeMaps() { if (!isset(self::$_charMap)) { self::$_charMap = array(); for ($byte = 0; $byte < 256; ++$byte) { self::$_charMap[$byte] = chr($byte); } self::$_byteMap = array_flip(self::$_charMap); } } } */ class Swift_CharacterStream_NgCharacterStream implements Swift_CharacterStream { /** * The char reader (lazy-loaded) for the current charset. * * @var Swift_CharacterReader */ private $_charReader; /** * A factory for creating CharacterReader instances. * * @var Swift_CharacterReaderFactory */ private $_charReaderFactory; /** * The character set this stream is using. * * @var string */ private $_charset; /** * The data's stored as-is. * * @var string */ private $_datas = ''; /** * Number of bytes in the stream * * @var int */ private $_datasSize = 0; /** * Map. * * @var mixed */ private $_map; /** * Map Type. * * @var int */ private $_mapType = 0; /** * Number of characters in the stream. * * @var int */ private $_charCount = 0; /** * Position in the stream. * * @var int */ private $_currentPos = 0; /** * Constructor. * * @param Swift_CharacterReaderFactory $factory * @param string $charset */ public function __construct(Swift_CharacterReaderFactory $factory, $charset) { $this->setCharacterReaderFactory($factory); $this->setCharacterSet($charset); } /* -- Changing parameters of the stream -- */ /** * Set the character set used in this CharacterStream. * * @param string $charset */ public function setCharacterSet($charset) { $this->_charset = $charset; $this->_charReader = null; $this->_mapType = 0; } /** * Set the CharacterReaderFactory for multi charset support. * * @param Swift_CharacterReaderFactory $factory */ public function setCharacterReaderFactory(Swift_CharacterReaderFactory $factory) { $this->_charReaderFactory = $factory; } /** * @see Swift_CharacterStream::flushContents() */ public function flushContents() { $this->_datas = null; $this->_map = null; $this->_charCount = 0; $this->_currentPos = 0; $this->_datasSize = 0; } /** * @see Swift_CharacterStream::importByteStream() * * @param Swift_OutputByteStream $os */ public function importByteStream(Swift_OutputByteStream $os) { $this->flushContents(); $blocks = 512; $os->setReadPointer(0); while (false !== ($read = $os->read($blocks))) { $this->write($read); } } /** * @see Swift_CharacterStream::importString() * * @param string $string */ public function importString($string) { $this->flushContents(); $this->write($string); } /** * @see Swift_CharacterStream::read() * * @param int $length * * @return string */ public function read($length) { if ($this->_currentPos >= $this->_charCount) { return false; } $ret = false; $length = ($this->_currentPos+$length > $this->_charCount) ? $this->_charCount - $this->_currentPos : $length; switch ($this->_mapType) { case Swift_CharacterReader::MAP_TYPE_FIXED_LEN: $len = $length*$this->_map; $ret = substr($this->_datas, $this->_currentPos * $this->_map, $len); $this->_currentPos += $length; break; case Swift_CharacterReader::MAP_TYPE_INVALID: $end = $this->_currentPos + $length; $end = $end > $this->_charCount ? $this->_charCount : $end; $ret = ''; for (; $this->_currentPos < $length; ++$this->_currentPos) { if (isset ($this->_map[$this->_currentPos])) { $ret .= '?'; } else { $ret .= $this->_datas[$this->_currentPos]; } } break; case Swift_CharacterReader::MAP_TYPE_POSITIONS: $end = $this->_currentPos + $length; $end = $end > $this->_charCount ? $this->_charCount : $end; $ret = ''; $start = 0; if ($this->_currentPos>0) { $start = $this->_map['p'][$this->_currentPos-1]; } $to = $start; for (; $this->_currentPos < $end; ++$this->_currentPos) { if (isset($this->_map['i'][$this->_currentPos])) { $ret .= substr($this->_datas, $start, $to - $start).'?'; $start = $this->_map['p'][$this->_currentPos]; } else { $to = $this->_map['p'][$this->_currentPos]; } } $ret .= substr($this->_datas, $start, $to - $start); break; } return $ret; } /** * @see Swift_CharacterStream::readBytes() * * @param int $length * * @return integer[] */ public function readBytes($length) { $read = $this->read($length); if ($read !== false) { $ret = array_map('ord', str_split($read, 1)); return $ret; } return false; } /** * @see Swift_CharacterStream::setPointer() * * @param int $charOffset */ public function setPointer($charOffset) { if ($this->_charCount<$charOffset) { $charOffset = $this->_charCount; } $this->_currentPos = $charOffset; } /** * @see Swift_CharacterStream::write() * * @param string $chars */ public function write($chars) { if (!isset($this->_charReader)) { $this->_charReader = $this->_charReaderFactory->getReaderFor( $this->_charset); $this->_map = array(); $this->_mapType = $this->_charReader->getMapType(); } $ignored = ''; $this->_datas .= $chars; $this->_charCount += $this->_charReader->getCharPositions(substr($this->_datas, $this->_datasSize), $this->_datasSize, $this->_map, $ignored); if ($ignored !== false) { $this->_datasSize = strlen($this->_datas)-strlen($ignored); } else { $this->_datasSize = strlen($this->_datas); } } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Base class for Spools (implements time and message limits). * * @author Fabien Potencier */ abstract class Swift_ConfigurableSpool implements Swift_Spool { /** The maximum number of messages to send per flush */ private $_message_limit; /** The time limit per flush */ private $_time_limit; /** * Sets the maximum number of messages to send per flush. * * @param int $limit */ public function setMessageLimit($limit) { $this->_message_limit = (int) $limit; } /** * Gets the maximum number of messages to send per flush. * * @return int The limit */ public function getMessageLimit() { return $this->_message_limit; } /** * Sets the time limit (in seconds) per flush. * * @param int $limit The limit */ public function setTimeLimit($limit) { $this->_time_limit = (int) $limit; } /** * Gets the time limit (in seconds) per flush. * * @return int The limit */ public function getTimeLimit() { return $this->_time_limit; } } _store); } /** * Test if an item is registered in this container with the given name. * * @see register() * * @param string $itemName * * @return bool */ public function has($itemName) { return array_key_exists($itemName, $this->_store) && isset($this->_store[$itemName]['lookupType']); } /** * Lookup the item with the given $itemName. * * @see register() * * @param string $itemName * * @return mixed * * @throws Swift_DependencyException If the dependency is not found */ public function lookup($itemName) { if (!$this->has($itemName)) { throw new Swift_DependencyException( 'Cannot lookup dependency "'.$itemName.'" since it is not registered.' ); } switch ($this->_store[$itemName]['lookupType']) { case self::TYPE_ALIAS: return $this->_createAlias($itemName); case self::TYPE_VALUE: return $this->_getValue($itemName); case self::TYPE_INSTANCE: return $this->_createNewInstance($itemName); case self::TYPE_SHARED: return $this->_createSharedInstance($itemName); } } /** * Create an array of arguments passed to the constructor of $itemName. * * @param string $itemName * * @return array */ public function createDependenciesFor($itemName) { $args = array(); if (isset($this->_store[$itemName]['args'])) { $args = $this->_resolveArgs($this->_store[$itemName]['args']); } return $args; } /** * Register a new dependency with $itemName. * * This method returns the current DependencyContainer instance because it * requires the use of the fluid interface to set the specific details for the * dependency. * @see asNewInstanceOf(), asSharedInstanceOf(), asValue() * * @param string $itemName * * @return Swift_DependencyContainer */ public function register($itemName) { $this->_store[$itemName] = array(); $this->_endPoint = & $this->_store[$itemName]; return $this; } /** * Specify the previously registered item as a literal value. * * {@link register()} must be called before this will work. * * @param mixed $value * * @return Swift_DependencyContainer */ public function asValue($value) { $endPoint = & $this->_getEndPoint(); $endPoint['lookupType'] = self::TYPE_VALUE; $endPoint['value'] = $value; return $this; } /** * Specify the previously registered item as an alias of another item. * * @param string $lookup * * @return Swift_DependencyContainer */ public function asAliasOf($lookup) { $endPoint = & $this->_getEndPoint(); $endPoint['lookupType'] = self::TYPE_ALIAS; $endPoint['ref'] = $lookup; return $this; } /** * Specify the previously registered item as a new instance of $className. * * {@link register()} must be called before this will work. * Any arguments can be set with {@link withDependencies()}, * {@link addConstructorValue()} or {@link addConstructorLookup()}. * * @see withDependencies(), addConstructorValue(), addConstructorLookup() * * @param string $className * * @return Swift_DependencyContainer */ public function asNewInstanceOf($className) { $endPoint = & $this->_getEndPoint(); $endPoint['lookupType'] = self::TYPE_INSTANCE; $endPoint['className'] = $className; return $this; } /** * Specify the previously registered item as a shared instance of $className. * * {@link register()} must be called before this will work. * * @param string $className * * @return Swift_DependencyContainer */ public function asSharedInstanceOf($className) { $endPoint = & $this->_getEndPoint(); $endPoint['lookupType'] = self::TYPE_SHARED; $endPoint['className'] = $className; return $this; } /** * Specify a list of injected dependencies for the previously registered item. * * This method takes an array of lookup names. * * @see addConstructorValue(), addConstructorLookup() * * @param array $lookups * * @return Swift_DependencyContainer */ public function withDependencies(array $lookups) { $endPoint = & $this->_getEndPoint(); $endPoint['args'] = array(); foreach ($lookups as $lookup) { $this->addConstructorLookup($lookup); } return $this; } /** * Specify a literal (non looked up) value for the constructor of the * previously registered item. * * @see withDependencies(), addConstructorLookup() * * @param mixed $value * * @return Swift_DependencyContainer */ public function addConstructorValue($value) { $endPoint = & $this->_getEndPoint(); if (!isset($endPoint['args'])) { $endPoint['args'] = array(); } $endPoint['args'][] = array('type' => 'value', 'item' => $value); return $this; } /** * Specify a dependency lookup for the constructor of the previously * registered item. * * @see withDependencies(), addConstructorValue() * * @param string $lookup * * @return Swift_DependencyContainer */ public function addConstructorLookup($lookup) { $endPoint = & $this->_getEndPoint(); if (!isset($this->_endPoint['args'])) { $endPoint['args'] = array(); } $endPoint['args'][] = array('type' => 'lookup', 'item' => $lookup); return $this; } /** Get the literal value with $itemName */ private function _getValue($itemName) { return $this->_store[$itemName]['value']; } /** Resolve an alias to another item */ private function _createAlias($itemName) { return $this->lookup($this->_store[$itemName]['ref']); } /** Create a fresh instance of $itemName */ private function _createNewInstance($itemName) { $reflector = new ReflectionClass($this->_store[$itemName]['className']); if ($reflector->getConstructor()) { return $reflector->newInstanceArgs( $this->createDependenciesFor($itemName) ); } else { return $reflector->newInstance(); } } /** Create and register a shared instance of $itemName */ private function _createSharedInstance($itemName) { if (!isset($this->_store[$itemName]['instance'])) { $this->_store[$itemName]['instance'] = $this->_createNewInstance($itemName); } return $this->_store[$itemName]['instance']; } /** Get the current endpoint in the store */ private function &_getEndPoint() { if (!isset($this->_endPoint)) { throw new BadMethodCallException( 'Component must first be registered by calling register()' ); } return $this->_endPoint; } /** Get an argument list with dependencies resolved */ private function _resolveArgs(array $args) { $resolved = array(); foreach ($args as $argDefinition) { switch ($argDefinition['type']) { case 'lookup': $resolved[] = $this->_lookupRecursive($argDefinition['item']); break; case 'value': $resolved[] = $argDefinition['item']; break; } } return $resolved; } /** Resolve a single dependency with an collections */ private function _lookupRecursive($item) { if (is_array($item)) { $collection = array(); foreach ($item as $k => $v) { $collection[$k] = $this->_lookupRecursive($v); } return $collection; } else { return $this->lookup($item); } } } createDependenciesFor('mime.embeddedfile') ); $this->setBody($data); $this->setFilename($filename); if ($contentType) { $this->setContentType($contentType); } } /** * Create a new EmbeddedFile. * * @param string|Swift_OutputByteStream $data * @param string $filename * @param string $contentType * * @return Swift_Mime_EmbeddedFile */ public static function newInstance($data = null, $filename = null, $contentType = null) { return new self($data, $filename, $contentType); } /** * Create a new EmbeddedFile from a filesystem path. * * @param string $path * * @return Swift_Mime_EmbeddedFile */ public static function fromPath($path) { return self::newInstance()->setFile( new Swift_ByteStream_FileByteStream($path) ); } } = $maxLineLength || 76 < $maxLineLength) { $maxLineLength = 76; } $encodedString = base64_encode($string); $firstLine = ''; if (0 != $firstLineOffset) { $firstLine = substr( $encodedString, 0, $maxLineLength - $firstLineOffset )."\r\n"; $encodedString = substr( $encodedString, $maxLineLength - $firstLineOffset ); } return $firstLine.trim(chunk_split($encodedString, $maxLineLength, "\r\n")); } /** * Does nothing. */ public function charsetChanged($charset) { } } '=00', 1 => '=01', 2 => '=02', 3 => '=03', 4 => '=04', 5 => '=05', 6 => '=06', 7 => '=07', 8 => '=08', 9 => '=09', 10 => '=0A', 11 => '=0B', 12 => '=0C', 13 => '=0D', 14 => '=0E', 15 => '=0F', 16 => '=10', 17 => '=11', 18 => '=12', 19 => '=13', 20 => '=14', 21 => '=15', 22 => '=16', 23 => '=17', 24 => '=18', 25 => '=19', 26 => '=1A', 27 => '=1B', 28 => '=1C', 29 => '=1D', 30 => '=1E', 31 => '=1F', 32 => '=20', 33 => '=21', 34 => '=22', 35 => '=23', 36 => '=24', 37 => '=25', 38 => '=26', 39 => '=27', 40 => '=28', 41 => '=29', 42 => '=2A', 43 => '=2B', 44 => '=2C', 45 => '=2D', 46 => '=2E', 47 => '=2F', 48 => '=30', 49 => '=31', 50 => '=32', 51 => '=33', 52 => '=34', 53 => '=35', 54 => '=36', 55 => '=37', 56 => '=38', 57 => '=39', 58 => '=3A', 59 => '=3B', 60 => '=3C', 61 => '=3D', 62 => '=3E', 63 => '=3F', 64 => '=40', 65 => '=41', 66 => '=42', 67 => '=43', 68 => '=44', 69 => '=45', 70 => '=46', 71 => '=47', 72 => '=48', 73 => '=49', 74 => '=4A', 75 => '=4B', 76 => '=4C', 77 => '=4D', 78 => '=4E', 79 => '=4F', 80 => '=50', 81 => '=51', 82 => '=52', 83 => '=53', 84 => '=54', 85 => '=55', 86 => '=56', 87 => '=57', 88 => '=58', 89 => '=59', 90 => '=5A', 91 => '=5B', 92 => '=5C', 93 => '=5D', 94 => '=5E', 95 => '=5F', 96 => '=60', 97 => '=61', 98 => '=62', 99 => '=63', 100 => '=64', 101 => '=65', 102 => '=66', 103 => '=67', 104 => '=68', 105 => '=69', 106 => '=6A', 107 => '=6B', 108 => '=6C', 109 => '=6D', 110 => '=6E', 111 => '=6F', 112 => '=70', 113 => '=71', 114 => '=72', 115 => '=73', 116 => '=74', 117 => '=75', 118 => '=76', 119 => '=77', 120 => '=78', 121 => '=79', 122 => '=7A', 123 => '=7B', 124 => '=7C', 125 => '=7D', 126 => '=7E', 127 => '=7F', 128 => '=80', 129 => '=81', 130 => '=82', 131 => '=83', 132 => '=84', 133 => '=85', 134 => '=86', 135 => '=87', 136 => '=88', 137 => '=89', 138 => '=8A', 139 => '=8B', 140 => '=8C', 141 => '=8D', 142 => '=8E', 143 => '=8F', 144 => '=90', 145 => '=91', 146 => '=92', 147 => '=93', 148 => '=94', 149 => '=95', 150 => '=96', 151 => '=97', 152 => '=98', 153 => '=99', 154 => '=9A', 155 => '=9B', 156 => '=9C', 157 => '=9D', 158 => '=9E', 159 => '=9F', 160 => '=A0', 161 => '=A1', 162 => '=A2', 163 => '=A3', 164 => '=A4', 165 => '=A5', 166 => '=A6', 167 => '=A7', 168 => '=A8', 169 => '=A9', 170 => '=AA', 171 => '=AB', 172 => '=AC', 173 => '=AD', 174 => '=AE', 175 => '=AF', 176 => '=B0', 177 => '=B1', 178 => '=B2', 179 => '=B3', 180 => '=B4', 181 => '=B5', 182 => '=B6', 183 => '=B7', 184 => '=B8', 185 => '=B9', 186 => '=BA', 187 => '=BB', 188 => '=BC', 189 => '=BD', 190 => '=BE', 191 => '=BF', 192 => '=C0', 193 => '=C1', 194 => '=C2', 195 => '=C3', 196 => '=C4', 197 => '=C5', 198 => '=C6', 199 => '=C7', 200 => '=C8', 201 => '=C9', 202 => '=CA', 203 => '=CB', 204 => '=CC', 205 => '=CD', 206 => '=CE', 207 => '=CF', 208 => '=D0', 209 => '=D1', 210 => '=D2', 211 => '=D3', 212 => '=D4', 213 => '=D5', 214 => '=D6', 215 => '=D7', 216 => '=D8', 217 => '=D9', 218 => '=DA', 219 => '=DB', 220 => '=DC', 221 => '=DD', 222 => '=DE', 223 => '=DF', 224 => '=E0', 225 => '=E1', 226 => '=E2', 227 => '=E3', 228 => '=E4', 229 => '=E5', 230 => '=E6', 231 => '=E7', 232 => '=E8', 233 => '=E9', 234 => '=EA', 235 => '=EB', 236 => '=EC', 237 => '=ED', 238 => '=EE', 239 => '=EF', 240 => '=F0', 241 => '=F1', 242 => '=F2', 243 => '=F3', 244 => '=F4', 245 => '=F5', 246 => '=F6', 247 => '=F7', 248 => '=F8', 249 => '=F9', 250 => '=FA', 251 => '=FB', 252 => '=FC', 253 => '=FD', 254 => '=FE', 255 => '=FF', ); protected static $_safeMapShare = array(); /** * A map of non-encoded ascii characters. * * @var string[] */ protected $_safeMap = array(); /** * Creates a new QpEncoder for the given CharacterStream. * * @param Swift_CharacterStream $charStream to use for reading characters * @param Swift_StreamFilter $filter if input should be canonicalized */ public function __construct(Swift_CharacterStream $charStream, Swift_StreamFilter $filter = null) { $this->_charStream = $charStream; if (!isset(self::$_safeMapShare[$this->getSafeMapShareId()])) { $this->initSafeMap(); self::$_safeMapShare[$this->getSafeMapShareId()] = $this->_safeMap; } else { $this->_safeMap = self::$_safeMapShare[$this->getSafeMapShareId()]; } $this->_filter = $filter; } public function __sleep() { return array('_charStream', '_filter'); } public function __wakeup() { if (!isset(self::$_safeMapShare[$this->getSafeMapShareId()])) { $this->initSafeMap(); self::$_safeMapShare[$this->getSafeMapShareId()] = $this->_safeMap; } else { $this->_safeMap = self::$_safeMapShare[$this->getSafeMapShareId()]; } } protected function getSafeMapShareId() { return get_class($this); } protected function initSafeMap() { foreach (array_merge( array(0x09, 0x20), range(0x21, 0x3C), range(0x3E, 0x7E)) as $byte) { $this->_safeMap[$byte] = chr($byte); } } /** * Takes an unencoded string and produces a QP encoded string from it. * * QP encoded strings have a maximum line length of 76 characters. * If the first line needs to be shorter, indicate the difference with * $firstLineOffset. * * @param string $string to encode * @param int $firstLineOffset, optional * @param int $maxLineLength, optional 0 indicates the default of 76 chars * * @return string */ public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) { if ($maxLineLength > 76 || $maxLineLength <= 0) { $maxLineLength = 76; } $thisLineLength = $maxLineLength - $firstLineOffset; $lines = array(); $lNo = 0; $lines[$lNo] = ''; $currentLine = & $lines[$lNo++]; $size = $lineLen = 0; $this->_charStream->flushContents(); $this->_charStream->importString($string); // Fetching more than 4 chars at one is slower, as is fetching fewer bytes // Conveniently 4 chars is the UTF-8 safe number since UTF-8 has up to 6 // bytes per char and (6 * 4 * 3 = 72 chars per line) * =NN is 3 bytes while (false !== $bytes = $this->_nextSequence()) { // If we're filtering the input if (isset($this->_filter)) { // If we can't filter because we need more bytes while ($this->_filter->shouldBuffer($bytes)) { // Then collect bytes into the buffer if (false === $moreBytes = $this->_nextSequence(1)) { break; } foreach ($moreBytes as $b) { $bytes[] = $b; } } // And filter them $bytes = $this->_filter->filter($bytes); } $enc = $this->_encodeByteSequence($bytes, $size); if ($currentLine && $lineLen+$size >= $thisLineLength) { $lines[$lNo] = ''; $currentLine = & $lines[$lNo++]; $thisLineLength = $maxLineLength; $lineLen = 0; } $lineLen += $size; $currentLine .= $enc; } return $this->_standardize(implode("=\r\n", $lines)); } /** * Updates the charset used. * * @param string $charset */ public function charsetChanged($charset) { $this->_charStream->setCharacterSet($charset); } /** * Encode the given byte array into a verbatim QP form. * * @param integer[] $bytes * @param int $size * * @return string */ protected function _encodeByteSequence(array $bytes, &$size) { $ret = ''; $size = 0; foreach ($bytes as $b) { if (isset($this->_safeMap[$b])) { $ret .= $this->_safeMap[$b]; ++$size; } else { $ret .= self::$_qpMap[$b]; $size += 3; } } return $ret; } /** * Get the next sequence of bytes to read from the char stream. * * @param int $size number of bytes to read * * @return integer[] */ protected function _nextSequence($size = 4) { return $this->_charStream->readBytes($size); } /** * Make sure CRLF is correct and HT/SPACE are in valid places. * * @param string $string * * @return string */ protected function _standardize($string) { $string = str_replace(array("\t=0D=0A", " =0D=0A", "=0D=0A"), array("=09\r\n", "=20\r\n", "\r\n"), $string ); switch ($end = ord(substr($string, -1))) { case 0x09: case 0x20: $string = substr_replace($string, self::$_qpMap[$end], -1); } return $string; } /** * Make a deep copy of object */ public function __clone() { $this->_charStream = clone $this->_charStream; } } _charStream = $charStream; } /** * Takes an unencoded string and produces a string encoded according to * RFC 2231 from it. * * @param string $string * @param int $firstLineOffset * @param int $maxLineLength optional, 0 indicates the default of 75 bytes * * @return string */ public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) { $lines = array(); $lineCount = 0; $lines[] = ''; $currentLine = & $lines[$lineCount++]; if (0 >= $maxLineLength) { $maxLineLength = 75; } $this->_charStream->flushContents(); $this->_charStream->importString($string); $thisLineLength = $maxLineLength - $firstLineOffset; while (false !== $char = $this->_charStream->read(4)) { $encodedChar = rawurlencode($char); if (0 != strlen($currentLine) && strlen($currentLine.$encodedChar) > $thisLineLength) { $lines[] = ''; $currentLine = & $lines[$lineCount++]; $thisLineLength = $maxLineLength; } $currentLine .= $encodedChar; } return implode("\r\n", $lines); } /** * Updates the charset used. * * @param string $charset */ public function charsetChanged($charset) { $this->_charStream->setCharacterSet($charset); } /** * Make a deep copy of object */ public function __clone() { $this->_charStream = clone $this->_charStream; } } lookup($key); } } _command = $command; $this->_successCodes = $successCodes; } /** * Get the command which was sent to the server. * * @return string */ public function getCommand() { return $this->_command; } /** * Get the numeric response codes which indicate success for this command. * * @return integer[] */ public function getSuccessCodes() { return $this->_successCodes; } } _source = $source; } /** * Get the source object of this event. * * @return object */ public function getSource() { return $this->_source; } /** * Prevent this Event from bubbling any further up the stack. * * @param bool $cancel, optional */ public function cancelBubble($cancel = true) { $this->_bubbleCancelled = $cancel; } /** * Returns true if this Event will not bubble any further up the stack. * * @return bool */ public function bubbleCancelled() { return $this->_bubbleCancelled; } } _response = $response; $this->_valid = $valid; } /** * Get the response which was received from the server. * * @return string */ public function getResponse() { return $this->_response; } /** * Get the success status of this Event. * * @return bool */ public function isValid() { return $this->_valid; } } _message = $message; $this->_result = self::RESULT_PENDING; } /** * Get the Transport used to send the Message. * * @return Swift_Transport */ public function getTransport() { return $this->getSource(); } /** * Get the Message being sent. * * @return Swift_Mime_Message */ public function getMessage() { return $this->_message; } /** * Set the array of addresses that failed in sending. * * @param array $recipients */ public function setFailedRecipients($recipients) { $this->_failedRecipients = $recipients; } /** * Get an recipient addresses which were not accepted for delivery. * * @return string[] */ public function getFailedRecipients() { return $this->_failedRecipients; } /** * Set the result of sending. * * @param int $result */ public function setResult($result) { $this->_result = $result; } /** * Get the result of this Event. * * The return value is a bitmask from * {@see RESULT_PENDING, RESULT_SUCCESS, RESULT_TENTATIVE, RESULT_FAILED} * * @return int */ public function getResult() { return $this->_result; } } _eventMap = array( 'Swift_Events_CommandEvent' => 'Swift_Events_CommandListener', 'Swift_Events_ResponseEvent' => 'Swift_Events_ResponseListener', 'Swift_Events_SendEvent' => 'Swift_Events_SendListener', 'Swift_Events_TransportChangeEvent' => 'Swift_Events_TransportChangeListener', 'Swift_Events_TransportExceptionEvent' => 'Swift_Events_TransportExceptionListener', ); } /** * Create a new SendEvent for $source and $message. * * @param Swift_Transport $source * @param Swift_Mime_Message * * @return Swift_Events_SendEvent */ public function createSendEvent(Swift_Transport $source, Swift_Mime_Message $message) { return new Swift_Events_SendEvent($source, $message); } /** * Create a new CommandEvent for $source and $command. * * @param Swift_Transport $source * @param string $command That will be executed * @param array $successCodes That are needed * * @return Swift_Events_CommandEvent */ public function createCommandEvent(Swift_Transport $source, $command, $successCodes = array()) { return new Swift_Events_CommandEvent($source, $command, $successCodes); } /** * Create a new ResponseEvent for $source and $response. * * @param Swift_Transport $source * @param string $response * @param bool $valid If the response is valid * * @return Swift_Events_ResponseEvent */ public function createResponseEvent(Swift_Transport $source, $response, $valid) { return new Swift_Events_ResponseEvent($source, $response, $valid); } /** * Create a new TransportChangeEvent for $source. * * @param Swift_Transport $source * * @return Swift_Events_TransportChangeEvent */ public function createTransportChangeEvent(Swift_Transport $source) { return new Swift_Events_TransportChangeEvent($source); } /** * Create a new TransportExceptionEvent for $source. * * @param Swift_Transport $source * @param Swift_TransportException $ex * * @return Swift_Events_TransportExceptionEvent */ public function createTransportExceptionEvent(Swift_Transport $source, Swift_TransportException $ex) { return new Swift_Events_TransportExceptionEvent($source, $ex); } /** * Bind an event listener to this dispatcher. * * @param Swift_Events_EventListener $listener */ public function bindEventListener(Swift_Events_EventListener $listener) { foreach ($this->_listeners as $l) { // Already loaded if ($l === $listener) { return; } } $this->_listeners[] = $listener; } /** * Dispatch the given Event to all suitable listeners. * * @param Swift_Events_EventObject $evt * @param string $target method */ public function dispatchEvent(Swift_Events_EventObject $evt, $target) { $this->_prepareBubbleQueue($evt); $this->_bubble($evt, $target); } /** Queue listeners on a stack ready for $evt to be bubbled up it */ private function _prepareBubbleQueue(Swift_Events_EventObject $evt) { $this->_bubbleQueue = array(); $evtClass = get_class($evt); foreach ($this->_listeners as $listener) { if (array_key_exists($evtClass, $this->_eventMap) && ($listener instanceof $this->_eventMap[$evtClass])) { $this->_bubbleQueue[] = $listener; } } } /** Bubble $evt up the stack calling $target() on each listener */ private function _bubble(Swift_Events_EventObject $evt, $target) { if (!$evt->bubbleCancelled() && $listener = array_shift($this->_bubbleQueue)) { $listener->$target($evt); $this->_bubble($evt, $target); } } } getSource(); } } _exception = $ex; } /** * Get the TransportException thrown. * * @return Swift_TransportException */ public function getException() { return $this->_exception; } } createDependenciesFor('transport.failover') ); $this->setTransports($transports); } /** * Create a new FailoverTransport instance. * * @param Swift_Transport[] $transports * * @return Swift_FailoverTransport */ public static function newInstance($transports = array()) { return new self($transports); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Stores Messages on the filesystem. * * @author Fabien Potencier * @author Xavier De Cock */ class Swift_FileSpool extends Swift_ConfigurableSpool { /** The spool directory */ private $_path; /** * File WriteRetry Limit * * @var int */ private $_retryLimit = 10; /** * Create a new FileSpool. * * @param string $path * * @throws Swift_IoException */ public function __construct($path) { $this->_path = $path; if (!file_exists($this->_path)) { if (!mkdir($this->_path, 0777, true)) { throw new Swift_IoException('Unable to create Path ['.$this->_path.']'); } } } /** * Tests if this Spool mechanism has started. * * @return bool */ public function isStarted() { return true; } /** * Starts this Spool mechanism. */ public function start() { } /** * Stops this Spool mechanism. */ public function stop() { } /** * Allow to manage the enqueuing retry limit. * * Default, is ten and allows over 64^20 different fileNames * * @param int $limit */ public function setRetryLimit($limit) { $this->_retryLimit = $limit; } /** * Queues a message. * * @param Swift_Mime_Message $message The message to store * * @return bool * * @throws Swift_IoException */ public function queueMessage(Swift_Mime_Message $message) { $ser = serialize($message); $fileName = $this->_path.'/'.$this->getRandomString(10); for ($i = 0; $i < $this->_retryLimit; ++$i) { /* We try an exclusive creation of the file. This is an atomic operation, it avoid locking mechanism */ $fp = @fopen($fileName.'.message', 'x'); if (false !== $fp) { if (false === fwrite($fp, $ser)) { return false; } return fclose($fp); } else { /* The file already exists, we try a longer fileName */ $fileName .= $this->getRandomString(1); } } throw new Swift_IoException('Unable to create a file for enqueuing Message'); } /** * Execute a recovery if for any reason a process is sending for too long. * * @param int $timeout in second Defaults is for very slow smtp responses */ public function recover($timeout = 900) { foreach (new DirectoryIterator($this->_path) as $file) { $file = $file->getRealPath(); if (substr($file, - 16) == '.message.sending') { $lockedtime = filectime($file); if ((time() - $lockedtime) > $timeout) { rename($file, substr($file, 0, - 8)); } } } } /** * Sends messages using the given transport instance. * * @param Swift_Transport $transport A transport instance * @param string[] $failedRecipients An array of failures by-reference * * @return int The number of sent e-mail's */ public function flushQueue(Swift_Transport $transport, &$failedRecipients = null) { $directoryIterator = new DirectoryIterator($this->_path); /* Start the transport only if there are queued files to send */ if (!$transport->isStarted()) { foreach ($directoryIterator as $file) { if (substr($file->getRealPath(), -8) == '.message') { $transport->start(); break; } } } $failedRecipients = (array) $failedRecipients; $count = 0; $time = time(); foreach ($directoryIterator as $file) { $file = $file->getRealPath(); if (substr($file, -8) != '.message') { continue; } /* We try a rename, it's an atomic operation, and avoid locking the file */ if (rename($file, $file.'.sending')) { $message = unserialize(file_get_contents($file.'.sending')); $count += $transport->send($message, $failedRecipients); unlink($file.'.sending'); } else { /* This message has just been catched by another process */ continue; } if ($this->getMessageLimit() && $count >= $this->getMessageLimit()) { break; } if ($this->getTimeLimit() && (time() - $time) >= $this->getTimeLimit()) { break; } } return $count; } /** * Returns a random string needed to generate a fileName for the queue. * * @param int $count * * @return string */ protected function getRandomString($count) { // This string MUST stay FS safe, avoid special chars $base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-."; $ret = ''; $strlen = strlen($base); for ($i = 0; $i < $count; ++$i) { $ret .= $base[((int) rand(0, $strlen - 1))]; } return $ret; } } setFile( new Swift_ByteStream_FileByteStream($path) ); return $image; } } _stream = $stream; } /** * Set a string into the cache under $itemKey for the namespace $nsKey. * * @see MODE_WRITE, MODE_APPEND * * @param string $nsKey * @param string $itemKey * @param string $string * @param int $mode */ public function setString($nsKey, $itemKey, $string, $mode) { $this->_prepareCache($nsKey); switch ($mode) { case self::MODE_WRITE: $this->_contents[$nsKey][$itemKey] = $string; break; case self::MODE_APPEND: if (!$this->hasKey($nsKey, $itemKey)) { $this->_contents[$nsKey][$itemKey] = ''; } $this->_contents[$nsKey][$itemKey] .= $string; break; default: throw new Swift_SwiftException( 'Invalid mode ['.$mode.'] used to set nsKey='. $nsKey.', itemKey='.$itemKey ); } } /** * Set a ByteStream into the cache under $itemKey for the namespace $nsKey. * * @see MODE_WRITE, MODE_APPEND * * @param string $nsKey * @param string $itemKey * @param Swift_OutputByteStream $os * @param int $mode */ public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode) { $this->_prepareCache($nsKey); switch ($mode) { case self::MODE_WRITE: $this->clearKey($nsKey, $itemKey); case self::MODE_APPEND: if (!$this->hasKey($nsKey, $itemKey)) { $this->_contents[$nsKey][$itemKey] = ''; } while (false !== $bytes = $os->read(8192)) { $this->_contents[$nsKey][$itemKey] .= $bytes; } break; default: throw new Swift_SwiftException( 'Invalid mode ['.$mode.'] used to set nsKey='. $nsKey.', itemKey='.$itemKey ); } } /** * Provides a ByteStream which when written to, writes data to $itemKey. * * NOTE: The stream will always write in append mode. * * @param string $nsKey * @param string $itemKey * @param Swift_InputByteStream $writeThrough * * @return Swift_InputByteStream */ public function getInputByteStream($nsKey, $itemKey, Swift_InputByteStream $writeThrough = null) { $is = clone $this->_stream; $is->setKeyCache($this); $is->setNsKey($nsKey); $is->setItemKey($itemKey); if (isset($writeThrough)) { $is->setWriteThroughStream($writeThrough); } return $is; } /** * Get data back out of the cache as a string. * * @param string $nsKey * @param string $itemKey * * @return string */ public function getString($nsKey, $itemKey) { $this->_prepareCache($nsKey); if ($this->hasKey($nsKey, $itemKey)) { return $this->_contents[$nsKey][$itemKey]; } } /** * Get data back out of the cache as a ByteStream. * * @param string $nsKey * @param string $itemKey * @param Swift_InputByteStream $is to write the data to */ public function exportToByteStream($nsKey, $itemKey, Swift_InputByteStream $is) { $this->_prepareCache($nsKey); $is->write($this->getString($nsKey, $itemKey)); } /** * Check if the given $itemKey exists in the namespace $nsKey. * * @param string $nsKey * @param string $itemKey * * @return bool */ public function hasKey($nsKey, $itemKey) { $this->_prepareCache($nsKey); return array_key_exists($itemKey, $this->_contents[$nsKey]); } /** * Clear data for $itemKey in the namespace $nsKey if it exists. * * @param string $nsKey * @param string $itemKey */ public function clearKey($nsKey, $itemKey) { unset($this->_contents[$nsKey][$itemKey]); } /** * Clear all data in the namespace $nsKey if it exists. * * @param string $nsKey */ public function clearAll($nsKey) { unset($this->_contents[$nsKey]); } /** * Initialize the namespace of $nsKey if needed. * * @param string $nsKey */ private function _prepareCache($nsKey) { if (!array_key_exists($nsKey, $this->_contents)) { $this->_contents[$nsKey] = array(); } } } _stream = $stream; $this->_path = $path; if (function_exists('get_magic_quotes_runtime') && @get_magic_quotes_runtime() == 1) { $this->_quotes = true; } } /** * Set a string into the cache under $itemKey for the namespace $nsKey. * * @see MODE_WRITE, MODE_APPEND * * @param string $nsKey * @param string $itemKey * @param string $string * @param int $mode * * @throws Swift_IoException */ public function setString($nsKey, $itemKey, $string, $mode) { $this->_prepareCache($nsKey); switch ($mode) { case self::MODE_WRITE: $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START); break; case self::MODE_APPEND: $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_END); break; default: throw new Swift_SwiftException( 'Invalid mode ['.$mode.'] used to set nsKey='. $nsKey.', itemKey='.$itemKey ); break; } fwrite($fp, $string); $this->_freeHandle($nsKey, $itemKey); } /** * Set a ByteStream into the cache under $itemKey for the namespace $nsKey. * * @see MODE_WRITE, MODE_APPEND * * @param string $nsKey * @param string $itemKey * @param Swift_OutputByteStream $os * @param int $mode * * @throws Swift_IoException */ public function importFromByteStream($nsKey, $itemKey, Swift_OutputByteStream $os, $mode) { $this->_prepareCache($nsKey); switch ($mode) { case self::MODE_WRITE: $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START); break; case self::MODE_APPEND: $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_END); break; default: throw new Swift_SwiftException( 'Invalid mode ['.$mode.'] used to set nsKey='. $nsKey.', itemKey='.$itemKey ); break; } while (false !== $bytes = $os->read(8192)) { fwrite($fp, $bytes); } $this->_freeHandle($nsKey, $itemKey); } /** * Provides a ByteStream which when written to, writes data to $itemKey. * * NOTE: The stream will always write in append mode. * * @param string $nsKey * @param string $itemKey * @param Swift_InputByteStream $writeThrough * * @return Swift_InputByteStream */ public function getInputByteStream($nsKey, $itemKey, Swift_InputByteStream $writeThrough = null) { $is = clone $this->_stream; $is->setKeyCache($this); $is->setNsKey($nsKey); $is->setItemKey($itemKey); if (isset($writeThrough)) { $is->setWriteThroughStream($writeThrough); } return $is; } /** * Get data back out of the cache as a string. * * @param string $nsKey * @param string $itemKey * * @return string * * @throws Swift_IoException */ public function getString($nsKey, $itemKey) { $this->_prepareCache($nsKey); if ($this->hasKey($nsKey, $itemKey)) { $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START); if ($this->_quotes) { ini_set('magic_quotes_runtime', 0); } $str = ''; while (!feof($fp) && false !== $bytes = fread($fp, 8192)) { $str .= $bytes; } if ($this->_quotes) { ini_set('magic_quotes_runtime', 1); } $this->_freeHandle($nsKey, $itemKey); return $str; } } /** * Get data back out of the cache as a ByteStream. * * @param string $nsKey * @param string $itemKey * @param Swift_InputByteStream $is to write the data to */ public function exportToByteStream($nsKey, $itemKey, Swift_InputByteStream $is) { if ($this->hasKey($nsKey, $itemKey)) { $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_START); if ($this->_quotes) { ini_set('magic_quotes_runtime', 0); } while (!feof($fp) && false !== $bytes = fread($fp, 8192)) { $is->write($bytes); } if ($this->_quotes) { ini_set('magic_quotes_runtime', 1); } $this->_freeHandle($nsKey, $itemKey); } } /** * Check if the given $itemKey exists in the namespace $nsKey. * * @param string $nsKey * @param string $itemKey * * @return bool */ public function hasKey($nsKey, $itemKey) { return is_file($this->_path.'/'.$nsKey.'/'.$itemKey); } /** * Clear data for $itemKey in the namespace $nsKey if it exists. * * @param string $nsKey * @param string $itemKey */ public function clearKey($nsKey, $itemKey) { if ($this->hasKey($nsKey, $itemKey)) { $this->_freeHandle($nsKey, $itemKey); unlink($this->_path.'/'.$nsKey.'/'.$itemKey); } } /** * Clear all data in the namespace $nsKey if it exists. * * @param string $nsKey */ public function clearAll($nsKey) { if (array_key_exists($nsKey, $this->_keys)) { foreach ($this->_keys[$nsKey] as $itemKey => $null) { $this->clearKey($nsKey, $itemKey); } if (is_dir($this->_path.'/'.$nsKey)) { rmdir($this->_path.'/'.$nsKey); } unset($this->_keys[$nsKey]); } } /** * Initialize the namespace of $nsKey if needed. * * @param string $nsKey */ private function _prepareCache($nsKey) { $cacheDir = $this->_path.'/'.$nsKey; if (!is_dir($cacheDir)) { if (!mkdir($cacheDir)) { throw new Swift_IoException('Failed to create cache directory '.$cacheDir); } $this->_keys[$nsKey] = array(); } } /** * Get a file handle on the cache item. * * @param string $nsKey * @param string $itemKey * @param int $position * * @return resource */ private function _getHandle($nsKey, $itemKey, $position) { if (!isset($this->_keys[$nsKey][$itemKey])) { $openMode = $this->hasKey($nsKey, $itemKey) ? 'r+b' : 'w+b' ; $fp = fopen($this->_path.'/'.$nsKey.'/'.$itemKey, $openMode); $this->_keys[$nsKey][$itemKey] = $fp; } if (self::POSITION_START == $position) { fseek($this->_keys[$nsKey][$itemKey], 0, SEEK_SET); } elseif (self::POSITION_END == $position) { fseek($this->_keys[$nsKey][$itemKey], 0, SEEK_END); } return $this->_keys[$nsKey][$itemKey]; } private function _freeHandle($nsKey, $itemKey) { $fp = $this->_getHandle($nsKey, $itemKey, self::POSITION_CURRENT); fclose($fp); $this->_keys[$nsKey][$itemKey] = null; } /** * Destructor. */ public function __destruct() { foreach ($this->_keys as $nsKey => $null) { $this->clearAll($nsKey); } } } _keyCache = $keyCache; } /** * Specify a stream to write through for each write(). * * @param Swift_InputByteStream $is */ public function setWriteThroughStream(Swift_InputByteStream $is) { $this->_writeThrough = $is; } /** * Writes $bytes to the end of the stream. * * @param string $bytes * @param Swift_InputByteStream $is optional */ public function write($bytes, Swift_InputByteStream $is = null) { $this->_keyCache->setString( $this->_nsKey, $this->_itemKey, $bytes, Swift_KeyCache::MODE_APPEND ); if (isset($is)) { $is->write($bytes); } if (isset($this->_writeThrough)) { $this->_writeThrough->write($bytes); } } /** * Not used. */ public function commit() { } /** * Not used. */ public function bind(Swift_InputByteStream $is) { } /** * Not used. */ public function unbind(Swift_InputByteStream $is) { } /** * Flush the contents of the stream (empty it) and set the internal pointer * to the beginning. */ public function flushBuffers() { $this->_keyCache->clearKey($this->_nsKey, $this->_itemKey); } /** * Set the nsKey which will be written to. * * @param string $nsKey */ public function setNsKey($nsKey) { $this->_nsKey = $nsKey; } /** * Set the itemKey which will be written to. * * @param string $itemKey */ public function setItemKey($itemKey) { $this->_itemKey = $itemKey; } /** * Any implementation should be cloneable, allowing the clone to access a * separate $nsKey and $itemKey. */ public function __clone() { $this->_writeThrough = null; } } createDependenciesFor('transport.loadbalanced') ); $this->setTransports($transports); } /** * Create a new LoadBalancedTransport instance. * * @param array $transports * * @return Swift_LoadBalancedTransport */ public static function newInstance($transports = array()) { return new self($transports); } } _recipients = $recipients; } /** * Returns true only if there are more recipients to send to. * * @return bool */ public function hasNext() { return !empty($this->_recipients); } /** * Returns an array where the keys are the addresses of recipients and the * values are the names. e.g. ('foo@bar' => 'Foo') or ('foo@bar' => NULL) * * @return array */ public function nextRecipient() { return array_splice($this->_recipients, 0, 1); } } 'Foo') or ('foo@bar' => NULL) * * @return array */ public function nextRecipient(); } _transport = $transport; } /** * Create a new Mailer instance. * * @param Swift_Transport $transport * * @return Swift_Mailer */ public static function newInstance(Swift_Transport $transport) { return new self($transport); } /** * Create a new class instance of one of the message services. * * For example 'mimepart' would create a 'message.mimepart' instance * * @param string $service * * @return object */ public function createMessage($service = 'message') { return Swift_DependencyContainer::getInstance() ->lookup('message.'.$service); } /** * Send the given Message like it would be sent in a mail client. * * All recipients (with the exception of Bcc) will be able to see the other * recipients this message was sent to. * * Recipient/sender data will be retrieved from the Message object. * * The return value is the number of recipients who were accepted for * delivery. * * @param Swift_Mime_Message $message * @param array $failedRecipients An array of failures by-reference * * @return int */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $failedRecipients = (array) $failedRecipients; if (!$this->_transport->isStarted()) { $this->_transport->start(); } $sent = 0; try { $sent = $this->_transport->send($message, $failedRecipients); } catch (Swift_RfcComplianceException $e) { foreach ($message->getTo() as $address => $name) { $failedRecipients[] = $address; } } return $sent; } /** * Register a plugin using a known unique key (e.g. myPlugin). * * @param Swift_Events_EventListener $plugin */ public function registerPlugin(Swift_Events_EventListener $plugin) { $this->_transport->registerPlugin($plugin); } /** * The Transport used to send messages. * * @return Swift_Transport */ public function getTransport() { return $this->_transport; } } createDependenciesFor('transport.mail') ); $this->setExtraParams($extraParams); } /** * Create a new MailTransport instance. * * @param string $extraParams To be passed to mail() * * @return Swift_MailTransport */ public static function newInstance($extraParams = '-f%s') { return new self($extraParams); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Stores Messages in memory. * * @author Fabien Potencier */ class Swift_MemorySpool implements Swift_Spool { protected $messages = array(); /** * Tests if this Transport mechanism has started. * * @return bool */ public function isStarted() { return true; } /** * Starts this Transport mechanism. */ public function start() { } /** * Stops this Transport mechanism. */ public function stop() { } /** * Stores a message in the queue. * * @param Swift_Mime_Message $message The message to store * * @return bool Whether the operation has succeeded */ public function queueMessage(Swift_Mime_Message $message) { //clone the message to make sure it is not changed while in the queue $this->messages[] = clone $message; return true; } /** * Sends messages using the given transport instance. * * @param Swift_Transport $transport A transport instance * @param string[] $failedRecipients An array of failures by-reference * * @return int The number of sent emails */ public function flushQueue(Swift_Transport $transport, &$failedRecipients = null) { if (!$this->messages) { return 0; } if (!$transport->isStarted()) { $transport->start(); } $count = 0; while ($message = array_pop($this->messages)) { $count += $transport->send($message, $failedRecipients); } return $count; } } createDependenciesFor('mime.message') ); if (!isset($charset)) { $charset = Swift_DependencyContainer::getInstance() ->lookup('properties.charset'); } $this->setSubject($subject); $this->setBody($body); $this->setCharset($charset); if ($contentType) { $this->setContentType($contentType); } } /** * Create a new Message. * * @param string $subject * @param string $body * @param string $contentType * @param string $charset * * @return Swift_Message */ public static function newInstance($subject = null, $body = null, $contentType = null, $charset = null) { return new self($subject, $body, $contentType, $charset); } /** * Add a MimePart to this Message. * * @param string|Swift_OutputByteStream $body * @param string $contentType * @param string $charset * * @return Swift_Mime_SimpleMessage */ public function addPart($body, $contentType = null, $charset = null) { return $this->attach(Swift_MimePart::newInstance( $body, $contentType, $charset )); } /** * Attach a new signature handler to the message. * * @param Swift_Signer $signer * @return Swift_Message */ public function attachSigner(Swift_Signer $signer) { if ($signer instanceof Swift_Signers_HeaderSigner) { $this->headerSigners[] = $signer; } elseif ($signer instanceof Swift_Signers_BodySigner) { $this->bodySigners[] = $signer; } return $this; } /** * Attach a new signature handler to the message. * * @param Swift_Signer $signer * @return Swift_Message */ public function detachSigner(Swift_Signer $signer) { if ($signer instanceof Swift_Signers_HeaderSigner) { foreach ($this->headerSigners as $k => $headerSigner) { if ($headerSigner === $signer) { unset($this->headerSigners[$k]); return $this; } } } elseif ($signer instanceof Swift_Signers_BodySigner) { foreach ($this->bodySigners as $k => $bodySigner) { if ($bodySigner === $signer) { unset($this->bodySigners[$k]); return $this; } } } return $this; } /** * Get this message as a complete string. * * @return string */ public function toString() { if (empty($this->headerSigners) && empty($this->bodySigners)) { return parent::toString(); } $this->saveMessage(); $this->doSign(); $string = parent::toString(); $this->restoreMessage(); return $string; } /** * Write this message to a {@link Swift_InputByteStream}. * * @param Swift_InputByteStream $is */ public function toByteStream(Swift_InputByteStream $is) { if (empty($this->headerSigners) && empty($this->bodySigners)) { parent::toByteStream($is); return; } $this->saveMessage(); $this->doSign(); parent::toByteStream($is); $this->restoreMessage(); } public function __wakeup() { Swift_DependencyContainer::getInstance()->createDependenciesFor('mime.message'); } /** * loops through signers and apply the signatures */ protected function doSign() { foreach ($this->bodySigners as $signer) { $altered = $signer->getAlteredHeaders(); $this->saveHeaders($altered); $signer->signMessage($this); } foreach ($this->headerSigners as $signer) { $altered = $signer->getAlteredHeaders(); $this->saveHeaders($altered); $signer->reset(); $signer->setHeaders($this->getHeaders()); $signer->startBody(); $this->_bodyToByteStream($signer); $signer->endBody(); $signer->addSignature($this->getHeaders()); } } /** * save the message before any signature is applied */ protected function saveMessage() { $this->savedMessage = array('headers' => array()); $this->savedMessage['body'] = $this->getBody(); $this->savedMessage['children'] = $this->getChildren(); if (count($this->savedMessage['children']) > 0 && $this->getBody() != '') { $this->setChildren(array_merge(array($this->_becomeMimePart()), $this->savedMessage['children'])); $this->setBody(''); } } /** * save the original headers * @param array $altered */ protected function saveHeaders(array $altered) { foreach ($altered as $head) { $lc = strtolower($head); if (!isset($this->savedMessage['headers'][$lc])) { $this->savedMessage['headers'][$lc] = $this->getHeaders()->getAll($head); } } } /** * Remove or restore altered headers */ protected function restoreHeaders() { foreach ($this->savedMessage['headers'] as $name => $savedValue) { $headers = $this->getHeaders()->getAll($name); foreach ($headers as $key => $value) { if (!isset($savedValue[$key])) { $this->getHeaders()->remove($name, $key); } } } } /** * Restore message body */ protected function restoreMessage() { $this->setBody($this->savedMessage['body']); $this->setChildren($this->savedMessage['children']); $this->restoreHeaders(); $this->savedMessage = array(); } /** * Clone Message Signers * @see Swift_Mime_SimpleMimeEntity::__clone() */ public function __clone() { parent::__clone(); foreach ($this->bodySigners as $key => $bodySigner) { $this->bodySigners[$key] = clone($bodySigner); } foreach ($this->headerSigners as $key => $headerSigner) { $this->headerSigners[$key] = clone($headerSigner); } } } setDisposition('attachment'); $this->setContentType('application/octet-stream'); $this->_mimeTypes = $mimeTypes; } /** * Get the nesting level used for this attachment. * * Always returns {@link LEVEL_MIXED}. * * @return int */ public function getNestingLevel() { return self::LEVEL_MIXED; } /** * Get the Content-Disposition of this attachment. * * By default attachments have a disposition of "attachment". * * @return string */ public function getDisposition() { return $this->_getHeaderFieldModel('Content-Disposition'); } /** * Set the Content-Disposition of this attachment. * * @param string $disposition * * @return Swift_Mime_Attachment */ public function setDisposition($disposition) { if (!$this->_setHeaderFieldModel('Content-Disposition', $disposition)) { $this->getHeaders()->addParameterizedHeader( 'Content-Disposition', $disposition ); } return $this; } /** * Get the filename of this attachment when downloaded. * * @return string */ public function getFilename() { return $this->_getHeaderParameter('Content-Disposition', 'filename'); } /** * Set the filename of this attachment. * * @param string $filename * * @return Swift_Mime_Attachment */ public function setFilename($filename) { $this->_setHeaderParameter('Content-Disposition', 'filename', $filename); $this->_setHeaderParameter('Content-Type', 'name', $filename); return $this; } /** * Get the file size of this attachment. * * @return int */ public function getSize() { return $this->_getHeaderParameter('Content-Disposition', 'size'); } /** * Set the file size of this attachment. * * @param int $size * * @return Swift_Mime_Attachment */ public function setSize($size) { $this->_setHeaderParameter('Content-Disposition', 'size', $size); return $this; } /** * Set the file that this attachment is for. * * @param Swift_FileStream $file * @param string $contentType optional * * @return Swift_Mime_Attachment */ public function setFile(Swift_FileStream $file, $contentType = null) { $this->setFilename(basename($file->getPath())); $this->setBody($file, $contentType); if (!isset($contentType)) { $extension = strtolower(substr( $file->getPath(), strrpos($file->getPath(), '.') + 1 )); if (array_key_exists($extension, $this->_mimeTypes)) { $this->setContentType($this->_mimeTypes[$extension]); } } return $this; } } = $maxLineLength || 76 < $maxLineLength) { $maxLineLength = 76; } $remainder = 0; while (false !== $bytes = $os->read(8190)) { $encoded = base64_encode($bytes); $encodedTransformed = ''; $thisMaxLineLength = $maxLineLength - $remainder - $firstLineOffset; while ($thisMaxLineLength < strlen($encoded)) { $encodedTransformed .= substr($encoded, 0, $thisMaxLineLength)."\r\n"; $firstLineOffset = 0; $encoded = substr($encoded, $thisMaxLineLength); $thisMaxLineLength = $maxLineLength; $remainder = 0; } if (0 < $remainingLength = strlen($encoded)) { $remainder += $remainingLength; $encodedTransformed .= $encoded; $encoded = null; } $is->write($encodedTransformed); } } /** * Get the name of this encoding scheme. * Returns the string 'base64'. * * @return string */ public function getName() { return 'base64'; } } charset = $charset ? $charset : 'utf-8'; } /** * Notify this observer that the entity's charset has changed. * * @param string $charset */ public function charsetChanged($charset) { $this->charset = $charset; } /** * Encode $in to $out. * * @param Swift_OutputByteStream $os to read from * @param Swift_InputByteStream $is to write to * @param int $firstLineOffset * @param int $maxLineLength 0 indicates the default length for this encoding * * @throws RuntimeException */ public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) { if ($this->charset !== 'utf-8') { throw new RuntimeException( sprintf('Charset "%s" not supported. NativeQpContentEncoder only supports "utf-8"', $this->charset)); } $string = ''; while (false !== $bytes = $os->read(8192)) { $string .= $bytes; } $is->write($this->encodeString($string)); } /** * Get the MIME name of this content encoding scheme. * * @return string */ public function getName() { return 'quoted-printable'; } /** * Encode a given string to produce an encoded string. * * @param string $string * @param int $firstLineOffset if first line needs to be shorter * @param int $maxLineLength 0 indicates the default length for this encoding * * @return string * * @throws RuntimeException */ public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) { if ($this->charset !== 'utf-8') { throw new RuntimeException( sprintf('Charset "%s" not supported. NativeQpContentEncoder only supports "utf-8"', $this->charset)); } return $this->_standardize(quoted_printable_encode($string)); } /** * Make sure CRLF is correct and HT/SPACE are in valid places. * * @param string $string * * @return string */ protected function _standardize($string) { // transform CR or LF to CRLF $string = preg_replace('~=0D(?!=0A)|(?_name = $name; $this->_canonical = $canonical; } /** * Encode a given string to produce an encoded string. * * @param string $string * @param int $firstLineOffset ignored * @param int $maxLineLength - 0 means no wrapping will occur * * @return string */ public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) { if ($this->_canonical) { $string = $this->_canonicalize($string); } return $this->_safeWordWrap($string, $maxLineLength, "\r\n"); } /** * Encode stream $in to stream $out. * * @param Swift_OutputByteStream $os * @param Swift_InputByteStream $is * @param int $firstLineOffset ignored * @param int $maxLineLength optional, 0 means no wrapping will occur */ public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) { $leftOver = ''; while (false !== $bytes = $os->read(8192)) { $toencode = $leftOver.$bytes; if ($this->_canonical) { $toencode = $this->_canonicalize($toencode); } $wrapped = $this->_safeWordWrap($toencode, $maxLineLength, "\r\n"); $lastLinePos = strrpos($wrapped, "\r\n"); $leftOver = substr($wrapped, $lastLinePos); $wrapped = substr($wrapped, 0, $lastLinePos); $is->write($wrapped); } if (strlen($leftOver)) { $is->write($leftOver); } } /** * Get the name of this encoding scheme. * * @return string */ public function getName() { return $this->_name; } /** * Not used. */ public function charsetChanged($charset) { } /** * A safer (but weaker) wordwrap for unicode. * * @param string $string * @param int $length * @param string $le * * @return string */ private function _safeWordwrap($string, $length = 75, $le = "\r\n") { if (0 >= $length) { return $string; } $originalLines = explode($le, $string); $lines = array(); $lineCount = 0; foreach ($originalLines as $originalLine) { $lines[] = ''; $currentLine = & $lines[$lineCount++]; //$chunks = preg_split('/(?<=[\ \t,\.!\?\-&\+\/])/', $originalLine); $chunks = preg_split('/(?<=\s)/', $originalLine); foreach ($chunks as $chunk) { if (0 != strlen($currentLine) && strlen($currentLine.$chunk) > $length) { $lines[] = ''; $currentLine = & $lines[$lineCount++]; } $currentLine .= $chunk; } } return implode("\r\n", $lines); } /** * Canonicalize string input (fix CRLF). * * @param string $string * * @return string */ private function _canonicalize($string) { return str_replace( array("\r\n", "\r", "\n"), array("\n", "\n", "\r\n"), $string ); } } _dotEscape = $dotEscape; parent::__construct($charStream, $filter); } public function __sleep() { return array('_charStream', '_filter', '_dotEscape'); } protected function getSafeMapShareId() { return get_class($this).($this->_dotEscape ? '.dotEscape' : ''); } protected function initSafeMap() { parent::initSafeMap(); if ($this->_dotEscape) { /* Encode . as =2e for buggy remote servers */ unset($this->_safeMap[0x2e]); } } /** * Encode stream $in to stream $out. * * QP encoded strings have a maximum line length of 76 characters. * If the first line needs to be shorter, indicate the difference with * $firstLineOffset. * * @param Swift_OutputByteStream $os output stream * @param Swift_InputByteStream $is input stream * @param int $firstLineOffset * @param int $maxLineLength */ public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) { if ($maxLineLength > 76 || $maxLineLength <= 0) { $maxLineLength = 76; } $thisLineLength = $maxLineLength - $firstLineOffset; $this->_charStream->flushContents(); $this->_charStream->importByteStream($os); $currentLine = ''; $prepend = ''; $size = $lineLen = 0; while (false !== $bytes = $this->_nextSequence()) { // If we're filtering the input if (isset($this->_filter)) { // If we can't filter because we need more bytes while ($this->_filter->shouldBuffer($bytes)) { // Then collect bytes into the buffer if (false === $moreBytes = $this->_nextSequence(1)) { break; } foreach ($moreBytes as $b) { $bytes[] = $b; } } // And filter them $bytes = $this->_filter->filter($bytes); } $enc = $this->_encodeByteSequence($bytes, $size); if ($currentLine && $lineLen+$size >= $thisLineLength) { $is->write($prepend.$this->_standardize($currentLine)); $currentLine = ''; $prepend = "=\r\n"; $thisLineLength = $maxLineLength; $lineLen = 0; } $lineLen += $size; $currentLine .= $enc; } if (strlen($currentLine)) { $is->write($prepend.$this->_standardize($currentLine)); } } /** * Get the name of this encoding scheme. * Returns the string 'quoted-printable'. * * @return string */ public function getName() { return 'quoted-printable'; } } */ class Swift_Mime_ContentEncoder_QpContentEncoderProxy implements Swift_Mime_ContentEncoder { /** * @var Swift_Mime_ContentEncoder_QpContentEncoder */ private $safeEncoder; /** * @var Swift_Mime_ContentEncoder_NativeQpContentEncoder */ private $nativeEncoder; /** * @var null|string */ private $charset; /** * Constructor. * * @param Swift_Mime_ContentEncoder_QpContentEncoder $safeEncoder * @param Swift_Mime_ContentEncoder_NativeQpContentEncoder $nativeEncoder * @param string|null $charset */ public function __construct(Swift_Mime_ContentEncoder_QpContentEncoder $safeEncoder, Swift_Mime_ContentEncoder_NativeQpContentEncoder $nativeEncoder, $charset) { $this->safeEncoder = $safeEncoder; $this->nativeEncoder = $nativeEncoder; $this->charset = $charset; } /** * Make a deep copy of object */ public function __clone() { $this->safeEncoder = clone $this->safeEncoder; $this->nativeEncoder = clone $this->nativeEncoder; } /** * {@inheritdoc} */ public function charsetChanged($charset) { $this->charset = $charset; } /** * {@inheritdoc} */ public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) { $this->getEncoder()->encodeByteStream($os, $is, $firstLineOffset, $maxLineLength); } /** * {@inheritdoc} */ public function getName() { return 'quoted-printable'; } /** * {@inheritdoc} */ public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) { return $this->getEncoder()->encodeString($string, $firstLineOffset, $maxLineLength); } /** * @return Swift_Mime_ContentEncoder */ private function getEncoder() { return 'utf-8' === $this->charset ? $this->nativeEncoder : $this->safeEncoder; } } */ class Swift_Mime_ContentEncoder_RawContentEncoder implements Swift_Mime_ContentEncoder { /** * Encode a given string to produce an encoded string. * * @param string $string * @param int $firstLineOffset ignored * @param int $maxLineLength ignored * @return string */ public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) { return $string; } /** * Encode stream $in to stream $out. * * @param Swift_OutputByteStream $in * @param Swift_InputByteStream $out * @param int $firstLineOffset ignored * @param int $maxLineLength ignored */ public function encodeByteStream(Swift_OutputByteStream $os, Swift_InputByteStream $is, $firstLineOffset = 0, $maxLineLength = 0) { while (false !== ($bytes = $os->read(8192))) { $is->write($bytes); } } /** * Get the name of this encoding scheme. * * @return string */ public function getName() { return 'raw'; } /** * Not used. */ public function charsetChanged($charset) { } } setDisposition('inline'); $this->setId($this->getId()); } /** * Get the nesting level of this EmbeddedFile. * * Returns {@see LEVEL_RELATED}. * * @return int */ public function getNestingLevel() { return self::LEVEL_RELATED; } } init(); } public function __wakeup() { $this->init(); } protected function init() { if (count(self::$_specials) > 0) { return; } self::$_specials = array( '(', ')', '<', '>', '[', ']', ':', ';', '@', ',', '.', '"', ); /*** Refer to RFC 2822 for ABNF grammar ***/ // All basic building blocks self::$_grammar['NO-WS-CTL'] = '[\x01-\x08\x0B\x0C\x0E-\x19\x7F]'; self::$_grammar['WSP'] = '[ \t]'; self::$_grammar['CRLF'] = '(?:\r\n)'; self::$_grammar['FWS'] = '(?:(?:'.self::$_grammar['WSP'].'*'. self::$_grammar['CRLF'].')?'.self::$_grammar['WSP'].')'; self::$_grammar['text'] = '[\x00-\x08\x0B\x0C\x0E-\x7F]'; self::$_grammar['quoted-pair'] = '(?:\\\\'.self::$_grammar['text'].')'; self::$_grammar['ctext'] = '(?:'.self::$_grammar['NO-WS-CTL']. '|[\x21-\x27\x2A-\x5B\x5D-\x7E])'; // Uses recursive PCRE (?1) -- could be a weak point?? self::$_grammar['ccontent'] = '(?:'.self::$_grammar['ctext'].'|'. self::$_grammar['quoted-pair'].'|(?1))'; self::$_grammar['comment'] = '(\((?:'.self::$_grammar['FWS'].'|'. self::$_grammar['ccontent'].')*'.self::$_grammar['FWS'].'?\))'; self::$_grammar['CFWS'] = '(?:(?:'.self::$_grammar['FWS'].'?'. self::$_grammar['comment'].')*(?:(?:'.self::$_grammar['FWS'].'?'. self::$_grammar['comment'].')|'.self::$_grammar['FWS'].'))'; self::$_grammar['qtext'] = '(?:'.self::$_grammar['NO-WS-CTL']. '|[\x21\x23-\x5B\x5D-\x7E])'; self::$_grammar['qcontent'] = '(?:'.self::$_grammar['qtext'].'|'. self::$_grammar['quoted-pair'].')'; self::$_grammar['quoted-string'] = '(?:'.self::$_grammar['CFWS'].'?"'. '('.self::$_grammar['FWS'].'?'.self::$_grammar['qcontent'].')*'. self::$_grammar['FWS'].'?"'.self::$_grammar['CFWS'].'?)'; self::$_grammar['atext'] = '[a-zA-Z0-9!#\$%&\'\*\+\-\/=\?\^_`\{\}\|~]'; self::$_grammar['atom'] = '(?:'.self::$_grammar['CFWS'].'?'. self::$_grammar['atext'].'+'.self::$_grammar['CFWS'].'?)'; self::$_grammar['dot-atom-text'] = '(?:'.self::$_grammar['atext'].'+'. '(\.'.self::$_grammar['atext'].'+)*)'; self::$_grammar['dot-atom'] = '(?:'.self::$_grammar['CFWS'].'?'. self::$_grammar['dot-atom-text'].'+'.self::$_grammar['CFWS'].'?)'; self::$_grammar['word'] = '(?:'.self::$_grammar['atom'].'|'. self::$_grammar['quoted-string'].')'; self::$_grammar['phrase'] = '(?:'.self::$_grammar['word'].'+?)'; self::$_grammar['no-fold-quote'] = '(?:"(?:'.self::$_grammar['qtext']. '|'.self::$_grammar['quoted-pair'].')*")'; self::$_grammar['dtext'] = '(?:'.self::$_grammar['NO-WS-CTL']. '|[\x21-\x5A\x5E-\x7E])'; self::$_grammar['no-fold-literal'] = '(?:\[(?:'.self::$_grammar['dtext']. '|'.self::$_grammar['quoted-pair'].')*\])'; // Message IDs self::$_grammar['id-left'] = '(?:'.self::$_grammar['dot-atom-text'].'|'. self::$_grammar['no-fold-quote'].')'; self::$_grammar['id-right'] = '(?:'.self::$_grammar['dot-atom-text'].'|'. self::$_grammar['no-fold-literal'].')'; // Addresses, mailboxes and paths self::$_grammar['local-part'] = '(?:'.self::$_grammar['dot-atom'].'|'. self::$_grammar['quoted-string'].')'; self::$_grammar['dcontent'] = '(?:'.self::$_grammar['dtext'].'|'. self::$_grammar['quoted-pair'].')'; self::$_grammar['domain-literal'] = '(?:'.self::$_grammar['CFWS'].'?\[('. self::$_grammar['FWS'].'?'.self::$_grammar['dcontent'].')*?'. self::$_grammar['FWS'].'?\]'.self::$_grammar['CFWS'].'?)'; self::$_grammar['domain'] = '(?:'.self::$_grammar['dot-atom'].'|'. self::$_grammar['domain-literal'].')'; self::$_grammar['addr-spec'] = '(?:'.self::$_grammar['local-part'].'@'. self::$_grammar['domain'].')'; } /** * Get the grammar defined for $name token. * * @param string $name exactly as written in the RFC * * @return string */ public function getDefinition($name) { if (array_key_exists($name, self::$_grammar)) { return self::$_grammar[$name]; } else { throw new Swift_RfcComplianceException( "No such grammar '".$name."' defined." ); } } /** * Returns the tokens defined in RFC 2822 (and some related RFCs). * * @return array */ public function getGrammarDefinitions() { return self::$_grammar; } /** * Returns the current special characters used in the syntax which need to be escaped. * * @return array */ public function getSpecials() { return self::$_specials; } /** * Escape special characters in a string (convert to quoted-pairs). * * @param string $token * @param string[] $include additional chars to escape * @param string[] $exclude chars from escaping * * @return string */ public function escapeSpecials($token, $include = array(), $exclude = array()) { foreach (array_merge(array('\\'), array_diff(self::$_specials, $exclude), $include) as $char) { $token = str_replace($char, '\\'.$char, $token); } return $token; } } getName(), "\r\n"); mb_internal_encoding($old); return $newstring; } return parent::encodeString($string, $firstLineOffset, $maxLineLength); } } _safeMap[$byte] = chr($byte); } } /** * Get the name of this encoding scheme. * * Returns the string 'Q'. * * @return string */ public function getName() { return 'Q'; } /** * Takes an unencoded string and produces a QP encoded string from it. * * @param string $string string to encode * @param int $firstLineOffset optional * @param int $maxLineLength optional, 0 indicates the default of 76 chars * * @return string */ public function encodeString($string, $firstLineOffset = 0, $maxLineLength = 0) { return str_replace(array(' ', '=20', "=\r\n"), array('_', '_', "\r\n"), parent::encodeString($string, $firstLineOffset, $maxLineLength) ); } } setGrammar($grammar); } /** * Set the character set used in this Header. * * @param string $charset */ public function setCharset($charset) { $this->clearCachedValueIf($charset != $this->_charset); $this->_charset = $charset; if (isset($this->_encoder)) { $this->_encoder->charsetChanged($charset); } } /** * Get the character set used in this Header. * * @return string */ public function getCharset() { return $this->_charset; } /** * Set the language used in this Header. * * For example, for US English, 'en-us'. * This can be unspecified. * * @param string $lang */ public function setLanguage($lang) { $this->clearCachedValueIf($this->_lang != $lang); $this->_lang = $lang; } /** * Get the language used in this Header. * * @return string */ public function getLanguage() { return $this->_lang; } /** * Set the encoder used for encoding the header. * * @param Swift_Mime_HeaderEncoder $encoder */ public function setEncoder(Swift_Mime_HeaderEncoder $encoder) { $this->_encoder = $encoder; $this->setCachedValue(null); } /** * Get the encoder used for encoding this Header. * * @return Swift_Mime_HeaderEncoder */ public function getEncoder() { return $this->_encoder; } /** * Set the grammar used for the header. * * @param Swift_Mime_Grammar $grammar */ public function setGrammar(Swift_Mime_Grammar $grammar) { $this->_grammar = $grammar; $this->setCachedValue(null); } /** * Get the grammar used for this Header. * * @return Swift_Mime_Grammar */ public function getGrammar() { return $this->_grammar; } /** * Get the name of this header (e.g. charset). * * @return string */ public function getFieldName() { return $this->_name; } /** * Set the maximum length of lines in the header (excluding EOL). * * @param int $lineLength */ public function setMaxLineLength($lineLength) { $this->clearCachedValueIf($this->_lineLength != $lineLength); $this->_lineLength = $lineLength; } /** * Get the maximum permitted length of lines in this Header. * * @return int */ public function getMaxLineLength() { return $this->_lineLength; } /** * Get this Header rendered as a RFC 2822 compliant string. * * @return string * * @throws Swift_RfcComplianceException */ public function toString() { return $this->_tokensToString($this->toTokens()); } /** * Returns a string representation of this object. * * @return string * * @see toString() */ public function __toString() { return $this->toString(); } // -- Points of extension /** * Set the name of this Header field. * * @param string $name */ protected function setFieldName($name) { $this->_name = $name; } /** * Produces a compliant, formatted RFC 2822 'phrase' based on the string given. * * @param Swift_Mime_Header $header * @param string $string as displayed * @param string $charset of the text * @param Swift_Mime_HeaderEncoder $encoder * @param bool $shorten the first line to make remove for header name * * @return string */ protected function createPhrase(Swift_Mime_Header $header, $string, $charset, Swift_Mime_HeaderEncoder $encoder = null, $shorten = false) { // Treat token as exactly what was given $phraseStr = $string; // If it's not valid if (!preg_match('/^'.$this->getGrammar()->getDefinition('phrase').'$/D', $phraseStr)) { // .. but it is just ascii text, try escaping some characters // and make it a quoted-string if (preg_match('/^'.$this->getGrammar()->getDefinition('text').'*$/D', $phraseStr)) { $phraseStr = $this->getGrammar()->escapeSpecials( $phraseStr, array('"'), $this->getGrammar()->getSpecials() ); $phraseStr = '"'.$phraseStr.'"'; } else { // ... otherwise it needs encoding // Determine space remaining on line if first line if ($shorten) { $usedLength = strlen($header->getFieldName().': '); } else { $usedLength = 0; } $phraseStr = $this->encodeWords($header, $string, $usedLength); } } return $phraseStr; } /** * Encode needed word tokens within a string of input. * * @param Swift_Mime_Header $header * @param string $input * @param string $usedLength optional * * @return string */ protected function encodeWords(Swift_Mime_Header $header, $input, $usedLength = -1) { $value = ''; $tokens = $this->getEncodableWordTokens($input); foreach ($tokens as $token) { // See RFC 2822, Sect 2.2 (really 2.2 ??) if ($this->tokenNeedsEncoding($token)) { // Don't encode starting WSP $firstChar = substr($token, 0, 1); switch ($firstChar) { case ' ': case "\t": $value .= $firstChar; $token = substr($token, 1); } if (-1 == $usedLength) { $usedLength = strlen($header->getFieldName().': ') + strlen($value); } $value .= $this->getTokenAsEncodedWord($token, $usedLength); $header->setMaxLineLength(76); // Forcefully override } else { $value .= $token; } } return $value; } /** * Test if a token needs to be encoded or not. * * @param string $token * * @return bool */ protected function tokenNeedsEncoding($token) { return preg_match('~[\x00-\x08\x10-\x19\x7F-\xFF\r\n]~', $token); } /** * Splits a string into tokens in blocks of words which can be encoded quickly. * * @param string $string * * @return string[] */ protected function getEncodableWordTokens($string) { $tokens = array(); $encodedToken = ''; // Split at all whitespace boundaries foreach (preg_split('~(?=[\t ])~', $string) as $token) { if ($this->tokenNeedsEncoding($token)) { $encodedToken .= $token; } else { if (strlen($encodedToken) > 0) { $tokens[] = $encodedToken; $encodedToken = ''; } $tokens[] = $token; } } if (strlen($encodedToken)) { $tokens[] = $encodedToken; } return $tokens; } /** * Get a token as an encoded word for safe insertion into headers. * * @param string $token token to encode * @param int $firstLineOffset optional * * @return string */ protected function getTokenAsEncodedWord($token, $firstLineOffset = 0) { // Adjust $firstLineOffset to account for space needed for syntax $charsetDecl = $this->_charset; if (isset($this->_lang)) { $charsetDecl .= '*'.$this->_lang; } $encodingWrapperLength = strlen( '=?'.$charsetDecl.'?'.$this->_encoder->getName().'??=' ); if ($firstLineOffset >= 75) { //Does this logic need to be here? $firstLineOffset = 0; } $encodedTextLines = explode("\r\n", $this->_encoder->encodeString( $token, $firstLineOffset, 75 - $encodingWrapperLength, $this->_charset ) ); if (strtolower($this->_charset) !== 'iso-2022-jp') { // special encoding for iso-2022-jp using mb_encode_mimeheader foreach ($encodedTextLines as $lineNum => $line) { $encodedTextLines[$lineNum] = '=?'.$charsetDecl. '?'.$this->_encoder->getName(). '?'.$line.'?='; } } return implode("\r\n ", $encodedTextLines); } /** * Generates tokens from the given string which include CRLF as individual tokens. * * @param string $token * * @return string[] */ protected function generateTokenLines($token) { return preg_split('~(\r\n)~', $token, -1, PREG_SPLIT_DELIM_CAPTURE); } /** * Set a value into the cache. * * @param string $value */ protected function setCachedValue($value) { $this->_cachedValue = $value; } /** * Get the value in the cache. * * @return string */ protected function getCachedValue() { return $this->_cachedValue; } /** * Clear the cached value if $condition is met. * * @param bool $condition */ protected function clearCachedValueIf($condition) { if ($condition) { $this->setCachedValue(null); } } /** * Generate a list of all tokens in the final header. * * @param string $string The string to tokenize * * @return array An array of tokens as strings */ protected function toTokens($string = null) { if (is_null($string)) { $string = $this->getFieldBody(); } $tokens = array(); // Generate atoms; split at all invisible boundaries followed by WSP foreach (preg_split('~(?=[ \t])~', $string) as $token) { $newTokens = $this->generateTokenLines($token); foreach ($newTokens as $newToken) { $tokens[] = $newToken; } } return $tokens; } /** * Takes an array of tokens which appear in the header and turns them into * an RFC 2822 compliant string, adding FWSP where needed. * * @param string[] $tokens * * @return string */ private function _tokensToString(array $tokens) { $lineCount = 0; $headerLines = array(); $headerLines[] = $this->_name.': '; $currentLine = & $headerLines[$lineCount++]; // Build all tokens back into compliant header foreach ($tokens as $i => $token) { // Line longer than specified maximum or token was just a new line if (("\r\n" == $token) || ($i > 0 && strlen($currentLine.$token) > $this->_lineLength) && 0 < strlen($currentLine)) { $headerLines[] = ''; $currentLine = & $headerLines[$lineCount++]; } // Append token to the line if ("\r\n" != $token) { $currentLine .= $token; } } // Implode with FWS (RFC 2822, 2.2.3) return implode("\r\n", $headerLines)."\r\n"; } } * * * * @param string $name of Header * @param Swift_Mime_Grammar $grammar */ public function __construct($name, Swift_Mime_Grammar $grammar) { $this->setFieldName($name); parent::__construct($grammar); } /** * Get the type of Header that this instance represents. * * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX * @see TYPE_DATE, TYPE_ID, TYPE_PATH * * @return int */ public function getFieldType() { return self::TYPE_DATE; } /** * Set the model for the field body. * * This method takes a UNIX timestamp. * * @param int $model */ public function setFieldBodyModel($model) { $this->setTimestamp($model); } /** * Get the model for the field body. * * This method returns a UNIX timestamp. * * @return mixed */ public function getFieldBodyModel() { return $this->getTimestamp(); } /** * Get the UNIX timestamp of the Date in this Header. * * @return int */ public function getTimestamp() { return $this->_timestamp; } /** * Set the UNIX timestamp of the Date in this Header. * * @param int $timestamp */ public function setTimestamp($timestamp) { if (!is_null($timestamp)) { $timestamp = (int) $timestamp; } $this->clearCachedValueIf($this->_timestamp != $timestamp); $this->_timestamp = $timestamp; } /** * Get the string value of the body in this Header. * * This is not necessarily RFC 2822 compliant since folding white space will * not be added at this stage (see {@link toString()} for that). * * @see toString() * * @return string */ public function getFieldBody() { if (!$this->getCachedValue()) { if (isset($this->_timestamp)) { $this->setCachedValue(date('r', $this->_timestamp)); } } return $this->getCachedValue(); } } setFieldName($name); parent::__construct($grammar); } /** * Get the type of Header that this instance represents. * * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX * @see TYPE_DATE, TYPE_ID, TYPE_PATH * * @return int */ public function getFieldType() { return self::TYPE_ID; } /** * Set the model for the field body. * * This method takes a string ID, or an array of IDs. * * @param mixed $model * * @throws Swift_RfcComplianceException */ public function setFieldBodyModel($model) { $this->setId($model); } /** * Get the model for the field body. * * This method returns an array of IDs * * @return array */ public function getFieldBodyModel() { return $this->getIds(); } /** * Set the ID used in the value of this header. * * @param string|array $id * * @throws Swift_RfcComplianceException */ public function setId($id) { $this->setIds(is_array($id) ? $id : array($id)); } /** * Get the ID used in the value of this Header. * * If multiple IDs are set only the first is returned. * * @return string */ public function getId() { if (count($this->_ids) > 0) { return $this->_ids[0]; } } /** * Set a collection of IDs to use in the value of this Header. * * @param string[] $ids * * @throws Swift_RfcComplianceException */ public function setIds(array $ids) { $actualIds = array(); foreach ($ids as $id) { $this->_assertValidId($id); $actualIds[] = $id; } $this->clearCachedValueIf($this->_ids != $actualIds); $this->_ids = $actualIds; } /** * Get the list of IDs used in this Header. * * @return string[] */ public function getIds() { return $this->_ids; } /** * Get the string value of the body in this Header. * * This is not necessarily RFC 2822 compliant since folding white space will * not be added at this stage (see {@see toString()} for that). * * @see toString() * * @return string * * @throws Swift_RfcComplianceException */ public function getFieldBody() { if (!$this->getCachedValue()) { $angleAddrs = array(); foreach ($this->_ids as $id) { $angleAddrs[] = '<'.$id.'>'; } $this->setCachedValue(implode(' ', $angleAddrs)); } return $this->getCachedValue(); } /** * Throws an Exception if the id passed does not comply with RFC 2822. * * @param string $id * * @throws Swift_RfcComplianceException */ private function _assertValidId($id) { if (!preg_match( '/^'.$this->getGrammar()->getDefinition('id-left').'@'. $this->getGrammar()->getDefinition('id-right').'$/D', $id )) { throw new Swift_RfcComplianceException( 'Invalid ID given <'.$id.'>' ); } } } setFieldName($name); $this->setEncoder($encoder); parent::__construct($grammar); } /** * Get the type of Header that this instance represents. * * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX * @see TYPE_DATE, TYPE_ID, TYPE_PATH * * @return int */ public function getFieldType() { return self::TYPE_MAILBOX; } /** * Set the model for the field body. * * This method takes a string, or an array of addresses. * * @param mixed $model * * @throws Swift_RfcComplianceException */ public function setFieldBodyModel($model) { $this->setNameAddresses($model); } /** * Get the model for the field body. * * This method returns an associative array like {@link getNameAddresses()} * * @return array * * @throws Swift_RfcComplianceException */ public function getFieldBodyModel() { return $this->getNameAddresses(); } /** * Set a list of mailboxes to be shown in this Header. * * The mailboxes can be a simple array of addresses, or an array of * key=>value pairs where (email => personalName). * Example: * * setNameAddresses(array( * 'chris@swiftmailer.org' => 'Chris Corbyn', * 'mark@swiftmailer.org' //No associated personal name * )); * ?> * * * @see __construct() * @see setAddresses() * @see setValue() * * @param string|string[] $mailboxes * * @throws Swift_RfcComplianceException */ public function setNameAddresses($mailboxes) { $this->_mailboxes = $this->normalizeMailboxes((array) $mailboxes); $this->setCachedValue(null); //Clear any cached value } /** * Get the full mailbox list of this Header as an array of valid RFC 2822 strings. * * Example: * * 'Chris Corbyn', * 'mark@swiftmailer.org' => 'Mark Corbyn') * ); * print_r($header->getNameAddressStrings()); * // array ( * // 0 => Chris Corbyn , * // 1 => Mark Corbyn * // ) * ?> * * * @see getNameAddresses() * @see toString() * * @return string[] * * @throws Swift_RfcComplianceException */ public function getNameAddressStrings() { return $this->_createNameAddressStrings($this->getNameAddresses()); } /** * Get all mailboxes in this Header as key=>value pairs. * * The key is the address and the value is the name (or null if none set). * Example: * * 'Chris Corbyn', * 'mark@swiftmailer.org' => 'Mark Corbyn') * ); * print_r($header->getNameAddresses()); * // array ( * // chris@swiftmailer.org => Chris Corbyn, * // mark@swiftmailer.org => Mark Corbyn * // ) * ?> * * * @see getAddresses() * @see getNameAddressStrings() * * @return string[] */ public function getNameAddresses() { return $this->_mailboxes; } /** * Makes this Header represent a list of plain email addresses with no names. * * Example: * * setAddresses( * array('one@domain.tld', 'two@domain.tld', 'three@domain.tld') * ); * ?> * * * @see setNameAddresses() * @see setValue() * * @param string[] $addresses * * @throws Swift_RfcComplianceException */ public function setAddresses($addresses) { $this->setNameAddresses(array_values((array) $addresses)); } /** * Get all email addresses in this Header. * * @see getNameAddresses() * * @return string[] */ public function getAddresses() { return array_keys($this->_mailboxes); } /** * Remove one or more addresses from this Header. * * @param string|string[] $addresses */ public function removeAddresses($addresses) { $this->setCachedValue(null); foreach ((array) $addresses as $address) { unset($this->_mailboxes[$address]); } } /** * Get the string value of the body in this Header. * * This is not necessarily RFC 2822 compliant since folding white space will * not be added at this stage (see {@link toString()} for that). * * @see toString() * * @return string * * @throws Swift_RfcComplianceException */ public function getFieldBody() { // Compute the string value of the header only if needed if (is_null($this->getCachedValue())) { $this->setCachedValue($this->createMailboxListString($this->_mailboxes)); } return $this->getCachedValue(); } // -- Points of extension /** * Normalizes a user-input list of mailboxes into consistent key=>value pairs. * * @param string[] $mailboxes * * @return string[] */ protected function normalizeMailboxes(array $mailboxes) { $actualMailboxes = array(); foreach ($mailboxes as $key => $value) { if (is_string($key)) { //key is email addr $address = $key; $name = $value; } else { $address = $value; $name = null; } $this->_assertValidAddress($address); $actualMailboxes[$address] = $name; } return $actualMailboxes; } /** * Produces a compliant, formatted display-name based on the string given. * * @param string $displayName as displayed * @param bool $shorten the first line to make remove for header name * * @return string */ protected function createDisplayNameString($displayName, $shorten = false) { return $this->createPhrase($this, $displayName, $this->getCharset(), $this->getEncoder(), $shorten ); } /** * Creates a string form of all the mailboxes in the passed array. * * @param string[] $mailboxes * * @return string * * @throws Swift_RfcComplianceException */ protected function createMailboxListString(array $mailboxes) { return implode(', ', $this->_createNameAddressStrings($mailboxes)); } /** * Redefine the encoding requirements for mailboxes. * * Commas and semicolons are used to separate * multiple addresses, and should therefore be encoded * * @param string $token * * @return bool */ protected function tokenNeedsEncoding($token) { return preg_match('/[,;]/', $token) || parent::tokenNeedsEncoding($token); } /** * Return an array of strings conforming the the name-addr spec of RFC 2822. * * @param string[] $mailboxes * * @return string[] */ private function _createNameAddressStrings(array $mailboxes) { $strings = array(); foreach ($mailboxes as $email => $name) { $mailboxStr = $email; if (!is_null($name)) { $nameStr = $this->createDisplayNameString($name, empty($strings)); $mailboxStr = $nameStr.' <'.$mailboxStr.'>'; } $strings[] = $mailboxStr; } return $strings; } /** * Throws an Exception if the address passed does not comply with RFC 2822. * * @param string $address * * @throws Swift_RfcComplianceException If invalid. */ private function _assertValidAddress($address) { if (!preg_match('/^'.$this->getGrammar()->getDefinition('addr-spec').'$/D', $address)) { throw new Swift_RfcComplianceException( 'Address in mailbox given ['.$address. '] does not comply with RFC 2822, 3.6.2.' ); } } } */ class Swift_Mime_Headers_OpenDKIMHeader implements Swift_Mime_Header { /** * The value of this Header. * * @var string */ private $_value; /** * The name of this Header * @var string */ private $_fieldName; /** * Creates a new SimpleHeader with $name. * * @param string $name * @param Swift_Mime_HeaderEncoder $encoder * @param Swift_Mime_Grammar $grammar */ public function __construct($name) { $this->_fieldName = $name; } /** * Get the type of Header that this instance represents. * * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX * @see TYPE_DATE, TYPE_ID, TYPE_PATH * * @return int */ public function getFieldType() { return self::TYPE_TEXT; } /** * Set the model for the field body. * * This method takes a string for the field value. * * @param string $model */ public function setFieldBodyModel($model) { $this->setValue($model); } /** * Get the model for the field body. * * This method returns a string. * * @return string */ public function getFieldBodyModel() { return $this->getValue(); } /** * Get the (unencoded) value of this header. * * @return string */ public function getValue() { return $this->_value; } /** * Set the (unencoded) value of this header. * * @param string $value */ public function setValue($value) { $this->_value = $value; } /** * Get the value of this header prepared for rendering. * * @return string */ public function getFieldBody() { return $this->_value; } /** * Get this Header rendered as a RFC 2822 compliant string. * * @return string */ public function toString() { return $this->_fieldName.': '.$this->_value; } /** * Set the Header FieldName * @see Swift_Mime_Header::getFieldName() */ public function getFieldName() { return $this->_fieldName; } /** * Ignored */ public function setCharset($charset) { } } _paramEncoder = $paramEncoder; } /** * Get the type of Header that this instance represents. * * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX * @see TYPE_DATE, TYPE_ID, TYPE_PATH * * @return int */ public function getFieldType() { return self::TYPE_PARAMETERIZED; } /** * Set the character set used in this Header. * * @param string $charset */ public function setCharset($charset) { parent::setCharset($charset); if (isset($this->_paramEncoder)) { $this->_paramEncoder->charsetChanged($charset); } } /** * Set the value of $parameter. * * @param string $parameter * @param string $value */ public function setParameter($parameter, $value) { $this->setParameters(array_merge($this->getParameters(), array($parameter => $value))); } /** * Get the value of $parameter. * * @param string $parameter * * @return string */ public function getParameter($parameter) { $params = $this->getParameters(); return array_key_exists($parameter, $params) ? $params[$parameter] : null; } /** * Set an associative array of parameter names mapped to values. * * @param string[] $parameters */ public function setParameters(array $parameters) { $this->clearCachedValueIf($this->_params != $parameters); $this->_params = $parameters; } /** * Returns an associative array of parameter names mapped to values. * * @return string[] */ public function getParameters() { return $this->_params; } /** * Get the value of this header prepared for rendering. * * @return string */ public function getFieldBody() //TODO: Check caching here { $body = parent::getFieldBody(); foreach ($this->_params as $name => $value) { if (!is_null($value)) { // Add the parameter $body .= '; '.$this->_createParameter($name, $value); } } return $body; } /** * Generate a list of all tokens in the final header. * * This doesn't need to be overridden in theory, but it is for implementation * reasons to prevent potential breakage of attributes. * * @param string $string The string to tokenize * * @return array An array of tokens as strings */ protected function toTokens($string = null) { $tokens = parent::toTokens(parent::getFieldBody()); // Try creating any parameters foreach ($this->_params as $name => $value) { if (!is_null($value)) { // Add the semi-colon separator $tokens[count($tokens)-1] .= ';'; $tokens = array_merge($tokens, $this->generateTokenLines( ' '.$this->_createParameter($name, $value) )); } } return $tokens; } /** * Render a RFC 2047 compliant header parameter from the $name and $value. * * @param string $name * @param string $value * * @return string */ private function _createParameter($name, $value) { $origValue = $value; $encoded = false; // Allow room for parameter name, indices, "=" and DQUOTEs $maxValueLength = $this->getMaxLineLength() - strlen($name.'=*N"";') - 1; $firstLineOffset = 0; // If it's not already a valid parameter value... if (!preg_match('/^'.self::TOKEN_REGEX.'$/D', $value)) { // TODO: text, or something else?? // ... and it's not ascii if (!preg_match('/^'.$this->getGrammar()->getDefinition('text').'*$/D', $value)) { $encoded = true; // Allow space for the indices, charset and language $maxValueLength = $this->getMaxLineLength() - strlen($name.'*N*="";') - 1; $firstLineOffset = strlen( $this->getCharset()."'".$this->getLanguage()."'" ); } } // Encode if we need to if ($encoded || strlen($value) > $maxValueLength) { if (isset($this->_paramEncoder)) { $value = $this->_paramEncoder->encodeString( $origValue, $firstLineOffset, $maxValueLength, $this->getCharset() ); } else { // We have to go against RFC 2183/2231 in some areas for interoperability $value = $this->getTokenAsEncodedWord($origValue); $encoded = false; } } $valueLines = isset($this->_paramEncoder) ? explode("\r\n", $value) : array($value); // Need to add indices if (count($valueLines) > 1) { $paramLines = array(); foreach ($valueLines as $i => $line) { $paramLines[] = $name.'*'.$i. $this->_getEndOfParameterValue($line, true, $i == 0); } return implode(";\r\n ", $paramLines); } else { return $name.$this->_getEndOfParameterValue( $valueLines[0], $encoded, true ); } } /** * Returns the parameter value from the "=" and beyond. * * @param string $value to append * @param bool $encoded * @param bool $firstLine * * @return string */ private function _getEndOfParameterValue($value, $encoded = false, $firstLine = false) { if (!preg_match('/^'.self::TOKEN_REGEX.'$/D', $value)) { $value = '"'.$value.'"'; } $prepend = '='; if ($encoded) { $prepend = '*='; if ($firstLine) { $prepend = '*='.$this->getCharset()."'".$this->getLanguage(). "'"; } } return $prepend.$value; } } setFieldName($name); parent::__construct($grammar); } /** * Get the type of Header that this instance represents. * * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX * @see TYPE_DATE, TYPE_ID, TYPE_PATH * * @return int */ public function getFieldType() { return self::TYPE_PATH; } /** * Set the model for the field body. * This method takes a string for an address. * * @param string $model * * @throws Swift_RfcComplianceException */ public function setFieldBodyModel($model) { $this->setAddress($model); } /** * Get the model for the field body. * This method returns a string email address. * * @return mixed */ public function getFieldBodyModel() { return $this->getAddress(); } /** * Set the Address which should appear in this Header. * * @param string $address * * @throws Swift_RfcComplianceException */ public function setAddress($address) { if (is_null($address)) { $this->_address = null; } elseif ('' == $address) { $this->_address = ''; } else { $this->_assertValidAddress($address); $this->_address = $address; } $this->setCachedValue(null); } /** * Get the address which is used in this Header (if any). * * Null is returned if no address is set. * * @return string */ public function getAddress() { return $this->_address; } /** * Get the string value of the body in this Header. * * This is not necessarily RFC 2822 compliant since folding white space will * not be added at this stage (see {@link toString()} for that). * * @see toString() * * @return string */ public function getFieldBody() { if (!$this->getCachedValue()) { if (isset($this->_address)) { $this->setCachedValue('<'.$this->_address.'>'); } } return $this->getCachedValue(); } /** * Throws an Exception if the address passed does not comply with RFC 2822. * * @param string $address * * @throws Swift_RfcComplianceException If address is invalid */ private function _assertValidAddress($address) { if (!preg_match('/^'.$this->getGrammar()->getDefinition('addr-spec').'$/D', $address)) { throw new Swift_RfcComplianceException( 'Address set in PathHeader does not comply with addr-spec of RFC 2822.' ); } } } setFieldName($name); $this->setEncoder($encoder); parent::__construct($grammar); } /** * Get the type of Header that this instance represents. * * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX * @see TYPE_DATE, TYPE_ID, TYPE_PATH * * @return int */ public function getFieldType() { return self::TYPE_TEXT; } /** * Set the model for the field body. * * This method takes a string for the field value. * * @param string $model */ public function setFieldBodyModel($model) { $this->setValue($model); } /** * Get the model for the field body. * * This method returns a string. * * @return string */ public function getFieldBodyModel() { return $this->getValue(); } /** * Get the (unencoded) value of this header. * * @return string */ public function getValue() { return $this->_value; } /** * Set the (unencoded) value of this header. * * @param string $value */ public function setValue($value) { $this->clearCachedValueIf($this->_value != $value); $this->_value = $value; } /** * Get the value of this header prepared for rendering. * * @return string */ public function getFieldBody() { if (!$this->getCachedValue()) { $this->setCachedValue( $this->encodeWords($this, $this->_value) ); } return $this->getCachedValue(); } } 'Real Name'). * * If the second parameter is provided and the first is a string, then $name * is associated with the address. * * @param mixed $address * @param string $name optional */ public function setSender($address, $name = null); /** * Get the sender address for this message. * * This has a higher significance than the From address. * * @return string */ public function getSender(); /** * Set the From address of this message. * * It is permissible for multiple From addresses to be set using an array. * * If multiple From addresses are used, you SHOULD set the Sender address and * according to RFC 2822, MUST set the sender address. * * An array can be used if display names are to be provided: i.e. * array('email@address.com' => 'Real Name'). * * If the second parameter is provided and the first is a string, then $name * is associated with the address. * * @param mixed $addresses * @param string $name optional */ public function setFrom($addresses, $name = null); /** * Get the From address(es) of this message. * * This method always returns an associative array where the keys are the * addresses. * * @return string[] */ public function getFrom(); /** * Set the Reply-To address(es). * * Any replies from the receiver will be sent to this address. * * It is permissible for multiple reply-to addresses to be set using an array. * * This method has the same synopsis as {@link setFrom()} and {@link setTo()}. * * If the second parameter is provided and the first is a string, then $name * is associated with the address. * * @param mixed $addresses * @param string $name optional */ public function setReplyTo($addresses, $name = null); /** * Get the Reply-To addresses for this message. * * This method always returns an associative array where the keys provide the * email addresses. * * @return string[] */ public function getReplyTo(); /** * Set the To address(es). * * Recipients set in this field will receive a copy of this message. * * This method has the same synopsis as {@link setFrom()} and {@link setCc()}. * * If the second parameter is provided and the first is a string, then $name * is associated with the address. * * @param mixed $addresses * @param string $name optional */ public function setTo($addresses, $name = null); /** * Get the To addresses for this message. * * This method always returns an associative array, whereby the keys provide * the actual email addresses. * * @return string[] */ public function getTo(); /** * Set the Cc address(es). * * Recipients set in this field will receive a 'carbon-copy' of this message. * * This method has the same synopsis as {@link setFrom()} and {@link setTo()}. * * @param mixed $addresses * @param string $name optional */ public function setCc($addresses, $name = null); /** * Get the Cc addresses for this message. * * This method always returns an associative array, whereby the keys provide * the actual email addresses. * * @return string[] */ public function getCc(); /** * Set the Bcc address(es). * * Recipients set in this field will receive a 'blind-carbon-copy' of this * message. * * In other words, they will get the message, but any other recipients of the * message will have no such knowledge of their receipt of it. * * This method has the same synopsis as {@link setFrom()} and {@link setTo()}. * * @param mixed $addresses * @param string $name optional */ public function setBcc($addresses, $name = null); /** * Get the Bcc addresses for this message. * * This method always returns an associative array, whereby the keys provide * the actual email addresses. * * @return string[] */ public function getBcc(); } setContentType('text/plain'); if (!is_null($charset)) { $this->setCharset($charset); } } /** * Set the body of this entity, either as a string, or as an instance of * {@link Swift_OutputByteStream}. * * @param mixed $body * @param string $contentType optional * @param string $charset optional * * @return Swift_Mime_MimePart */ public function setBody($body, $contentType = null, $charset = null) { if (isset($charset)) { $this->setCharset($charset); } $body = $this->_convertString($body); parent::setBody($body, $contentType); return $this; } /** * Get the character set of this entity. * * @return string */ public function getCharset() { return $this->_getHeaderParameter('Content-Type', 'charset'); } /** * Set the character set of this entity. * * @param string $charset * * @return Swift_Mime_MimePart */ public function setCharset($charset) { $this->_setHeaderParameter('Content-Type', 'charset', $charset); if ($charset !== $this->_userCharset) { $this->_clearCache(); } $this->_userCharset = $charset; parent::charsetChanged($charset); return $this; } /** * Get the format of this entity (i.e. flowed or fixed). * * @return string */ public function getFormat() { return $this->_getHeaderParameter('Content-Type', 'format'); } /** * Set the format of this entity (flowed or fixed). * * @param string $format * * @return Swift_Mime_MimePart */ public function setFormat($format) { $this->_setHeaderParameter('Content-Type', 'format', $format); $this->_userFormat = $format; return $this; } /** * Test if delsp is being used for this entity. * * @return bool */ public function getDelSp() { return ($this->_getHeaderParameter('Content-Type', 'delsp') == 'yes') ? true : false; } /** * Turn delsp on or off for this entity. * * @param bool $delsp * * @return Swift_Mime_MimePart */ public function setDelSp($delsp = true) { $this->_setHeaderParameter('Content-Type', 'delsp', $delsp ? 'yes' : null); $this->_userDelSp = $delsp; return $this; } /** * Get the nesting level of this entity. * * @see LEVEL_TOP, LEVEL_ALTERNATIVE, LEVEL_MIXED, LEVEL_RELATED * * @return int */ public function getNestingLevel() { return $this->_nestingLevel; } /** * Receive notification that the charset has changed on this document, or a * parent document. * * @param string $charset */ public function charsetChanged($charset) { $this->setCharset($charset); } /** Fix the content-type and encoding of this entity */ protected function _fixHeaders() { parent::_fixHeaders(); if (count($this->getChildren())) { $this->_setHeaderParameter('Content-Type', 'charset', null); $this->_setHeaderParameter('Content-Type', 'format', null); $this->_setHeaderParameter('Content-Type', 'delsp', null); } else { $this->setCharset($this->_userCharset); $this->setFormat($this->_userFormat); $this->setDelSp($this->_userDelSp); } } /** Set the nesting level of this entity */ protected function _setNestingLevel($level) { $this->_nestingLevel = $level; } /** Encode charset when charset is not utf-8 */ protected function _convertString($string) { $charset = strtolower($this->getCharset()); if (!in_array($charset, array('utf-8', 'iso-8859-1', ''))) { // mb_convert_encoding must be the first one to check, since iconv cannot convert some words. if (function_exists('mb_convert_encoding')) { $string = mb_convert_encoding($string, $charset, 'utf-8'); } elseif (function_exists('iconv')) { $string = iconv('utf-8//TRANSLIT//IGNORE', $charset, $string); } else { throw new Swift_SwiftException('No suitable convert encoding function (use UTF-8 as your charset or install the mbstring or iconv extension).'); } return $string; } return $string; } } _encoder = $encoder; $this->_paramEncoder = $paramEncoder; $this->_grammar = $grammar; $this->_charset = $charset; } /** * Create a new Mailbox Header with a list of $addresses. * * @param string $name * @param array|string|null $addresses * * @return Swift_Mime_Header */ public function createMailboxHeader($name, $addresses = null) { $header = new Swift_Mime_Headers_MailboxHeader($name, $this->_encoder, $this->_grammar); if (isset($addresses)) { $header->setFieldBodyModel($addresses); } $this->_setHeaderCharset($header); return $header; } /** * Create a new Date header using $timestamp (UNIX time). * @param string $name * @param int|null $timestamp * * @return Swift_Mime_Header */ public function createDateHeader($name, $timestamp = null) { $header = new Swift_Mime_Headers_DateHeader($name, $this->_grammar); if (isset($timestamp)) { $header->setFieldBodyModel($timestamp); } $this->_setHeaderCharset($header); return $header; } /** * Create a new basic text header with $name and $value. * * @param string $name * @param string $value * * @return Swift_Mime_Header */ public function createTextHeader($name, $value = null) { $header = new Swift_Mime_Headers_UnstructuredHeader($name, $this->_encoder, $this->_grammar); if (isset($value)) { $header->setFieldBodyModel($value); } $this->_setHeaderCharset($header); return $header; } /** * Create a new ParameterizedHeader with $name, $value and $params. * * @param string $name * @param string $value * @param array $params * * @return Swift_Mime_ParameterizedHeader */ public function createParameterizedHeader($name, $value = null, $params = array()) { $header = new Swift_Mime_Headers_ParameterizedHeader($name, $this->_encoder, (strtolower($name) == 'content-disposition') ? $this->_paramEncoder : null, $this->_grammar ); if (isset($value)) { $header->setFieldBodyModel($value); } foreach ($params as $k => $v) { $header->setParameter($k, $v); } $this->_setHeaderCharset($header); return $header; } /** * Create a new ID header for Message-ID or Content-ID. * * @param string $name * @param string|array $ids * * @return Swift_Mime_Header */ public function createIdHeader($name, $ids = null) { $header = new Swift_Mime_Headers_IdentificationHeader($name, $this->_grammar); if (isset($ids)) { $header->setFieldBodyModel($ids); } $this->_setHeaderCharset($header); return $header; } /** * Create a new Path header with an address (path) in it. * * @param string $name * @param string $path * * @return Swift_Mime_Header */ public function createPathHeader($name, $path = null) { $header = new Swift_Mime_Headers_PathHeader($name, $this->_grammar); if (isset($path)) { $header->setFieldBodyModel($path); } $this->_setHeaderCharset($header); return $header; } /** * Notify this observer that the entity's charset has changed. * * @param string $charset */ public function charsetChanged($charset) { $this->_charset = $charset; $this->_encoder->charsetChanged($charset); $this->_paramEncoder->charsetChanged($charset); } /** * Make a deep copy of object */ public function __clone() { $this->_encoder = clone $this->_encoder; $this->_paramEncoder = clone $this->_paramEncoder; } /** Apply the charset to the Header */ private function _setHeaderCharset(Swift_Mime_Header $header) { if (isset($this->_charset)) { $header->setCharset($this->_charset); } } } _factory = $factory; if (isset($charset)) { $this->setCharset($charset); } } /** * Set the charset used by these headers. * * @param string $charset */ public function setCharset($charset) { $this->_charset = $charset; $this->_factory->charsetChanged($charset); $this->_notifyHeadersOfCharset($charset); } /** * Add a new Mailbox Header with a list of $addresses. * * @param string $name * @param array|string $addresses */ public function addMailboxHeader($name, $addresses = null) { $this->_storeHeader($name, $this->_factory->createMailboxHeader($name, $addresses)); } /** * Add a new Date header using $timestamp (UNIX time). * * @param string $name * @param int $timestamp */ public function addDateHeader($name, $timestamp = null) { $this->_storeHeader($name, $this->_factory->createDateHeader($name, $timestamp)); } /** * Add a new basic text header with $name and $value. * * @param string $name * @param string $value */ public function addTextHeader($name, $value = null) { $this->_storeHeader($name, $this->_factory->createTextHeader($name, $value)); } /** * Add a new ParameterizedHeader with $name, $value and $params. * * @param string $name * @param string $value * @param array $params */ public function addParameterizedHeader($name, $value = null, $params = array()) { $this->_storeHeader($name, $this->_factory->createParameterizedHeader($name, $value, $params)); } /** * Add a new ID header for Message-ID or Content-ID. * * @param string $name * @param string|array $ids */ public function addIdHeader($name, $ids = null) { $this->_storeHeader($name, $this->_factory->createIdHeader($name, $ids)); } /** * Add a new Path header with an address (path) in it. * * @param string $name * @param string $path */ public function addPathHeader($name, $path = null) { $this->_storeHeader($name, $this->_factory->createPathHeader($name, $path)); } /** * Returns true if at least one header with the given $name exists. * * If multiple headers match, the actual one may be specified by $index. * * @param string $name * @param int $index * * @return bool */ public function has($name, $index = 0) { $lowerName = strtolower($name); return array_key_exists($lowerName, $this->_headers) && array_key_exists($index, $this->_headers[$lowerName]); } /** * Set a header in the HeaderSet. * * The header may be a previously fetched header via {@link get()} or it may * be one that has been created separately. * * If $index is specified, the header will be inserted into the set at this * offset. * * @param Swift_Mime_Header $header * @param int $index */ public function set(Swift_Mime_Header $header, $index = 0) { $this->_storeHeader($header->getFieldName(), $header, $index); } /** * Get the header with the given $name. * * If multiple headers match, the actual one may be specified by $index. * Returns NULL if none present. * * @param string $name * @param int $index * * @return Swift_Mime_Header */ public function get($name, $index = 0) { if ($this->has($name, $index)) { $lowerName = strtolower($name); return $this->_headers[$lowerName][$index]; } } /** * Get all headers with the given $name. * * @param string $name * * @return array */ public function getAll($name = null) { if (!isset($name)) { $headers = array(); foreach ($this->_headers as $collection) { $headers = array_merge($headers, $collection); } return $headers; } $lowerName = strtolower($name); if (!array_key_exists($lowerName, $this->_headers)) { return array(); } return $this->_headers[$lowerName]; } /** * Return the name of all Headers * * @return array */ public function listAll() { $headers = $this->_headers; if ($this->_canSort()) { uksort($headers, array($this, '_sortHeaders')); } return array_keys($headers); } /** * Remove the header with the given $name if it's set. * * If multiple headers match, the actual one may be specified by $index. * * @param string $name * @param int $index */ public function remove($name, $index = 0) { $lowerName = strtolower($name); unset($this->_headers[$lowerName][$index]); } /** * Remove all headers with the given $name. * * @param string $name */ public function removeAll($name) { $lowerName = strtolower($name); unset($this->_headers[$lowerName]); } /** * Create a new instance of this HeaderSet. * * @return Swift_Mime_HeaderSet */ public function newInstance() { return new self($this->_factory); } /** * Define a list of Header names as an array in the correct order. * * These Headers will be output in the given order where present. * * @param array $sequence */ public function defineOrdering(array $sequence) { $this->_order = array_flip(array_map('strtolower', $sequence)); } /** * Set a list of header names which must always be displayed when set. * * Usually headers without a field value won't be output unless set here. * * @param array $names */ public function setAlwaysDisplayed(array $names) { $this->_required = array_flip(array_map('strtolower', $names)); } /** * Notify this observer that the entity's charset has changed. * * @param string $charset */ public function charsetChanged($charset) { $this->setCharset($charset); } /** * Returns a string with a representation of all headers. * * @return string */ public function toString() { $string = ''; $headers = $this->_headers; if ($this->_canSort()) { uksort($headers, array($this, '_sortHeaders')); } foreach ($headers as $collection) { foreach ($collection as $header) { if ($this->_isDisplayed($header) || $header->getFieldBody() != '') { $string .= $header->toString(); } } } return $string; } /** * Returns a string representation of this object. * * @return string * * @see toString() */ public function __toString() { return $this->toString(); } /** Save a Header to the internal collection */ private function _storeHeader($name, Swift_Mime_Header $header, $offset = null) { if (!isset($this->_headers[strtolower($name)])) { $this->_headers[strtolower($name)] = array(); } if (!isset($offset)) { $this->_headers[strtolower($name)][] = $header; } else { $this->_headers[strtolower($name)][$offset] = $header; } } /** Test if the headers can be sorted */ private function _canSort() { return count($this->_order) > 0; } /** uksort() algorithm for Header ordering */ private function _sortHeaders($a, $b) { $lowerA = strtolower($a); $lowerB = strtolower($b); $aPos = array_key_exists($lowerA, $this->_order) ? $this->_order[$lowerA] : -1; $bPos = array_key_exists($lowerB, $this->_order) ? $this->_order[$lowerB] : -1; if ($aPos == -1) { return 1; } elseif ($bPos == -1) { return -1; } return ($aPos < $bPos) ? -1 : 1; } /** Test if the given Header is always displayed */ private function _isDisplayed(Swift_Mime_Header $header) { return array_key_exists(strtolower($header->getFieldName()), $this->_required); } /** Notify all Headers of the new charset */ private function _notifyHeadersOfCharset($charset) { foreach ($this->_headers as $headerGroup) { foreach ($headerGroup as $header) { $header->setCharset($charset); } } } /** * Make a deep copy of object */ public function __clone() { $this->_factory = clone $this->_factory; foreach ($this->_headers as $groupKey => $headerGroup) { foreach ($headerGroup as $key => $header) { $this->_headers[$groupKey][$key] = clone $header; } } } } getHeaders()->defineOrdering(array( 'Return-Path', 'Received', 'DKIM-Signature', 'DomainKey-Signature', 'Sender', 'Message-ID', 'Date', 'Subject', 'From', 'Reply-To', 'To', 'Cc', 'Bcc', 'MIME-Version', 'Content-Type', 'Content-Transfer-Encoding', )); $this->getHeaders()->setAlwaysDisplayed(array('Date', 'Message-ID', 'From')); $this->getHeaders()->addTextHeader('MIME-Version', '1.0'); $this->setDate(time()); $this->setId($this->getId()); $this->getHeaders()->addMailboxHeader('From'); } /** * Always returns {@link LEVEL_TOP} for a message instance. * * @return int */ public function getNestingLevel() { return self::LEVEL_TOP; } /** * Set the subject of this message. * * @param string $subject * * @return Swift_Mime_SimpleMessage */ public function setSubject($subject) { if (!$this->_setHeaderFieldModel('Subject', $subject)) { $this->getHeaders()->addTextHeader('Subject', $subject); } return $this; } /** * Get the subject of this message. * * @return string */ public function getSubject() { return $this->_getHeaderFieldModel('Subject'); } /** * Set the date at which this message was created. * * @param int $date * * @return Swift_Mime_SimpleMessage */ public function setDate($date) { if (!$this->_setHeaderFieldModel('Date', $date)) { $this->getHeaders()->addDateHeader('Date', $date); } return $this; } /** * Get the date at which this message was created. * * @return int */ public function getDate() { return $this->_getHeaderFieldModel('Date'); } /** * Set the return-path (the bounce address) of this message. * * @param string $address * * @return Swift_Mime_SimpleMessage */ public function setReturnPath($address) { if (!$this->_setHeaderFieldModel('Return-Path', $address)) { $this->getHeaders()->addPathHeader('Return-Path', $address); } return $this; } /** * Get the return-path (bounce address) of this message. * * @return string */ public function getReturnPath() { return $this->_getHeaderFieldModel('Return-Path'); } /** * Set the sender of this message. * * This does not override the From field, but it has a higher significance. * * @param string $address * @param string $name optional * * @return Swift_Mime_SimpleMessage */ public function setSender($address, $name = null) { if (!is_array($address) && isset($name)) { $address = array($address => $name); } if (!$this->_setHeaderFieldModel('Sender', (array) $address)) { $this->getHeaders()->addMailboxHeader('Sender', (array) $address); } return $this; } /** * Get the sender of this message. * * @return string */ public function getSender() { return $this->_getHeaderFieldModel('Sender'); } /** * Add a From: address to this message. * * If $name is passed this name will be associated with the address. * * @param string $address * @param string $name optional * * @return Swift_Mime_SimpleMessage */ public function addFrom($address, $name = null) { $current = $this->getFrom(); $current[$address] = $name; return $this->setFrom($current); } /** * Set the from address of this message. * * You may pass an array of addresses if this message is from multiple people. * * If $name is passed and the first parameter is a string, this name will be * associated with the address. * * @param string $addresses * @param string $name optional * * @return Swift_Mime_SimpleMessage */ public function setFrom($addresses, $name = null) { if (!is_array($addresses) && isset($name)) { $addresses = array($addresses => $name); } if (!$this->_setHeaderFieldModel('From', (array) $addresses)) { $this->getHeaders()->addMailboxHeader('From', (array) $addresses); } return $this; } /** * Get the from address of this message. * * @return mixed */ public function getFrom() { return $this->_getHeaderFieldModel('From'); } /** * Add a Reply-To: address to this message. * * If $name is passed this name will be associated with the address. * * @param string $address * @param string $name optional * * @return Swift_Mime_SimpleMessage */ public function addReplyTo($address, $name = null) { $current = $this->getReplyTo(); $current[$address] = $name; return $this->setReplyTo($current); } /** * Set the reply-to address of this message. * * You may pass an array of addresses if replies will go to multiple people. * * If $name is passed and the first parameter is a string, this name will be * associated with the address. * * @param string $addresses * @param string $name optional * * @return Swift_Mime_SimpleMessage */ public function setReplyTo($addresses, $name = null) { if (!is_array($addresses) && isset($name)) { $addresses = array($addresses => $name); } if (!$this->_setHeaderFieldModel('Reply-To', (array) $addresses)) { $this->getHeaders()->addMailboxHeader('Reply-To', (array) $addresses); } return $this; } /** * Get the reply-to address of this message. * * @return string */ public function getReplyTo() { return $this->_getHeaderFieldModel('Reply-To'); } /** * Add a To: address to this message. * * If $name is passed this name will be associated with the address. * * @param string $address * @param string $name optional * * @return Swift_Mime_SimpleMessage */ public function addTo($address, $name = null) { $current = $this->getTo(); $current[$address] = $name; return $this->setTo($current); } /** * Set the to addresses of this message. * * If multiple recipients will receive the message an array should be used. * Example: array('receiver@domain.org', 'other@domain.org' => 'A name') * * If $name is passed and the first parameter is a string, this name will be * associated with the address. * * @param mixed $addresses * @param string $name optional * * @return Swift_Mime_SimpleMessage */ public function setTo($addresses, $name = null) { if (!is_array($addresses) && isset($name)) { $addresses = array($addresses => $name); } if (!$this->_setHeaderFieldModel('To', (array) $addresses)) { $this->getHeaders()->addMailboxHeader('To', (array) $addresses); } return $this; } /** * Get the To addresses of this message. * * @return array */ public function getTo() { return $this->_getHeaderFieldModel('To'); } /** * Add a Cc: address to this message. * * If $name is passed this name will be associated with the address. * * @param string $address * @param string $name optional * * @return Swift_Mime_SimpleMessage */ public function addCc($address, $name = null) { $current = $this->getCc(); $current[$address] = $name; return $this->setCc($current); } /** * Set the Cc addresses of this message. * * If $name is passed and the first parameter is a string, this name will be * associated with the address. * * @param mixed $addresses * @param string $name optional * * @return Swift_Mime_SimpleMessage */ public function setCc($addresses, $name = null) { if (!is_array($addresses) && isset($name)) { $addresses = array($addresses => $name); } if (!$this->_setHeaderFieldModel('Cc', (array) $addresses)) { $this->getHeaders()->addMailboxHeader('Cc', (array) $addresses); } return $this; } /** * Get the Cc address of this message. * * @return array */ public function getCc() { return $this->_getHeaderFieldModel('Cc'); } /** * Add a Bcc: address to this message. * * If $name is passed this name will be associated with the address. * * @param string $address * @param string $name optional * * @return Swift_Mime_SimpleMessage */ public function addBcc($address, $name = null) { $current = $this->getBcc(); $current[$address] = $name; return $this->setBcc($current); } /** * Set the Bcc addresses of this message. * * If $name is passed and the first parameter is a string, this name will be * associated with the address. * * @param mixed $addresses * @param string $name optional * * @return Swift_Mime_SimpleMessage */ public function setBcc($addresses, $name = null) { if (!is_array($addresses) && isset($name)) { $addresses = array($addresses => $name); } if (!$this->_setHeaderFieldModel('Bcc', (array) $addresses)) { $this->getHeaders()->addMailboxHeader('Bcc', (array) $addresses); } return $this; } /** * Get the Bcc addresses of this message. * * @return array */ public function getBcc() { return $this->_getHeaderFieldModel('Bcc'); } /** * Set the priority of this message. * * The value is an integer where 1 is the highest priority and 5 is the lowest. * * @param int $priority * * @return Swift_Mime_SimpleMessage */ public function setPriority($priority) { $priorityMap = array( 1 => 'Highest', 2 => 'High', 3 => 'Normal', 4 => 'Low', 5 => 'Lowest', ); $pMapKeys = array_keys($priorityMap); if ($priority > max($pMapKeys)) { $priority = max($pMapKeys); } elseif ($priority < min($pMapKeys)) { $priority = min($pMapKeys); } if (!$this->_setHeaderFieldModel('X-Priority', sprintf('%d (%s)', $priority, $priorityMap[$priority]))) { $this->getHeaders()->addTextHeader('X-Priority', sprintf('%d (%s)', $priority, $priorityMap[$priority])); } return $this; } /** * Get the priority of this message. * * The returned value is an integer where 1 is the highest priority and 5 * is the lowest. * * @return int */ public function getPriority() { list($priority) = sscanf($this->_getHeaderFieldModel('X-Priority'), '%[1-5]' ); return isset($priority) ? $priority : 3; } /** * Ask for a delivery receipt from the recipient to be sent to $addresses * * @param array $addresses * * @return Swift_Mime_SimpleMessage */ public function setReadReceiptTo($addresses) { if (!$this->_setHeaderFieldModel('Disposition-Notification-To', $addresses)) { $this->getHeaders() ->addMailboxHeader('Disposition-Notification-To', $addresses); } return $this; } /** * Get the addresses to which a read-receipt will be sent. * * @return string */ public function getReadReceiptTo() { return $this->_getHeaderFieldModel('Disposition-Notification-To'); } /** * Attach a {@link Swift_Mime_MimeEntity} such as an Attachment or MimePart. * * @param Swift_Mime_MimeEntity $entity * * @return Swift_Mime_SimpleMessage */ public function attach(Swift_Mime_MimeEntity $entity) { $this->setChildren(array_merge($this->getChildren(), array($entity))); return $this; } /** * Remove an already attached entity. * * @param Swift_Mime_MimeEntity $entity * * @return Swift_Mime_SimpleMessage */ public function detach(Swift_Mime_MimeEntity $entity) { $newChildren = array(); foreach ($this->getChildren() as $child) { if ($entity !== $child) { $newChildren[] = $child; } } $this->setChildren($newChildren); return $this; } /** * Attach a {@link Swift_Mime_MimeEntity} and return it's CID source. * This method should be used when embedding images or other data in a message. * * @param Swift_Mime_MimeEntity $entity * * @return string */ public function embed(Swift_Mime_MimeEntity $entity) { $this->attach($entity); return 'cid:'.$entity->getId(); } /** * Get this message as a complete string. * * @return string */ public function toString() { if (count($children = $this->getChildren()) > 0 && $this->getBody() != '') { $this->setChildren(array_merge(array($this->_becomeMimePart()), $children)); $string = parent::toString(); $this->setChildren($children); } else { $string = parent::toString(); } return $string; } /** * Returns a string representation of this object. * * @see toString() * * @return string */ public function __toString() { return $this->toString(); } /** * Write this message to a {@link Swift_InputByteStream}. * * @param Swift_InputByteStream $is */ public function toByteStream(Swift_InputByteStream $is) { if (count($children = $this->getChildren()) > 0 && $this->getBody() != '') { $this->setChildren(array_merge(array($this->_becomeMimePart()), $children)); parent::toByteStream($is); $this->setChildren($children); } else { parent::toByteStream($is); } } /** @see Swift_Mime_SimpleMimeEntity::_getIdField() */ protected function _getIdField() { return 'Message-ID'; } /** Turn the body of this message into a child of itself if needed */ protected function _becomeMimePart() { $part = new parent($this->getHeaders()->newInstance(), $this->getEncoder(), $this->_getCache(), $this->_getGrammar(), $this->_userCharset ); $part->setContentType($this->_userContentType); $part->setBody($this->getBody()); $part->setFormat($this->_userFormat); $part->setDelSp($this->_userDelSp); $part->_setNestingLevel($this->_getTopNestingLevel()); return $part; } /** Get the highest nesting level nested inside this message */ private function _getTopNestingLevel() { $highestLevel = $this->getNestingLevel(); foreach ($this->getChildren() as $child) { $childLevel = $child->getNestingLevel(); if ($highestLevel < $childLevel) { $highestLevel = $childLevel; } } return $highestLevel; } } array(self::LEVEL_TOP, self::LEVEL_MIXED), 'multipart/alternative' => array(self::LEVEL_MIXED, self::LEVEL_ALTERNATIVE), 'multipart/related' => array(self::LEVEL_ALTERNATIVE, self::LEVEL_RELATED), ); /** A set of filter rules to define what level an entity should be nested at */ private $_compoundLevelFilters = array(); /** The nesting level of this entity */ private $_nestingLevel = self::LEVEL_ALTERNATIVE; /** A KeyCache instance used during encoding and streaming */ private $_cache; /** Direct descendants of this entity */ private $_immediateChildren = array(); /** All descendants of this entity */ private $_children = array(); /** The maximum line length of the body of this entity */ private $_maxLineLength = 78; /** The order in which alternative mime types should appear */ private $_alternativePartOrder = array( 'text/plain' => 1, 'text/html' => 2, 'multipart/related' => 3, ); /** The CID of this entity */ private $_id; /** The key used for accessing the cache */ private $_cacheKey; protected $_userContentType; /** * Create a new SimpleMimeEntity with $headers, $encoder and $cache. * * @param Swift_Mime_HeaderSet $headers * @param Swift_Mime_ContentEncoder $encoder * @param Swift_KeyCache $cache * @param Swift_Mime_Grammar $grammar */ public function __construct(Swift_Mime_HeaderSet $headers, Swift_Mime_ContentEncoder $encoder, Swift_KeyCache $cache, Swift_Mime_Grammar $grammar) { $this->_cacheKey = md5(uniqid(getmypid().mt_rand(), true)); $this->_cache = $cache; $this->_headers = $headers; $this->_grammar = $grammar; $this->setEncoder($encoder); $this->_headers->defineOrdering(array('Content-Type', 'Content-Transfer-Encoding')); // This array specifies that, when the entire MIME document contains // $compoundLevel, then for each child within $level, if its Content-Type // is $contentType then it should be treated as if it's level is // $neededLevel instead. I tried to write that unambiguously! :-\ // Data Structure: // array ( // $compoundLevel => array( // $level => array( // $contentType => $neededLevel // ) // ) // ) $this->_compoundLevelFilters = array( (self::LEVEL_ALTERNATIVE + self::LEVEL_RELATED) => array( self::LEVEL_ALTERNATIVE => array( 'text/plain' => self::LEVEL_ALTERNATIVE, 'text/html' => self::LEVEL_RELATED, ), ), ); $this->_id = $this->getRandomId(); } /** * Generate a new Content-ID or Message-ID for this MIME entity. * * @return string */ public function generateId() { $this->setId($this->getRandomId()); return $this->_id; } /** * Get the {@link Swift_Mime_HeaderSet} for this entity. * * @return Swift_Mime_HeaderSet */ public function getHeaders() { return $this->_headers; } /** * Get the nesting level of this entity. * * @see LEVEL_TOP, LEVEL_MIXED, LEVEL_RELATED, LEVEL_ALTERNATIVE * * @return int */ public function getNestingLevel() { return $this->_nestingLevel; } /** * Get the Content-type of this entity. * * @return string */ public function getContentType() { return $this->_getHeaderFieldModel('Content-Type'); } /** * Set the Content-type of this entity. * * @param string $type * * @return Swift_Mime_SimpleMimeEntity */ public function setContentType($type) { $this->_setContentTypeInHeaders($type); // Keep track of the value so that if the content-type changes automatically // due to added child entities, it can be restored if they are later removed $this->_userContentType = $type; return $this; } /** * Get the CID of this entity. * * The CID will only be present in headers if a Content-ID header is present. * * @return string */ public function getId() { $tmp = (array) $this->_getHeaderFieldModel($this->_getIdField()); return $this->_headers->has($this->_getIdField()) ? current($tmp) : $this->_id; } /** * Set the CID of this entity. * * @param string $id * * @return Swift_Mime_SimpleMimeEntity */ public function setId($id) { if (!$this->_setHeaderFieldModel($this->_getIdField(), $id)) { $this->_headers->addIdHeader($this->_getIdField(), $id); } $this->_id = $id; return $this; } /** * Get the description of this entity. * * This value comes from the Content-Description header if set. * * @return string */ public function getDescription() { return $this->_getHeaderFieldModel('Content-Description'); } /** * Set the description of this entity. * * This method sets a value in the Content-ID header. * * @param string $description * * @return Swift_Mime_SimpleMimeEntity */ public function setDescription($description) { if (!$this->_setHeaderFieldModel('Content-Description', $description)) { $this->_headers->addTextHeader('Content-Description', $description); } return $this; } /** * Get the maximum line length of the body of this entity. * * @return int */ public function getMaxLineLength() { return $this->_maxLineLength; } /** * Set the maximum line length of lines in this body. * * Though not enforced by the library, lines should not exceed 1000 chars. * * @param int $length * * @return Swift_Mime_SimpleMimeEntity */ public function setMaxLineLength($length) { $this->_maxLineLength = $length; return $this; } /** * Get all children added to this entity. * * @return Swift_Mime_MimeEntity[] */ public function getChildren() { return $this->_children; } /** * Set all children of this entity. * * @param Swift_Mime_MimeEntity[] $children * @param int $compoundLevel For internal use only * * @return Swift_Mime_SimpleMimeEntity */ public function setChildren(array $children, $compoundLevel = null) { // TODO: Try to refactor this logic $compoundLevel = isset($compoundLevel) ? $compoundLevel : $this->_getCompoundLevel($children) ; $immediateChildren = array(); $grandchildren = array(); $newContentType = $this->_userContentType; foreach ($children as $child) { $level = $this->_getNeededChildLevel($child, $compoundLevel); if (empty($immediateChildren)) { //first iteration $immediateChildren = array($child); } else { $nextLevel = $this->_getNeededChildLevel($immediateChildren[0], $compoundLevel); if ($nextLevel == $level) { $immediateChildren[] = $child; } elseif ($level < $nextLevel) { // Re-assign immediateChildren to grandchildren $grandchildren = array_merge($grandchildren, $immediateChildren); // Set new children $immediateChildren = array($child); } else { $grandchildren[] = $child; } } } if (!empty($immediateChildren)) { $lowestLevel = $this->_getNeededChildLevel($immediateChildren[0], $compoundLevel); // Determine which composite media type is needed to accommodate the // immediate children foreach ($this->_compositeRanges as $mediaType => $range) { if ($lowestLevel > $range[0] && $lowestLevel <= $range[1]) { $newContentType = $mediaType; break; } } // Put any grandchildren in a subpart if (!empty($grandchildren)) { $subentity = $this->_createChild(); $subentity->_setNestingLevel($lowestLevel); $subentity->setChildren($grandchildren, $compoundLevel); array_unshift($immediateChildren, $subentity); } } $this->_immediateChildren = $immediateChildren; $this->_children = $children; $this->_setContentTypeInHeaders($newContentType); $this->_fixHeaders(); $this->_sortChildren(); return $this; } /** * Get the body of this entity as a string. * * @return string */ public function getBody() { return ($this->_body instanceof Swift_OutputByteStream) ? $this->_readStream($this->_body) : $this->_body; } /** * Set the body of this entity, either as a string, or as an instance of * {@link Swift_OutputByteStream}. * * @param mixed $body * @param string $contentType optional * * @return Swift_Mime_SimpleMimeEntity */ public function setBody($body, $contentType = null) { if ($body !== $this->_body) { $this->_clearCache(); } $this->_body = $body; if (isset($contentType)) { $this->setContentType($contentType); } return $this; } /** * Get the encoder used for the body of this entity. * * @return Swift_Mime_ContentEncoder */ public function getEncoder() { return $this->_encoder; } /** * Set the encoder used for the body of this entity. * * @param Swift_Mime_ContentEncoder $encoder * * @return Swift_Mime_SimpleMimeEntity */ public function setEncoder(Swift_Mime_ContentEncoder $encoder) { if ($encoder !== $this->_encoder) { $this->_clearCache(); } $this->_encoder = $encoder; $this->_setEncoding($encoder->getName()); $this->_notifyEncoderChanged($encoder); return $this; } /** * Get the boundary used to separate children in this entity. * * @return string */ public function getBoundary() { if (!isset($this->_boundary)) { $this->_boundary = '_=_swift_v4_'.time().'_'.md5(getmypid().mt_rand().uniqid('', true)).'_=_'; } return $this->_boundary; } /** * Set the boundary used to separate children in this entity. * * @param string $boundary * * @return Swift_Mime_SimpleMimeEntity * * @throws Swift_RfcComplianceException */ public function setBoundary($boundary) { $this->_assertValidBoundary($boundary); $this->_boundary = $boundary; return $this; } /** * Receive notification that the charset of this entity, or a parent entity * has changed. * * @param string $charset */ public function charsetChanged($charset) { $this->_notifyCharsetChanged($charset); } /** * Receive notification that the encoder of this entity or a parent entity * has changed. * * @param Swift_Mime_ContentEncoder $encoder */ public function encoderChanged(Swift_Mime_ContentEncoder $encoder) { $this->_notifyEncoderChanged($encoder); } /** * Get this entire entity as a string. * * @return string */ public function toString() { $string = $this->_headers->toString(); $string .= $this->_bodyToString(); return $string; } /** * Get this entire entity as a string. * * @return string */ protected function _bodyToString() { $string = ''; if (isset($this->_body) && empty($this->_immediateChildren)) { if ($this->_cache->hasKey($this->_cacheKey, 'body')) { $body = $this->_cache->getString($this->_cacheKey, 'body'); } else { $body = "\r\n".$this->_encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength() ); $this->_cache->setString($this->_cacheKey, 'body', $body, Swift_KeyCache::MODE_WRITE ); } $string .= $body; } if (!empty($this->_immediateChildren)) { foreach ($this->_immediateChildren as $child) { $string .= "\r\n\r\n--".$this->getBoundary()."\r\n"; $string .= $child->toString(); } $string .= "\r\n\r\n--".$this->getBoundary()."--\r\n"; } return $string; } /** * Returns a string representation of this object. * * @see toString() * * @return string */ public function __toString() { return $this->toString(); } /** * Write this entire entity to a {@see Swift_InputByteStream}. * * @param Swift_InputByteStream */ public function toByteStream(Swift_InputByteStream $is) { $is->write($this->_headers->toString()); $is->commit(); $this->_bodyToByteStream($is); } /** * Write this entire entity to a {@link Swift_InputByteStream}. * * @param Swift_InputByteStream */ protected function _bodyToByteStream(Swift_InputByteStream $is) { if (empty($this->_immediateChildren)) { if (isset($this->_body)) { if ($this->_cache->hasKey($this->_cacheKey, 'body')) { $this->_cache->exportToByteStream($this->_cacheKey, 'body', $is); } else { $cacheIs = $this->_cache->getInputByteStream($this->_cacheKey, 'body'); if ($cacheIs) { $is->bind($cacheIs); } $is->write("\r\n"); if ($this->_body instanceof Swift_OutputByteStream) { $this->_body->setReadPointer(0); $this->_encoder->encodeByteStream($this->_body, $is, 0, $this->getMaxLineLength()); } else { $is->write($this->_encoder->encodeString($this->getBody(), 0, $this->getMaxLineLength())); } if ($cacheIs) { $is->unbind($cacheIs); } } } } if (!empty($this->_immediateChildren)) { foreach ($this->_immediateChildren as $child) { $is->write("\r\n\r\n--".$this->getBoundary()."\r\n"); $child->toByteStream($is); } $is->write("\r\n\r\n--".$this->getBoundary()."--\r\n"); } } /** * Get the name of the header that provides the ID of this entity */ protected function _getIdField() { return 'Content-ID'; } /** * Get the model data (usually an array or a string) for $field. */ protected function _getHeaderFieldModel($field) { if ($this->_headers->has($field)) { return $this->_headers->get($field)->getFieldBodyModel(); } } /** * Set the model data for $field. */ protected function _setHeaderFieldModel($field, $model) { if ($this->_headers->has($field)) { $this->_headers->get($field)->setFieldBodyModel($model); return true; } else { return false; } } /** * Get the parameter value of $parameter on $field header. */ protected function _getHeaderParameter($field, $parameter) { if ($this->_headers->has($field)) { return $this->_headers->get($field)->getParameter($parameter); } } /** * Set the parameter value of $parameter on $field header. */ protected function _setHeaderParameter($field, $parameter, $value) { if ($this->_headers->has($field)) { $this->_headers->get($field)->setParameter($parameter, $value); return true; } else { return false; } } /** * Re-evaluate what content type and encoding should be used on this entity. */ protected function _fixHeaders() { if (count($this->_immediateChildren)) { $this->_setHeaderParameter('Content-Type', 'boundary', $this->getBoundary() ); $this->_headers->remove('Content-Transfer-Encoding'); } else { $this->_setHeaderParameter('Content-Type', 'boundary', null); $this->_setEncoding($this->_encoder->getName()); } } /** * Get the KeyCache used in this entity. * * @return Swift_KeyCache */ protected function _getCache() { return $this->_cache; } /** * Get the grammar used for validation. * * @return Swift_Mime_Grammar */ protected function _getGrammar() { return $this->_grammar; } /** * Empty the KeyCache for this entity. */ protected function _clearCache() { $this->_cache->clearKey($this->_cacheKey, 'body'); } /** * Returns a random Content-ID or Message-ID. * * @return string */ protected function getRandomId() { $idLeft = md5(getmypid().'.'.time().'.'.uniqid(mt_rand(), true)); $idRight = !empty($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'swift.generated'; $id = $idLeft.'@'.$idRight; try { $this->_assertValidId($id); } catch (Swift_RfcComplianceException $e) { $id = $idLeft.'@swift.generated'; } return $id; } private function _readStream(Swift_OutputByteStream $os) { $string = ''; while (false !== $bytes = $os->read(8192)) { $string .= $bytes; } return $string; } private function _setEncoding($encoding) { if (!$this->_setHeaderFieldModel('Content-Transfer-Encoding', $encoding)) { $this->_headers->addTextHeader('Content-Transfer-Encoding', $encoding); } } private function _assertValidBoundary($boundary) { if (!preg_match( '/^[a-z0-9\'\(\)\+_\-,\.\/:=\?\ ]{0,69}[a-z0-9\'\(\)\+_\-,\.\/:=\?]$/Di', $boundary)) { throw new Swift_RfcComplianceException('Mime boundary set is not RFC 2046 compliant.'); } } private function _setContentTypeInHeaders($type) { if (!$this->_setHeaderFieldModel('Content-Type', $type)) { $this->_headers->addParameterizedHeader('Content-Type', $type); } } private function _setNestingLevel($level) { $this->_nestingLevel = $level; } private function _getCompoundLevel($children) { $level = 0; foreach ($children as $child) { $level |= $child->getNestingLevel(); } return $level; } private function _getNeededChildLevel($child, $compoundLevel) { $filter = array(); foreach ($this->_compoundLevelFilters as $bitmask => $rules) { if (($compoundLevel & $bitmask) === $bitmask) { $filter = $rules + $filter; } } $realLevel = $child->getNestingLevel(); $lowercaseType = strtolower($child->getContentType()); if (isset($filter[$realLevel]) && isset($filter[$realLevel][$lowercaseType])) { return $filter[$realLevel][$lowercaseType]; } else { return $realLevel; } } private function _createChild() { return new self($this->_headers->newInstance(), $this->_encoder, $this->_cache, $this->_grammar); } private function _notifyEncoderChanged(Swift_Mime_ContentEncoder $encoder) { foreach ($this->_immediateChildren as $child) { $child->encoderChanged($encoder); } } private function _notifyCharsetChanged($charset) { $this->_encoder->charsetChanged($charset); $this->_headers->charsetChanged($charset); foreach ($this->_immediateChildren as $child) { $child->charsetChanged($charset); } } private function _sortChildren() { $shouldSort = false; foreach ($this->_immediateChildren as $child) { // NOTE: This include alternative parts moved into a related part if ($child->getNestingLevel() == self::LEVEL_ALTERNATIVE) { $shouldSort = true; break; } } // Sort in order of preference, if there is one if ($shouldSort) { usort($this->_immediateChildren, array($this, '_childSortAlgorithm')); } } private function _childSortAlgorithm($a, $b) { $typePrefs = array(); $types = array( strtolower($a->getContentType()), strtolower($b->getContentType()), ); foreach ($types as $type) { $typePrefs[] = (array_key_exists($type, $this->_alternativePartOrder)) ? $this->_alternativePartOrder[$type] : (max($this->_alternativePartOrder) + 1); } return ($typePrefs[0] >= $typePrefs[1]) ? 1 : -1; } // -- Destructor /** * Empties it's own contents from the cache. */ public function __destruct() { $this->_cache->clearAll($this->_cacheKey); } /** * Throws an Exception if the id passed does not comply with RFC 2822. * * @param string $id * * @throws Swift_RfcComplianceException */ private function _assertValidId($id) { if (!preg_match( '/^'.$this->_grammar->getDefinition('id-left').'@'. $this->_grammar->getDefinition('id-right').'$/D', $id )) { throw new Swift_RfcComplianceException( 'Invalid ID given <'.$id.'>' ); } } /** * Make a deep copy of object */ public function __clone() { $this->_headers = clone $this->_headers; $this->_encoder = clone $this->_encoder; $this->_cacheKey = uniqid(); $children = array(); foreach ($this->_children as $pos => $child) { $children[$pos] = clone $child; } $this->setChildren($children); } } createDependenciesFor('mime.part') ); if (!isset($charset)) { $charset = Swift_DependencyContainer::getInstance() ->lookup('properties.charset'); } $this->setBody($body); $this->setCharset($charset); if ($contentType) { $this->setContentType($contentType); } } /** * Create a new MimePart. * * @param string $body * @param string $contentType * @param string $charset * * @return Swift_Mime_MimePart */ public static function newInstance($body = null, $contentType = null, $charset = null) { return new self($body, $contentType, $charset); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Pretends messages have been sent, but just ignores them. * * @author Fabien Potencier */ class Swift_NullTransport extends Swift_Transport_NullTransport { /** * Create a new NullTransport. */ public function __construct() { call_user_func_array( array($this, 'Swift_Transport_NullTransport::__construct'), Swift_DependencyContainer::getInstance() ->createDependenciesFor('transport.null') ); } /** * Create a new NullTransport instance. * * @return Swift_NullTransport */ public static function newInstance() { return new self(); } } setThreshold($threshold); $this->setSleepTime($sleep); $this->_sleeper = $sleeper; } /** * Set the number of emails to send before restarting. * * @param int $threshold */ public function setThreshold($threshold) { $this->_threshold = $threshold; } /** * Get the number of emails to send before restarting. * * @return int */ public function getThreshold() { return $this->_threshold; } /** * Set the number of seconds to sleep for during a restart. * * @param int $sleep time */ public function setSleepTime($sleep) { $this->_sleep = $sleep; } /** * Get the number of seconds to sleep for during a restart. * * @return int */ public function getSleepTime() { return $this->_sleep; } /** * Invoked immediately before the Message is sent. * * @param Swift_Events_SendEvent $evt */ public function beforeSendPerformed(Swift_Events_SendEvent $evt) { } /** * Invoked immediately after the Message is sent. * * @param Swift_Events_SendEvent $evt */ public function sendPerformed(Swift_Events_SendEvent $evt) { ++$this->_counter; if ($this->_counter >= $this->_threshold) { $transport = $evt->getTransport(); $transport->stop(); if ($this->_sleep) { $this->sleep($this->_sleep); } $transport->start(); $this->_counter = 0; } } /** * Sleep for $seconds. * * @param int $seconds */ public function sleep($seconds) { if (isset($this->_sleeper)) { $this->_sleeper->sleep($seconds); } else { sleep($seconds); } } } getMessage(); $message->toByteStream($this); } /** * Invoked immediately following a command being sent. * * @param Swift_Events_CommandEvent $evt */ public function commandSent(Swift_Events_CommandEvent $evt) { $command = $evt->getCommand(); $this->_out += strlen($command); } /** * Invoked immediately following a response coming back. * * @param Swift_Events_ResponseEvent $evt */ public function responseReceived(Swift_Events_ResponseEvent $evt) { $response = $evt->getResponse(); $this->_in += strlen($response); } /** * Called when a message is sent so that the outgoing counter can be increased. * * @param string $bytes */ public function write($bytes) { $this->_out += strlen($bytes); foreach ($this->_mirrors as $stream) { $stream->write($bytes); } } /** * Not used. */ public function commit() { } /** * Attach $is to this stream. * * The stream acts as an observer, receiving all data that is written. * All {@link write()} and {@link flushBuffers()} operations will be mirrored. * * @param Swift_InputByteStream $is */ public function bind(Swift_InputByteStream $is) { $this->_mirrors[] = $is; } /** * Remove an already bound stream. * * If $is is not bound, no errors will be raised. * If the stream currently has any buffered data it will be written to $is * before unbinding occurs. * * @param Swift_InputByteStream $is */ public function unbind(Swift_InputByteStream $is) { foreach ($this->_mirrors as $k => $stream) { if ($is === $stream) { unset($this->_mirrors[$k]); } } } /** * Not used. */ public function flushBuffers() { foreach ($this->_mirrors as $stream) { $stream->flushBuffers(); } } /** * Get the total number of bytes sent to the server. * * @return int */ public function getBytesOut() { return $this->_out; } /** * Get the total number of bytes received from the server. * * @return int */ public function getBytesIn() { return $this->_in; } /** * Reset the internal counters to zero. */ public function reset() { $this->_out = 0; $this->_in = 0; } } * $replacements = array( * "address1@domain.tld" => array("{a}" => "b", "{c}" => "d"), * "address2@domain.tld" => array("{a}" => "x", "{c}" => "y") * ) * * * When using an instance of {@link Swift_Plugins_Decorator_Replacements}, * the object should return just the array of replacements for the address * given to {@link Swift_Plugins_Decorator_Replacements::getReplacementsFor()}. * * @param mixed $replacements Array or Swift_Plugins_Decorator_Replacements */ public function __construct($replacements) { $this->setReplacements($replacements); } /** * Sets replacements. * * @param mixed $replacements Array or Swift_Plugins_Decorator_Replacements * * @see __construct() */ public function setReplacements($replacements) { if (!($replacements instanceof Swift_Plugins_Decorator_Replacements)) { $this->_replacements = (array) $replacements; } else { $this->_replacements = $replacements; } } /** * Invoked immediately before the Message is sent. * * @param Swift_Events_SendEvent $evt */ public function beforeSendPerformed(Swift_Events_SendEvent $evt) { $message = $evt->getMessage(); $this->_restoreMessage($message); $to = array_keys($message->getTo()); $address = array_shift($to); if ($replacements = $this->getReplacementsFor($address)) { $body = $message->getBody(); $search = array_keys($replacements); $replace = array_values($replacements); $bodyReplaced = str_replace( $search, $replace, $body ); if ($body != $bodyReplaced) { $this->_originalBody = $body; $message->setBody($bodyReplaced); } foreach ($message->getHeaders()->getAll() as $header) { $body = $header->getFieldBodyModel(); $count = 0; if (is_array($body)) { $bodyReplaced = array(); foreach ($body as $key => $value) { $count1 = 0; $count2 = 0; $key = is_string($key) ? str_replace($search, $replace, $key, $count1) : $key; $value = is_string($value) ? str_replace($search, $replace, $value, $count2) : $value; $bodyReplaced[$key] = $value; if (!$count && ($count1 || $count2)) { $count = 1; } } } else { $bodyReplaced = str_replace($search, $replace, $body, $count); } if ($count) { $this->_originalHeaders[$header->getFieldName()] = $body; $header->setFieldBodyModel($bodyReplaced); } } $children = (array) $message->getChildren(); foreach ($children as $child) { list($type, ) = sscanf($child->getContentType(), '%[^/]/%s'); if ('text' == $type) { $body = $child->getBody(); $bodyReplaced = str_replace( $search, $replace, $body ); if ($body != $bodyReplaced) { $child->setBody($bodyReplaced); $this->_originalChildBodies[$child->getId()] = $body; } } } $this->_lastMessage = $message; } } /** * Find a map of replacements for the address. * * If this plugin was provided with a delegate instance of * {@link Swift_Plugins_Decorator_Replacements} then the call will be * delegated to it. Otherwise, it will attempt to find the replacements * from the array provided in the constructor. * * If no replacements can be found, an empty value (NULL) is returned. * * @param string $address * * @return array */ public function getReplacementsFor($address) { if ($this->_replacements instanceof Swift_Plugins_Decorator_Replacements) { return $this->_replacements->getReplacementsFor($address); } else { return isset($this->_replacements[$address]) ? $this->_replacements[$address] : null ; } } /** * Invoked immediately after the Message is sent. * * @param Swift_Events_SendEvent $evt */ public function sendPerformed(Swift_Events_SendEvent $evt) { $this->_restoreMessage($evt->getMessage()); } /** Restore a changed message back to its original state */ private function _restoreMessage(Swift_Mime_Message $message) { if ($this->_lastMessage === $message) { if (isset($this->_originalBody)) { $message->setBody($this->_originalBody); $this->_originalBody = null; } if (!empty($this->_originalHeaders)) { foreach ($message->getHeaders()->getAll() as $header) { if (array_key_exists($header->getFieldName(), $this->_originalHeaders)) { $header->setFieldBodyModel($this->_originalHeaders[$header->getFieldName()]); } } $this->_originalHeaders = array(); } if (!empty($this->_originalChildBodies)) { $children = (array) $message->getChildren(); foreach ($children as $child) { $id = $child->getId(); if (array_key_exists($id, $this->_originalChildBodies)) { $child->setBody($this->_originalChildBodies[$id]); } } $this->_originalChildBodies = array(); } $this->_lastMessage = null; } } } _sender = $sender; } /** * Invoked immediately before the Message is sent. * * @param Swift_Events_SendEvent $evt */ public function beforeSendPerformed(Swift_Events_SendEvent $evt) { $message = $evt->getMessage(); $headers = $message->getHeaders(); // save current recipients $headers->addPathHeader('X-Swift-Return-Path', $message->getReturnPath()); // replace them with the one to send to $message->setReturnPath($this->_sender); } /** * Invoked immediately after the Message is sent. * * @param Swift_Events_SendEvent $evt */ public function sendPerformed(Swift_Events_SendEvent $evt) { $message = $evt->getMessage(); // restore original headers $headers = $message->getHeaders(); if ($headers->has('X-Swift-Return-Path')) { $message->setReturnPath($headers->get('X-Swift-Return-Path')->getAddress()); $headers->removeAll('X-Swift-Return-Path'); } } } _logger = $logger; } /** * Add a log entry. * * @param string $entry */ public function add($entry) { $this->_logger->add($entry); } /** * Clear the log contents. */ public function clear() { $this->_logger->clear(); } /** * Get this log as a string. * * @return string */ public function dump() { return $this->_logger->dump(); } /** * Invoked immediately following a command being sent. * * @param Swift_Events_CommandEvent $evt */ public function commandSent(Swift_Events_CommandEvent $evt) { $command = $evt->getCommand(); $this->_logger->add(sprintf(">> %s", $command)); } /** * Invoked immediately following a response coming back. * * @param Swift_Events_ResponseEvent $evt */ public function responseReceived(Swift_Events_ResponseEvent $evt) { $response = $evt->getResponse(); $this->_logger->add(sprintf("<< %s", $response)); } /** * Invoked just before a Transport is started. * * @param Swift_Events_TransportChangeEvent $evt */ public function beforeTransportStarted(Swift_Events_TransportChangeEvent $evt) { $transportName = get_class($evt->getSource()); $this->_logger->add(sprintf("++ Starting %s", $transportName)); } /** * Invoked immediately after the Transport is started. * * @param Swift_Events_TransportChangeEvent $evt */ public function transportStarted(Swift_Events_TransportChangeEvent $evt) { $transportName = get_class($evt->getSource()); $this->_logger->add(sprintf("++ %s started", $transportName)); } /** * Invoked just before a Transport is stopped. * * @param Swift_Events_TransportChangeEvent $evt */ public function beforeTransportStopped(Swift_Events_TransportChangeEvent $evt) { $transportName = get_class($evt->getSource()); $this->_logger->add(sprintf("++ Stopping %s", $transportName)); } /** * Invoked immediately after the Transport is stopped. * * @param Swift_Events_TransportChangeEvent $evt */ public function transportStopped(Swift_Events_TransportChangeEvent $evt) { $transportName = get_class($evt->getSource()); $this->_logger->add(sprintf("++ %s stopped", $transportName)); } /** * Invoked as a TransportException is thrown in the Transport system. * * @param Swift_Events_TransportExceptionEvent $evt */ public function exceptionThrown(Swift_Events_TransportExceptionEvent $evt) { $e = $evt->getException(); $message = $e->getMessage(); $this->_logger->add(sprintf("!! %s", $message)); $message .= PHP_EOL; $message .= 'Log data:'.PHP_EOL; $message .= $this->_logger->dump(); $evt->cancelBubble(); throw new Swift_TransportException($message); } } _size = $size; } /** * Add a log entry. * * @param string $entry */ public function add($entry) { $this->_log[] = $entry; while (count($this->_log) > $this->_size) { array_shift($this->_log); } } /** * Clear the log contents. */ public function clear() { $this->_log = array(); } /** * Get this log as a string. * * @return string */ public function dump() { return implode(PHP_EOL, $this->_log); } } _isHtml = $isHtml; } /** * Add a log entry. * * @param string $entry */ public function add($entry) { if ($this->_isHtml) { printf('%s%s%s', htmlspecialchars($entry, ENT_QUOTES), '
', PHP_EOL); } else { printf('%s%s', $entry, PHP_EOL); } } /** * Not implemented. */ public function clear() { } /** * Not implemented. */ public function dump() { } } messages = array(); } /** * Get the message list * * @return array */ public function getMessages() { return $this->messages; } /** * Get the message count * * @return int count */ public function countMessages() { return count($this->messages); } /** * Empty the message list * */ public function clear() { $this->messages = array(); } /** * Invoked immediately before the Message is sent. * * @param Swift_Events_SendEvent $evt */ public function beforeSendPerformed(Swift_Events_SendEvent $evt) { $this->messages[] = clone $evt->getMessage(); } /** * Invoked immediately after the Message is sent. * * @param Swift_Events_SendEvent $evt */ public function sendPerformed(Swift_Events_SendEvent $evt) { } } _host = $host; $this->_port = $port; $this->_crypto = $crypto; } /** * Create a new PopBeforeSmtpPlugin for $host and $port. * * @param string $host * @param int $port * @param string $crypto as "tls" or "ssl" * * @return Swift_Plugins_PopBeforeSmtpPlugin */ public static function newInstance($host, $port = 110, $crypto = null) { return new self($host, $port, $crypto); } /** * Set a Pop3Connection to delegate to instead of connecting directly. * * @param Swift_Plugins_Pop_Pop3Connection $connection * * @return Swift_Plugins_PopBeforeSmtpPlugin */ public function setConnection(Swift_Plugins_Pop_Pop3Connection $connection) { $this->_connection = $connection; return $this; } /** * Bind this plugin to a specific SMTP transport instance. * * @param Swift_Transport */ public function bindSmtp(Swift_Transport $smtp) { $this->_transport = $smtp; } /** * Set the connection timeout in seconds (default 10). * * @param int $timeout * * @return Swift_Plugins_PopBeforeSmtpPlugin */ public function setTimeout($timeout) { $this->_timeout = (int) $timeout; return $this; } /** * Set the username to use when connecting (if needed). * * @param string $username * * @return Swift_Plugins_PopBeforeSmtpPlugin */ public function setUsername($username) { $this->_username = $username; return $this; } /** * Set the password to use when connecting (if needed). * * @param string $password * * @return Swift_Plugins_PopBeforeSmtpPlugin */ public function setPassword($password) { $this->_password = $password; return $this; } /** * Connect to the POP3 host and authenticate. * * @throws Swift_Plugins_Pop_Pop3Exception if connection fails */ public function connect() { if (isset($this->_connection)) { $this->_connection->connect(); } else { if (!isset($this->_socket)) { if (!$socket = fsockopen( $this->_getHostString(), $this->_port, $errno, $errstr, $this->_timeout)) { throw new Swift_Plugins_Pop_Pop3Exception( sprintf('Failed to connect to POP3 host [%s]: %s', $this->_host, $errstr) ); } $this->_socket = $socket; if (false === $greeting = fgets($this->_socket)) { throw new Swift_Plugins_Pop_Pop3Exception( sprintf('Failed to connect to POP3 host [%s]', trim($greeting)) ); } $this->_assertOk($greeting); if ($this->_username) { $this->_command(sprintf("USER %s\r\n", $this->_username)); $this->_command(sprintf("PASS %s\r\n", $this->_password)); } } } } /** * Disconnect from the POP3 host. */ public function disconnect() { if (isset($this->_connection)) { $this->_connection->disconnect(); } else { $this->_command("QUIT\r\n"); if (!fclose($this->_socket)) { throw new Swift_Plugins_Pop_Pop3Exception( sprintf('POP3 host [%s] connection could not be stopped', $this->_host) ); } $this->_socket = null; } } /** * Invoked just before a Transport is started. * * @param Swift_Events_TransportChangeEvent $evt */ public function beforeTransportStarted(Swift_Events_TransportChangeEvent $evt) { if (isset($this->_transport)) { if ($this->_transport !== $evt->getTransport()) { return; } } $this->connect(); $this->disconnect(); } /** * Not used. */ public function transportStarted(Swift_Events_TransportChangeEvent $evt) { } /** * Not used. */ public function beforeTransportStopped(Swift_Events_TransportChangeEvent $evt) { } /** * Not used. */ public function transportStopped(Swift_Events_TransportChangeEvent $evt) { } private function _command($command) { if (!fwrite($this->_socket, $command)) { throw new Swift_Plugins_Pop_Pop3Exception( sprintf('Failed to write command [%s] to POP3 host', trim($command)) ); } if (false === $response = fgets($this->_socket)) { throw new Swift_Plugins_Pop_Pop3Exception( sprintf('Failed to read from POP3 host after command [%s]', trim($command)) ); } $this->_assertOk($response); return $response; } private function _assertOk($response) { if (substr($response, 0, 3) != '+OK') { throw new Swift_Plugins_Pop_Pop3Exception( sprintf('POP3 command failed [%s]', trim($response)) ); } } private function _getHostString() { $host = $this->_host; switch (strtolower($this->_crypto)) { case 'ssl': $host = 'ssl://'.$host; break; case 'tls': $host = 'tls://'.$host; break; } return $host; } } _recipient = $recipient; $this->_whitelist = $whitelist; } /** * Set the recipient of all messages. * * @param mixed $recipient */ public function setRecipient($recipient) { $this->_recipient = $recipient; } /** * Get the recipient of all messages. * * @return mixed */ public function getRecipient() { return $this->_recipient; } /** * Set a list of regular expressions to whitelist certain recipients * * @param array $whitelist */ public function setWhitelist(array $whitelist) { $this->_whitelist = $whitelist; } /** * Get the whitelist * * @return array */ public function getWhitelist() { return $this->_whitelist; } /** * Invoked immediately before the Message is sent. * * @param Swift_Events_SendEvent $evt */ public function beforeSendPerformed(Swift_Events_SendEvent $evt) { $message = $evt->getMessage(); $headers = $message->getHeaders(); // conditionally save current recipients if ($headers->has('to')) { $headers->addMailboxHeader('X-Swift-To', $message->getTo()); } if ($headers->has('cc')) { $headers->addMailboxHeader('X-Swift-Cc', $message->getCc()); } if ($headers->has('bcc')) { $headers->addMailboxHeader('X-Swift-Bcc', $message->getBcc()); } // Filter remaining headers against whitelist $this->_filterHeaderSet($headers, 'To'); $this->_filterHeaderSet($headers, 'Cc'); $this->_filterHeaderSet($headers, 'Bcc'); // Add each hard coded recipient $to = $message->getTo(); if (null === $to) { $to = array(); } foreach ( (array) $this->_recipient as $recipient) { if (!array_key_exists($recipient, $to)) { $message->addTo($recipient); } } } /** * Filter header set against a whitelist of regular expressions * * @param Swift_Mime_HeaderSet $headerSet * @param string $type */ private function _filterHeaderSet(Swift_Mime_HeaderSet $headerSet, $type) { foreach ($headerSet->getAll($type) as $headers) { $headers->setNameAddresses($this->_filterNameAddresses($headers->getNameAddresses())); } } /** * Filtered list of addresses => name pairs * * @param array $recipients * @return array */ private function _filterNameAddresses(array $recipients) { $filtered = array(); foreach ($recipients as $address => $name) { if ($this->_isWhitelisted($address)) { $filtered[$address] = $name; } } return $filtered; } /** * Matches address against whitelist of regular expressions * * @param $recipient * @return bool */ protected function _isWhitelisted($recipient) { if (in_array($recipient, (array) $this->_recipient)) { return true; } foreach ($this->_whitelist as $pattern) { if (preg_match($pattern, $recipient)) { return true; } } return false; } /** * Invoked immediately after the Message is sent. * * @param Swift_Events_SendEvent $evt */ public function sendPerformed(Swift_Events_SendEvent $evt) { $this->_restoreMessage($evt->getMessage()); } private function _restoreMessage(Swift_Mime_Message $message) { // restore original headers $headers = $message->getHeaders(); if ($headers->has('X-Swift-To')) { $message->setTo($headers->get('X-Swift-To')->getNameAddresses()); $headers->removeAll('X-Swift-To'); } else { $message->setTo(null); } if ($headers->has('X-Swift-Cc')) { $message->setCc($headers->get('X-Swift-Cc')->getNameAddresses()); $headers->removeAll('X-Swift-Cc'); } if ($headers->has('X-Swift-Bcc')) { $message->setBcc($headers->get('X-Swift-Bcc')->getNameAddresses()); $headers->removeAll('X-Swift-Bcc'); } } } _reporter = $reporter; } /** * Not used. */ public function beforeSendPerformed(Swift_Events_SendEvent $evt) { } /** * Invoked immediately after the Message is sent. * * @param Swift_Events_SendEvent $evt */ public function sendPerformed(Swift_Events_SendEvent $evt) { $message = $evt->getMessage(); $failures = array_flip($evt->getFailedRecipients()); foreach ((array) $message->getTo() as $address => $null) { $this->_reporter->notify( $message, $address, (array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS) ); } foreach ((array) $message->getCc() as $address => $null) { $this->_reporter->notify( $message, $address, (array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS) ); } foreach ((array) $message->getBcc() as $address => $null) { $this->_reporter->notify( $message, $address, (array_key_exists($address, $failures) ? Swift_Plugins_Reporter::RESULT_FAIL : Swift_Plugins_Reporter::RESULT_PASS) ); } } } _failures_cache[$address])) { $this->_failures[] = $address; $this->_failures_cache[$address] = true; } } /** * Get an array of addresses for which delivery failed. * * @return array */ public function getFailedRecipients() { return $this->_failures; } /** * Clear the buffer (empty the list). */ public function clear() { $this->_failures = $this->_failures_cache = array(); } } ".PHP_EOL; echo "PASS ".$address.PHP_EOL; echo "".PHP_EOL; flush(); } else { echo "
".PHP_EOL; echo "FAIL ".$address.PHP_EOL; echo "
".PHP_EOL; flush(); } } } _rate = $rate; $this->_mode = $mode; $this->_sleeper = $sleeper; $this->_timer = $timer; } /** * Invoked immediately before the Message is sent. * * @param Swift_Events_SendEvent $evt */ public function beforeSendPerformed(Swift_Events_SendEvent $evt) { $time = $this->getTimestamp(); if (!isset($this->_start)) { $this->_start = $time; } $duration = $time - $this->_start; switch ($this->_mode) { case self::BYTES_PER_MINUTE : $sleep = $this->_throttleBytesPerMinute($duration); break; case self::MESSAGES_PER_SECOND : $sleep = $this->_throttleMessagesPerSecond($duration); break; case self::MESSAGES_PER_MINUTE : $sleep = $this->_throttleMessagesPerMinute($duration); break; default : $sleep = 0; break; } if ($sleep > 0) { $this->sleep($sleep); } } /** * Invoked when a Message is sent. * * @param Swift_Events_SendEvent $evt */ public function sendPerformed(Swift_Events_SendEvent $evt) { parent::sendPerformed($evt); ++$this->_messages; } /** * Sleep for $seconds. * * @param int $seconds */ public function sleep($seconds) { if (isset($this->_sleeper)) { $this->_sleeper->sleep($seconds); } else { sleep($seconds); } } /** * Get the current UNIX timestamp. * * @return int */ public function getTimestamp() { if (isset($this->_timer)) { return $this->_timer->getTimestamp(); } else { return time(); } } /** * Get a number of seconds to sleep for. * * @param int $timePassed * * @return int */ private function _throttleBytesPerMinute($timePassed) { $expectedDuration = $this->getBytesOut() / ($this->_rate / 60); return (int) ceil($expectedDuration - $timePassed); } /** * Get a number of seconds to sleep for. * * @param int $timePassed * * @return int */ private function _throttleMessagesPerSecond($timePassed) { $expectedDuration = $this->_messages / ($this->_rate); return (int) ceil($expectedDuration - $timePassed); } /** * Get a number of seconds to sleep for. * * @param int $timePassed * * @return int */ private function _throttleMessagesPerMinute($timePassed) { $expectedDuration = $this->_messages / ($this->_rate / 60); return (int) ceil($expectedDuration - $timePassed); } } register('properties.charset')->asValue($charset); return $this; } /** * Set the directory where temporary files can be saved. * * @param string $dir * * @return Swift_Preferences */ public function setTempDir($dir) { Swift_DependencyContainer::getInstance() ->register('tempdir')->asValue($dir); return $this; } /** * Set the type of cache to use (i.e. "disk" or "array"). * * @param string $type * * @return Swift_Preferences */ public function setCacheType($type) { Swift_DependencyContainer::getInstance() ->register('cache')->asAliasOf(sprintf('cache.%s', $type)); return $this; } /** * Set the QuotedPrintable dot escaper preference. * * @param bool $dotEscape * * @return Swift_Preferences */ public function setQPDotEscape($dotEscape) { $dotEscape = !empty($dotEscape); Swift_DependencyContainer::getInstance() ->register('mime.qpcontentencoder') ->asNewInstanceOf('Swift_Mime_ContentEncoder_QpContentEncoder') ->withDependencies(array('mime.charstream', 'mime.bytecanonicalizer')) ->addConstructorValue($dotEscape); return $this; } } createDependenciesFor('transport.sendmail') ); $this->setCommand($command); } /** * Create a new SendmailTransport instance. * * @param string $command * * @return Swift_SendmailTransport */ public static function newInstance($command = '/usr/sbin/sendmail -bs') { return new self($command); } } * @deprecated */ class Swift_SignedMessage extends Swift_Message { } */ interface Swift_Signer { public function reset(); } */ interface Swift_Signers_BodySigner extends Swift_Signer { /** * Change the Swift_Signed_Message to apply the singing. * * @param Swift_Message $message * * @return Swift_Signers_BodySigner */ public function signMessage(Swift_Message $message); /** * Return the list of header a signer might tamper * * @return array */ public function getAlteredHeaders(); } */ class Swift_Signers_DKIMSigner implements Swift_Signers_HeaderSigner { /** * PrivateKey * * @var string */ protected $_privateKey; /** * DomainName * * @var string */ protected $_domainName; /** * Selector * * @var string */ protected $_selector; /** * Hash algorithm used * * @var string */ protected $_hashAlgorithm = 'rsa-sha1'; /** * Body canon method * * @var string */ protected $_bodyCanon = 'simple'; /** * Header canon method * * @var string */ protected $_headerCanon = 'simple'; /** * Headers not being signed * * @var array */ protected $_ignoredHeaders = array(); /** * Signer identity * * @var unknown_type */ protected $_signerIdentity; /** * BodyLength * * @var int */ protected $_bodyLen = 0; /** * Maximum signedLen * * @var int */ protected $_maxLen = PHP_INT_MAX; /** * Embbed bodyLen in signature * * @var bool */ protected $_showLen = false; /** * When the signature has been applied (true means time()), false means not embedded * * @var mixed */ protected $_signatureTimestamp = true; /** * When will the signature expires false means not embedded, if sigTimestamp is auto * Expiration is relative, otherwhise it's absolute * * @var int */ protected $_signatureExpiration = false; /** * Must we embed signed headers? * * @var bool */ protected $_debugHeaders = false; // work variables /** * Headers used to generate hash * * @var array */ protected $_signedHeaders = array(); /** * If debugHeaders is set store debugDatas here * * @var string */ private $_debugHeadersData = ''; /** * Stores the bodyHash * * @var string */ private $_bodyHash = ''; /** * Stores the signature header * * @var Swift_Mime_Headers_ParameterizedHeader */ protected $_dkimHeader; /** * Hash Handler * * @var hash_ressource */ private $_headerHashHandler; private $_bodyHashHandler; private $_headerHash; private $_headerCanonData = ''; private $_bodyCanonEmptyCounter = 0; private $_bodyCanonIgnoreStart = 2; private $_bodyCanonSpace = false; private $_bodyCanonLastChar = null; private $_bodyCanonLine = ''; private $_bound = array(); /** * Constructor * * @param string $privateKey * @param string $domainName * @param string $selector */ public function __construct($privateKey, $domainName, $selector) { $this->_privateKey = $privateKey; $this->_domainName = $domainName; $this->_signerIdentity = '@'.$domainName; $this->_selector = $selector; } /** * Instanciate DKIMSigner * * @param string $privateKey * @param string $domainName * @param string $selector * @return Swift_Signers_DKIMSigner */ public static function newInstance($privateKey, $domainName, $selector) { return new static($privateKey, $domainName, $selector); } /** * Reset the Signer * @see Swift_Signer::reset() */ public function reset() { $this->_headerHash = null; $this->_signedHeaders = array(); $this->_headerHashHandler = null; $this->_bodyHash = null; $this->_bodyHashHandler = null; $this->_bodyCanonIgnoreStart = 2; $this->_bodyCanonEmptyCounter = 0; $this->_bodyCanonLastChar = null; $this->_bodyCanonSpace = false; } /** * Writes $bytes to the end of the stream. * * Writing may not happen immediately if the stream chooses to buffer. If * you want to write these bytes with immediate effect, call {@link commit()} * after calling write(). * * This method returns the sequence ID of the write (i.e. 1 for first, 2 for * second, etc etc). * * @param string $bytes * @return int * @throws Swift_IoException */ public function write($bytes) { $this->_canonicalizeBody($bytes); foreach ($this->_bound as $is) { $is->write($bytes); } } /** * For any bytes that are currently buffered inside the stream, force them * off the buffer. * * @throws Swift_IoException */ public function commit() { // Nothing to do return; } /** * Attach $is to this stream. * The stream acts as an observer, receiving all data that is written. * All {@link write()} and {@link flushBuffers()} operations will be mirrored. * * @param Swift_InputByteStream $is */ public function bind(Swift_InputByteStream $is) { // Don't have to mirror anything $this->_bound[] = $is; return; } /** * Remove an already bound stream. * If $is is not bound, no errors will be raised. * If the stream currently has any buffered data it will be written to $is * before unbinding occurs. * * @param Swift_InputByteStream $is */ public function unbind(Swift_InputByteStream $is) { // Don't have to mirror anything foreach ($this->_bound as $k => $stream) { if ($stream === $is) { unset($this->_bound[$k]); return; } } return; } /** * Flush the contents of the stream (empty it) and set the internal pointer * to the beginning. * * @throws Swift_IoException */ public function flushBuffers() { $this->reset(); } /** * Set hash_algorithm, must be one of rsa-sha256 | rsa-sha1 defaults to rsa-sha256 * * @param string $hash * @return Swift_Signers_DKIMSigner */ public function setHashAlgorithm($hash) { // Unable to sign with rsa-sha256 if ($hash == 'rsa-sha1') { $this->_hashAlgorithm = 'rsa-sha1'; } else { $this->_hashAlgorithm = 'rsa-sha256'; } return $this; } /** * Set the body canonicalization algorithm * * @param string $canon * @return Swift_Signers_DKIMSigner */ public function setBodyCanon($canon) { if ($canon == 'relaxed') { $this->_bodyCanon = 'relaxed'; } else { $this->_bodyCanon = 'simple'; } return $this; } /** * Set the header canonicalization algorithm * * @param string $canon * @return Swift_Signers_DKIMSigner */ public function setHeaderCanon($canon) { if ($canon == 'relaxed') { $this->_headerCanon = 'relaxed'; } else { $this->_headerCanon = 'simple'; } return $this; } /** * Set the signer identity * * @param string $identity * @return Swift_Signers_DKIMSigner */ public function setSignerIdentity($identity) { $this->_signerIdentity = $identity; return $this; } /** * Set the length of the body to sign * * @param mixed $len (bool or int) * @return Swift_Signers_DKIMSigner */ public function setBodySignedLen($len) { if ($len === true) { $this->_showLen = true; $this->_maxLen = PHP_INT_MAX; } elseif ($len === false) { $this->showLen = false; $this->_maxLen = PHP_INT_MAX; } else { $this->_showLen = true; $this->_maxLen = (int) $len; } return $this; } /** * Set the signature timestamp * * @param timestamp $time * @return Swift_Signers_DKIMSigner */ public function setSignatureTimestamp($time) { $this->_signatureTimestamp = $time; return $this; } /** * Set the signature expiration timestamp * * @param timestamp $time * @return Swift_Signers_DKIMSigner */ public function setSignatureExpiration($time) { $this->_signatureExpiration = $time; return $this; } /** * Enable / disable the DebugHeaders * * @param bool $debug * @return Swift_Signers_DKIMSigner */ public function setDebugHeaders($debug) { $this->_debugHeaders = (bool) $debug; return $this; } /** * Start Body * */ public function startBody() { // Init switch ($this->_hashAlgorithm) { case 'rsa-sha256' : $this->_bodyHashHandler = hash_init('sha256'); break; case 'rsa-sha1' : $this->_bodyHashHandler = hash_init('sha1'); break; } $this->_bodyCanonLine = ''; } /** * End Body * */ public function endBody() { $this->_endOfBody(); } /** * Returns the list of Headers Tampered by this plugin * * @return array */ public function getAlteredHeaders() { if ($this->_debugHeaders) { return array('DKIM-Signature', 'X-DebugHash'); } else { return array('DKIM-Signature'); } } /** * Adds an ignored Header * * @param string $header_name * @return Swift_Signers_DKIMSigner */ public function ignoreHeader($header_name) { $this->_ignoredHeaders[strtolower($header_name)] = true; return $this; } /** * Set the headers to sign * * @param Swift_Mime_HeaderSet $headers * @return Swift_Signers_DKIMSigner */ public function setHeaders(Swift_Mime_HeaderSet $headers) { $this->_headerCanonData = ''; // Loop through Headers $listHeaders = $headers->listAll(); foreach ($listHeaders as $hName) { // Check if we need to ignore Header if (! isset($this->_ignoredHeaders[strtolower($hName)])) { if ($headers->has($hName)) { $tmp = $headers->getAll($hName); foreach ($tmp as $header) { if ($header->getFieldBody() != '') { $this->_addHeader($header->toString()); $this->_signedHeaders[] = $header->getFieldName(); } } } } } return $this; } /** * Add the signature to the given Headers * * @param Swift_Mime_HeaderSet $headers * @return Swift_Signers_DKIMSigner */ public function addSignature(Swift_Mime_HeaderSet $headers) { // Prepare the DKIM-Signature $params = array('v' => '1', 'a' => $this->_hashAlgorithm, 'bh' => base64_encode($this->_bodyHash), 'd' => $this->_domainName, 'h' => implode(': ', $this->_signedHeaders), 'i' => $this->_signerIdentity, 's' => $this->_selector); if ($this->_bodyCanon != 'simple') { $params['c'] = $this->_headerCanon.'/'.$this->_bodyCanon; } elseif ($this->_headerCanon != 'simple') { $params['c'] = $this->_headerCanon; } if ($this->_showLen) { $params['l'] = $this->_bodyLen; } if ($this->_signatureTimestamp === true) { $params['t'] = time(); if ($this->_signatureExpiration !== false) { $params['x'] = $params['t'] + $this->_signatureExpiration; } } else { if ($this->_signatureTimestamp !== false) { $params['t'] = $this->_signatureTimestamp; } if ($this->_signatureExpiration !== false) { $params['x'] = $this->_signatureExpiration; } } if ($this->_debugHeaders) { $params['z'] = implode('|', $this->_debugHeadersData); } $string = ''; foreach ($params as $k => $v) { $string .= $k.'='.$v.'; '; } $string = trim($string); $headers->addTextHeader('DKIM-Signature', $string); // Add the last DKIM-Signature $tmp = $headers->getAll('DKIM-Signature'); $this->_dkimHeader = end($tmp); $this->_addHeader(trim($this->_dkimHeader->toString())."\r\n b=", true); $this->_endOfHeaders(); if ($this->_debugHeaders) { $headers->addTextHeader('X-DebugHash', base64_encode($this->_headerHash)); } $this->_dkimHeader->setValue($string." b=".trim(chunk_split(base64_encode($this->_getEncryptedHash()), 73, " "))); return $this; } /* Private helpers */ protected function _addHeader($header, $is_sig = false) { switch ($this->_headerCanon) { case 'relaxed' : // Prepare Header and cascade $exploded = explode(':', $header, 2); $name = strtolower(trim($exploded[0])); $value = str_replace("\r\n", "", $exploded[1]); $value = preg_replace("/[ \t][ \t]+/", " ", $value); $header = $name.":".trim($value).($is_sig ? '' : "\r\n"); case 'simple' : // Nothing to do } $this->_addToHeaderHash($header); } protected function _endOfHeaders() { //$this->_headerHash=hash_final($this->_headerHashHandler, true); } protected function _canonicalizeBody($string) { $len = strlen($string); $canon = ''; $method = ($this->_bodyCanon == "relaxed"); for ($i = 0; $i < $len; ++$i) { if ($this->_bodyCanonIgnoreStart > 0) { --$this->_bodyCanonIgnoreStart; continue; } switch ($string[$i]) { case "\r" : $this->_bodyCanonLastChar = "\r"; break; case "\n" : if ($this->_bodyCanonLastChar == "\r") { if ($method) { $this->_bodyCanonSpace = false; } if ($this->_bodyCanonLine == '') { ++$this->_bodyCanonEmptyCounter; } else { $this->_bodyCanonLine = ''; $canon .= "\r\n"; } } else { // Wooops Error // todo handle it but should never happen } break; case " " : case "\t" : if ($method) { $this->_bodyCanonSpace = true; break; } default : if ($this->_bodyCanonEmptyCounter > 0) { $canon .= str_repeat("\r\n", $this->_bodyCanonEmptyCounter); $this->_bodyCanonEmptyCounter = 0; } if ($this->_bodyCanonSpace) { $this->_bodyCanonLine .= ' '; $canon .= ' '; $this->_bodyCanonSpace = false; } $this->_bodyCanonLine .= $string[$i]; $canon .= $string[$i]; } } $this->_addToBodyHash($canon); } protected function _endOfBody() { // Add trailing Line return if last line is non empty if (strlen($this->_bodyCanonLine) > 0) { $this->_addToBodyHash("\r\n"); } $this->_bodyHash = hash_final($this->_bodyHashHandler, true); } private function _addToBodyHash($string) { $len = strlen($string); if ($len > ($new_len = ($this->_maxLen - $this->_bodyLen))) { $string = substr($string, 0, $new_len); $len = $new_len; } hash_update($this->_bodyHashHandler, $string); $this->_bodyLen += $len; } private function _addToHeaderHash($header) { if ($this->_debugHeaders) { $this->_debugHeadersData[] = trim($header); } $this->_headerCanonData .= $header; } /** * @throws Swift_SwiftException * @return string */ private function _getEncryptedHash() { $signature = ''; switch ($this->_hashAlgorithm) { case 'rsa-sha1': $algorithm = OPENSSL_ALGO_SHA1; break; case 'rsa-sha256': $algorithm = OPENSSL_ALGO_SHA256; break; } $pkeyId = openssl_get_privatekey($this->_privateKey); if (!$pkeyId) { throw new Swift_SwiftException('Unable to load DKIM Private Key ['.openssl_error_string().']'); } if (openssl_sign($this->_headerCanonData, $signature, $pkeyId, $algorithm)) { return $signature; } throw new Swift_SwiftException('Unable to sign DKIM Hash ['.openssl_error_string().']'); } } */ class Swift_Signers_DomainKeySigner implements Swift_Signers_HeaderSigner { /** * PrivateKey * * @var string */ protected $_privateKey; /** * DomainName * * @var string */ protected $_domainName; /** * Selector * * @var string */ protected $_selector; /** * Hash algorithm used * * @var string */ protected $_hashAlgorithm = 'rsa-sha1'; /** * Canonisation method * * @var string */ protected $_canon = 'simple'; /** * Headers not being signed * * @var array */ protected $_ignoredHeaders = array(); /** * Signer identity * * @var string */ protected $_signerIdentity; /** * Must we embed signed headers? * * @var bool */ protected $_debugHeaders = false; // work variables /** * Headers used to generate hash * * @var array */ private $_signedHeaders = array(); /** * Stores the signature header * * @var Swift_Mime_Headers_ParameterizedHeader */ protected $_domainKeyHeader; /** * Hash Handler * * @var resource|null */ private $_hashHandler; private $_hash; private $_canonData = ''; private $_bodyCanonEmptyCounter = 0; private $_bodyCanonIgnoreStart = 2; private $_bodyCanonSpace = false; private $_bodyCanonLastChar = null; private $_bodyCanonLine = ''; private $_bound = array(); /** * Constructor * * @param string $privateKey * @param string $domainName * @param string $selector */ public function __construct($privateKey, $domainName, $selector) { $this->_privateKey = $privateKey; $this->_domainName = $domainName; $this->_signerIdentity = '@'.$domainName; $this->_selector = $selector; } /** * Instanciate DomainKeySigner * * @param string $privateKey * @param string $domainName * @param string $selector * @return Swift_Signers_DomainKeySigner */ public static function newInstance($privateKey, $domainName, $selector) { return new static($privateKey, $domainName, $selector); } /** * Resets internal states * * @return Swift_Signers_DomainKeysSigner */ public function reset() { $this->_hash = null; $this->_hashHandler = null; $this->_bodyCanonIgnoreStart = 2; $this->_bodyCanonEmptyCounter = 0; $this->_bodyCanonLastChar = null; $this->_bodyCanonSpace = false; return $this; } /** * Writes $bytes to the end of the stream. * * Writing may not happen immediately if the stream chooses to buffer. If * you want to write these bytes with immediate effect, call {@link commit()} * after calling write(). * * This method returns the sequence ID of the write (i.e. 1 for first, 2 for * second, etc etc). * * @param string $bytes * @return int * @throws Swift_IoException * @return Swift_Signers_DomainKeysSigner */ public function write($bytes) { $this->_canonicalizeBody($bytes); foreach ($this->_bound as $is) { $is->write($bytes); } return $this; } /** * For any bytes that are currently buffered inside the stream, force them * off the buffer. * * @throws Swift_IoException * @return Swift_Signers_DomainKeysSigner */ public function commit() { // Nothing to do return $this; } /** * Attach $is to this stream. * The stream acts as an observer, receiving all data that is written. * All {@link write()} and {@link flushBuffers()} operations will be mirrored. * * @param Swift_InputByteStream $is * @return Swift_Signers_DomainKeysSigner */ public function bind(Swift_InputByteStream $is) { // Don't have to mirror anything $this->_bound[] = $is; return $this; } /** * Remove an already bound stream. * If $is is not bound, no errors will be raised. * If the stream currently has any buffered data it will be written to $is * before unbinding occurs. * * @param Swift_InputByteStream $is * @return Swift_Signers_DomainKeysSigner */ public function unbind(Swift_InputByteStream $is) { // Don't have to mirror anything foreach ($this->_bound as $k => $stream) { if ($stream === $is) { unset($this->_bound[$k]); return; } } return $this; } /** * Flush the contents of the stream (empty it) and set the internal pointer * to the beginning. * * @throws Swift_IoException * @return Swift_Signers_DomainKeysSigner */ public function flushBuffers() { $this->reset(); return $this; } /** * Set hash_algorithm, must be one of rsa-sha256 | rsa-sha1 defaults to rsa-sha256 * * @param string $hash * @return Swift_Signers_DomainKeysSigner */ public function setHashAlgorithm($hash) { $this->_hashAlgorithm = 'rsa-sha1'; return $this; } /** * Set the canonicalization algorithm * * @param string $canon simple | nofws defaults to simple * @return Swift_Signers_DomainKeysSigner */ public function setCanon($canon) { if ($canon == 'nofws') { $this->_canon = 'nofws'; } else { $this->_canon = 'simple'; } return $this; } /** * Set the signer identity * * @param string $identity * @return Swift_Signers_DomainKeySigner */ public function setSignerIdentity($identity) { $this->_signerIdentity = $identity; return $this; } /** * Enable / disable the DebugHeaders * * @param bool $debug * @return Swift_Signers_DomainKeySigner */ public function setDebugHeaders($debug) { $this->_debugHeaders = (bool) $debug; return $this; } /** * Start Body * */ public function startBody() { } /** * End Body * */ public function endBody() { $this->_endOfBody(); } /** * Returns the list of Headers Tampered by this plugin * * @return array */ public function getAlteredHeaders() { if ($this->_debugHeaders) { return array('DomainKey-Signature', 'X-DebugHash'); } else { return array('DomainKey-Signature'); } } /** * Adds an ignored Header * * @param string $header_name * @return Swift_Signers_DomainKeySigner */ public function ignoreHeader($header_name) { $this->_ignoredHeaders[strtolower($header_name)] = true; return $this; } /** * Set the headers to sign * * @param Swift_Mime_HeaderSet $headers * @return Swift_Signers_DomainKeySigner */ public function setHeaders(Swift_Mime_HeaderSet $headers) { $this->_startHash(); $this->_canonData = ''; // Loop through Headers $listHeaders = $headers->listAll(); foreach ($listHeaders as $hName) { // Check if we need to ignore Header if (! isset($this->_ignoredHeaders[strtolower($hName)])) { if ($headers->has($hName)) { $tmp = $headers->getAll($hName); foreach ($tmp as $header) { if ($header->getFieldBody() != '') { $this->_addHeader($header->toString()); $this->_signedHeaders[] = $header->getFieldName(); } } } } } $this->_endOfHeaders(); return $this; } /** * Add the signature to the given Headers * * @param Swift_Mime_HeaderSet $headers * @return Swift_Signers_DomainKeySigner */ public function addSignature(Swift_Mime_HeaderSet $headers) { // Prepare the DomainKey-Signature Header $params = array('a' => $this->_hashAlgorithm, 'b' => chunk_split(base64_encode($this->_getEncryptedHash()), 73, " "), 'c' => $this->_canon, 'd' => $this->_domainName, 'h' => implode(': ', $this->_signedHeaders), 'q' => 'dns', 's' => $this->_selector); $string = ''; foreach ($params as $k => $v) { $string .= $k.'='.$v.'; '; } $string = trim($string); $headers->addTextHeader('DomainKey-Signature', $string); return $this; } /* Private helpers */ protected function _addHeader($header) { switch ($this->_canon) { case 'nofws' : // Prepare Header and cascade $exploded = explode(':', $header, 2); $name = strtolower(trim($exploded[0])); $value = str_replace("\r\n", "", $exploded[1]); $value = preg_replace("/[ \t][ \t]+/", " ", $value); $header = $name.":".trim($value)."\r\n"; case 'simple' : // Nothing to do } $this->_addToHash($header); } protected function _endOfHeaders() { $this->_bodyCanonEmptyCounter = 1; } protected function _canonicalizeBody($string) { $len = strlen($string); $canon = ''; $nofws = ($this->_canon == "nofws"); for ($i = 0; $i < $len; ++$i) { if ($this->_bodyCanonIgnoreStart > 0) { --$this->_bodyCanonIgnoreStart; continue; } switch ($string[$i]) { case "\r" : $this->_bodyCanonLastChar = "\r"; break; case "\n" : if ($this->_bodyCanonLastChar == "\r") { if ($nofws) { $this->_bodyCanonSpace = false; } if ($this->_bodyCanonLine == '') { ++$this->_bodyCanonEmptyCounter; } else { $this->_bodyCanonLine = ''; $canon .= "\r\n"; } } else { // Wooops Error throw new Swift_SwiftException('Invalid new line sequence in mail found \n without preceding \r'); } break; case " " : case "\t" : case "\x09": //HTAB if ($nofws) { $this->_bodyCanonSpace = true; break; } default : if ($this->_bodyCanonEmptyCounter > 0) { $canon .= str_repeat("\r\n", $this->_bodyCanonEmptyCounter); $this->_bodyCanonEmptyCounter = 0; } $this->_bodyCanonLine .= $string[$i]; $canon .= $string[$i]; } } $this->_addToHash($canon); } protected function _endOfBody() { if (strlen($this->_bodyCanonLine) > 0) { $this->_addToHash("\r\n"); } $this->_hash = hash_final($this->_hashHandler, true); } private function _addToHash($string) { $this->_canonData .= $string; hash_update($this->_hashHandler, $string); } private function _startHash() { // Init switch ($this->_hashAlgorithm) { case 'rsa-sha1' : $this->_hashHandler = hash_init('sha1'); break; } $this->_canonLine = ''; } /** * @throws Swift_SwiftException * @return string */ private function _getEncryptedHash() { $signature = ''; $pkeyId = openssl_get_privatekey($this->_privateKey); if (!$pkeyId) { throw new Swift_SwiftException('Unable to load DomainKey Private Key ['.openssl_error_string().']'); } if (openssl_sign($this->_canonData, $signature, $pkeyId, OPENSSL_ALGO_SHA1)) { return $signature; } throw new Swift_SwiftException('Unable to sign DomainKey Hash ['.openssl_error_string().']'); } } */ interface Swift_Signers_HeaderSigner extends Swift_Signer, Swift_InputByteStream { /** * Exclude an header from the signed headers * * @param string $header_name * * @return Swift_Signers_HeaderSigner */ public function ignoreHeader($header_name); /** * Prepare the Signer to get a new Body * * @return Swift_Signers_HeaderSigner */ public function startBody(); /** * Give the signal that the body has finished streaming * * @return Swift_Signers_HeaderSigner */ public function endBody(); /** * Give the headers already given * * @param Swift_Mime_SimpleHeaderSet $headers * * @return Swift_Signers_HeaderSigner */ public function setHeaders(Swift_Mime_HeaderSet $headers); /** * Add the header(s) to the headerSet * * @param Swift_Mime_HeaderSet $headers * * @return Swift_Signers_HeaderSigner */ public function addSignature(Swift_Mime_HeaderSet $headers); /** * Return the list of header a signer might tamper * * @return array */ public function getAlteredHeaders(); } */ class Swift_Signers_OpenDKIMSigner extends Swift_Signers_DKIMSigner { private $_peclLoaded = false; private $_dkimHandler = null; private $dropFirstLF = true; const CANON_RELAXED = 1; const CANON_SIMPLE = 2; const SIG_RSA_SHA1 = 3; const SIG_RSA_SHA256 = 4; public function __construct($privateKey, $domainName, $selector) { if (extension_loaded('opendkim')) { $this->_peclLoaded = true; } else { throw new Swift_SwiftException('php-opendkim extension not found'); } parent::__construct($privateKey, $domainName, $selector); } public static function newInstance($privateKey, $domainName, $selector) { return new static($privateKey, $domainName, $selector); } public function addSignature(Swift_Mime_HeaderSet $headers) { $header = new Swift_Mime_Headers_OpenDKIMHeader('DKIM-Signature'); $headerVal = $this->_dkimHandler->getSignatureHeader(); if (!$headerVal) { throw new Swift_SwiftException('OpenDKIM Error: '.$this->_dkimHandler->getError()); } $header->setValue($headerVal); $headers->set($header); return $this; } public function setHeaders(Swift_Mime_HeaderSet $headers) { $bodyLen = $this->_bodyLen; if (is_bool($bodyLen)) { $bodyLen = - 1; } $hash = ($this->_hashAlgorithm == 'rsa-sha1') ? OpenDKIMSign::ALG_RSASHA1 : OpenDKIMSign::ALG_RSASHA256; $bodyCanon = ($this->_bodyCanon == 'simple') ? OpenDKIMSign::CANON_SIMPLE : OpenDKIMSign::CANON_RELAXED; $headerCanon = ($this->_headerCanon == 'simple') ? OpenDKIMSign::CANON_SIMPLE : OpenDKIMSign::CANON_RELAXED; $this->_dkimHandler = new OpenDKIMSign($this->_privateKey, $this->_selector, $this->_domainName, $headerCanon, $bodyCanon, $hash, $bodyLen); // Hardcode signature Margin for now $this->_dkimHandler->setMargin(78); if (!is_numeric($this->_signatureTimestamp)) { OpenDKIM::setOption(OpenDKIM::OPTS_FIXEDTIME, time()); } else { if (!OpenDKIM::setOption(OpenDKIM::OPTS_FIXEDTIME, $this->_signatureTimestamp)) { throw new Swift_SwiftException('Unable to force signature timestamp ['.openssl_error_string().']'); } } if (isset($this->_signerIdentity)) { $this->_dkimHandler->setSigner($this->_signerIdentity); } $listHeaders = $headers->listAll(); foreach ($listHeaders as $hName) { // Check if we need to ignore Header if (! isset($this->_ignoredHeaders[strtolower($hName)])) { $tmp = $headers->getAll($hName); if ($headers->has($hName)) { foreach ($tmp as $header) { if ($header->getFieldBody() != '') { $htosign = $header->toString(); $this->_dkimHandler->header($htosign); $this->_signedHeaders[] = $header->getFieldName(); } } } } } return $this; } public function startBody() { if (! $this->_peclLoaded) { return parent::startBody(); } $this->dropFirstLF = true; $this->_dkimHandler->eoh(); return $this; } public function endBody() { if (! $this->_peclLoaded) { return parent::endBody(); } $this->_dkimHandler->eom(); return $this; } public function reset() { $this->_dkimHandler = null; parent::reset(); return $this; } /** * Set the signature timestamp * * @param timestamp $time * @return Swift_Signers_DKIMSigner */ public function setSignatureTimestamp($time) { $this->_signatureTimestamp = $time; return $this; } /** * Set the signature expiration timestamp * * @param timestamp $time * @return Swift_Signers_DKIMSigner */ public function setSignatureExpiration($time) { $this->_signatureExpiration = $time; return $this; } /** * Enable / disable the DebugHeaders * * @param bool $debug * @return Swift_Signers_DKIMSigner */ public function setDebugHeaders($debug) { $this->_debugHeaders = (bool) $debug; return $this; } // Protected protected function _canonicalizeBody($string) { if (! $this->_peclLoaded) { return parent::_canonicalizeBody($string); } if (false && $this->dropFirstLF === true) { if ($string[0] == "\r" && $string[1] == "\n") { $string = substr($string, 2); } } $this->dropFirstLF = false; if (strlen($string)) { $this->_dkimHandler->body($string); } } } */ class Swift_Signers_SMimeSigner implements Swift_Signers_BodySigner { protected $signCertificate; protected $signPrivateKey; protected $encryptCert; protected $signThenEncrypt = true; protected $signLevel; protected $encryptLevel; protected $signOptions; protected $encryptOptions; protected $encryptCipher; /** * @var Swift_StreamFilters_StringReplacementFilterFactory */ protected $replacementFactory; /** * @var Swift_Mime_HeaderFactory */ protected $headerFactory; /** * Constructor. * * @param string $certificate * @param string $privateKey * @param string $encryptCertificate */ public function __construct($signCertificate = null, $signPrivateKey = null, $encryptCertificate = null) { if (null !== $signPrivateKey) { $this->setSignCertificate($signCertificate, $signPrivateKey); } if (null !== $encryptCertificate) { $this->setEncryptCertificate($encryptCertificate); } $this->replacementFactory = Swift_DependencyContainer::getInstance() ->lookup('transport.replacementfactory'); $this->signOptions = PKCS7_DETACHED; // Supported since php5.4 if (defined('OPENSSL_CIPHER_AES_128_CBC')) { $this->encryptCipher = OPENSSL_CIPHER_AES_128_CBC; } else { $this->encryptCipher = OPENSSL_CIPHER_RC2_128; } } /** * Returns an new Swift_Signers_SMimeSigner instance. * * @param string $certificate * @param string $privateKey * * @return Swift_Signers_SMimeSigner */ public static function newInstance($certificate = null, $privateKey = null) { return new self($certificate, $privateKey); } /** * Set the certificate location to use for signing. * * @link http://www.php.net/manual/en/openssl.pkcs7.flags.php * * @param string $certificate * @param string|array $privateKey If the key needs an passphrase use array('file-location', 'passphrase') instead * @param int $signOptions Bitwise operator options for openssl_pkcs7_sign() * * @return Swift_Signers_SMimeSigner */ public function setSignCertificate($certificate, $privateKey = null, $signOptions = PKCS7_DETACHED) { $this->signCertificate = 'file://'.str_replace('\\', '/', realpath($certificate)); if (null !== $privateKey) { if (is_array($privateKey)) { $this->signPrivateKey = $privateKey; $this->signPrivateKey[0] = 'file://'.str_replace('\\', '/', realpath($privateKey[0])); } else { $this->signPrivateKey = 'file://'.str_replace('\\', '/', realpath($privateKey)); } } $this->signOptions = $signOptions; return $this; } /** * Set the certificate location to use for encryption. * * @link http://www.php.net/manual/en/openssl.pkcs7.flags.php * @link http://nl3.php.net/manual/en/openssl.ciphers.php * * @param string|array $recipientCerts Either an single X.509 certificate, or an assoc array of X.509 certificates. * @param int $cipher * * @return Swift_Signers_SMimeSigner */ public function setEncryptCertificate($recipientCerts, $cipher = null) { if (is_array($recipientCerts)) { $this->encryptCert = array(); foreach ($recipientCerts as $cert) { $this->encryptCert[] = 'file://'.str_replace('\\', '/', realpath($cert)); } } else { $this->encryptCert = 'file://'.str_replace('\\', '/', realpath($recipientCerts)); } if (null !== $cipher) { $this->encryptCipher = $cipher; } return $this; } /** * @return string */ public function getSignCertificate() { return $this->signCertificate; } /** * @return string */ public function getSignPrivateKey() { return $this->signPrivateKey; } /** * Set perform signing before encryption. * * The default is to first sign the message and then encrypt. * But some older mail clients, namely Microsoft Outlook 2000 will work when the message first encrypted. * As this goes against the official specs, its recommended to only use 'encryption -> signing' when specifically targeting these 'broken' clients. * * @param string $signThenEncrypt * * @return Swift_Signers_SMimeSigner */ public function setSignThenEncrypt($signThenEncrypt = true) { $this->signThenEncrypt = $signThenEncrypt; return $this; } /** * @return bool */ public function isSignThenEncrypt() { return $this->signThenEncrypt; } /** * Resets internal states. * * @return Swift_Signers_SMimeSigner */ public function reset() { return $this; } /** * Change the Swift_Message to apply the signing. * * @param Swift_Message $message * * @return Swift_Signers_SMimeSigner */ public function signMessage(Swift_Message $message) { if (null === $this->signCertificate && null === $this->encryptCert) { return $this; } // Store the message using ByteStream to a file{1} // Remove all Children // Sign file{1}, parse the new MIME headers and set them on the primary MimeEntity // Set the singed-body as the new body (without boundary) $messageStream = new Swift_ByteStream_TemporaryFileByteStream(); $this->toSMimeByteStream($messageStream, $message); $message->setEncoder(Swift_DependencyContainer::getInstance()->lookup('mime.rawcontentencoder')); $message->setChildren(array()); $this->streamToMime($messageStream, $message); } /** * Return the list of header a signer might tamper. * * @return array */ public function getAlteredHeaders() { return array('Content-Type', 'Content-Transfer-Encoding', 'Content-Disposition'); } /** * @param Swift_InputByteStream $inputStream * @param Swift_Message $mimeEntity */ protected function toSMimeByteStream(Swift_InputByteStream $inputStream, Swift_Message $message) { $mimeEntity = $this->createMessage($message); $messageStream = new Swift_ByteStream_TemporaryFileByteStream(); $mimeEntity->toByteStream($messageStream); $messageStream->commit(); if (null !== $this->signCertificate && null !== $this->encryptCert) { $temporaryStream = new Swift_ByteStream_TemporaryFileByteStream(); if ($this->signThenEncrypt) { $this->messageStreamToSignedByteStream($messageStream, $temporaryStream); $this->messageStreamToEncryptedByteStream($temporaryStream, $inputStream); } else { $this->messageStreamToEncryptedByteStream($messageStream, $temporaryStream); $this->messageStreamToSignedByteStream($temporaryStream, $inputStream); } } elseif ($this->signCertificate !== null) { $this->messageStreamToSignedByteStream($messageStream, $inputStream); } else { $this->messageStreamToEncryptedByteStream($messageStream, $inputStream); } } /** * @param Swift_Message $message * * @return Swift_Message */ protected function createMessage(Swift_Message $message) { $mimeEntity = new Swift_Message('', $message->getBody(), $message->getContentType(), $message->getCharset()); $mimeEntity->setChildren($message->getChildren()); $messageHeaders = $mimeEntity->getHeaders(); $messageHeaders->remove('Message-ID'); $messageHeaders->remove('Date'); $messageHeaders->remove('Subject'); $messageHeaders->remove('MIME-Version'); $messageHeaders->remove('To'); $messageHeaders->remove('From'); return $mimeEntity; } /** * @param Swift_FileStream $outputStream * @param Swift_InputByteStream $inputStream * * @throws Swift_IoException */ protected function messageStreamToSignedByteStream(Swift_FileStream $outputStream, Swift_InputByteStream $inputStream) { $signedMessageStream = new Swift_ByteStream_TemporaryFileByteStream(); if (!openssl_pkcs7_sign($outputStream->getPath(), $signedMessageStream->getPath(), $this->signCertificate, $this->signPrivateKey, array(), $this->signOptions)) { throw new Swift_IoException(sprintf('Failed to sign S/Mime message. Error: "%s".', openssl_error_string())); } $this->copyFromOpenSSLOutput($signedMessageStream, $inputStream); } /** * @param Swift_FileStream $outputStream * @param Swift_InputByteStream $is * * @throws Swift_IoException */ protected function messageStreamToEncryptedByteStream(Swift_FileStream $outputStream, Swift_InputByteStream $is) { $encryptedMessageStream = new Swift_ByteStream_TemporaryFileByteStream(); if (!openssl_pkcs7_encrypt($outputStream->getPath(), $encryptedMessageStream->getPath(), $this->encryptCert, array(), 0, $this->encryptCipher)) { throw new Swift_IoException(sprintf('Failed to encrypt S/Mime message. Error: "%s".', openssl_error_string())); } $this->copyFromOpenSSLOutput($encryptedMessageStream, $is); } /** * @param Swift_OutputByteStream $fromStream * @param Swift_InputByteStream $toStream */ protected function copyFromOpenSSLOutput(Swift_OutputByteStream $fromStream, Swift_InputByteStream $toStream) { $bufferLength = 4096; $filteredStream = new Swift_ByteStream_TemporaryFileByteStream(); $filteredStream->addFilter($this->replacementFactory->createFilter("\r\n", "\n"), 'CRLF to LF'); $filteredStream->addFilter($this->replacementFactory->createFilter("\n", "\r\n"), 'LF to CRLF'); while (false !== ($buffer = $fromStream->read($bufferLength))) { $filteredStream->write($buffer); } $filteredStream->flushBuffers(); while (false !== ($buffer = $filteredStream->read($bufferLength))) { $toStream->write($buffer); } $toStream->commit(); } /** * Merges an OutputByteStream to Swift_Message. * * @param Swift_OutputByteStream $fromStream * @param Swift_Message $message */ protected function streamToMime(Swift_OutputByteStream $fromStream, Swift_Message $message) { $bufferLength = 78; $headerData = ''; $fromStream->setReadPointer(0); while (($buffer = $fromStream->read($bufferLength)) !== false) { $headerData .= $buffer; if (false !== strpos($buffer, "\r\n\r\n")) { break; } } $headersPosEnd = strpos($headerData, "\r\n\r\n"); $headerData = trim($headerData); $headerData = substr($headerData, 0, $headersPosEnd); $headerLines = explode("\r\n", $headerData); unset($headerData); $headers = array(); $currentHeaderName = ''; foreach ($headerLines as $headerLine) { // Line separated if (ctype_space($headerLines[0]) || false === strpos($headerLine, ':')) { $headers[$currentHeaderName] .= ' '.trim($headerLine); continue; } $header = explode(':', $headerLine, 2); $currentHeaderName = strtolower($header[0]); $headers[$currentHeaderName] = trim($header[1]); } $messageStream = new Swift_ByteStream_TemporaryFileByteStream(); $messageStream->addFilter($this->replacementFactory->createFilter("\r\n", "\n"), 'CRLF to LF'); $messageStream->addFilter($this->replacementFactory->createFilter("\n", "\r\n"), 'LF to CRLF'); $messageHeaders = $message->getHeaders(); // No need to check for 'application/pkcs7-mime', as this is always base64 if ('multipart/signed;' === substr($headers['content-type'], 0, 17)) { if (!preg_match('/boundary=("[^"]+"|(?:[^\s]+|$))/is', $headers['content-type'], $contentTypeData)) { throw new Swift_SwiftException('Failed to find Boundary parameter'); } $boundary = trim($contentTypeData['1'], '"'); $boundaryLen = strlen($boundary); // Skip the header and CRLF CRLF $fromStream->setReadPointer($headersPosEnd + 4); while (false !== ($buffer = $fromStream->read($bufferLength))) { $messageStream->write($buffer); } $messageStream->commit(); $messageHeaders->remove('Content-Transfer-Encoding'); $message->setContentType($headers['content-type']); $message->setBoundary($boundary); $message->setBody($messageStream); } else { $fromStream->setReadPointer($headersPosEnd + 4); if (null === $this->headerFactory) { $this->headerFactory = Swift_DependencyContainer::getInstance()->lookup('mime.headerfactory'); } $message->setContentType($headers['content-type']); $messageHeaders->set($this->headerFactory->createTextHeader('Content-Transfer-Encoding', $headers['content-transfer-encoding'])); $messageHeaders->set($this->headerFactory->createTextHeader('Content-Disposition', $headers['content-disposition'])); while (false !== ($buffer = $fromStream->read($bufferLength))) { $messageStream->write($buffer); } $messageStream->commit(); $message->setBody($messageStream); } } } createDependenciesFor('transport.smtp') ); $this->setHost($host); $this->setPort($port); $this->setEncryption($security); } /** * Create a new SmtpTransport instance. * * @param string $host * @param int $port * @param string $security * * @return Swift_SmtpTransport */ public static function newInstance($host = 'localhost', $port = 25, $security = null) { return new self($host, $port, $security); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Interface for spools. * * @author Fabien Potencier */ interface Swift_Spool { /** * Starts this Spool mechanism. */ public function start(); /** * Stops this Spool mechanism. */ public function stop(); /** * Tests if this Spool mechanism has started. * * @return bool */ public function isStarted(); /** * Queues a message. * * @param Swift_Mime_Message $message The message to store * * @return bool Whether the operation has succeeded */ public function queueMessage(Swift_Mime_Message $message); /** * Sends messages using the given transport instance. * * @param Swift_Transport $transport A transport instance * @param string[] $failedRecipients An array of failures by-reference * * @return int The number of sent emails */ public function flushQueue(Swift_Transport $transport, &$failedRecipients = null); } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Stores Messages in a queue. * * @author Fabien Potencier */ class Swift_SpoolTransport extends Swift_Transport_SpoolTransport { /** * Create a new SpoolTransport. * * @param Swift_Spool $spool */ public function __construct(Swift_Spool $spool) { $arguments = Swift_DependencyContainer::getInstance() ->createDependenciesFor('transport.spool'); $arguments[] = $spool; call_user_func_array( array($this, 'Swift_Transport_SpoolTransport::__construct'), $arguments ); } /** * Create a new SpoolTransport instance. * * @param Swift_Spool $spool * * @return Swift_SpoolTransport */ public static function newInstance(Swift_Spool $spool) { return new self($spool); } } _search = $search; $this->_index = array(); $this->_tree = array(); $this->_replace = array(); $this->_repSize = array(); $tree = null; $i = null; $last_size = $size = 0; foreach ($search as $i => $search_element) { if ($tree !== null) { $tree[-1] = min (count($replace) - 1, $i - 1); $tree[-2] = $last_size; } $tree = &$this->_tree; if (is_array ($search_element)) { foreach ($search_element as $k => $char) { $this->_index[$char] = true; if (!isset($tree[$char])) { $tree[$char] = array(); } $tree = &$tree[$char]; } $last_size = $k+1; $size = max($size, $last_size); } else { $last_size = 1; if (!isset($tree[$search_element])) { $tree[$search_element] = array(); } $tree = &$tree[$search_element]; $size = max($last_size, $size); $this->_index[$search_element] = true; } } if ($i !== null) { $tree[-1] = min (count ($replace) - 1, $i); $tree[-2] = $last_size; $this->_treeMaxLen = $size; } foreach ($replace as $rep) { if (!is_array($rep)) { $rep = array ($rep); } $this->_replace[] = $rep; } for ($i = count($this->_replace) - 1; $i >= 0; --$i) { $this->_replace[$i] = $rep = $this->filter($this->_replace[$i], $i); $this->_repSize[$i] = count($rep); } } /** * Returns true if based on the buffer passed more bytes should be buffered. * * @param array $buffer * * @return bool */ public function shouldBuffer($buffer) { $endOfBuffer = end($buffer); return isset ($this->_index[$endOfBuffer]); } /** * Perform the actual replacements on $buffer and return the result. * * @param array $buffer * @param int $_minReplaces * * @return array */ public function filter($buffer, $_minReplaces = -1) { if ($this->_treeMaxLen == 0) { return $buffer; } $newBuffer = array(); $buf_size = count($buffer); for ($i = 0; $i < $buf_size; ++$i) { $search_pos = $this->_tree; $last_found = PHP_INT_MAX; // We try to find if the next byte is part of a search pattern for ($j = 0; $j <= $this->_treeMaxLen; ++$j) { // We have a new byte for a search pattern if (isset ($buffer [$p = $i + $j]) && isset($search_pos[$buffer[$p]])) { $search_pos = $search_pos[$buffer[$p]]; // We have a complete pattern, save, in case we don't find a better match later if (isset($search_pos[- 1]) && $search_pos[-1] < $last_found && $search_pos[-1] > $_minReplaces) { $last_found = $search_pos[-1]; $last_size = $search_pos[-2]; } } // We got a complete pattern elseif ($last_found !== PHP_INT_MAX) { // Adding replacement datas to output buffer $rep_size = $this->_repSize[$last_found]; for ($j = 0; $j < $rep_size; ++$j) { $newBuffer[] = $this->_replace[$last_found][$j]; } // We Move cursor forward $i += $last_size - 1; // Edge Case, last position in buffer if ($i >= $buf_size) { $newBuffer[] = $buffer[$i]; } // We start the next loop continue 2; } else { // this byte is not in a pattern and we haven't found another pattern break; } } // Normal byte, move it to output buffer $newBuffer[] = $buffer[$i]; } return $newBuffer; } } _search = $search; $this->_replace = $replace; } /** * Returns true if based on the buffer passed more bytes should be buffered. * * @param string $buffer * * @return bool */ public function shouldBuffer($buffer) { $endOfBuffer = substr($buffer, -1); foreach ((array) $this->_search as $needle) { if (false !== strpos($needle, $endOfBuffer)) { return true; } } return false; } /** * Perform the actual replacements on $buffer and return the result. * * @param string $buffer * * @return string */ public function filter($buffer) { return str_replace($this->_search, $this->_replace, $buffer); } } _filters[$search][$replace])) { if (!isset($this->_filters[$search])) { $this->_filters[$search] = array(); } if (!isset($this->_filters[$search][$replace])) { $this->_filters[$search][$replace] = array(); } $this->_filters[$search][$replace] = new Swift_StreamFilters_StringReplacementFilter($search, $replace); } return $this->_filters[$search][$replace]; } } _eventDispatcher = $dispatcher; $this->_buffer = $buf; $this->_lookupHostname(); } /** * Set the name of the local domain which Swift will identify itself as. * * This should be a fully-qualified domain name and should be truly the domain * you're using. * * If your server doesn't have a domain name, use the IP in square * brackets (i.e. [127.0.0.1]). * * @param string $domain * * @return Swift_Transport_AbstractSmtpTransport */ public function setLocalDomain($domain) { $this->_domain = $domain; return $this; } /** * Get the name of the domain Swift will identify as. * * @return string */ public function getLocalDomain() { return $this->_domain; } /** * Sets the source IP. * * @param string $source */ public function setSourceIp($source) { $this->_sourceIp = $source; } /** * Returns the IP used to connect to the destination * * @return string */ public function getSourceIp() { return $this->_sourceIp; } /** * Start the SMTP connection. */ public function start() { if (!$this->_started) { if ($evt = $this->_eventDispatcher->createTransportChangeEvent($this)) { $this->_eventDispatcher->dispatchEvent($evt, 'beforeTransportStarted'); if ($evt->bubbleCancelled()) { return; } } try { $this->_buffer->initialize($this->_getBufferParams()); } catch (Swift_TransportException $e) { $this->_throwException($e); } $this->_readGreeting(); $this->_doHeloCommand(); if ($evt) { $this->_eventDispatcher->dispatchEvent($evt, 'transportStarted'); } $this->_started = true; } } /** * Test if an SMTP connection has been established. * * @return bool */ public function isStarted() { return $this->_started; } /** * Send the given Message. * * Recipient/sender data will be retrieved from the Message API. * The return value is the number of recipients who were accepted for delivery. * * @param Swift_Mime_Message $message * @param string[] $failedRecipients An array of failures by-reference * * @return int */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $sent = 0; $failedRecipients = (array) $failedRecipients; if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); if ($evt->bubbleCancelled()) { return 0; } } if (!$reversePath = $this->_getReversePath($message)) { $this->_throwException(new Swift_TransportException( 'Cannot send message without a sender address' ) ); } $to = (array) $message->getTo(); $cc = (array) $message->getCc(); $tos = array_merge($to, $cc); $bcc = (array) $message->getBcc(); $message->setBcc(array()); try { $sent += $this->_sendTo($message, $reversePath, $tos, $failedRecipients); $sent += $this->_sendBcc($message, $reversePath, $bcc, $failedRecipients); } catch (Exception $e) { $message->setBcc($bcc); throw $e; } $message->setBcc($bcc); if ($evt) { if ($sent == count($to) + count($cc) + count($bcc)) { $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS); } elseif ($sent > 0) { $evt->setResult(Swift_Events_SendEvent::RESULT_TENTATIVE); } else { $evt->setResult(Swift_Events_SendEvent::RESULT_FAILED); } $evt->setFailedRecipients($failedRecipients); $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); } $message->generateId(); //Make sure a new Message ID is used return $sent; } /** * Stop the SMTP connection. */ public function stop() { if ($this->_started) { if ($evt = $this->_eventDispatcher->createTransportChangeEvent($this)) { $this->_eventDispatcher->dispatchEvent($evt, 'beforeTransportStopped'); if ($evt->bubbleCancelled()) { return; } } try { $this->executeCommand("QUIT\r\n", array(221)); } catch (Swift_TransportException $e) { } try { $this->_buffer->terminate(); if ($evt) { $this->_eventDispatcher->dispatchEvent($evt, 'transportStopped'); } } catch (Swift_TransportException $e) { $this->_throwException($e); } } $this->_started = false; } /** * Register a plugin. * * @param Swift_Events_EventListener $plugin */ public function registerPlugin(Swift_Events_EventListener $plugin) { $this->_eventDispatcher->bindEventListener($plugin); } /** * Reset the current mail transaction. */ public function reset() { $this->executeCommand("RSET\r\n", array(250)); } /** * Get the IoBuffer where read/writes are occurring. * * @return Swift_Transport_IoBuffer */ public function getBuffer() { return $this->_buffer; } /** * Run a command against the buffer, expecting the given response codes. * * If no response codes are given, the response will not be validated. * If codes are given, an exception will be thrown on an invalid response. * * @param string $command * @param int[] $codes * @param string[] $failures An array of failures by-reference * * @return string */ public function executeCommand($command, $codes = array(), &$failures = null) { $failures = (array) $failures; $seq = $this->_buffer->write($command); $response = $this->_getFullResponse($seq); if ($evt = $this->_eventDispatcher->createCommandEvent($this, $command, $codes)) { $this->_eventDispatcher->dispatchEvent($evt, 'commandSent'); } $this->_assertResponseCode($response, $codes); return $response; } /** Read the opening SMTP greeting */ protected function _readGreeting() { $this->_assertResponseCode($this->_getFullResponse(0), array(220)); } /** Send the HELO welcome */ protected function _doHeloCommand() { $this->executeCommand( sprintf("HELO %s\r\n", $this->_domain), array(250) ); } /** Send the MAIL FROM command */ protected function _doMailFromCommand($address) { $this->executeCommand( sprintf("MAIL FROM: <%s>\r\n", $address), array(250) ); } /** Send the RCPT TO command */ protected function _doRcptToCommand($address) { $this->executeCommand( sprintf("RCPT TO: <%s>\r\n", $address), array(250, 251, 252) ); } /** Send the DATA command */ protected function _doDataCommand() { $this->executeCommand("DATA\r\n", array(354)); } /** Stream the contents of the message over the buffer */ protected function _streamMessage(Swift_Mime_Message $message) { $this->_buffer->setWriteTranslations(array("\r\n." => "\r\n..")); try { $message->toByteStream($this->_buffer); $this->_buffer->flushBuffers(); } catch (Swift_TransportException $e) { $this->_throwException($e); } $this->_buffer->setWriteTranslations(array()); $this->executeCommand("\r\n.\r\n", array(250)); } /** Determine the best-use reverse path for this message */ protected function _getReversePath(Swift_Mime_Message $message) { $return = $message->getReturnPath(); $sender = $message->getSender(); $from = $message->getFrom(); $path = null; if (!empty($return)) { $path = $return; } elseif (!empty($sender)) { // Don't use array_keys reset($sender); // Reset Pointer to first pos $path = key($sender); // Get key } elseif (!empty($from)) { reset($from); // Reset Pointer to first pos $path = key($from); // Get key } return $path; } /** Throw a TransportException, first sending it to any listeners */ protected function _throwException(Swift_TransportException $e) { if ($evt = $this->_eventDispatcher->createTransportExceptionEvent($this, $e)) { $this->_eventDispatcher->dispatchEvent($evt, 'exceptionThrown'); if (!$evt->bubbleCancelled()) { throw $e; } } else { throw $e; } } /** Throws an Exception if a response code is incorrect */ protected function _assertResponseCode($response, $wanted) { list($code) = sscanf($response, '%3d'); $valid = (empty($wanted) || in_array($code, $wanted)); if ($evt = $this->_eventDispatcher->createResponseEvent($this, $response, $valid)) { $this->_eventDispatcher->dispatchEvent($evt, 'responseReceived'); } if (!$valid) { $this->_throwException( new Swift_TransportException( 'Expected response code '.implode('/', $wanted).' but got code '. '"'.$code.'", with message "'.$response.'"', $code) ); } } /** Get an entire multi-line response using its sequence number */ protected function _getFullResponse($seq) { $response = ''; try { do { $line = $this->_buffer->readLine($seq); $response .= $line; } while (null !== $line && false !== $line && ' ' != $line{3}); } catch (Swift_TransportException $e) { $this->_throwException($e); } catch (Swift_IoException $e) { $this->_throwException( new Swift_TransportException( $e->getMessage()) ); } return $response; } /** Send an email to the given recipients from the given reverse path */ private function _doMailTransaction($message, $reversePath, array $recipients, array &$failedRecipients) { $sent = 0; $this->_doMailFromCommand($reversePath); foreach ($recipients as $forwardPath) { try { $this->_doRcptToCommand($forwardPath); $sent++; } catch (Swift_TransportException $e) { $failedRecipients[] = $forwardPath; } } if ($sent != 0) { $this->_doDataCommand(); $this->_streamMessage($message); } else { $this->reset(); } return $sent; } /** Send a message to the given To: recipients */ private function _sendTo(Swift_Mime_Message $message, $reversePath, array $to, array &$failedRecipients) { if (empty($to)) { return 0; } return $this->_doMailTransaction($message, $reversePath, array_keys($to), $failedRecipients); } /** Send a message to all Bcc: recipients */ private function _sendBcc(Swift_Mime_Message $message, $reversePath, array $bcc, array &$failedRecipients) { $sent = 0; foreach ($bcc as $forwardPath => $name) { $message->setBcc(array($forwardPath => $name)); $sent += $this->_doMailTransaction( $message, $reversePath, array($forwardPath), $failedRecipients ); } return $sent; } /** Try to determine the hostname of the server this is run on */ private function _lookupHostname() { if (!empty($_SERVER['SERVER_NAME']) && $this->_isFqdn($_SERVER['SERVER_NAME'])) { $this->_domain = $_SERVER['SERVER_NAME']; } elseif (!empty($_SERVER['SERVER_ADDR'])) { $this->_domain = sprintf('[%s]', $_SERVER['SERVER_ADDR']); } } /** Determine is the $hostname is a fully-qualified name */ private function _isFqdn($hostname) { // We could do a really thorough check, but there's really no point if (false !== $dotPos = strpos($hostname, '.')) { return ($dotPos > 0) && ($dotPos != strlen($hostname) - 1); } else { return false; } } /** * Destructor. */ public function __destruct() { $this->stop(); } } executeCommand("AUTH CRAM-MD5\r\n", array(334)); $challenge = base64_decode(substr($challenge, 4)); $message = base64_encode( $username.' '.$this->_getResponse($password, $challenge) ); $agent->executeCommand(sprintf("%s\r\n", $message), array(235)); return true; } catch (Swift_TransportException $e) { $agent->executeCommand("RSET\r\n", array(250)); return false; } } /** * Generate a CRAM-MD5 response from a server challenge. * * @param string $secret * @param string $challenge * * @return string */ private function _getResponse($secret, $challenge) { if (strlen($secret) > 64) { $secret = pack('H32', md5($secret)); } if (strlen($secret) < 64) { $secret = str_pad($secret, 64, chr(0)); } $k_ipad = substr($secret, 0, 64) ^ str_repeat(chr(0x36), 64); $k_opad = substr($secret, 0, 64) ^ str_repeat(chr(0x5C), 64); $inner = pack('H32', md5($k_ipad.$challenge)); $digest = md5($k_opad.$inner); return $digest; } } executeCommand("AUTH LOGIN\r\n", array(334)); $agent->executeCommand(sprintf("%s\r\n", base64_encode($username)), array(334)); $agent->executeCommand(sprintf("%s\r\n", base64_encode($password)), array(235)); return true; } catch (Swift_TransportException $e) { $agent->executeCommand("RSET\r\n", array(250)); return false; } } } */ class Swift_Transport_Esmtp_Auth_NTLMAuthenticator implements Swift_Transport_Esmtp_Authenticator { const NTLMSIG = "NTLMSSP\x00"; const DESCONST = "KGS!@#$%"; /** * Get the name of the AUTH mechanism this Authenticator handles. * * @return string */ public function getAuthKeyword() { return 'NTLM'; } /** * Try to authenticate the user with $username and $password. * * @param Swift_Transport_SmtpAgent $agent * @param string $username * @param string $password * * @return bool */ public function authenticate(Swift_Transport_SmtpAgent $agent, $username, $password) { if (!function_exists('mcrypt_module_open')) { throw new LogicException('The mcrypt functions need to be enabled to use the NTLM authenticator.'); } if (!function_exists('openssl_random_pseudo_bytes')) { throw new LogicException('The OpenSSL extension must be enabled to use the NTLM authenticator.'); } if (!function_exists('bcmul')) { throw new LogicException('The BCMatch functions must be enabled to use the NTLM authenticator.'); } try { // execute AUTH command and filter out the code at the beginning // AUTH NTLM xxxx $response = base64_decode(substr(trim($this->sendMessage1($agent)), 4)); // extra parameters for our unit cases $timestamp = func_num_args() > 3 ? func_get_arg(3) : $this->getCorrectTimestamp(bcmul(microtime(true), "1000")); $client = func_num_args() > 4 ? func_get_arg(4) : $this->getRandomBytes(8); // Message 3 response $this->sendMessage3($response, $username, $password, $timestamp, $client, $agent); return true; } catch (Swift_TransportException $e) { $agent->executeCommand("RSET\r\n", array(250)); return false; } } protected function si2bin($si, $bits = 32) { $bin = null; if ($si >= -pow(2, $bits - 1) && ($si <= pow(2, $bits - 1))) { // positive or zero if ($si >= 0) { $bin = base_convert($si, 10, 2); // pad to $bits bit $bin_length = strlen($bin); if ($bin_length < $bits) { $bin = str_repeat("0", $bits - $bin_length).$bin; } } else { // negative $si = -$si - pow(2, $bits); $bin = base_convert($si, 10, 2); $bin_length = strlen($bin); if ($bin_length > $bits) { $bin = str_repeat("1", $bits - $bin_length).$bin; } } } return $bin; } /** * Send our auth message and returns the response * * @param Swift_Transport_SmtpAgent $agent * @return string SMTP Response */ protected function sendMessage1(Swift_Transport_SmtpAgent $agent) { $message = $this->createMessage1(); return $agent->executeCommand(sprintf("AUTH %s %s\r\n", $this->getAuthKeyword(), base64_encode($message)), array(334)); } /** * Fetch all details of our response (message 2) * * @param string $response * @return array our response parsed */ protected function parseMessage2($response) { $responseHex = bin2hex($response); $length = floor(hexdec(substr($responseHex, 28, 4)) / 256) * 2; $offset = floor(hexdec(substr($responseHex, 32, 4)) / 256) * 2; $challenge = $this->hex2bin(substr($responseHex, 48, 16)); $context = $this->hex2bin(substr($responseHex, 64, 16)); $targetInfoH = $this->hex2bin(substr($responseHex, 80, 16)); $targetName = $this->hex2bin(substr($responseHex, $offset, $length)); $offset = floor(hexdec(substr($responseHex, 88, 4)) / 256) * 2; $targetInfoBlock = substr($responseHex, $offset); list($domainName, $serverName, $DNSDomainName, $DNSServerName, $terminatorByte) = $this->readSubBlock($targetInfoBlock); return array( $challenge, $context, $targetInfoH, $targetName, $domainName, $serverName, $DNSDomainName, $DNSServerName, $this->hex2bin($targetInfoBlock), $terminatorByte, ); } /** * Read the blob information in from message2 * * @param $block * @return array */ protected function readSubBlock($block) { // remove terminatorByte cause it's always the same $block = substr($block, 0, -8); $length = strlen($block); $offset = 0; $data = array(); while ($offset < $length) { $blockLength = hexdec(substr(substr($block, $offset, 8), -4)) / 256; $offset += 8; $data[] = $this->hex2bin(substr($block, $offset, $blockLength * 2)); $offset += $blockLength * 2; } if (count($data) == 3) { $data[] = $data[2]; $data[2] = ''; } $data[] = $this->createByte('00'); return $data; } /** * Send our final message with all our data * * @param string $response Message 1 response (message 2) * @param string $username * @param string $password * @param string $timestamp * @param string $client * @param Swift_Transport_SmtpAgent $agent * @param bool $v2 Use version2 of the protocol * @return string */ protected function sendMessage3($response, $username, $password, $timestamp, $client, Swift_Transport_SmtpAgent $agent, $v2 = true) { list($domain, $username) = $this->getDomainAndUsername($username); //$challenge, $context, $targetInfoH, $targetName, $domainName, $workstation, $DNSDomainName, $DNSServerName, $blob, $ter list($challenge, , , , , $workstation, , , $blob) = $this->parseMessage2($response); if (!$v2) { // LMv1 $lmResponse = $this->createLMPassword($password, $challenge); // NTLMv1 $ntlmResponse = $this->createNTLMPassword($password, $challenge); } else { // LMv2 $lmResponse = $this->createLMv2Password($password, $username, $domain, $challenge, $client); // NTLMv2 $ntlmResponse = $this->createNTLMv2Hash($password, $username, $domain, $challenge, $blob, $timestamp, $client); } $message = $this->createMessage3($domain, $username, $workstation, $lmResponse, $ntlmResponse); return $agent->executeCommand(sprintf("%s\r\n", base64_encode($message)), array(235)); } /** * Create our message 1 * * @return string */ protected function createMessage1() { return self::NTLMSIG .$this->createByte('01') // Message 1 .$this->createByte('0702'); // Flags } /** * Create our message 3 * * @param string $domain * @param string $username * @param string $workstation * @param string $lmResponse * @param string $ntlmResponse * @return string */ protected function createMessage3($domain, $username, $workstation, $lmResponse, $ntlmResponse) { // Create security buffers $domainSec = $this->createSecurityBuffer($domain, 64); $domainInfo = $this->readSecurityBuffer(bin2hex($domainSec)); $userSec = $this->createSecurityBuffer($username, ($domainInfo[0] + $domainInfo[1]) / 2); $userInfo = $this->readSecurityBuffer(bin2hex($userSec)); $workSec = $this->createSecurityBuffer($workstation, ($userInfo[0] + $userInfo[1]) / 2); $workInfo = $this->readSecurityBuffer(bin2hex($workSec)); $lmSec = $this->createSecurityBuffer($lmResponse, ($workInfo[0] + $workInfo[1]) / 2, true); $lmInfo = $this->readSecurityBuffer(bin2hex($lmSec)); $ntlmSec = $this->createSecurityBuffer($ntlmResponse, ($lmInfo[0] + $lmInfo[1]) / 2, true); return self::NTLMSIG .$this->createByte('03') // TYPE 3 message .$lmSec // LM response header .$ntlmSec // NTLM response header .$domainSec // Domain header .$userSec // User header .$workSec // Workstation header .$this->createByte("000000009a", 8) // session key header (empty) .$this->createByte('01020000') // FLAGS .$this->convertTo16bit($domain) // domain name .$this->convertTo16bit($username) // username .$this->convertTo16bit($workstation) // workstation .$lmResponse .$ntlmResponse; } /** * @param string $timestamp Epoch timestamp in microseconds * @param string $client Random bytes * @param string $targetInfo * @return string */ protected function createBlob($timestamp, $client, $targetInfo) { return $this->createByte('0101') .$this->createByte('00') .$timestamp .$client .$this->createByte('00') .$targetInfo .$this->createByte('00'); } /** * Get domain and username from our username * * @example DOMAIN\username * * @param string $name * @return array */ protected function getDomainAndUsername($name) { if (strpos($name, '\\') !== false) { return explode('\\', $name); } list($user, $domain) = explode('@', $name); return array($domain, $user); } /** * Create LMv1 response * * @param string $password * @param string $challenge * @return string */ protected function createLMPassword($password, $challenge) { // FIRST PART $password = $this->createByte(strtoupper($password), 14, false); list($key1, $key2) = str_split($password, 7); $desKey1 = $this->createDesKey($key1); $desKey2 = $this->createDesKey($key2); $constantDecrypt = $this->createByte($this->desEncrypt(self::DESCONST, $desKey1).$this->desEncrypt(self::DESCONST, $desKey2), 21, false); // SECOND PART list($key1, $key2, $key3) = str_split($constantDecrypt, 7); $desKey1 = $this->createDesKey($key1); $desKey2 = $this->createDesKey($key2); $desKey3 = $this->createDesKey($key3); return $this->desEncrypt($challenge, $desKey1).$this->desEncrypt($challenge, $desKey2).$this->desEncrypt($challenge, $desKey3); } /** * Create NTLMv1 response * * @param string $password * @param string $challenge * @return string */ protected function createNTLMPassword($password, $challenge) { // FIRST PART $ntlmHash = $this->createByte($this->md4Encrypt($password), 21, false); list($key1, $key2, $key3) = str_split($ntlmHash, 7); $desKey1 = $this->createDesKey($key1); $desKey2 = $this->createDesKey($key2); $desKey3 = $this->createDesKey($key3); return $this->desEncrypt($challenge, $desKey1).$this->desEncrypt($challenge, $desKey2).$this->desEncrypt($challenge, $desKey3); } /** * Convert a normal timestamp to a tenth of a microtime epoch time * * @param string $time * @return string */ protected function getCorrectTimestamp($time) { // Get our timestamp (tricky!) bcscale(0); $time = number_format($time, 0, '.', ''); // save microtime to string $time = bcadd($time, "11644473600000"); // add epoch time $time = bcmul($time, 10000); // tenths of a microsecond. $binary = $this->si2bin($time, 64); // create 64 bit binary string $timestamp = ""; for ($i = 0; $i < 8; $i++) { $timestamp .= chr(bindec(substr($binary, -(($i + 1) * 8), 8))); } return $timestamp; } /** * Create LMv2 response * * @param string $password * @param string $username * @param string $domain * @param string $challenge NTLM Challenge * @param string $client Random string * @return string */ protected function createLMv2Password($password, $username, $domain, $challenge, $client) { $lmPass = '00'; // by default 00 // if $password > 15 than we can't use this method if (strlen($password) <= 15) { $ntlmHash = $this->md4Encrypt($password); $ntml2Hash = $this->md5Encrypt($ntlmHash, $this->convertTo16bit(strtoupper($username).$domain)); $lmPass = bin2hex($this->md5Encrypt($ntml2Hash, $challenge.$client).$client); } return $this->createByte($lmPass, 24); } /** * Create NTLMv2 response * * @param string $password * @param string $username * @param string $domain * @param string $challenge Hex values * @param string $targetInfo Hex values * @param string $timestamp * @param string $client Random bytes * @return string * @see http://davenport.sourceforge.net/ntlm.html#theNtlmResponse */ protected function createNTLMv2Hash($password, $username, $domain, $challenge, $targetInfo, $timestamp, $client) { $ntlmHash = $this->md4Encrypt($password); $ntml2Hash = $this->md5Encrypt($ntlmHash, $this->convertTo16bit(strtoupper($username).$domain)); // create blob $blob = $this->createBlob($timestamp, $client, $targetInfo); $ntlmv2Response = $this->md5Encrypt($ntml2Hash, $challenge.$blob); return $ntlmv2Response.$blob; } protected function createDesKey($key) { $material = array(bin2hex($key[0])); $len = strlen($key); for ($i = 1; $i < $len; $i++) { list($high, $low) = str_split(bin2hex($key[$i])); $v = $this->castToByte(ord($key[$i - 1]) << (7 + 1 - $i) | $this->uRShift(hexdec(dechex(hexdec($high) & 0xf).dechex(hexdec($low) & 0xf)), $i)); $material[] = str_pad(substr(dechex($v), -2), 2, '0', STR_PAD_LEFT); // cast to byte } $material[] = str_pad(substr(dechex($this->castToByte(ord($key[6]) << 1)), -2), 2, '0'); // odd parity foreach ($material as $k => $v) { $b = $this->castToByte(hexdec($v)); $needsParity = (($this->uRShift($b, 7) ^ $this->uRShift($b, 6) ^ $this->uRShift($b, 5) ^ $this->uRShift($b, 4) ^ $this->uRShift($b, 3) ^ $this->uRShift($b, 2) ^ $this->uRShift($b, 1)) & 0x01) == 0; list($high, $low) = str_split($v); if ($needsParity) { $material[$k] = dechex(hexdec($high) | 0x0).dechex(hexdec($low) | 0x1); } else { $material[$k] = dechex(hexdec($high) & 0xf).dechex(hexdec($low) & 0xe); } } return $this->hex2bin(implode('', $material)); } /** HELPER FUNCTIONS */ /** * Create our security buffer depending on length and offset * * @param string $value Value we want to put in * @param int $offset start of value * @param bool $is16 Do we 16bit string or not? * @return string */ protected function createSecurityBuffer($value, $offset, $is16 = false) { $length = strlen(bin2hex($value)); $length = $is16 ? $length / 2 : $length; $length = $this->createByte(str_pad(dechex($length), 2, '0', STR_PAD_LEFT), 2); return $length.$length.$this->createByte(dechex($offset), 4); } /** * Read our security buffer to fetch length and offset of our value * * @param string $value Securitybuffer in hex * @return array array with length and offset */ protected function readSecurityBuffer($value) { $length = floor(hexdec(substr($value, 0, 4)) / 256) * 2; $offset = floor(hexdec(substr($value, 8, 4)) / 256) * 2; return array($length, $offset); } /** * Cast to byte java equivalent to (byte) * * @param int $v * @return int */ protected function castToByte($v) { return (($v + 128) % 256) - 128; } /** * Java unsigned right bitwise * $a >>> $b * * @param int $a * @param int $b * @return int */ protected function uRShift($a, $b) { if ($b == 0) { return $a; } return ($a >> $b) & ~(1 << (8 * PHP_INT_SIZE - 1) >> ($b - 1)); } /** * Right padding with 0 to certain length * * @param string $input * @param int $bytes Length of bytes * @param bool $isHex Did we provided hex value * @return string */ protected function createByte($input, $bytes = 4, $isHex = true) { if ($isHex) { $byte = $this->hex2bin(str_pad($input, $bytes * 2, '00')); } else { $byte = str_pad($input, $bytes, "\x00"); } return $byte; } /** * Create random bytes * * @param $length * @return string */ protected function getRandomBytes($length) { $bytes = openssl_random_pseudo_bytes($length, $strong); if (false !== $bytes && true === $strong) { return $bytes; } throw new RuntimeException('OpenSSL did not produce a secure random number.'); } /** ENCRYPTION ALGORITHMS */ /** * DES Encryption * * @param string $value * @param string $key * @return string */ protected function desEncrypt($value, $key) { $cipher = mcrypt_module_open(MCRYPT_DES, '', 'ecb', ''); mcrypt_generic_init($cipher, $key, mcrypt_create_iv(mcrypt_enc_get_iv_size($cipher), MCRYPT_DEV_RANDOM)); return mcrypt_generic($cipher, $value); } /** * MD5 Encryption * * @param string $key Encryption key * @param string $msg Message to encrypt * @return string */ protected function md5Encrypt($key, $msg) { $blocksize = 64; if (strlen($key) > $blocksize) { $key = pack('H*', md5($key)); } $key = str_pad($key, $blocksize, "\0"); $ipadk = $key ^ str_repeat("\x36", $blocksize); $opadk = $key ^ str_repeat("\x5c", $blocksize); return pack('H*', md5($opadk.pack('H*', md5($ipadk.$msg)))); } /** * MD4 Encryption * * @param string $input * @return string * @see http://php.net/manual/en/ref.hash.php */ protected function md4Encrypt($input) { $input = $this->convertTo16bit($input); return function_exists('hash') ? $this->hex2bin(hash('md4', $input)) : mhash(MHASH_MD4, $input); } /** * Convert UTF-8 to UTF-16 * * @param string $input * @return string */ protected function convertTo16bit($input) { return iconv('UTF-8', 'UTF-16LE', $input); } /** * Hex2bin replacement for < PHP 5.4 * @param string $hex * @return string Binary */ protected function hex2bin($hex) { if (function_exists('hex2bin')) { return hex2bin($hex); } else { return pack('H*', $hex); } } /** * @param string $message */ protected function debug($message) { $message = bin2hex($message); $messageId = substr($message, 16, 8); echo substr($message, 0, 16)." NTLMSSP Signature
\n"; echo $messageId." Type Indicator
\n"; if ($messageId == "02000000") { $map = array( 'Challenge', 'Context', 'Target Information Security Buffer', 'Target Name Data', 'NetBIOS Domain Name', 'NetBIOS Server Name', 'DNS Domain Name', 'DNS Server Name', 'BLOB', 'Target Information Terminator', ); $data = $this->parseMessage2($this->hex2bin($message)); foreach ($map as $key => $value) { echo bin2hex($data[$key]).' - '.$data[$key].' ||| '.$value."
\n"; } } elseif ($messageId == "03000000") { $i = 0; $data[$i++] = substr($message, 24, 16); list($lmLength, $lmOffset) = $this->readSecurityBuffer($data[$i - 1]); $data[$i++] = substr($message, 40, 16); list($ntmlLength, $ntmlOffset) = $this->readSecurityBuffer($data[$i - 1]); $data[$i++] = substr($message, 56, 16); list($targetLength, $targetOffset) = $this->readSecurityBuffer($data[$i - 1]); $data[$i++] = substr($message, 72, 16); list($userLength, $userOffset) = $this->readSecurityBuffer($data[$i - 1]); $data[$i++] = substr($message, 88, 16); list($workLength, $workOffset) = $this->readSecurityBuffer($data[$i - 1]); $data[$i++] = substr($message, 104, 16); $data[$i++] = substr($message, 120, 8); $data[$i++] = substr($message, $targetOffset, $targetLength); $data[$i++] = substr($message, $userOffset, $userLength); $data[$i++] = substr($message, $workOffset, $workLength); $data[$i++] = substr($message, $lmOffset, $lmLength); $data[$i] = substr($message, $ntmlOffset, $ntmlLength); $map = array( 'LM Response Security Buffer', 'NTLM Response Security Buffer', 'Target Name Security Buffer', 'User Name Security Buffer', 'Workstation Name Security Buffer', 'Session Key Security Buffer', 'Flags', 'Target Name Data', 'User Name Data', 'Workstation Name Data', 'LM Response Data', 'NTLM Response Data', ); foreach ($map as $key => $value) { echo $data[$key].' - '.$this->hex2bin($data[$key]).' ||| '.$value."
\n"; } } echo "

"; } } executeCommand(sprintf("AUTH PLAIN %s\r\n", $message), array(235)); return true; } catch (Swift_TransportException $e) { $agent->executeCommand("RSET\r\n", array(250)); return false; } } } * $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 587, 'tls') * ->setAuthMode('XOAUTH2') * ->setUsername('YOUR_EMAIL_ADDRESS') * ->setPassword('YOUR_ACCESS_TOKEN'); * * * @author xu.li * @see https://developers.google.com/google-apps/gmail/xoauth2_protocol */ class Swift_Transport_Esmtp_Auth_XOAuth2Authenticator implements Swift_Transport_Esmtp_Authenticator { /** * Get the name of the AUTH mechanism this Authenticator handles. * * @return string */ public function getAuthKeyword() { return 'XOAUTH2'; } /** * Try to authenticate the user with $email and $token. * * @param Swift_Transport_SmtpAgent $agent * @param string $email * @param string $token * * @return bool */ public function authenticate(Swift_Transport_SmtpAgent $agent, $email, $token) { try { $param = $this->constructXOAuth2Params($email, $token); $agent->executeCommand("AUTH XOAUTH2 ".$param."\r\n", array(235)); return true; } catch (Swift_TransportException $e) { $agent->executeCommand("RSET\r\n", array(250)); return false; } } /** * Construct the auth parameter * * @see https://developers.google.com/google-apps/gmail/xoauth2_protocol#the_sasl_xoauth2_mechanism */ protected function constructXOAuth2Params($email, $token) { return base64_encode("user=$email\1auth=Bearer $token\1\1"); } } setAuthenticators($authenticators); } /** * Set the Authenticators which can process a login request. * * @param Swift_Transport_Esmtp_Authenticator[] $authenticators */ public function setAuthenticators(array $authenticators) { $this->_authenticators = $authenticators; } /** * Get the Authenticators which can process a login request. * * @return Swift_Transport_Esmtp_Authenticator[] */ public function getAuthenticators() { return $this->_authenticators; } /** * Set the username to authenticate with. * * @param string $username */ public function setUsername($username) { $this->_username = $username; } /** * Get the username to authenticate with. * * @return string */ public function getUsername() { return $this->_username; } /** * Set the password to authenticate with. * * @param string $password */ public function setPassword($password) { $this->_password = $password; } /** * Get the password to authenticate with. * * @return string */ public function getPassword() { return $this->_password; } /** * Set the auth mode to use to authenticate. * * @param string $mode */ public function setAuthMode($mode) { $this->_auth_mode = $mode; } /** * Get the auth mode to use to authenticate. * * @return string */ public function getAuthMode() { return $this->_auth_mode; } /** * Get the name of the ESMTP extension this handles. * * @return bool */ public function getHandledKeyword() { return 'AUTH'; } /** * Set the parameters which the EHLO greeting indicated. * * @param string[] $parameters */ public function setKeywordParams(array $parameters) { $this->_esmtpParams = $parameters; } /** * Runs immediately after a EHLO has been issued. * * @param Swift_Transport_SmtpAgent $agent to read/write */ public function afterEhlo(Swift_Transport_SmtpAgent $agent) { if ($this->_username) { $count = 0; foreach ($this->_getAuthenticatorsForAgent() as $authenticator) { if (in_array(strtolower($authenticator->getAuthKeyword()), array_map('strtolower', $this->_esmtpParams))) { $count++; if ($authenticator->authenticate($agent, $this->_username, $this->_password)) { return; } } } throw new Swift_TransportException( 'Failed to authenticate on SMTP server with username "'. $this->_username.'" using '.$count.' possible authenticators' ); } } /** * Not used. */ public function getMailParams() { return array(); } /** * Not used. */ public function getRcptParams() { return array(); } /** * Not used. */ public function onCommand(Swift_Transport_SmtpAgent $agent, $command, $codes = array(), &$failedRecipients = null, &$stop = false) { } /** * Returns +1, -1 or 0 according to the rules for usort(). * * This method is called to ensure extensions can be execute in an appropriate order. * * @param string $esmtpKeyword to compare with * * @return int */ public function getPriorityOver($esmtpKeyword) { return 0; } /** * Returns an array of method names which are exposed to the Esmtp class. * * @return string[] */ public function exposeMixinMethods() { return array('setUsername', 'getUsername', 'setPassword', 'getPassword', 'setAuthMode', 'getAuthMode'); } /** * Not used. */ public function resetState() { } /** * Returns the authenticator list for the given agent. * * @param Swift_Transport_SmtpAgent $agent * * @return array */ protected function _getAuthenticatorsForAgent() { if (!$mode = strtolower($this->_auth_mode)) { return $this->_authenticators; } foreach ($this->_authenticators as $authenticator) { if (strtolower($authenticator->getAuthKeyword()) == $mode) { return array($authenticator); } } throw new Swift_TransportException('Auth mode '.$mode.' is invalid'); } } . * * @return string[] */ public function getMailParams(); /** * Get params which are appended to RCPT TO:<>. * * @return string[] */ public function getRcptParams(); /** * Runs when a command is due to be sent. * * @param Swift_Transport_SmtpAgent $agent to read/write * @param string $command to send * @param int[] $codes expected in response * @param string[] $failedRecipients to collect failures * @param bool $stop to be set true by-reference if the command is now sent */ public function onCommand(Swift_Transport_SmtpAgent $agent, $command, $codes = array(), &$failedRecipients = null, &$stop = false); /** * Returns +1, -1 or 0 according to the rules for usort(). * * This method is called to ensure extensions can be execute in an appropriate order. * * @param string $esmtpKeyword to compare with * * @return int */ public function getPriorityOver($esmtpKeyword); /** * Returns an array of method names which are exposed to the Esmtp class. * * @return string[] */ public function exposeMixinMethods(); /** * Tells this handler to clear any buffers and reset its state. */ public function resetState(); } 'tcp', 'host' => 'localhost', 'port' => 25, 'timeout' => 30, 'blocking' => 1, 'tls' => false, 'type' => Swift_Transport_IoBuffer::TYPE_SOCKET, ); /** * Creates a new EsmtpTransport using the given I/O buffer. * * @param Swift_Transport_IoBuffer $buf * @param Swift_Transport_EsmtpHandler[] $extensionHandlers * @param Swift_Events_EventDispatcher $dispatcher */ public function __construct(Swift_Transport_IoBuffer $buf, array $extensionHandlers, Swift_Events_EventDispatcher $dispatcher) { parent::__construct($buf, $dispatcher); $this->setExtensionHandlers($extensionHandlers); } /** * Set the host to connect to. * * @param string $host * * @return Swift_Transport_EsmtpTransport */ public function setHost($host) { $this->_params['host'] = $host; return $this; } /** * Get the host to connect to. * * @return string */ public function getHost() { return $this->_params['host']; } /** * Set the port to connect to. * * @param int $port * * @return Swift_Transport_EsmtpTransport */ public function setPort($port) { $this->_params['port'] = (int) $port; return $this; } /** * Get the port to connect to. * * @return int */ public function getPort() { return $this->_params['port']; } /** * Set the connection timeout. * * @param int $timeout seconds * * @return Swift_Transport_EsmtpTransport */ public function setTimeout($timeout) { $this->_params['timeout'] = (int) $timeout; $this->_buffer->setParam('timeout', (int) $timeout); return $this; } /** * Get the connection timeout. * * @return int */ public function getTimeout() { return $this->_params['timeout']; } /** * Set the encryption type (tls or ssl) * * @param string $encryption * * @return Swift_Transport_EsmtpTransport */ public function setEncryption($encryption) { if ('tls' == $encryption) { $this->_params['protocol'] = 'tcp'; $this->_params['tls'] = true; } else { $this->_params['protocol'] = $encryption; $this->_params['tls'] = false; } return $this; } /** * Get the encryption type. * * @return string */ public function getEncryption() { return $this->_params['tls'] ? 'tls' : $this->_params['protocol']; } /** * Sets the source IP. * * @param string $source * * @return Swift_Transport_EsmtpTransport */ public function setSourceIp($source) { $this->_params['sourceIp'] = $source; return $this; } /** * Returns the IP used to connect to the destination. * * @return string */ public function getSourceIp() { return $this->_params['sourceIp']; } /** * Set ESMTP extension handlers. * * @param Swift_Transport_EsmtpHandler[] $handlers * * @return Swift_Transport_EsmtpTransport */ public function setExtensionHandlers(array $handlers) { $assoc = array(); foreach ($handlers as $handler) { $assoc[$handler->getHandledKeyword()] = $handler; } uasort($assoc, array($this, '_sortHandlers')); $this->_handlers = $assoc; $this->_setHandlerParams(); return $this; } /** * Get ESMTP extension handlers. * * @return Swift_Transport_EsmtpHandler[] */ public function getExtensionHandlers() { return array_values($this->_handlers); } /** * Run a command against the buffer, expecting the given response codes. * * If no response codes are given, the response will not be validated. * If codes are given, an exception will be thrown on an invalid response. * * @param string $command * @param int[] $codes * @param string[] $failures An array of failures by-reference * * @return string */ public function executeCommand($command, $codes = array(), &$failures = null) { $failures = (array) $failures; $stopSignal = false; $response = null; foreach ($this->_getActiveHandlers() as $handler) { $response = $handler->onCommand( $this, $command, $codes, $failures, $stopSignal ); if ($stopSignal) { return $response; } } return parent::executeCommand($command, $codes, $failures); } // -- Mixin invocation code /** Mixin handling method for ESMTP handlers */ public function __call($method, $args) { foreach ($this->_handlers as $handler) { if (in_array(strtolower($method), array_map('strtolower', (array) $handler->exposeMixinMethods()) )) { $return = call_user_func_array(array($handler, $method), $args); // Allow fluid method calls if (is_null($return) && substr($method, 0, 3) == 'set') { return $this; } else { return $return; } } } trigger_error('Call to undefined method '.$method, E_USER_ERROR); } /** Get the params to initialize the buffer */ protected function _getBufferParams() { return $this->_params; } /** Overridden to perform EHLO instead */ protected function _doHeloCommand() { try { $response = $this->executeCommand( sprintf("EHLO %s\r\n", $this->_domain), array(250) ); } catch (Swift_TransportException $e) { return parent::_doHeloCommand(); } if ($this->_params['tls']) { try { $this->executeCommand("STARTTLS\r\n", array(220)); if (!$this->_buffer->startTLS()) { throw new Swift_TransportException('Unable to connect with TLS encryption'); } try { $response = $this->executeCommand( sprintf("EHLO %s\r\n", $this->_domain), array(250) ); } catch (Swift_TransportException $e) { return parent::_doHeloCommand(); } } catch (Swift_TransportException $e) { $this->_throwException($e); } } $this->_capabilities = $this->_getCapabilities($response); $this->_setHandlerParams(); foreach ($this->_getActiveHandlers() as $handler) { $handler->afterEhlo($this); } } /** Overridden to add Extension support */ protected function _doMailFromCommand($address) { $handlers = $this->_getActiveHandlers(); $params = array(); foreach ($handlers as $handler) { $params = array_merge($params, (array) $handler->getMailParams()); } $paramStr = !empty($params) ? ' '.implode(' ', $params) : ''; $this->executeCommand( sprintf("MAIL FROM: <%s>%s\r\n", $address, $paramStr), array(250) ); } /** Overridden to add Extension support */ protected function _doRcptToCommand($address) { $handlers = $this->_getActiveHandlers(); $params = array(); foreach ($handlers as $handler) { $params = array_merge($params, (array) $handler->getRcptParams()); } $paramStr = !empty($params) ? ' '.implode(' ', $params) : ''; $this->executeCommand( sprintf("RCPT TO: <%s>%s\r\n", $address, $paramStr), array(250, 251, 252) ); } /** Determine ESMTP capabilities by function group */ private function _getCapabilities($ehloResponse) { $capabilities = array(); $ehloResponse = trim($ehloResponse); $lines = explode("\r\n", $ehloResponse); array_shift($lines); foreach ($lines as $line) { if (preg_match('/^[0-9]{3}[ -]([A-Z0-9-]+)((?:[ =].*)?)$/Di', $line, $matches)) { $keyword = strtoupper($matches[1]); $paramStr = strtoupper(ltrim($matches[2], ' =')); $params = !empty($paramStr) ? explode(' ', $paramStr) : array(); $capabilities[$keyword] = $params; } } return $capabilities; } /** Set parameters which are used by each extension handler */ private function _setHandlerParams() { foreach ($this->_handlers as $keyword => $handler) { if (array_key_exists($keyword, $this->_capabilities)) { $handler->setKeywordParams($this->_capabilities[$keyword]); } } } /** Get ESMTP handlers which are currently ok to use */ private function _getActiveHandlers() { $handlers = array(); foreach ($this->_handlers as $keyword => $handler) { if (array_key_exists($keyword, $this->_capabilities)) { $handlers[] = $handler; } } return $handlers; } /** Custom sort for extension handler ordering */ private function _sortHandlers($a, $b) { return $a->getPriorityOver($b->getHandledKeyword()); } } _transports); $sent = 0; for ($i = 0; $i < $maxTransports && $transport = $this->_getNextTransport(); ++$i) { try { if (!$transport->isStarted()) { $transport->start(); } return $transport->send($message, $failedRecipients); } catch (Swift_TransportException $e) { $this->_killCurrentTransport(); } } if (count($this->_transports) == 0) { throw new Swift_TransportException( 'All Transports in FailoverTransport failed, or no Transports available' ); } return $sent; } protected function _getNextTransport() { if (!isset($this->_currentTransport)) { $this->_currentTransport = parent::_getNextTransport(); } return $this->_currentTransport; } protected function _killCurrentTransport() { $this->_currentTransport = null; parent::_killCurrentTransport(); } } _transports = $transports; $this->_deadTransports = array(); } /** * Get $transports to delegate to. * * @return Swift_Transport[] */ public function getTransports() { return array_merge($this->_transports, $this->_deadTransports); } /** * Test if this Transport mechanism has started. * * @return bool */ public function isStarted() { return count($this->_transports) > 0; } /** * Start this Transport mechanism. */ public function start() { $this->_transports = array_merge($this->_transports, $this->_deadTransports); } /** * Stop this Transport mechanism. */ public function stop() { foreach ($this->_transports as $transport) { $transport->stop(); } } /** * Send the given Message. * * Recipient/sender data will be retrieved from the Message API. * The return value is the number of recipients who were accepted for delivery. * * @param Swift_Mime_Message $message * @param string[] $failedRecipients An array of failures by-reference * * @return int */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $maxTransports = count($this->_transports); $sent = 0; for ($i = 0; $i < $maxTransports && $transport = $this->_getNextTransport(); ++$i) { try { if (!$transport->isStarted()) { $transport->start(); } if ($sent = $transport->send($message, $failedRecipients)) { break; } } catch (Swift_TransportException $e) { $this->_killCurrentTransport(); } } if (count($this->_transports) == 0) { throw new Swift_TransportException( 'All Transports in LoadBalancedTransport failed, or no Transports available' ); } return $sent; } /** * Register a plugin. * * @param Swift_Events_EventListener $plugin */ public function registerPlugin(Swift_Events_EventListener $plugin) { foreach ($this->_transports as $transport) { $transport->registerPlugin($plugin); } } /** * Rotates the transport list around and returns the first instance. * * @return Swift_Transport */ protected function _getNextTransport() { if ($next = array_shift($this->_transports)) { $this->_transports[] = $next; } return $next; } /** * Tag the currently used (top of stack) transport as dead/useless. */ protected function _killCurrentTransport() { if ($transport = array_pop($this->_transports)) { try { $transport->stop(); } catch (Exception $e) { } $this->_deadTransports[] = $transport; } } } _invoker = $invoker; $this->_eventDispatcher = $eventDispatcher; } /** * Not used. */ public function isStarted() { return false; } /** * Not used. */ public function start() { } /** * Not used. */ public function stop() { } /** * Set the additional parameters used on the mail() function. * * This string is formatted for sprintf() where %s is the sender address. * * @param string $params * * @return Swift_Transport_MailTransport */ public function setExtraParams($params) { $this->_extraParams = $params; return $this; } /** * Get the additional parameters used on the mail() function. * * This string is formatted for sprintf() where %s is the sender address. * * @return string */ public function getExtraParams() { return $this->_extraParams; } /** * Send the given Message. * * Recipient/sender data will be retrieved from the Message API. * The return value is the number of recipients who were accepted for delivery. * * @param Swift_Mime_Message $message * @param string[] $failedRecipients An array of failures by-reference * * @return int */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $failedRecipients = (array) $failedRecipients; if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); if ($evt->bubbleCancelled()) { return 0; } } $count = ( count((array) $message->getTo()) + count((array) $message->getCc()) + count((array) $message->getBcc()) ); $toHeader = $message->getHeaders()->get('To'); $subjectHeader = $message->getHeaders()->get('Subject'); if (!$toHeader) { $this->_throwException(new Swift_TransportException('Cannot send message without a recipient')); } $to = $toHeader->getFieldBody(); $subject = $subjectHeader ? $subjectHeader->getFieldBody() : ''; $reversePath = $this->_getReversePath($message); // Remove headers that would otherwise be duplicated $message->getHeaders()->remove('To'); $message->getHeaders()->remove('Subject'); $messageStr = $message->toString(); $message->getHeaders()->set($toHeader); $message->getHeaders()->set($subjectHeader); // Separate headers from body if (false !== $endHeaders = strpos($messageStr, "\r\n\r\n")) { $headers = substr($messageStr, 0, $endHeaders)."\r\n"; //Keep last EOL $body = substr($messageStr, $endHeaders + 4); } else { $headers = $messageStr."\r\n"; $body = ''; } unset($messageStr); if ("\r\n" != PHP_EOL) { // Non-windows (not using SMTP) $headers = str_replace("\r\n", PHP_EOL, $headers); $body = str_replace("\r\n", PHP_EOL, $body); } else { // Windows, using SMTP $headers = str_replace("\r\n.", "\r\n..", $headers); $body = str_replace("\r\n.", "\r\n..", $body); } if ($this->_invoker->mail($to, $subject, $body, $headers, sprintf($this->_extraParams, $reversePath))) { if ($evt) { $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS); $evt->setFailedRecipients($failedRecipients); $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); } } else { $failedRecipients = array_merge( $failedRecipients, array_keys((array) $message->getTo()), array_keys((array) $message->getCc()), array_keys((array) $message->getBcc()) ); if ($evt) { $evt->setResult(Swift_Events_SendEvent::RESULT_FAILED); $evt->setFailedRecipients($failedRecipients); $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); } $message->generateId(); $count = 0; } return $count; } /** * Register a plugin. * * @param Swift_Events_EventListener $plugin */ public function registerPlugin(Swift_Events_EventListener $plugin) { $this->_eventDispatcher->bindEventListener($plugin); } /** Throw a TransportException, first sending it to any listeners */ protected function _throwException(Swift_TransportException $e) { if ($evt = $this->_eventDispatcher->createTransportExceptionEvent($this, $e)) { $this->_eventDispatcher->dispatchEvent($evt, 'exceptionThrown'); if (!$evt->bubbleCancelled()) { throw $e; } } else { throw $e; } } /** Determine the best-use reverse path for this message */ private function _getReversePath(Swift_Mime_Message $message) { $return = $message->getReturnPath(); $sender = $message->getSender(); $from = $message->getFrom(); $path = null; if (!empty($return)) { $path = $return; } elseif (!empty($sender)) { $keys = array_keys($sender); $path = array_shift($keys); } elseif (!empty($from)) { $keys = array_keys($from); $path = array_shift($keys); } return $path; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Pretends messages have been sent, but just ignores them. * * @author Fabien Potencier */ class Swift_Transport_NullTransport implements Swift_Transport { /** The event dispatcher from the plugin API */ private $_eventDispatcher; /** * Constructor. */ public function __construct(Swift_Events_EventDispatcher $eventDispatcher) { $this->_eventDispatcher = $eventDispatcher; } /** * Tests if this Transport mechanism has started. * * @return bool */ public function isStarted() { return true; } /** * Starts this Transport mechanism. */ public function start() { } /** * Stops this Transport mechanism. */ public function stop() { } /** * Sends the given message. * * @param Swift_Mime_Message $message * @param string[] $failedRecipients An array of failures by-reference * * @return int The number of sent emails */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); if ($evt->bubbleCancelled()) { return 0; } } if ($evt) { $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS); $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); } $count = ( count((array) $message->getTo()) + count((array) $message->getCc()) + count((array) $message->getBcc()) ); return $count; } /** * Register a plugin. * * @param Swift_Events_EventListener $plugin */ public function registerPlugin(Swift_Events_EventListener $plugin) { $this->_eventDispatcher->bindEventListener($plugin); } } 30, 'blocking' => 1, 'command' => '/usr/sbin/sendmail -bs', 'type' => Swift_Transport_IoBuffer::TYPE_PROCESS, ); /** * Create a new SendmailTransport with $buf for I/O. * * @param Swift_Transport_IoBuffer $buf * @param Swift_Events_EventDispatcher $dispatcher */ public function __construct(Swift_Transport_IoBuffer $buf, Swift_Events_EventDispatcher $dispatcher) { parent::__construct($buf, $dispatcher); } /** * Start the standalone SMTP session if running in -bs mode. */ public function start() { if (false !== strpos($this->getCommand(), ' -bs')) { parent::start(); } } /** * Set the command to invoke. * * If using -t mode you are strongly advised to include -oi or -i in the flags. * For example: /usr/sbin/sendmail -oi -t * Swift will append a -f flag if one is not present. * * The recommended mode is "-bs" since it is interactive and failure notifications * are hence possible. * * @param string $command * * @return Swift_Transport_SendmailTransport */ public function setCommand($command) { $this->_params['command'] = $command; return $this; } /** * Get the sendmail command which will be invoked. * * @return string */ public function getCommand() { return $this->_params['command']; } /** * Send the given Message. * * Recipient/sender data will be retrieved from the Message API. * * The return value is the number of recipients who were accepted for delivery. * NOTE: If using 'sendmail -t' you will not be aware of any failures until * they bounce (i.e. send() will always return 100% success). * * @param Swift_Mime_Message $message * @param string[] $failedRecipients An array of failures by-reference * * @return int */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $failedRecipients = (array) $failedRecipients; $command = $this->getCommand(); $buffer = $this->getBuffer(); if (false !== strpos($command, ' -t')) { if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); if ($evt->bubbleCancelled()) { return 0; } } if (false === strpos($command, ' -f')) { $command .= ' -f'.escapeshellarg($this->_getReversePath($message)); } $buffer->initialize(array_merge($this->_params, array('command' => $command))); if (false === strpos($command, ' -i') && false === strpos($command, ' -oi')) { $buffer->setWriteTranslations(array("\r\n" => "\n", "\n." => "\n..")); } else { $buffer->setWriteTranslations(array("\r\n" => "\n")); } $count = count((array) $message->getTo()) + count((array) $message->getCc()) + count((array) $message->getBcc()) ; $message->toByteStream($buffer); $buffer->flushBuffers(); $buffer->setWriteTranslations(array()); $buffer->terminate(); if ($evt) { $evt->setResult(Swift_Events_SendEvent::RESULT_SUCCESS); $evt->setFailedRecipients($failedRecipients); $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); } $message->generateId(); } elseif (false !== strpos($command, ' -bs')) { $count = parent::send($message, $failedRecipients); } else { $this->_throwException(new Swift_TransportException( 'Unsupported sendmail command flags ['.$command.']. '. 'Must be one of "-bs" or "-t" but can include additional flags.' )); } return $count; } /** Get the params to initialize the buffer */ protected function _getBufferParams() { return $this->_params; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Stores Messages in a queue. * * @author Fabien Potencier */ class Swift_Transport_SpoolTransport implements Swift_Transport { /** The spool instance */ private $_spool; /** The event dispatcher from the plugin API */ private $_eventDispatcher; /** * Constructor. */ public function __construct(Swift_Events_EventDispatcher $eventDispatcher, Swift_Spool $spool = null) { $this->_eventDispatcher = $eventDispatcher; $this->_spool = $spool; } /** * Sets the spool object. * * @param Swift_Spool $spool * * @return Swift_Transport_SpoolTransport */ public function setSpool(Swift_Spool $spool) { $this->_spool = $spool; return $this; } /** * Get the spool object. * * @return Swift_Spool */ public function getSpool() { return $this->_spool; } /** * Tests if this Transport mechanism has started. * * @return bool */ public function isStarted() { return true; } /** * Starts this Transport mechanism. */ public function start() { } /** * Stops this Transport mechanism. */ public function stop() { } /** * Sends the given message. * * @param Swift_Mime_Message $message * @param string[] $failedRecipients An array of failures by-reference * * @return int The number of sent e-mail's */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { if ($evt = $this->_eventDispatcher->createSendEvent($this, $message)) { $this->_eventDispatcher->dispatchEvent($evt, 'beforeSendPerformed'); if ($evt->bubbleCancelled()) { return 0; } } $success = $this->_spool->queueMessage($message); if ($evt) { $evt->setResult($success ? Swift_Events_SendEvent::RESULT_SUCCESS : Swift_Events_SendEvent::RESULT_FAILED); $this->_eventDispatcher->dispatchEvent($evt, 'sendPerformed'); } return 1; } /** * Register a plugin. * * @param Swift_Events_EventListener $plugin */ public function registerPlugin(Swift_Events_EventListener $plugin) { $this->_eventDispatcher->bindEventListener($plugin); } } _replacementFactory = $replacementFactory; } /** * Perform any initialization needed, using the given $params. * * Parameters will vary depending upon the type of IoBuffer used. * * @param array $params */ public function initialize(array $params) { $this->_params = $params; switch ($params['type']) { case self::TYPE_PROCESS: $this->_establishProcessConnection(); break; case self::TYPE_SOCKET: default: $this->_establishSocketConnection(); break; } } /** * Set an individual param on the buffer (e.g. switching to SSL). * * @param string $param * @param mixed $value */ public function setParam($param, $value) { if (isset($this->_stream)) { switch ($param) { case 'timeout': if ($this->_stream) { stream_set_timeout($this->_stream, $value); } break; case 'blocking': if ($this->_stream) { stream_set_blocking($this->_stream, 1); } } } $this->_params[$param] = $value; } public function startTLS() { return stream_socket_enable_crypto($this->_stream, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); } /** * Perform any shutdown logic needed. */ public function terminate() { if (isset($this->_stream)) { switch ($this->_params['type']) { case self::TYPE_PROCESS: fclose($this->_in); fclose($this->_out); proc_close($this->_stream); break; case self::TYPE_SOCKET: default: fclose($this->_stream); break; } } $this->_stream = null; $this->_out = null; $this->_in = null; } /** * Set an array of string replacements which should be made on data written * to the buffer. * * This could replace LF with CRLF for example. * * @param string[] $replacements */ public function setWriteTranslations(array $replacements) { foreach ($this->_translations as $search => $replace) { if (!isset($replacements[$search])) { $this->removeFilter($search); unset($this->_translations[$search]); } } foreach ($replacements as $search => $replace) { if (!isset($this->_translations[$search])) { $this->addFilter( $this->_replacementFactory->createFilter($search, $replace), $search ); $this->_translations[$search] = true; } } } /** * Get a line of output (including any CRLF). * * The $sequence number comes from any writes and may or may not be used * depending upon the implementation. * * @param int $sequence of last write to scan from * * @return string * * @throws Swift_IoException */ public function readLine($sequence) { if (isset($this->_out) && !feof($this->_out)) { $line = fgets($this->_out); if (strlen($line) == 0) { $metas = stream_get_meta_data($this->_out); if ($metas['timed_out']) { throw new Swift_IoException( 'Connection to '. $this->_getReadConnectionDescription(). ' Timed Out' ); } } return $line; } } /** * Reads $length bytes from the stream into a string and moves the pointer * through the stream by $length. * * If less bytes exist than are requested the remaining bytes are given instead. * If no bytes are remaining at all, boolean false is returned. * * @param int $length * * @return string|bool * * @throws Swift_IoException */ public function read($length) { if (isset($this->_out) && !feof($this->_out)) { $ret = fread($this->_out, $length); if (strlen($ret) == 0) { $metas = stream_get_meta_data($this->_out); if ($metas['timed_out']) { throw new Swift_IoException( 'Connection to '. $this->_getReadConnectionDescription(). ' Timed Out' ); } } return $ret; } } /** Not implemented */ public function setReadPointer($byteOffset) { } /** Flush the stream contents */ protected function _flush() { if (isset($this->_in)) { fflush($this->_in); } } /** Write this bytes to the stream */ protected function _commit($bytes) { if (isset($this->_in)) { $bytesToWrite = strlen($bytes); $totalBytesWritten = 0; while ($totalBytesWritten < $bytesToWrite) { $bytesWritten = fwrite($this->_in, substr($bytes, $totalBytesWritten)); if (false === $bytesWritten || 0 === $bytesWritten) { break; } $totalBytesWritten += $bytesWritten; } if ($totalBytesWritten > 0) { return ++$this->_sequence; } } } /** * Establishes a connection to a remote server. */ private function _establishSocketConnection() { $host = $this->_params['host']; if (!empty($this->_params['protocol'])) { $host = $this->_params['protocol'].'://'.$host; } $timeout = 15; if (!empty($this->_params['timeout'])) { $timeout = $this->_params['timeout']; } $options = array(); if (!empty($this->_params['sourceIp'])) { $options['socket']['bindto'] = $this->_params['sourceIp'].':0'; } $this->_stream = @stream_socket_client($host.':'.$this->_params['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, stream_context_create($options)); if (false === $this->_stream) { throw new Swift_TransportException( 'Connection could not be established with host '.$this->_params['host']. ' ['.$errstr.' #'.$errno.']' ); } if (!empty($this->_params['blocking'])) { stream_set_blocking($this->_stream, 1); } else { stream_set_blocking($this->_stream, 0); } stream_set_timeout($this->_stream, $timeout); $this->_in = & $this->_stream; $this->_out = & $this->_stream; } /** * Opens a process for input/output. */ private function _establishProcessConnection() { $command = $this->_params['command']; $descriptorSpec = array( 0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w'), ); $this->_stream = proc_open($command, $descriptorSpec, $pipes); stream_set_blocking($pipes[2], 0); if ($err = stream_get_contents($pipes[2])) { throw new Swift_TransportException( 'Process could not be started ['.$err.']' ); } $this->_in = & $pipes[0]; $this->_out = & $pipes[1]; } private function _getReadConnectionDescription() { switch ($this->_params['type']) { case self::TYPE_PROCESS: return 'Process '.$this->_params['command']; break; case self::TYPE_SOCKET: default: $host = $this->_params['host']; if (!empty($this->_params['protocol'])) { $host = $this->_params['protocol'].'://'.$host; } $host .= ':'.$this->_params['port']; return $host; break; } } } */ class Swift_Validate { /** * Grammar Object * * @var Swift_Mime_Grammar */ private static $grammar = null; /** * Checks if an e-mail address matches the current grammars. * * @param string $email * * @return bool */ public static function email($email) { if (self::$grammar === null) { self::$grammar = Swift_DependencyContainer::getInstance() ->lookup('mime.grammar'); } return (bool) preg_match( '/^'.self::$grammar->getDefinition('addr-spec').'$/D', $email ); } } register('cache') ->asAliasOf('cache.array') ->register('tempdir') ->asValue('/tmp') ->register('cache.null') ->asSharedInstanceOf('Swift_KeyCache_NullKeyCache') ->register('cache.array') ->asSharedInstanceOf('Swift_KeyCache_ArrayKeyCache') ->withDependencies(array('cache.inputstream')) ->register('cache.disk') ->asSharedInstanceOf('Swift_KeyCache_DiskKeyCache') ->withDependencies(array('cache.inputstream', 'tempdir')) ->register('cache.inputstream') ->asNewInstanceOf('Swift_KeyCache_SimpleKeyCacheInputStream') ; register('message.message') ->asNewInstanceOf('Swift_Message') ->register('message.mimepart') ->asNewInstanceOf('Swift_MimePart') ; register('properties.charset') ->asValue('utf-8') ->register('mime.grammar') ->asSharedInstanceOf('Swift_Mime_Grammar') ->register('mime.message') ->asNewInstanceOf('Swift_Mime_SimpleMessage') ->withDependencies(array( 'mime.headerset', 'mime.qpcontentencoder', 'cache', 'mime.grammar', 'properties.charset', )) ->register('mime.part') ->asNewInstanceOf('Swift_Mime_MimePart') ->withDependencies(array( 'mime.headerset', 'mime.qpcontentencoder', 'cache', 'mime.grammar', 'properties.charset', )) ->register('mime.attachment') ->asNewInstanceOf('Swift_Mime_Attachment') ->withDependencies(array( 'mime.headerset', 'mime.base64contentencoder', 'cache', 'mime.grammar', )) ->addConstructorValue($swift_mime_types) ->register('mime.embeddedfile') ->asNewInstanceOf('Swift_Mime_EmbeddedFile') ->withDependencies(array( 'mime.headerset', 'mime.base64contentencoder', 'cache', 'mime.grammar', )) ->addConstructorValue($swift_mime_types) ->register('mime.headerfactory') ->asNewInstanceOf('Swift_Mime_SimpleHeaderFactory') ->withDependencies(array( 'mime.qpheaderencoder', 'mime.rfc2231encoder', 'mime.grammar', 'properties.charset', )) ->register('mime.headerset') ->asNewInstanceOf('Swift_Mime_SimpleHeaderSet') ->withDependencies(array('mime.headerfactory', 'properties.charset')) ->register('mime.qpheaderencoder') ->asNewInstanceOf('Swift_Mime_HeaderEncoder_QpHeaderEncoder') ->withDependencies(array('mime.charstream')) ->register('mime.base64headerencoder') ->asNewInstanceOf('Swift_Mime_HeaderEncoder_Base64HeaderEncoder') ->withDependencies(array('mime.charstream')) ->register('mime.charstream') ->asNewInstanceOf('Swift_CharacterStream_NgCharacterStream') ->withDependencies(array('mime.characterreaderfactory', 'properties.charset')) ->register('mime.bytecanonicalizer') ->asSharedInstanceOf('Swift_StreamFilters_ByteArrayReplacementFilter') ->addConstructorValue(array(array(0x0D, 0x0A), array(0x0D), array(0x0A))) ->addConstructorValue(array(array(0x0A), array(0x0A), array(0x0D, 0x0A))) ->register('mime.characterreaderfactory') ->asSharedInstanceOf('Swift_CharacterReaderFactory_SimpleCharacterReaderFactory') ->register('mime.safeqpcontentencoder') ->asNewInstanceOf('Swift_Mime_ContentEncoder_QpContentEncoder') ->withDependencies(array('mime.charstream', 'mime.bytecanonicalizer')) ->register('mime.rawcontentencoder') ->asNewInstanceOf('Swift_Mime_ContentEncoder_RawContentEncoder') ->register('mime.nativeqpcontentencoder') ->withDependencies(array('properties.charset')) ->asNewInstanceOf('Swift_Mime_ContentEncoder_NativeQpContentEncoder') ->register('mime.qpcontentencoderproxy') ->asNewInstanceOf('Swift_Mime_ContentEncoder_QpContentEncoderProxy') ->withDependencies(array('mime.safeqpcontentencoder', 'mime.nativeqpcontentencoder', 'properties.charset')) ->register('mime.7bitcontentencoder') ->asNewInstanceOf('Swift_Mime_ContentEncoder_PlainContentEncoder') ->addConstructorValue('7bit') ->addConstructorValue(true) ->register('mime.8bitcontentencoder') ->asNewInstanceOf('Swift_Mime_ContentEncoder_PlainContentEncoder') ->addConstructorValue('8bit') ->addConstructorValue(true) ->register('mime.base64contentencoder') ->asSharedInstanceOf('Swift_Mime_ContentEncoder_Base64ContentEncoder') ->register('mime.rfc2231encoder') ->asNewInstanceOf('Swift_Encoder_Rfc2231Encoder') ->withDependencies(array('mime.charstream')) // As of PHP 5.4.7, the quoted_printable_encode() function behaves correctly. // see https://github.com/php/php-src/commit/18bb426587d62f93c54c40bf8535eb8416603629 ->register('mime.qpcontentencoder') ->asAliasOf(version_compare(phpversion(), '5.4.7', '>=') ? 'mime.qpcontentencoderproxy' : 'mime.safeqpcontentencoder') ; unset($swift_mime_types); register('transport.smtp') ->asNewInstanceOf('Swift_Transport_EsmtpTransport') ->withDependencies(array( 'transport.buffer', array('transport.authhandler'), 'transport.eventdispatcher', )) ->register('transport.sendmail') ->asNewInstanceOf('Swift_Transport_SendmailTransport') ->withDependencies(array( 'transport.buffer', 'transport.eventdispatcher', )) ->register('transport.mail') ->asNewInstanceOf('Swift_Transport_MailTransport') ->withDependencies(array('transport.mailinvoker', 'transport.eventdispatcher')) ->register('transport.loadbalanced') ->asNewInstanceOf('Swift_Transport_LoadBalancedTransport') ->register('transport.failover') ->asNewInstanceOf('Swift_Transport_FailoverTransport') ->register('transport.spool') ->asNewInstanceOf('Swift_Transport_SpoolTransport') ->withDependencies(array('transport.eventdispatcher')) ->register('transport.null') ->asNewInstanceOf('Swift_Transport_NullTransport') ->withDependencies(array('transport.eventdispatcher')) ->register('transport.mailinvoker') ->asSharedInstanceOf('Swift_Transport_SimpleMailInvoker') ->register('transport.buffer') ->asNewInstanceOf('Swift_Transport_StreamBuffer') ->withDependencies(array('transport.replacementfactory')) ->register('transport.authhandler') ->asNewInstanceOf('Swift_Transport_Esmtp_AuthHandler') ->withDependencies(array( array( 'transport.crammd5auth', 'transport.loginauth', 'transport.plainauth', 'transport.ntlmauth', 'transport.xoauth2auth', ), )) ->register('transport.crammd5auth') ->asNewInstanceOf('Swift_Transport_Esmtp_Auth_CramMd5Authenticator') ->register('transport.loginauth') ->asNewInstanceOf('Swift_Transport_Esmtp_Auth_LoginAuthenticator') ->register('transport.plainauth') ->asNewInstanceOf('Swift_Transport_Esmtp_Auth_PlainAuthenticator') ->register('transport.xoauth2auth') ->asNewInstanceOf('Swift_Transport_Esmtp_Auth_XOAuth2Authenticator') ->register('transport.ntlmauth') ->asNewInstanceOf('Swift_Transport_Esmtp_Auth_NTLMAuthenticator') ->register('transport.eventdispatcher') ->asNewInstanceOf('Swift_Events_SimpleEventDispatcher') ->register('transport.replacementfactory') ->asSharedInstanceOf('Swift_StreamFilters_StringReplacementFilterFactory') ; Copyright (c) 2013 Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 'text/vnd.in3d.3dml', '3ds' => 'image/x-3ds', '3g2' => 'video/3gpp2', '3gp' => 'video/3gpp', '7z' => 'application/x-7z-compressed', 'aab' => 'application/x-authorware-bin', 'aac' => 'audio/x-aac', 'aam' => 'application/x-authorware-map', 'aas' => 'application/x-authorware-seg', 'abw' => 'application/x-abiword', 'ac' => 'application/pkix-attr-cert', 'acc' => 'application/vnd.americandynamics.acc', 'ace' => 'application/x-ace-compressed', 'acu' => 'application/vnd.acucobol', 'acutc' => 'application/vnd.acucorp', 'adp' => 'audio/adpcm', 'aep' => 'application/vnd.audiograph', 'afm' => 'application/x-font-type1', 'afp' => 'application/vnd.ibm.modcap', 'ahead' => 'application/vnd.ahead.space', 'ai' => 'application/postscript', 'aif' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'air' => 'application/vnd.adobe.air-application-installer-package+zip', 'ait' => 'application/vnd.dvb.ait', 'ami' => 'application/vnd.amiga.ami', 'apk' => 'application/vnd.android.package-archive', 'appcache' => 'text/cache-manifest', 'apr' => 'application/vnd.lotus-approach', 'aps' => 'application/postscript', 'arc' => 'application/x-freearc', 'asc' => 'application/pgp-signature', 'asf' => 'video/x-ms-asf', 'asm' => 'text/x-asm', 'aso' => 'application/vnd.accpac.simply.aso', 'asx' => 'video/x-ms-asf', 'atc' => 'application/vnd.acucorp', 'atom' => 'application/atom+xml', 'atomcat' => 'application/atomcat+xml', 'atomsvc' => 'application/atomsvc+xml', 'atx' => 'application/vnd.antix.game-component', 'au' => 'audio/basic', 'avi' => 'video/x-msvideo', 'aw' => 'application/applixware', 'azf' => 'application/vnd.airzip.filesecure.azf', 'azs' => 'application/vnd.airzip.filesecure.azs', 'azw' => 'application/vnd.amazon.ebook', 'bat' => 'application/x-msdownload', 'bcpio' => 'application/x-bcpio', 'bdf' => 'application/x-font-bdf', 'bdm' => 'application/vnd.syncml.dm+wbxml', 'bed' => 'application/vnd.realvnc.bed', 'bh2' => 'application/vnd.fujitsu.oasysprs', 'bin' => 'application/octet-stream', 'blb' => 'application/x-blorb', 'blorb' => 'application/x-blorb', 'bmi' => 'application/vnd.bmi', 'bmp' => 'image/bmp', 'book' => 'application/vnd.framemaker', 'box' => 'application/vnd.previewsystems.box', 'boz' => 'application/x-bzip2', 'bpk' => 'application/octet-stream', 'btif' => 'image/prs.btif', 'bz' => 'application/x-bzip', 'bz2' => 'application/x-bzip2', 'c' => 'text/x-c', 'c11amc' => 'application/vnd.cluetrust.cartomobile-config', 'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg', 'c4d' => 'application/vnd.clonk.c4group', 'c4f' => 'application/vnd.clonk.c4group', 'c4g' => 'application/vnd.clonk.c4group', 'c4p' => 'application/vnd.clonk.c4group', 'c4u' => 'application/vnd.clonk.c4group', 'cab' => 'application/vnd.ms-cab-compressed', 'caf' => 'audio/x-caf', 'cap' => 'application/vnd.tcpdump.pcap', 'car' => 'application/vnd.curl.car', 'cat' => 'application/vnd.ms-pki.seccat', 'cb7' => 'application/x-cbr', 'cba' => 'application/x-cbr', 'cbr' => 'application/x-cbr', 'cbt' => 'application/x-cbr', 'cbz' => 'application/x-cbr', 'cc' => 'text/x-c', 'cct' => 'application/x-director', 'ccxml' => 'application/ccxml+xml', 'cdbcmsg' => 'application/vnd.contact.cmsg', 'cdf' => 'application/x-netcdf', 'cdkey' => 'application/vnd.mediastation.cdkey', 'cdmia' => 'application/cdmi-capability', 'cdmic' => 'application/cdmi-container', 'cdmid' => 'application/cdmi-domain', 'cdmio' => 'application/cdmi-object', 'cdmiq' => 'application/cdmi-queue', 'cdx' => 'chemical/x-cdx', 'cdxml' => 'application/vnd.chemdraw+xml', 'cdy' => 'application/vnd.cinderella', 'cer' => 'application/pkix-cert', 'cfs' => 'application/x-cfs-compressed', 'cgm' => 'image/cgm', 'chat' => 'application/x-chat', 'chm' => 'application/vnd.ms-htmlhelp', 'chrt' => 'application/vnd.kde.kchart', 'cif' => 'chemical/x-cif', 'cii' => 'application/vnd.anser-web-certificate-issue-initiation', 'cil' => 'application/vnd.ms-artgalry', 'cla' => 'application/vnd.claymore', 'class' => 'application/java-vm', 'clkk' => 'application/vnd.crick.clicker.keyboard', 'clkp' => 'application/vnd.crick.clicker.palette', 'clkt' => 'application/vnd.crick.clicker.template', 'clkw' => 'application/vnd.crick.clicker.wordbank', 'clkx' => 'application/vnd.crick.clicker', 'clp' => 'application/x-msclip', 'cmc' => 'application/vnd.cosmocaller', 'cmdf' => 'chemical/x-cmdf', 'cml' => 'chemical/x-cml', 'cmp' => 'application/vnd.yellowriver-custom-menu', 'cmx' => 'image/x-cmx', 'cod' => 'application/vnd.rim.cod', 'com' => 'application/x-msdownload', 'conf' => 'text/plain', 'cpio' => 'application/x-cpio', 'cpp' => 'text/x-c', 'cpt' => 'application/mac-compactpro', 'crd' => 'application/x-mscardfile', 'crl' => 'application/pkix-crl', 'crt' => 'application/x-x509-ca-cert', 'csh' => 'application/x-csh', 'csml' => 'chemical/x-csml', 'csp' => 'application/vnd.commonspace', 'css' => 'text/css', 'cst' => 'application/x-director', 'csv' => 'text/csv', 'cu' => 'application/cu-seeme', 'curl' => 'text/vnd.curl', 'cww' => 'application/prs.cww', 'cxt' => 'application/x-director', 'cxx' => 'text/x-c', 'dae' => 'model/vnd.collada+xml', 'daf' => 'application/vnd.mobius.daf', 'dart' => 'application/vnd.dart', 'dataless' => 'application/vnd.fdsn.seed', 'davmount' => 'application/davmount+xml', 'dbk' => 'application/docbook+xml', 'dcr' => 'application/x-director', 'dcurl' => 'text/vnd.curl.dcurl', 'dd2' => 'application/vnd.oma.dd2+xml', 'ddd' => 'application/vnd.fujixerox.ddd', 'deb' => 'application/x-debian-package', 'def' => 'text/plain', 'deploy' => 'application/octet-stream', 'der' => 'application/x-x509-ca-cert', 'dfac' => 'application/vnd.dreamfactory', 'dgc' => 'application/x-dgc-compressed', 'dic' => 'text/x-c', 'dir' => 'application/x-director', 'dis' => 'application/vnd.mobius.dis', 'dist' => 'application/octet-stream', 'distz' => 'application/octet-stream', 'djv' => 'image/vnd.djvu', 'djvu' => 'image/vnd.djvu', 'dll' => 'application/x-msdownload', 'dmg' => 'application/x-apple-diskimage', 'dmp' => 'application/vnd.tcpdump.pcap', 'dms' => 'application/octet-stream', 'dna' => 'application/vnd.dna', 'doc' => 'application/msword', 'docm' => 'application/vnd.ms-word.document.macroenabled.12', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'dot' => 'application/msword', 'dotm' => 'application/vnd.ms-word.template.macroenabled.12', 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'dp' => 'application/vnd.osgi.dp', 'dpg' => 'application/vnd.dpgraph', 'dra' => 'audio/vnd.dra', 'dsc' => 'text/prs.lines.tag', 'dssc' => 'application/dssc+der', 'dtb' => 'application/x-dtbook+xml', 'dtd' => 'application/xml-dtd', 'dts' => 'audio/vnd.dts', 'dtshd' => 'audio/vnd.dts.hd', 'dump' => 'application/octet-stream', 'dvb' => 'video/vnd.dvb.file', 'dvi' => 'application/x-dvi', 'dwf' => 'model/vnd.dwf', 'dwg' => 'image/vnd.dwg', 'dxf' => 'image/vnd.dxf', 'dxp' => 'application/vnd.spotfire.dxp', 'dxr' => 'application/x-director', 'ecelp4800' => 'audio/vnd.nuera.ecelp4800', 'ecelp7470' => 'audio/vnd.nuera.ecelp7470', 'ecelp9600' => 'audio/vnd.nuera.ecelp9600', 'ecma' => 'application/ecmascript', 'edm' => 'application/vnd.novadigm.edm', 'edx' => 'application/vnd.novadigm.edx', 'efif' => 'application/vnd.picsel', 'ei6' => 'application/vnd.pg.osasli', 'elc' => 'application/octet-stream', 'emf' => 'application/x-msmetafile', 'eml' => 'message/rfc822', 'emma' => 'application/emma+xml', 'emz' => 'application/x-msmetafile', 'eol' => 'audio/vnd.digital-winds', 'eot' => 'application/vnd.ms-fontobject', 'eps' => 'application/postscript', 'epub' => 'application/epub+zip', 'es3' => 'application/vnd.eszigno3+xml', 'esa' => 'application/vnd.osgi.subsystem', 'esf' => 'application/vnd.epson.esf', 'et3' => 'application/vnd.eszigno3+xml', 'etx' => 'text/x-setext', 'eva' => 'application/x-eva', 'evy' => 'application/x-envoy', 'exe' => 'application/x-msdownload', 'exi' => 'application/exi', 'ext' => 'application/vnd.novadigm.ext', 'ez' => 'application/andrew-inset', 'ez2' => 'application/vnd.ezpix-album', 'ez3' => 'application/vnd.ezpix-package', 'f' => 'text/x-fortran', 'f4v' => 'video/x-f4v', 'f77' => 'text/x-fortran', 'f90' => 'text/x-fortran', 'fbs' => 'image/vnd.fastbidsheet', 'fcdt' => 'application/vnd.adobe.formscentral.fcdt', 'fcs' => 'application/vnd.isac.fcs', 'fdf' => 'application/vnd.fdf', 'fe_launch' => 'application/vnd.denovo.fcselayout-link', 'fg5' => 'application/vnd.fujitsu.oasysgp', 'fgd' => 'application/x-director', 'fh' => 'image/x-freehand', 'fh4' => 'image/x-freehand', 'fh5' => 'image/x-freehand', 'fh7' => 'image/x-freehand', 'fhc' => 'image/x-freehand', 'fig' => 'application/x-xfig', 'flac' => 'audio/x-flac', 'fli' => 'video/x-fli', 'flo' => 'application/vnd.micrografx.flo', 'flv' => 'video/x-flv', 'flw' => 'application/vnd.kde.kivio', 'flx' => 'text/vnd.fmi.flexstor', 'fly' => 'text/vnd.fly', 'fm' => 'application/vnd.framemaker', 'fnc' => 'application/vnd.frogans.fnc', 'for' => 'text/x-fortran', 'fpx' => 'image/vnd.fpx', 'frame' => 'application/vnd.framemaker', 'fsc' => 'application/vnd.fsc.weblaunch', 'fst' => 'image/vnd.fst', 'ftc' => 'application/vnd.fluxtime.clip', 'fti' => 'application/vnd.anser-web-funds-transfer-initiation', 'fvt' => 'video/vnd.fvt', 'fxp' => 'application/vnd.adobe.fxp', 'fxpl' => 'application/vnd.adobe.fxp', 'fzs' => 'application/vnd.fuzzysheet', 'g2w' => 'application/vnd.geoplan', 'g3' => 'image/g3fax', 'g3w' => 'application/vnd.geospace', 'gac' => 'application/vnd.groove-account', 'gam' => 'application/x-tads', 'gbr' => 'application/rpki-ghostbusters', 'gca' => 'application/x-gca-compressed', 'gdl' => 'model/vnd.gdl', 'geo' => 'application/vnd.dynageo', 'gex' => 'application/vnd.geometry-explorer', 'ggb' => 'application/vnd.geogebra.file', 'ggt' => 'application/vnd.geogebra.tool', 'ghf' => 'application/vnd.groove-help', 'gif' => 'image/gif', 'gim' => 'application/vnd.groove-identity-message', 'gml' => 'application/gml+xml', 'gmx' => 'application/vnd.gmx', 'gnumeric' => 'application/x-gnumeric', 'gph' => 'application/vnd.flographit', 'gpx' => 'application/gpx+xml', 'gqf' => 'application/vnd.grafeq', 'gqs' => 'application/vnd.grafeq', 'gram' => 'application/srgs', 'gramps' => 'application/x-gramps-xml', 'gre' => 'application/vnd.geometry-explorer', 'grv' => 'application/vnd.groove-injector', 'grxml' => 'application/srgs+xml', 'gsf' => 'application/x-font-ghostscript', 'gtar' => 'application/x-gtar', 'gtm' => 'application/vnd.groove-tool-message', 'gtw' => 'model/vnd.gtw', 'gv' => 'text/vnd.graphviz', 'gxf' => 'application/gxf', 'gxt' => 'application/vnd.geonext', 'gz' => 'application/x-gzip', 'h' => 'text/x-c', 'h261' => 'video/h261', 'h263' => 'video/h263', 'h264' => 'video/h264', 'hal' => 'application/vnd.hal+xml', 'hbci' => 'application/vnd.hbci', 'hdf' => 'application/x-hdf', 'hh' => 'text/x-c', 'hlp' => 'application/winhlp', 'hpgl' => 'application/vnd.hp-hpgl', 'hpid' => 'application/vnd.hp-hpid', 'hps' => 'application/vnd.hp-hps', 'hqx' => 'application/mac-binhex40', 'htke' => 'application/vnd.kenameaapp', 'htm' => 'text/html', 'html' => 'text/html', 'hvd' => 'application/vnd.yamaha.hv-dic', 'hvp' => 'application/vnd.yamaha.hv-voice', 'hvs' => 'application/vnd.yamaha.hv-script', 'i2g' => 'application/vnd.intergeo', 'icc' => 'application/vnd.iccprofile', 'ice' => 'x-conference/x-cooltalk', 'icm' => 'application/vnd.iccprofile', 'ico' => 'image/x-icon', 'ics' => 'text/calendar', 'ief' => 'image/ief', 'ifb' => 'text/calendar', 'ifm' => 'application/vnd.shana.informed.formdata', 'iges' => 'model/iges', 'igl' => 'application/vnd.igloader', 'igm' => 'application/vnd.insors.igm', 'igs' => 'model/iges', 'igx' => 'application/vnd.micrografx.igx', 'iif' => 'application/vnd.shana.informed.interchange', 'imp' => 'application/vnd.accpac.simply.imp', 'ims' => 'application/vnd.ms-ims', 'in' => 'text/plain', 'ink' => 'application/inkml+xml', 'inkml' => 'application/inkml+xml', 'install' => 'application/x-install-instructions', 'iota' => 'application/vnd.astraea-software.iota', 'ipfix' => 'application/ipfix', 'ipk' => 'application/vnd.shana.informed.package', 'irm' => 'application/vnd.ibm.rights-management', 'irp' => 'application/vnd.irepository.package+xml', 'iso' => 'application/x-iso9660-image', 'itp' => 'application/vnd.shana.informed.formtemplate', 'ivp' => 'application/vnd.immervision-ivp', 'ivu' => 'application/vnd.immervision-ivu', 'jad' => 'text/vnd.sun.j2me.app-descriptor', 'jam' => 'application/vnd.jam', 'jar' => 'application/java-archive', 'java' => 'text/x-java-source', 'jisp' => 'application/vnd.jisp', 'jlt' => 'application/vnd.hp-jlyt', 'jnlp' => 'application/x-java-jnlp-file', 'joda' => 'application/vnd.joost.joda-archive', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'jpgm' => 'video/jpm', 'jpgv' => 'video/jpeg', 'jpm' => 'video/jpm', 'js' => 'application/javascript', 'json' => 'application/json', 'jsonml' => 'application/jsonml+json', 'kar' => 'audio/midi', 'karbon' => 'application/vnd.kde.karbon', 'kfo' => 'application/vnd.kde.kformula', 'kia' => 'application/vnd.kidspiration', 'kml' => 'application/vnd.google-earth.kml+xml', 'kmz' => 'application/vnd.google-earth.kmz', 'kne' => 'application/vnd.kinar', 'knp' => 'application/vnd.kinar', 'kon' => 'application/vnd.kde.kontour', 'kpr' => 'application/vnd.kde.kpresenter', 'kpt' => 'application/vnd.kde.kpresenter', 'kpxx' => 'application/vnd.ds-keypoint', 'ksp' => 'application/vnd.kde.kspread', 'ktr' => 'application/vnd.kahootz', 'ktx' => 'image/ktx', 'ktz' => 'application/vnd.kahootz', 'kwd' => 'application/vnd.kde.kword', 'kwt' => 'application/vnd.kde.kword', 'lasxml' => 'application/vnd.las.las+xml', 'latex' => 'application/x-latex', 'lbd' => 'application/vnd.llamagraphics.life-balance.desktop', 'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml', 'les' => 'application/vnd.hhe.lesson-player', 'lha' => 'application/x-lzh-compressed', 'link66' => 'application/vnd.route66.link66+xml', 'list' => 'text/plain', 'list3820' => 'application/vnd.ibm.modcap', 'listafp' => 'application/vnd.ibm.modcap', 'lnk' => 'application/x-ms-shortcut', 'log' => 'text/plain', 'lostxml' => 'application/lost+xml', 'lrf' => 'application/octet-stream', 'lrm' => 'application/vnd.ms-lrm', 'ltf' => 'application/vnd.frogans.ltf', 'lvp' => 'audio/vnd.lucent.voice', 'lwp' => 'application/vnd.lotus-wordpro', 'lzh' => 'application/x-lzh-compressed', 'm13' => 'application/x-msmediaview', 'm14' => 'application/x-msmediaview', 'm1v' => 'video/mpeg', 'm21' => 'application/mp21', 'm2a' => 'audio/mpeg', 'm2v' => 'video/mpeg', 'm3a' => 'audio/mpeg', 'm3u' => 'audio/x-mpegurl', 'm3u8' => 'application/vnd.apple.mpegurl', 'm4a' => 'audio/mp4', 'm4u' => 'video/vnd.mpegurl', 'm4v' => 'video/x-m4v', 'ma' => 'application/mathematica', 'mads' => 'application/mads+xml', 'mag' => 'application/vnd.ecowin.chart', 'maker' => 'application/vnd.framemaker', 'man' => 'text/troff', 'mar' => 'application/octet-stream', 'mathml' => 'application/mathml+xml', 'mb' => 'application/mathematica', 'mbk' => 'application/vnd.mobius.mbk', 'mbox' => 'application/mbox', 'mc1' => 'application/vnd.medcalcdata', 'mcd' => 'application/vnd.mcd', 'mcurl' => 'text/vnd.curl.mcurl', 'mdb' => 'application/x-msaccess', 'mdi' => 'image/vnd.ms-modi', 'me' => 'text/troff', 'mesh' => 'model/mesh', 'meta4' => 'application/metalink4+xml', 'metalink' => 'application/metalink+xml', 'mets' => 'application/mets+xml', 'mfm' => 'application/vnd.mfmp', 'mft' => 'application/rpki-manifest', 'mgp' => 'application/vnd.osgeo.mapguide.package', 'mgz' => 'application/vnd.proteus.magazine', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mie' => 'application/x-mie', 'mif' => 'application/vnd.mif', 'mime' => 'message/rfc822', 'mj2' => 'video/mj2', 'mjp2' => 'video/mj2', 'mk3d' => 'video/x-matroska', 'mka' => 'audio/x-matroska', 'mks' => 'video/x-matroska', 'mkv' => 'video/x-matroska', 'mlp' => 'application/vnd.dolby.mlp', 'mmd' => 'application/vnd.chipnuts.karaoke-mmd', 'mmf' => 'application/vnd.smaf', 'mmr' => 'image/vnd.fujixerox.edmics-mmr', 'mng' => 'video/x-mng', 'mny' => 'application/x-msmoney', 'mobi' => 'application/x-mobipocket-ebook', 'mods' => 'application/mods+xml', 'mov' => 'video/quicktime', 'movie' => 'video/x-sgi-movie', 'mp2' => 'audio/mpeg', 'mp21' => 'application/mp21', 'mp2a' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'mp4' => 'video/mp4', 'mp4a' => 'audio/mp4', 'mp4s' => 'application/mp4', 'mp4v' => 'video/mp4', 'mpc' => 'application/vnd.mophun.certificate', 'mpe' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpg4' => 'video/mp4', 'mpga' => 'audio/mpeg', 'mpkg' => 'application/vnd.apple.installer+xml', 'mpm' => 'application/vnd.blueice.multipass', 'mpn' => 'application/vnd.mophun.application', 'mpp' => 'application/vnd.ms-project', 'mpt' => 'application/vnd.ms-project', 'mpy' => 'application/vnd.ibm.minipay', 'mqy' => 'application/vnd.mobius.mqy', 'mrc' => 'application/marc', 'mrcx' => 'application/marcxml+xml', 'ms' => 'text/troff', 'mscml' => 'application/mediaservercontrol+xml', 'mseed' => 'application/vnd.fdsn.mseed', 'mseq' => 'application/vnd.mseq', 'msf' => 'application/vnd.epson.msf', 'msh' => 'model/mesh', 'msi' => 'application/x-msdownload', 'msl' => 'application/vnd.mobius.msl', 'msty' => 'application/vnd.muvee.style', 'mts' => 'model/vnd.mts', 'mus' => 'application/vnd.musician', 'musicxml' => 'application/vnd.recordare.musicxml+xml', 'mvb' => 'application/x-msmediaview', 'mwf' => 'application/vnd.mfer', 'mxf' => 'application/mxf', 'mxl' => 'application/vnd.recordare.musicxml', 'mxml' => 'application/xv+xml', 'mxs' => 'application/vnd.triscape.mxs', 'mxu' => 'video/vnd.mpegurl', 'n-gage' => 'application/vnd.nokia.n-gage.symbian.install', 'n3' => 'text/n3', 'nb' => 'application/mathematica', 'nbp' => 'application/vnd.wolfram.player', 'nc' => 'application/x-netcdf', 'ncx' => 'application/x-dtbncx+xml', 'nfo' => 'text/x-nfo', 'ngdat' => 'application/vnd.nokia.n-gage.data', 'nitf' => 'application/vnd.nitf', 'nlu' => 'application/vnd.neurolanguage.nlu', 'nml' => 'application/vnd.enliven', 'nnd' => 'application/vnd.noblenet-directory', 'nns' => 'application/vnd.noblenet-sealer', 'nnw' => 'application/vnd.noblenet-web', 'npx' => 'image/vnd.net-fpx', 'nsc' => 'application/x-conference', 'nsf' => 'application/vnd.lotus-notes', 'ntf' => 'application/vnd.nitf', 'nzb' => 'application/x-nzb', 'oa2' => 'application/vnd.fujitsu.oasys2', 'oa3' => 'application/vnd.fujitsu.oasys3', 'oas' => 'application/vnd.fujitsu.oasys', 'obd' => 'application/x-msbinder', 'obj' => 'application/x-tgif', 'oda' => 'application/oda', 'odb' => 'application/vnd.oasis.opendocument.database', 'odc' => 'application/vnd.oasis.opendocument.chart', 'odf' => 'application/vnd.oasis.opendocument.formula', 'odft' => 'application/vnd.oasis.opendocument.formula-template', 'odg' => 'application/vnd.oasis.opendocument.graphics', 'odi' => 'application/vnd.oasis.opendocument.image', 'odm' => 'application/vnd.oasis.opendocument.text-master', 'odp' => 'application/vnd.oasis.opendocument.presentation', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', 'odt' => 'application/vnd.oasis.opendocument.text', 'oga' => 'audio/ogg', 'ogg' => 'audio/ogg', 'ogv' => 'video/ogg', 'ogx' => 'application/ogg', 'omdoc' => 'application/omdoc+xml', 'onepkg' => 'application/onenote', 'onetmp' => 'application/onenote', 'onetoc' => 'application/onenote', 'onetoc2' => 'application/onenote', 'opf' => 'application/oebps-package+xml', 'opml' => 'text/x-opml', 'oprc' => 'application/vnd.palm', 'org' => 'application/vnd.lotus-organizer', 'osf' => 'application/vnd.yamaha.openscoreformat', 'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml', 'otc' => 'application/vnd.oasis.opendocument.chart-template', 'otf' => 'application/x-font-otf', 'otg' => 'application/vnd.oasis.opendocument.graphics-template', 'oth' => 'application/vnd.oasis.opendocument.text-web', 'oti' => 'application/vnd.oasis.opendocument.image-template', 'otp' => 'application/vnd.oasis.opendocument.presentation-template', 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', 'ott' => 'application/vnd.oasis.opendocument.text-template', 'oxps' => 'application/oxps', 'oxt' => 'application/vnd.openofficeorg.extension', 'p' => 'text/x-pascal', 'p10' => 'application/pkcs10', 'p12' => 'application/x-pkcs12', 'p7b' => 'application/x-pkcs7-certificates', 'p7c' => 'application/pkcs7-mime', 'p7m' => 'application/pkcs7-mime', 'p7r' => 'application/x-pkcs7-certreqresp', 'p7s' => 'application/pkcs7-signature', 'p8' => 'application/pkcs8', 'pas' => 'text/x-pascal', 'paw' => 'application/vnd.pawaafile', 'pbd' => 'application/vnd.powerbuilder6', 'pbm' => 'image/x-portable-bitmap', 'pcap' => 'application/vnd.tcpdump.pcap', 'pcf' => 'application/x-font-pcf', 'pcl' => 'application/vnd.hp-pcl', 'pclxl' => 'application/vnd.hp-pclxl', 'pct' => 'image/x-pict', 'pcurl' => 'application/vnd.curl.pcurl', 'pcx' => 'image/x-pcx', 'pdb' => 'application/vnd.palm', 'pdf' => 'application/pdf', 'pfa' => 'application/x-font-type1', 'pfb' => 'application/x-font-type1', 'pfm' => 'application/x-font-type1', 'pfr' => 'application/font-tdpfr', 'pfx' => 'application/x-pkcs12', 'pgm' => 'image/x-portable-graymap', 'pgn' => 'application/x-chess-pgn', 'pgp' => 'application/pgp-encrypted', 'php' => 'application/x-php', 'php3' => 'application/x-php', 'php4' => 'application/x-php', 'php5' => 'application/x-php', 'pic' => 'image/x-pict', 'pkg' => 'application/octet-stream', 'pki' => 'application/pkixcmp', 'pkipath' => 'application/pkix-pkipath', 'plb' => 'application/vnd.3gpp.pic-bw-large', 'plc' => 'application/vnd.mobius.plc', 'plf' => 'application/vnd.pocketlearn', 'pls' => 'application/pls+xml', 'pml' => 'application/vnd.ctc-posml', 'png' => 'image/png', 'pnm' => 'image/x-portable-anymap', 'portpkg' => 'application/vnd.macports.portpkg', 'pot' => 'application/vnd.ms-powerpoint', 'potm' => 'application/vnd.ms-powerpoint.template.macroenabled.12', 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', 'ppam' => 'application/vnd.ms-powerpoint.addin.macroenabled.12', 'ppd' => 'application/vnd.cups-ppd', 'ppm' => 'image/x-portable-pixmap', 'pps' => 'application/vnd.ms-powerpoint', 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroenabled.12', 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'ppt' => 'application/vnd.ms-powerpoint', 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroenabled.12', 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'pqa' => 'application/vnd.palm', 'prc' => 'application/x-mobipocket-ebook', 'pre' => 'application/vnd.lotus-freelance', 'prf' => 'application/pics-rules', 'ps' => 'application/postscript', 'psb' => 'application/vnd.3gpp.pic-bw-small', 'psd' => 'image/vnd.adobe.photoshop', 'psf' => 'application/x-font-linux-psf', 'pskcxml' => 'application/pskc+xml', 'ptid' => 'application/vnd.pvi.ptid1', 'pub' => 'application/x-mspublisher', 'pvb' => 'application/vnd.3gpp.pic-bw-var', 'pwn' => 'application/vnd.3m.post-it-notes', 'pya' => 'audio/vnd.ms-playready.media.pya', 'pyv' => 'video/vnd.ms-playready.media.pyv', 'qam' => 'application/vnd.epson.quickanime', 'qbo' => 'application/vnd.intu.qbo', 'qfx' => 'application/vnd.intu.qfx', 'qps' => 'application/vnd.publishare-delta-tree', 'qt' => 'video/quicktime', 'qwd' => 'application/vnd.quark.quarkxpress', 'qwt' => 'application/vnd.quark.quarkxpress', 'qxb' => 'application/vnd.quark.quarkxpress', 'qxd' => 'application/vnd.quark.quarkxpress', 'qxl' => 'application/vnd.quark.quarkxpress', 'qxt' => 'application/vnd.quark.quarkxpress', 'ra' => 'audio/x-pn-realaudio', 'ram' => 'audio/x-pn-realaudio', 'rar' => 'application/x-rar-compressed', 'ras' => 'image/x-cmu-raster', 'rcprofile' => 'application/vnd.ipunplugged.rcprofile', 'rdf' => 'application/rdf+xml', 'rdz' => 'application/vnd.data-vision.rdz', 'rep' => 'application/vnd.businessobjects', 'res' => 'application/x-dtbresource+xml', 'rgb' => 'image/x-rgb', 'rif' => 'application/reginfo+xml', 'rip' => 'audio/vnd.rip', 'ris' => 'application/x-research-info-systems', 'rl' => 'application/resource-lists+xml', 'rlc' => 'image/vnd.fujixerox.edmics-rlc', 'rld' => 'application/resource-lists-diff+xml', 'rm' => 'application/vnd.rn-realmedia', 'rmi' => 'audio/midi', 'rmp' => 'audio/x-pn-realaudio-plugin', 'rms' => 'application/vnd.jcp.javame.midlet-rms', 'rmvb' => 'application/vnd.rn-realmedia-vbr', 'rnc' => 'application/relax-ng-compact-syntax', 'roa' => 'application/rpki-roa', 'roff' => 'text/troff', 'rp9' => 'application/vnd.cloanto.rp9', 'rpss' => 'application/vnd.nokia.radio-presets', 'rpst' => 'application/vnd.nokia.radio-preset', 'rq' => 'application/sparql-query', 'rs' => 'application/rls-services+xml', 'rsd' => 'application/rsd+xml', 'rss' => 'application/rss+xml', 'rtf' => 'application/rtf', 'rtx' => 'text/richtext', 's' => 'text/x-asm', 's3m' => 'audio/s3m', 'saf' => 'application/vnd.yamaha.smaf-audio', 'sbml' => 'application/sbml+xml', 'sc' => 'application/vnd.ibm.secure-container', 'scd' => 'application/x-msschedule', 'scm' => 'application/vnd.lotus-screencam', 'scq' => 'application/scvp-cv-request', 'scs' => 'application/scvp-cv-response', 'scurl' => 'text/vnd.curl.scurl', 'sda' => 'application/vnd.stardivision.draw', 'sdc' => 'application/vnd.stardivision.calc', 'sdd' => 'application/vnd.stardivision.impress', 'sdkd' => 'application/vnd.solent.sdkm+xml', 'sdkm' => 'application/vnd.solent.sdkm+xml', 'sdp' => 'application/sdp', 'sdw' => 'application/vnd.stardivision.writer', 'see' => 'application/vnd.seemail', 'seed' => 'application/vnd.fdsn.seed', 'sema' => 'application/vnd.sema', 'semd' => 'application/vnd.semd', 'semf' => 'application/vnd.semf', 'ser' => 'application/java-serialized-object', 'setpay' => 'application/set-payment-initiation', 'setreg' => 'application/set-registration-initiation', 'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data', 'sfs' => 'application/vnd.spotfire.sfs', 'sfv' => 'text/x-sfv', 'sgi' => 'image/sgi', 'sgl' => 'application/vnd.stardivision.writer-global', 'sgm' => 'text/sgml', 'sgml' => 'text/sgml', 'sh' => 'application/x-sh', 'shar' => 'application/x-shar', 'shf' => 'application/shf+xml', 'sid' => 'image/x-mrsid-image', 'sig' => 'application/pgp-signature', 'sil' => 'audio/silk', 'silo' => 'model/mesh', 'sis' => 'application/vnd.symbian.install', 'sisx' => 'application/vnd.symbian.install', 'sit' => 'application/x-stuffit', 'sitx' => 'application/x-stuffitx', 'skd' => 'application/vnd.koan', 'skm' => 'application/vnd.koan', 'skp' => 'application/vnd.koan', 'skt' => 'application/vnd.koan', 'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12', 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', 'slt' => 'application/vnd.epson.salt', 'sm' => 'application/vnd.stepmania.stepchart', 'smf' => 'application/vnd.stardivision.math', 'smi' => 'application/smil+xml', 'smil' => 'application/smil+xml', 'smv' => 'video/x-smv', 'smzip' => 'application/vnd.stepmania.package', 'snd' => 'audio/basic', 'snf' => 'application/x-font-snf', 'so' => 'application/octet-stream', 'spc' => 'application/x-pkcs7-certificates', 'spf' => 'application/vnd.yamaha.smaf-phrase', 'spl' => 'application/x-futuresplash', 'spot' => 'text/vnd.in3d.spot', 'spp' => 'application/scvp-vp-response', 'spq' => 'application/scvp-vp-request', 'spx' => 'audio/ogg', 'sql' => 'application/x-sql', 'src' => 'application/x-wais-source', 'srt' => 'application/x-subrip', 'sru' => 'application/sru+xml', 'srx' => 'application/sparql-results+xml', 'ssdl' => 'application/ssdl+xml', 'sse' => 'application/vnd.kodak-descriptor', 'ssf' => 'application/vnd.epson.ssf', 'ssml' => 'application/ssml+xml', 'st' => 'application/vnd.sailingtracker.track', 'stc' => 'application/vnd.sun.xml.calc.template', 'std' => 'application/vnd.sun.xml.draw.template', 'stf' => 'application/vnd.wt.stf', 'sti' => 'application/vnd.sun.xml.impress.template', 'stk' => 'application/hyperstudio', 'stl' => 'application/vnd.ms-pki.stl', 'str' => 'application/vnd.pg.format', 'stw' => 'application/vnd.sun.xml.writer.template', 'sub' => 'text/vnd.dvb.subtitle', 'sus' => 'application/vnd.sus-calendar', 'susp' => 'application/vnd.sus-calendar', 'sv4cpio' => 'application/x-sv4cpio', 'sv4crc' => 'application/x-sv4crc', 'svc' => 'application/vnd.dvb.service', 'svd' => 'application/vnd.svd', 'svg' => 'image/svg+xml', 'svgz' => 'image/svg+xml', 'swa' => 'application/x-director', 'swf' => 'application/x-shockwave-flash', 'swi' => 'application/vnd.aristanetworks.swi', 'sxc' => 'application/vnd.sun.xml.calc', 'sxd' => 'application/vnd.sun.xml.draw', 'sxg' => 'application/vnd.sun.xml.writer.global', 'sxi' => 'application/vnd.sun.xml.impress', 'sxm' => 'application/vnd.sun.xml.math', 'sxw' => 'application/vnd.sun.xml.writer', 't' => 'text/troff', 't3' => 'application/x-t3vm-image', 'taglet' => 'application/vnd.mynfc', 'tao' => 'application/vnd.tao.intent-module-archive', 'tar' => 'application/x-tar', 'tcap' => 'application/vnd.3gpp2.tcap', 'tcl' => 'application/x-tcl', 'teacher' => 'application/vnd.smart.teacher', 'tei' => 'application/tei+xml', 'teicorpus' => 'application/tei+xml', 'tex' => 'application/x-tex', 'texi' => 'application/x-texinfo', 'texinfo' => 'application/x-texinfo', 'text' => 'text/plain', 'tfi' => 'application/thraud+xml', 'tfm' => 'application/x-tex-tfm', 'tga' => 'image/x-tga', 'thmx' => 'application/vnd.ms-officetheme', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'tmo' => 'application/vnd.tmobile-livetv', 'torrent' => 'application/x-bittorrent', 'tpl' => 'application/vnd.groove-tool-template', 'tpt' => 'application/vnd.trid.tpt', 'tr' => 'text/troff', 'tra' => 'application/vnd.trueapp', 'trm' => 'application/x-msterminal', 'tsd' => 'application/timestamped-data', 'tsv' => 'text/tab-separated-values', 'ttc' => 'application/x-font-ttf', 'ttf' => 'application/x-font-ttf', 'ttl' => 'text/turtle', 'twd' => 'application/vnd.simtech-mindmapper', 'twds' => 'application/vnd.simtech-mindmapper', 'txd' => 'application/vnd.genomatix.tuxedo', 'txf' => 'application/vnd.mobius.txf', 'txt' => 'text/plain', 'u32' => 'application/x-authorware-bin', 'udeb' => 'application/x-debian-package', 'ufd' => 'application/vnd.ufdl', 'ufdl' => 'application/vnd.ufdl', 'ulx' => 'application/x-glulx', 'umj' => 'application/vnd.umajin', 'unityweb' => 'application/vnd.unity', 'uoml' => 'application/vnd.uoml+xml', 'uri' => 'text/uri-list', 'uris' => 'text/uri-list', 'urls' => 'text/uri-list', 'ustar' => 'application/x-ustar', 'utz' => 'application/vnd.uiq.theme', 'uu' => 'text/x-uuencode', 'uva' => 'audio/vnd.dece.audio', 'uvd' => 'application/vnd.dece.data', 'uvf' => 'application/vnd.dece.data', 'uvg' => 'image/vnd.dece.graphic', 'uvh' => 'video/vnd.dece.hd', 'uvi' => 'image/vnd.dece.graphic', 'uvm' => 'video/vnd.dece.mobile', 'uvp' => 'video/vnd.dece.pd', 'uvs' => 'video/vnd.dece.sd', 'uvt' => 'application/vnd.dece.ttml+xml', 'uvu' => 'video/vnd.uvvu.mp4', 'uvv' => 'video/vnd.dece.video', 'uvva' => 'audio/vnd.dece.audio', 'uvvd' => 'application/vnd.dece.data', 'uvvf' => 'application/vnd.dece.data', 'uvvg' => 'image/vnd.dece.graphic', 'uvvh' => 'video/vnd.dece.hd', 'uvvi' => 'image/vnd.dece.graphic', 'uvvm' => 'video/vnd.dece.mobile', 'uvvp' => 'video/vnd.dece.pd', 'uvvs' => 'video/vnd.dece.sd', 'uvvt' => 'application/vnd.dece.ttml+xml', 'uvvu' => 'video/vnd.uvvu.mp4', 'uvvv' => 'video/vnd.dece.video', 'uvvx' => 'application/vnd.dece.unspecified', 'uvvz' => 'application/vnd.dece.zip', 'uvx' => 'application/vnd.dece.unspecified', 'uvz' => 'application/vnd.dece.zip', 'vcard' => 'text/vcard', 'vcd' => 'application/x-cdlink', 'vcf' => 'text/x-vcard', 'vcg' => 'application/vnd.groove-vcard', 'vcs' => 'text/x-vcalendar', 'vcx' => 'application/vnd.vcx', 'vis' => 'application/vnd.visionary', 'viv' => 'video/vnd.vivo', 'vob' => 'video/x-ms-vob', 'vor' => 'application/vnd.stardivision.writer', 'vox' => 'application/x-authorware-bin', 'vrml' => 'model/vrml', 'vsd' => 'application/vnd.visio', 'vsf' => 'application/vnd.vsf', 'vss' => 'application/vnd.visio', 'vst' => 'application/vnd.visio', 'vsw' => 'application/vnd.visio', 'vtu' => 'model/vnd.vtu', 'vxml' => 'application/voicexml+xml', 'w3d' => 'application/x-director', 'wad' => 'application/x-doom', 'wav' => 'audio/x-wav', 'wax' => 'audio/x-ms-wax', 'wbmp' => 'image/vnd.wap.wbmp', 'wbs' => 'application/vnd.criticaltools.wbs+xml', 'wbxml' => 'application/vnd.wap.wbxml', 'wcm' => 'application/vnd.ms-works', 'wdb' => 'application/vnd.ms-works', 'wdp' => 'image/vnd.ms-photo', 'weba' => 'audio/webm', 'webm' => 'video/webm', 'webp' => 'image/webp', 'wg' => 'application/vnd.pmi.widget', 'wgt' => 'application/widget', 'wks' => 'application/vnd.ms-works', 'wm' => 'video/x-ms-wm', 'wma' => 'audio/x-ms-wma', 'wmd' => 'application/x-ms-wmd', 'wmf' => 'application/x-msmetafile', 'wml' => 'text/vnd.wap.wml', 'wmlc' => 'application/vnd.wap.wmlc', 'wmls' => 'text/vnd.wap.wmlscript', 'wmlsc' => 'application/vnd.wap.wmlscriptc', 'wmv' => 'video/x-ms-wmv', 'wmx' => 'video/x-ms-wmx', 'wmz' => 'application/x-msmetafile', 'woff' => 'application/font-woff', 'wpd' => 'application/vnd.wordperfect', 'wpl' => 'application/vnd.ms-wpl', 'wps' => 'application/vnd.ms-works', 'wqd' => 'application/vnd.wqd', 'wri' => 'application/x-mswrite', 'wrl' => 'model/vrml', 'wsdl' => 'application/wsdl+xml', 'wspolicy' => 'application/wspolicy+xml', 'wtb' => 'application/vnd.webturbo', 'wvx' => 'video/x-ms-wvx', 'x32' => 'application/x-authorware-bin', 'x3d' => 'model/x3d+xml', 'x3db' => 'model/x3d+binary', 'x3dbz' => 'model/x3d+binary', 'x3dv' => 'model/x3d+vrml', 'x3dvz' => 'model/x3d+vrml', 'x3dz' => 'model/x3d+xml', 'xaml' => 'application/xaml+xml', 'xap' => 'application/x-silverlight-app', 'xar' => 'application/vnd.xara', 'xbap' => 'application/x-ms-xbap', 'xbd' => 'application/vnd.fujixerox.docuworks.binder', 'xbm' => 'image/x-xbitmap', 'xdf' => 'application/xcap-diff+xml', 'xdm' => 'application/vnd.syncml.dm+xml', 'xdp' => 'application/vnd.adobe.xdp+xml', 'xdssc' => 'application/dssc+xml', 'xdw' => 'application/vnd.fujixerox.docuworks', 'xenc' => 'application/xenc+xml', 'xer' => 'application/patch-ops-error+xml', 'xfdf' => 'application/vnd.adobe.xfdf', 'xfdl' => 'application/vnd.xfdl', 'xht' => 'application/xhtml+xml', 'xhtml' => 'application/xhtml+xml', 'xhvml' => 'application/xv+xml', 'xif' => 'image/vnd.xiff', 'xla' => 'application/vnd.ms-excel', 'xlam' => 'application/vnd.ms-excel.addin.macroenabled.12', 'xlc' => 'application/vnd.ms-excel', 'xlf' => 'application/x-xliff+xml', 'xlm' => 'application/vnd.ms-excel', 'xls' => 'application/vnd.ms-excel', 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroenabled.12', 'xlsm' => 'application/vnd.ms-excel.sheet.macroenabled.12', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xlt' => 'application/vnd.ms-excel', 'xltm' => 'application/vnd.ms-excel.template.macroenabled.12', 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'xlw' => 'application/vnd.ms-excel', 'xm' => 'audio/xm', 'xml' => 'application/xml', 'xo' => 'application/vnd.olpc-sugar', 'xop' => 'application/xop+xml', 'xpi' => 'application/x-xpinstall', 'xpl' => 'application/xproc+xml', 'xpm' => 'image/x-xpixmap', 'xpr' => 'application/vnd.is-xpr', 'xps' => 'application/vnd.ms-xpsdocument', 'xpw' => 'application/vnd.intercon.formnet', 'xpx' => 'application/vnd.intercon.formnet', 'xsl' => 'application/xml', 'xslt' => 'application/xslt+xml', 'xsm' => 'application/vnd.syncml+xml', 'xspf' => 'application/xspf+xml', 'xul' => 'application/vnd.mozilla.xul+xml', 'xvm' => 'application/xv+xml', 'xvml' => 'application/xv+xml', 'xwd' => 'image/x-xwindowdump', 'xyz' => 'chemical/x-xyz', 'xz' => 'application/x-xz', 'yang' => 'application/yang', 'yin' => 'application/yin+xml', 'z1' => 'application/x-zmachine', 'z2' => 'application/x-zmachine', 'z3' => 'application/x-zmachine', 'z4' => 'application/x-zmachine', 'z5' => 'application/x-zmachine', 'z6' => 'application/x-zmachine', 'z7' => 'application/x-zmachine', 'z8' => 'application/x-zmachine', 'zaz' => 'application/vnd.zzazz.deck+xml', 'zip' => 'application/zip', 'zir' => 'application/vnd.zul', 'zirz' => 'application/vnd.zul', 'zmm' => 'application/vnd.handheld-entertainment+xml', '123' => 'application/vnd.lotus-1-2-3', ); setCharset('utf-8'); // Without these lines the default caching mechanism is "array" but this uses a lot of memory. // If possible, use a disk cache to enable attaching large attachments etc. // You can override the default temporary directory by setting the TMPDIR environment variable. if (@is_writable($tmpDir = sys_get_temp_dir())) { $preferences->setTempDir($tmpDir)->setCacheType('disk'); } // this should only be done when Swiftmailer won't use the native QP content encoder // see mime_deps.php if (version_compare(phpversion(), '5.4.7', '<')) { $preferences->setQPDotEscape(false); } 'application/x-php', 'php3' => 'application/x-php', 'php4' => 'application/x-php', 'php5' => 'application/x-php', 'zip' => 'application/zip', 'gif' => 'image/gif', 'png' => 'image/png', 'css' => 'text/css', 'js' => 'text/javascript', 'txt' => 'text/plain', 'xml' => 'text/xml', 'aif' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'avi' => 'video/avi', 'bmp' => 'image/bmp', 'bz2' => 'application/x-bz2', 'csv' => 'text/csv', 'dmg' => 'application/x-apple-diskimage', 'doc' => 'application/msword', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'eml' => 'message/rfc822', 'aps' => 'application/postscript', 'exe' => 'application/x-ms-dos-executable', 'flv' => 'video/x-flv', 'gz' => 'application/x-gzip', 'hqx' => 'application/stuffit', 'htm' => 'text/html', 'html' => 'text/html', 'jar' => 'application/x-java-archive', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'm3u' => 'audio/x-mpegurl', 'm4a' => 'audio/mp4', 'mdb' => 'application/x-msaccess', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mov' => 'video/quicktime', 'mp3' => 'audio/mpeg', 'mp4' => 'video/mp4', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'odg' => 'vnd.oasis.opendocument.graphics', 'odp' => 'vnd.oasis.opendocument.presentation', 'odt' => 'vnd.oasis.opendocument.text', 'ods' => 'vnd.oasis.opendocument.spreadsheet', 'ogg' => 'audio/ogg', 'pdf' => 'application/pdf', 'ppt' => 'application/vnd.ms-powerpoint', 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'ps' => 'application/postscript', 'rar' => 'application/x-rar-compressed', 'rtf' => 'application/rtf', 'tar' => 'application/x-tar', 'sit' => 'application/x-stuffit', 'svg' => 'image/svg+xml', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'ttf' => 'application/x-font-truetype', 'vcf' => 'text/x-vcard', 'wav' => 'audio/wav', 'wma' => 'audio/x-ms-wma', 'wmv' => 'audio/x-ms-wmv', 'xls' => 'application/excel', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xml' => 'application/xml', ); // wrap array for generating file foreach ($valid_mime_types_preset as $extension => $mime_type) { // generate array for mimetype to extension resolver (only first match) $valid_mime_types[$extension] = "'{$extension}' => '{$mime_type}'"; } // collect extensions $valid_extensions = array(); // all extensions from second match foreach ($matches[2] as $i => $extensions) { // explode multiple extensions from string $extensions = explode(" ", strtolower($extensions)); // force array for foreach if (!is_array($extensions)) { $extensions = array($extensions); } foreach ($extensions as $extension) { // get mime type $mime_type = $matches[1][$i]; // check if string length lower than 10 if (strlen($extension) < 10) { // add extension $valid_extensions[] = $extension; if (!isset($valid_mime_types[$mime_type])) { // generate array for mimetype to extension resolver (only first match) $valid_mime_types[$extension] = "'{$extension}' => '{$mime_type}'"; } } } } } $xml = simplexml_load_string($mime_xml); foreach ($xml as $node) { // check if there is no pattern if (!isset($node->glob["pattern"])) { continue; } // get all matching extensions from match foreach ((array) $node->glob["pattern"] as $extension) { // skip none glob extensions if (strpos($extension, '.') === FALSE) { continue; } // remove get only last part $extension = explode('.', strtolower($extension)); $extension = end($extension); // maximum length in database column if (strlen($extension) <= 9) { $valid_extensions[] = $extension; } } if (isset($node->glob["pattern"][0])) { // mime type $mime_type = strtolower((string) $node["type"]); // get first extension $extension = strtolower(trim($node->glob["ddpattern"][0], '*.')); // skip none glob extensions and check if string length between 1 and 10 if (strpos($extension, '.') !== FALSE || strlen($extension) < 1 || strlen($extension) > 9) { continue; } // check if string length lower than 10 if (!isset($valid_mime_types[$mime_type])) { // generate array for mimetype to extension resolver (only first match) $valid_mime_types[$extension] = "'{$extension}' => '{$mime_type}'"; } } } // full list of valid extensions only $valid_mime_types = array_unique($valid_mime_types); ksort($valid_mime_types); // combine mime types and extensions array $output = "$preamble\$swift_mime_types = array(\n ".implode($valid_mime_types, ",\n ")."\n);"; // write mime_types.php config file @file_put_contents('./mime_types.php', $output); } generateUpToDateMimeArray(); * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Lazily loads listeners and subscribers from the dependency injection * container. * * @author Fabien Potencier * @author Bernhard Schussek * @author Jordan Alliot */ class ContainerAwareEventDispatcher extends EventDispatcher { /** * The container from where services are loaded. * * @var ContainerInterface */ private $container; /** * The service IDs of the event listeners and subscribers. * * @var array */ private $listenerIds = array(); /** * The services registered as listeners. * * @var array */ private $listeners = array(); /** * Constructor. * * @param ContainerInterface $container A ContainerInterface instance */ public function __construct(ContainerInterface $container) { $this->container = $container; } /** * Adds a service as event listener. * * @param string $eventName Event for which the listener is added * @param array $callback The service ID of the listener service & the method * name that has to be called * @param int $priority The higher this value, the earlier an event listener * will be triggered in the chain. * Defaults to 0. * * @throws \InvalidArgumentException */ public function addListenerService($eventName, $callback, $priority = 0) { if (!is_array($callback) || 2 !== count($callback)) { throw new \InvalidArgumentException('Expected an array("service", "method") argument'); } $this->listenerIds[$eventName][] = array($callback[0], $callback[1], $priority); } public function removeListener($eventName, $listener) { $this->lazyLoad($eventName); if (isset($this->listenerIds[$eventName])) { foreach ($this->listenerIds[$eventName] as $i => $args) { list($serviceId, $method, $priority) = $args; $key = $serviceId.'.'.$method; if (isset($this->listeners[$eventName][$key]) && $listener === array($this->listeners[$eventName][$key], $method)) { unset($this->listeners[$eventName][$key]); if (empty($this->listeners[$eventName])) { unset($this->listeners[$eventName]); } unset($this->listenerIds[$eventName][$i]); if (empty($this->listenerIds[$eventName])) { unset($this->listenerIds[$eventName]); } } } } parent::removeListener($eventName, $listener); } /** * @see EventDispatcherInterface::hasListeners() */ public function hasListeners($eventName = null) { if (null === $eventName) { return (bool) count($this->listenerIds) || (bool) count($this->listeners); } if (isset($this->listenerIds[$eventName])) { return true; } return parent::hasListeners($eventName); } /** * @see EventDispatcherInterface::getListeners() */ public function getListeners($eventName = null) { if (null === $eventName) { foreach (array_keys($this->listenerIds) as $serviceEventName) { $this->lazyLoad($serviceEventName); } } else { $this->lazyLoad($eventName); } return parent::getListeners($eventName); } /** * Adds a service as event subscriber. * * @param string $serviceId The service ID of the subscriber service * @param string $class The service's class name (which must implement EventSubscriberInterface) */ public function addSubscriberService($serviceId, $class) { foreach ($class::getSubscribedEvents() as $eventName => $params) { if (is_string($params)) { $this->listenerIds[$eventName][] = array($serviceId, $params, 0); } elseif (is_string($params[0])) { $this->listenerIds[$eventName][] = array($serviceId, $params[0], isset($params[1]) ? $params[1] : 0); } else { foreach ($params as $listener) { $this->listenerIds[$eventName][] = array($serviceId, $listener[0], isset($listener[1]) ? $listener[1] : 0); } } } } /** * {@inheritdoc} * * Lazily loads listeners for this event from the dependency injection * container. * * @throws \InvalidArgumentException if the service is not defined */ public function dispatch($eventName, Event $event = null) { $this->lazyLoad($eventName); return parent::dispatch($eventName, $event); } public function getContainer() { return $this->container; } /** * Lazily loads listeners for this event from the dependency injection * container. * * @param string $eventName The name of the event to dispatch. The name of * the event is the name of the method that is * invoked on listeners. */ protected function lazyLoad($eventName) { if (isset($this->listenerIds[$eventName])) { foreach ($this->listenerIds[$eventName] as $args) { list($serviceId, $method, $priority) = $args; $listener = $this->container->get($serviceId); $key = $serviceId.'.'.$method; if (!isset($this->listeners[$eventName][$key])) { $this->addListener($eventName, array($listener, $method), $priority); } elseif ($listener !== $this->listeners[$eventName][$key]) { parent::removeListener($eventName, array($this->listeners[$eventName][$key], $method)); $this->addListener($eventName, array($listener, $method), $priority); } $this->listeners[$eventName][$key] = $listener; } } } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher\Debug; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\Stopwatch\Stopwatch; use Psr\Log\LoggerInterface; /** * Collects some data about event listeners. * * This event dispatcher delegates the dispatching to another one. * * @author Fabien Potencier */ class TraceableEventDispatcher implements TraceableEventDispatcherInterface { protected $logger; protected $stopwatch; private $called; private $dispatcher; /** * Constructor. * * @param EventDispatcherInterface $dispatcher An EventDispatcherInterface instance * @param Stopwatch $stopwatch A Stopwatch instance * @param LoggerInterface $logger A LoggerInterface instance */ public function __construct(EventDispatcherInterface $dispatcher, Stopwatch $stopwatch, LoggerInterface $logger = null) { $this->dispatcher = $dispatcher; $this->stopwatch = $stopwatch; $this->logger = $logger; $this->called = array(); } /** * {@inheritdoc} */ public function addListener($eventName, $listener, $priority = 0) { $this->dispatcher->addListener($eventName, $listener, $priority); } /** * {@inheritdoc} */ public function addSubscriber(EventSubscriberInterface $subscriber) { $this->dispatcher->addSubscriber($subscriber); } /** * {@inheritdoc} */ public function removeListener($eventName, $listener) { return $this->dispatcher->removeListener($eventName, $listener); } /** * {@inheritdoc} */ public function removeSubscriber(EventSubscriberInterface $subscriber) { return $this->dispatcher->removeSubscriber($subscriber); } /** * {@inheritdoc} */ public function getListeners($eventName = null) { return $this->dispatcher->getListeners($eventName); } /** * {@inheritdoc} */ public function hasListeners($eventName = null) { return $this->dispatcher->hasListeners($eventName); } /** * {@inheritdoc} */ public function dispatch($eventName, Event $event = null) { if (null === $event) { $event = new Event(); } $this->preProcess($eventName); $this->preDispatch($eventName, $event); $e = $this->stopwatch->start($eventName, 'section'); $this->dispatcher->dispatch($eventName, $event); if ($e->isStarted()) { $e->stop(); } $this->postDispatch($eventName, $event); $this->postProcess($eventName); return $event; } /** * {@inheritdoc} */ public function getCalledListeners() { $called = array(); foreach ($this->called as $eventName => $listeners) { foreach ($listeners as $listener) { $info = $this->getListenerInfo($listener->getWrappedListener(), $eventName); $called[$eventName.'.'.$info['pretty']] = $info; } } return $called; } /** * {@inheritdoc} */ public function getNotCalledListeners() { try { $allListeners = $this->getListeners(); } catch (\Exception $e) { if (null !== $this->logger) { $this->logger->info(sprintf('An exception was thrown while getting the uncalled listeners (%s)', $e->getMessage()), array('exception' => $e)); } // unable to retrieve the uncalled listeners return array(); } $notCalled = array(); foreach ($allListeners as $eventName => $listeners) { foreach ($listeners as $listener) { $called = false; if (isset($this->called[$eventName])) { foreach ($this->called[$eventName] as $l) { if ($l->getWrappedListener() === $listener) { $called = true; break; } } } if (!$called) { $info = $this->getListenerInfo($listener, $eventName); $notCalled[$eventName.'.'.$info['pretty']] = $info; } } } return $notCalled; } /** * Proxies all method calls to the original event dispatcher. * * @param string $method The method name * @param array $arguments The method arguments * * @return mixed */ public function __call($method, $arguments) { return call_user_func_array(array($this->dispatcher, $method), $arguments); } /** * Called before dispatching the event. * * @param string $eventName The event name * @param Event $event The event */ protected function preDispatch($eventName, Event $event) { } /** * Called after dispatching the event. * * @param string $eventName The event name * @param Event $event The event */ protected function postDispatch($eventName, Event $event) { } private function preProcess($eventName) { foreach ($this->dispatcher->getListeners($eventName) as $listener) { $this->dispatcher->removeListener($eventName, $listener); $info = $this->getListenerInfo($listener, $eventName); $name = isset($info['class']) ? $info['class'] : $info['type']; $this->dispatcher->addListener($eventName, new WrappedListener($listener, $name, $this->stopwatch, $this)); } } private function postProcess($eventName) { $skipped = false; foreach ($this->dispatcher->getListeners($eventName) as $listener) { if (!$listener instanceof WrappedListener) { // #12845: a new listener was added during dispatch. continue; } // Unwrap listener $this->dispatcher->removeListener($eventName, $listener); $this->dispatcher->addListener($eventName, $listener->getWrappedListener()); $info = $this->getListenerInfo($listener->getWrappedListener(), $eventName); if ($listener->wasCalled()) { if (null !== $this->logger) { $this->logger->debug(sprintf('Notified event "%s" to listener "%s".', $eventName, $info['pretty'])); } if (!isset($this->called[$eventName])) { $this->called[$eventName] = new \SplObjectStorage(); } $this->called[$eventName]->attach($listener); } if (null !== $this->logger && $skipped) { $this->logger->debug(sprintf('Listener "%s" was not called for event "%s".', $info['pretty'], $eventName)); } if ($listener->stoppedPropagation()) { if (null !== $this->logger) { $this->logger->debug(sprintf('Listener "%s" stopped propagation of the event "%s".', $info['pretty'], $eventName)); } $skipped = true; } } } /** * Returns information about the listener * * @param object $listener The listener * @param string $eventName The event name * * @return array Information about the listener */ private function getListenerInfo($listener, $eventName) { $info = array( 'event' => $eventName, ); if ($listener instanceof \Closure) { $info += array( 'type' => 'Closure', 'pretty' => 'closure', ); } elseif (is_string($listener)) { try { $r = new \ReflectionFunction($listener); $file = $r->getFileName(); $line = $r->getStartLine(); } catch (\ReflectionException $e) { $file = null; $line = null; } $info += array( 'type' => 'Function', 'function' => $listener, 'file' => $file, 'line' => $line, 'pretty' => $listener, ); } elseif (is_array($listener) || (is_object($listener) && is_callable($listener))) { if (!is_array($listener)) { $listener = array($listener, '__invoke'); } $class = is_object($listener[0]) ? get_class($listener[0]) : $listener[0]; try { $r = new \ReflectionMethod($class, $listener[1]); $file = $r->getFileName(); $line = $r->getStartLine(); } catch (\ReflectionException $e) { $file = null; $line = null; } $info += array( 'type' => 'Method', 'class' => $class, 'method' => $listener[1], 'file' => $file, 'line' => $line, 'pretty' => $class.'::'.$listener[1], ); } return $info; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher\Debug; use Symfony\Component\EventDispatcher\EventDispatcherInterface; /** * @author Fabien Potencier */ interface TraceableEventDispatcherInterface extends EventDispatcherInterface { /** * Gets the called listeners. * * @return array An array of called listeners */ public function getCalledListeners(); /** * Gets the not called listeners. * * @return array An array of not called listeners */ public function getNotCalledListeners(); } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher\Debug; use Symfony\Component\Stopwatch\Stopwatch; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\EventDispatcher\EventDispatcherInterface; /** * @author Fabien Potencier */ class WrappedListener { private $listener; private $name; private $called; private $stoppedPropagation; private $stopwatch; private $dispatcher; public function __construct($listener, $name, Stopwatch $stopwatch, EventDispatcherInterface $dispatcher = null) { $this->listener = $listener; $this->name = $name; $this->stopwatch = $stopwatch; $this->dispatcher = $dispatcher; $this->called = false; $this->stoppedPropagation = false; } public function getWrappedListener() { return $this->listener; } public function wasCalled() { return $this->called; } public function stoppedPropagation() { return $this->stoppedPropagation; } public function __invoke(Event $event, $eventName, EventDispatcherInterface $dispatcher) { $this->called = true; $e = $this->stopwatch->start($this->name, 'event_listener'); call_user_func($this->listener, $event, $eventName, $this->dispatcher ?: $dispatcher); if ($e->isStarted()) { $e->stop(); } if ($event->isPropagationStopped()) { $this->stoppedPropagation = true; } } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; /** * Compiler pass to register tagged services for an event dispatcher. */ class RegisterListenersPass implements CompilerPassInterface { /** * @var string */ protected $dispatcherService; /** * @var string */ protected $listenerTag; /** * @var string */ protected $subscriberTag; /** * Constructor. * * @param string $dispatcherService Service name of the event dispatcher in processed container * @param string $listenerTag Tag name used for listener * @param string $subscriberTag Tag name used for subscribers */ public function __construct($dispatcherService = 'event_dispatcher', $listenerTag = 'kernel.event_listener', $subscriberTag = 'kernel.event_subscriber') { $this->dispatcherService = $dispatcherService; $this->listenerTag = $listenerTag; $this->subscriberTag = $subscriberTag; } public function process(ContainerBuilder $container) { if (!$container->hasDefinition($this->dispatcherService) && !$container->hasAlias($this->dispatcherService)) { return; } $definition = $container->findDefinition($this->dispatcherService); foreach ($container->findTaggedServiceIds($this->listenerTag) as $id => $events) { $def = $container->getDefinition($id); if (!$def->isPublic()) { throw new \InvalidArgumentException(sprintf('The service "%s" must be public as event listeners are lazy-loaded.', $id)); } if ($def->isAbstract()) { throw new \InvalidArgumentException(sprintf('The service "%s" must not be abstract as event listeners are lazy-loaded.', $id)); } foreach ($events as $event) { $priority = isset($event['priority']) ? $event['priority'] : 0; if (!isset($event['event'])) { throw new \InvalidArgumentException(sprintf('Service "%s" must define the "event" attribute on "%s" tags.', $id, $this->listenerTag)); } if (!isset($event['method'])) { $event['method'] = 'on'.preg_replace_callback(array( '/(?<=\b)[a-z]/i', '/[^a-z0-9]/i', ), function ($matches) { return strtoupper($matches[0]); }, $event['event']); $event['method'] = preg_replace('/[^a-z0-9]/i', '', $event['method']); } $definition->addMethodCall('addListenerService', array($event['event'], array($id, $event['method']), $priority)); } } foreach ($container->findTaggedServiceIds($this->subscriberTag) as $id => $attributes) { $def = $container->getDefinition($id); if (!$def->isPublic()) { throw new \InvalidArgumentException(sprintf('The service "%s" must be public as event subscribers are lazy-loaded.', $id)); } if ($def->isAbstract()) { throw new \InvalidArgumentException(sprintf('The service "%s" must not be abstract as event subscribers are lazy-loaded.', $id)); } // We must assume that the class value has been correctly filled, even if the service is created by a factory $class = $container->getParameterBag()->resolveValue($def->getClass()); $refClass = new \ReflectionClass($class); $interface = 'Symfony\Component\EventDispatcher\EventSubscriberInterface'; if (!$refClass->implementsInterface($interface)) { throw new \InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, $interface)); } $definition->addMethodCall('addSubscriberService', array($id, $class)); } } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher; /** * Event is the base class for classes containing event data. * * This class contains no event data. It is used by events that do not pass * state information to an event handler when an event is raised. * * You can call the method stopPropagation() to abort the execution of * further listeners in your event listener. * * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel * @author Bernhard Schussek * * @api */ class Event { /** * @var bool Whether no further event listeners should be triggered */ private $propagationStopped = false; /** * @var EventDispatcher Dispatcher that dispatched this event */ private $dispatcher; /** * @var string This event's name */ private $name; /** * Returns whether further event listeners should be triggered. * * @see Event::stopPropagation() * * @return bool Whether propagation was already stopped for this event. * * @api */ public function isPropagationStopped() { return $this->propagationStopped; } /** * Stops the propagation of the event to further event listeners. * * If multiple event listeners are connected to the same event, no * further event listener will be triggered once any trigger calls * stopPropagation(). * * @api */ public function stopPropagation() { $this->propagationStopped = true; } /** * Stores the EventDispatcher that dispatches this Event. * * @param EventDispatcherInterface $dispatcher * * @deprecated Deprecated in 2.4, to be removed in 3.0. The event dispatcher is passed to the listener call. * * @api */ public function setDispatcher(EventDispatcherInterface $dispatcher) { $this->dispatcher = $dispatcher; } /** * Returns the EventDispatcher that dispatches this Event. * * @return EventDispatcherInterface * * @deprecated Deprecated in 2.4, to be removed in 3.0. The event dispatcher is passed to the listener call. * * @api */ public function getDispatcher() { return $this->dispatcher; } /** * Gets the event's name. * * @return string * * @deprecated Deprecated in 2.4, to be removed in 3.0. The event name is passed to the listener call. * * @api */ public function getName() { return $this->name; } /** * Sets the event's name property. * * @param string $name The event name. * * @deprecated Deprecated in 2.4, to be removed in 3.0. The event name is passed to the listener call. * * @api */ public function setName($name) { $this->name = $name; } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher; /** * The EventDispatcherInterface is the central point of Symfony's event listener system. * * Listeners are registered on the manager and events are dispatched through the * manager. * * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel * @author Bernhard Schussek * @author Fabien Potencier * @author Jordi Boggiano * @author Jordan Alliot * * @api */ class EventDispatcher implements EventDispatcherInterface { private $listeners = array(); private $sorted = array(); /** * @see EventDispatcherInterface::dispatch() * * @api */ public function dispatch($eventName, Event $event = null) { if (null === $event) { $event = new Event(); } $event->setDispatcher($this); $event->setName($eventName); if (!isset($this->listeners[$eventName])) { return $event; } $this->doDispatch($this->getListeners($eventName), $eventName, $event); return $event; } /** * @see EventDispatcherInterface::getListeners() */ public function getListeners($eventName = null) { if (null !== $eventName) { if (!isset($this->sorted[$eventName])) { $this->sortListeners($eventName); } return $this->sorted[$eventName]; } foreach (array_keys($this->listeners) as $eventName) { if (!isset($this->sorted[$eventName])) { $this->sortListeners($eventName); } } return array_filter($this->sorted); } /** * @see EventDispatcherInterface::hasListeners() */ public function hasListeners($eventName = null) { return (bool) count($this->getListeners($eventName)); } /** * @see EventDispatcherInterface::addListener() * * @api */ public function addListener($eventName, $listener, $priority = 0) { $this->listeners[$eventName][$priority][] = $listener; unset($this->sorted[$eventName]); } /** * @see EventDispatcherInterface::removeListener() */ public function removeListener($eventName, $listener) { if (!isset($this->listeners[$eventName])) { return; } foreach ($this->listeners[$eventName] as $priority => $listeners) { if (false !== ($key = array_search($listener, $listeners, true))) { unset($this->listeners[$eventName][$priority][$key], $this->sorted[$eventName]); } } } /** * @see EventDispatcherInterface::addSubscriber() * * @api */ public function addSubscriber(EventSubscriberInterface $subscriber) { foreach ($subscriber->getSubscribedEvents() as $eventName => $params) { if (is_string($params)) { $this->addListener($eventName, array($subscriber, $params)); } elseif (is_string($params[0])) { $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0); } else { foreach ($params as $listener) { $this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0); } } } } /** * @see EventDispatcherInterface::removeSubscriber() */ public function removeSubscriber(EventSubscriberInterface $subscriber) { foreach ($subscriber->getSubscribedEvents() as $eventName => $params) { if (is_array($params) && is_array($params[0])) { foreach ($params as $listener) { $this->removeListener($eventName, array($subscriber, $listener[0])); } } else { $this->removeListener($eventName, array($subscriber, is_string($params) ? $params : $params[0])); } } } /** * Triggers the listeners of an event. * * This method can be overridden to add functionality that is executed * for each listener. * * @param callable[] $listeners The event listeners. * @param string $eventName The name of the event to dispatch. * @param Event $event The event object to pass to the event handlers/listeners. */ protected function doDispatch($listeners, $eventName, Event $event) { foreach ($listeners as $listener) { call_user_func($listener, $event, $eventName, $this); if ($event->isPropagationStopped()) { break; } } } /** * Sorts the internal list of listeners for the given event by priority. * * @param string $eventName The name of the event. */ private function sortListeners($eventName) { $this->sorted[$eventName] = array(); if (isset($this->listeners[$eventName])) { krsort($this->listeners[$eventName]); $this->sorted[$eventName] = call_user_func_array('array_merge', $this->listeners[$eventName]); } } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher; /** * The EventDispatcherInterface is the central point of Symfony's event listener system. * Listeners are registered on the manager and events are dispatched through the * manager. * * @author Bernhard Schussek * * @api */ interface EventDispatcherInterface { /** * Dispatches an event to all registered listeners. * * @param string $eventName The name of the event to dispatch. The name of * the event is the name of the method that is * invoked on listeners. * @param Event $event The event to pass to the event handlers/listeners. * If not supplied, an empty Event instance is created. * * @return Event * * @api */ public function dispatch($eventName, Event $event = null); /** * Adds an event listener that listens on the specified events. * * @param string $eventName The event to listen on * @param callable $listener The listener * @param int $priority The higher this value, the earlier an event * listener will be triggered in the chain (defaults to 0) * * @api */ public function addListener($eventName, $listener, $priority = 0); /** * Adds an event subscriber. * * The subscriber is asked for all the events he is * interested in and added as a listener for these events. * * @param EventSubscriberInterface $subscriber The subscriber. * * @api */ public function addSubscriber(EventSubscriberInterface $subscriber); /** * Removes an event listener from the specified events. * * @param string $eventName The event to remove a listener from * @param callable $listener The listener to remove */ public function removeListener($eventName, $listener); /** * Removes an event subscriber. * * @param EventSubscriberInterface $subscriber The subscriber */ public function removeSubscriber(EventSubscriberInterface $subscriber); /** * Gets the listeners of a specific event or all listeners. * * @param string $eventName The name of the event * * @return array The event listeners for the specified event, or all event listeners by event name */ public function getListeners($eventName = null); /** * Checks whether an event has any registered listeners. * * @param string $eventName The name of the event * * @return bool true if the specified event has any listeners, false otherwise */ public function hasListeners($eventName = null); } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher; /** * An EventSubscriber knows himself what events he is interested in. * If an EventSubscriber is added to an EventDispatcherInterface, the manager invokes * {@link getSubscribedEvents} and registers the subscriber as a listener for all * returned events. * * @author Guilherme Blanco * @author Jonathan Wage * @author Roman Borschel * @author Bernhard Schussek * * @api */ interface EventSubscriberInterface { /** * Returns an array of event names this subscriber wants to listen to. * * The array keys are event names and the value can be: * * * The method name to call (priority defaults to 0) * * An array composed of the method name to call and the priority * * An array of arrays composed of the method names to call and respective * priorities, or 0 if unset * * For instance: * * * array('eventName' => 'methodName') * * array('eventName' => array('methodName', $priority)) * * array('eventName' => array(array('methodName1', $priority), array('methodName2')) * * @return array The event names to listen to * * @api */ public static function getSubscribedEvents(); } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher; /** * Event encapsulation class. * * Encapsulates events thus decoupling the observer from the subject they encapsulate. * * @author Drak */ class GenericEvent extends Event implements \ArrayAccess, \IteratorAggregate { /** * Event subject. * * @var mixed usually object or callable */ protected $subject; /** * Array of arguments. * * @var array */ protected $arguments; /** * Encapsulate an event with $subject and $args. * * @param mixed $subject The subject of the event, usually an object. * @param array $arguments Arguments to store in the event. */ public function __construct($subject = null, array $arguments = array()) { $this->subject = $subject; $this->arguments = $arguments; } /** * Getter for subject property. * * @return mixed $subject The observer subject. */ public function getSubject() { return $this->subject; } /** * Get argument by key. * * @param string $key Key. * * @throws \InvalidArgumentException If key is not found. * * @return mixed Contents of array key. */ public function getArgument($key) { if ($this->hasArgument($key)) { return $this->arguments[$key]; } throw new \InvalidArgumentException(sprintf('%s not found in %s', $key, $this->getName())); } /** * Add argument to event. * * @param string $key Argument name. * @param mixed $value Value. * * @return GenericEvent */ public function setArgument($key, $value) { $this->arguments[$key] = $value; return $this; } /** * Getter for all arguments. * * @return array */ public function getArguments() { return $this->arguments; } /** * Set args property. * * @param array $args Arguments. * * @return GenericEvent */ public function setArguments(array $args = array()) { $this->arguments = $args; return $this; } /** * Has argument. * * @param string $key Key of arguments array. * * @return bool */ public function hasArgument($key) { return array_key_exists($key, $this->arguments); } /** * ArrayAccess for argument getter. * * @param string $key Array key. * * @throws \InvalidArgumentException If key does not exist in $this->args. * * @return mixed */ public function offsetGet($key) { return $this->getArgument($key); } /** * ArrayAccess for argument setter. * * @param string $key Array key to set. * @param mixed $value Value. */ public function offsetSet($key, $value) { $this->setArgument($key, $value); } /** * ArrayAccess for unset argument. * * @param string $key Array key. */ public function offsetUnset($key) { if ($this->hasArgument($key)) { unset($this->arguments[$key]); } } /** * ArrayAccess has argument. * * @param string $key Array key. * * @return bool */ public function offsetExists($key) { return $this->hasArgument($key); } /** * IteratorAggregate for iterating over the object like an array. * * @return \ArrayIterator */ public function getIterator() { return new \ArrayIterator($this->arguments); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher; /** * A read-only proxy for an event dispatcher. * * @author Bernhard Schussek */ class ImmutableEventDispatcher implements EventDispatcherInterface { /** * The proxied dispatcher. * * @var EventDispatcherInterface */ private $dispatcher; /** * Creates an unmodifiable proxy for an event dispatcher. * * @param EventDispatcherInterface $dispatcher The proxied event dispatcher. */ public function __construct(EventDispatcherInterface $dispatcher) { $this->dispatcher = $dispatcher; } /** * {@inheritdoc} */ public function dispatch($eventName, Event $event = null) { return $this->dispatcher->dispatch($eventName, $event); } /** * {@inheritdoc} */ public function addListener($eventName, $listener, $priority = 0) { throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.'); } /** * {@inheritdoc} */ public function addSubscriber(EventSubscriberInterface $subscriber) { throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.'); } /** * {@inheritdoc} */ public function removeListener($eventName, $listener) { throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.'); } /** * {@inheritdoc} */ public function removeSubscriber(EventSubscriberInterface $subscriber) { throw new \BadMethodCallException('Unmodifiable event dispatchers must not be modified.'); } /** * {@inheritdoc} */ public function getListeners($eventName = null) { return $this->dispatcher->getListeners($eventName); } /** * {@inheritdoc} */ public function hasListeners($eventName = null) { return $this->dispatcher->hasListeners($eventName); } } Copyright (c) 2004-2015 Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher\Tests; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\EventDispatcher\EventSubscriberInterface; abstract class AbstractEventDispatcherTest extends \PHPUnit_Framework_TestCase { /* Some pseudo events */ const preFoo = 'pre.foo'; const postFoo = 'post.foo'; const preBar = 'pre.bar'; const postBar = 'post.bar'; /** * @var EventDispatcher */ private $dispatcher; private $listener; protected function setUp() { $this->dispatcher = $this->createEventDispatcher(); $this->listener = new TestEventListener(); } protected function tearDown() { $this->dispatcher = null; $this->listener = null; } abstract protected function createEventDispatcher(); public function testInitialState() { $this->assertEquals(array(), $this->dispatcher->getListeners()); $this->assertFalse($this->dispatcher->hasListeners(self::preFoo)); $this->assertFalse($this->dispatcher->hasListeners(self::postFoo)); } public function testAddListener() { $this->dispatcher->addListener('pre.foo', array($this->listener, 'preFoo')); $this->dispatcher->addListener('post.foo', array($this->listener, 'postFoo')); $this->assertTrue($this->dispatcher->hasListeners(self::preFoo)); $this->assertTrue($this->dispatcher->hasListeners(self::postFoo)); $this->assertCount(1, $this->dispatcher->getListeners(self::preFoo)); $this->assertCount(1, $this->dispatcher->getListeners(self::postFoo)); $this->assertCount(2, $this->dispatcher->getListeners()); } public function testGetListenersSortsByPriority() { $listener1 = new TestEventListener(); $listener2 = new TestEventListener(); $listener3 = new TestEventListener(); $listener1->name = '1'; $listener2->name = '2'; $listener3->name = '3'; $this->dispatcher->addListener('pre.foo', array($listener1, 'preFoo'), -10); $this->dispatcher->addListener('pre.foo', array($listener2, 'preFoo'), 10); $this->dispatcher->addListener('pre.foo', array($listener3, 'preFoo')); $expected = array( array($listener2, 'preFoo'), array($listener3, 'preFoo'), array($listener1, 'preFoo'), ); $this->assertSame($expected, $this->dispatcher->getListeners('pre.foo')); } public function testGetAllListenersSortsByPriority() { $listener1 = new TestEventListener(); $listener2 = new TestEventListener(); $listener3 = new TestEventListener(); $listener4 = new TestEventListener(); $listener5 = new TestEventListener(); $listener6 = new TestEventListener(); $this->dispatcher->addListener('pre.foo', $listener1, -10); $this->dispatcher->addListener('pre.foo', $listener2); $this->dispatcher->addListener('pre.foo', $listener3, 10); $this->dispatcher->addListener('post.foo', $listener4, -10); $this->dispatcher->addListener('post.foo', $listener5); $this->dispatcher->addListener('post.foo', $listener6, 10); $expected = array( 'pre.foo' => array($listener3, $listener2, $listener1), 'post.foo' => array($listener6, $listener5, $listener4), ); $this->assertSame($expected, $this->dispatcher->getListeners()); } public function testDispatch() { $this->dispatcher->addListener('pre.foo', array($this->listener, 'preFoo')); $this->dispatcher->addListener('post.foo', array($this->listener, 'postFoo')); $this->dispatcher->dispatch(self::preFoo); $this->assertTrue($this->listener->preFooInvoked); $this->assertFalse($this->listener->postFooInvoked); $this->assertInstanceOf('Symfony\Component\EventDispatcher\Event', $this->dispatcher->dispatch('noevent')); $this->assertInstanceOf('Symfony\Component\EventDispatcher\Event', $this->dispatcher->dispatch(self::preFoo)); $event = new Event(); $return = $this->dispatcher->dispatch(self::preFoo, $event); $this->assertEquals('pre.foo', $event->getName()); $this->assertSame($event, $return); } public function testDispatchForClosure() { $invoked = 0; $listener = function () use (&$invoked) { $invoked++; }; $this->dispatcher->addListener('pre.foo', $listener); $this->dispatcher->addListener('post.foo', $listener); $this->dispatcher->dispatch(self::preFoo); $this->assertEquals(1, $invoked); } public function testStopEventPropagation() { $otherListener = new TestEventListener(); // postFoo() stops the propagation, so only one listener should // be executed // Manually set priority to enforce $this->listener to be called first $this->dispatcher->addListener('post.foo', array($this->listener, 'postFoo'), 10); $this->dispatcher->addListener('post.foo', array($otherListener, 'preFoo')); $this->dispatcher->dispatch(self::postFoo); $this->assertTrue($this->listener->postFooInvoked); $this->assertFalse($otherListener->postFooInvoked); } public function testDispatchByPriority() { $invoked = array(); $listener1 = function () use (&$invoked) { $invoked[] = '1'; }; $listener2 = function () use (&$invoked) { $invoked[] = '2'; }; $listener3 = function () use (&$invoked) { $invoked[] = '3'; }; $this->dispatcher->addListener('pre.foo', $listener1, -10); $this->dispatcher->addListener('pre.foo', $listener2); $this->dispatcher->addListener('pre.foo', $listener3, 10); $this->dispatcher->dispatch(self::preFoo); $this->assertEquals(array('3', '2', '1'), $invoked); } public function testRemoveListener() { $this->dispatcher->addListener('pre.bar', $this->listener); $this->assertTrue($this->dispatcher->hasListeners(self::preBar)); $this->dispatcher->removeListener('pre.bar', $this->listener); $this->assertFalse($this->dispatcher->hasListeners(self::preBar)); $this->dispatcher->removeListener('notExists', $this->listener); } public function testAddSubscriber() { $eventSubscriber = new TestEventSubscriber(); $this->dispatcher->addSubscriber($eventSubscriber); $this->assertTrue($this->dispatcher->hasListeners(self::preFoo)); $this->assertTrue($this->dispatcher->hasListeners(self::postFoo)); } public function testAddSubscriberWithPriorities() { $eventSubscriber = new TestEventSubscriber(); $this->dispatcher->addSubscriber($eventSubscriber); $eventSubscriber = new TestEventSubscriberWithPriorities(); $this->dispatcher->addSubscriber($eventSubscriber); $listeners = $this->dispatcher->getListeners('pre.foo'); $this->assertTrue($this->dispatcher->hasListeners(self::preFoo)); $this->assertCount(2, $listeners); $this->assertInstanceOf('Symfony\Component\EventDispatcher\Tests\TestEventSubscriberWithPriorities', $listeners[0][0]); } public function testAddSubscriberWithMultipleListeners() { $eventSubscriber = new TestEventSubscriberWithMultipleListeners(); $this->dispatcher->addSubscriber($eventSubscriber); $listeners = $this->dispatcher->getListeners('pre.foo'); $this->assertTrue($this->dispatcher->hasListeners(self::preFoo)); $this->assertCount(2, $listeners); $this->assertEquals('preFoo2', $listeners[0][1]); } public function testRemoveSubscriber() { $eventSubscriber = new TestEventSubscriber(); $this->dispatcher->addSubscriber($eventSubscriber); $this->assertTrue($this->dispatcher->hasListeners(self::preFoo)); $this->assertTrue($this->dispatcher->hasListeners(self::postFoo)); $this->dispatcher->removeSubscriber($eventSubscriber); $this->assertFalse($this->dispatcher->hasListeners(self::preFoo)); $this->assertFalse($this->dispatcher->hasListeners(self::postFoo)); } public function testRemoveSubscriberWithPriorities() { $eventSubscriber = new TestEventSubscriberWithPriorities(); $this->dispatcher->addSubscriber($eventSubscriber); $this->assertTrue($this->dispatcher->hasListeners(self::preFoo)); $this->dispatcher->removeSubscriber($eventSubscriber); $this->assertFalse($this->dispatcher->hasListeners(self::preFoo)); } public function testRemoveSubscriberWithMultipleListeners() { $eventSubscriber = new TestEventSubscriberWithMultipleListeners(); $this->dispatcher->addSubscriber($eventSubscriber); $this->assertTrue($this->dispatcher->hasListeners(self::preFoo)); $this->assertCount(2, $this->dispatcher->getListeners(self::preFoo)); $this->dispatcher->removeSubscriber($eventSubscriber); $this->assertFalse($this->dispatcher->hasListeners(self::preFoo)); } public function testEventReceivesTheDispatcherInstance() { $dispatcher = null; $this->dispatcher->addListener('test', function ($event) use (&$dispatcher) { $dispatcher = $event->getDispatcher(); }); $this->dispatcher->dispatch('test'); $this->assertSame($this->dispatcher, $dispatcher); } public function testEventReceivesTheDispatcherInstanceAsArgument() { $listener = new TestWithDispatcher(); $this->dispatcher->addListener('test', array($listener, 'foo')); $this->assertNull($listener->name); $this->assertNull($listener->dispatcher); $this->dispatcher->dispatch('test'); $this->assertEquals('test', $listener->name); $this->assertSame($this->dispatcher, $listener->dispatcher); } /** * @see https://bugs.php.net/bug.php?id=62976 * * This bug affects: * - The PHP 5.3 branch for versions < 5.3.18 * - The PHP 5.4 branch for versions < 5.4.8 * - The PHP 5.5 branch is not affected */ public function testWorkaroundForPhpBug62976() { $dispatcher = $this->createEventDispatcher(); $dispatcher->addListener('bug.62976', new CallableClass()); $dispatcher->removeListener('bug.62976', function () {}); $this->assertTrue($dispatcher->hasListeners('bug.62976')); } public function testHasListenersWhenAddedCallbackListenerIsRemoved() { $listener = function () {}; $this->dispatcher->addListener('foo', $listener); $this->dispatcher->removeListener('foo', $listener); $this->assertFalse($this->dispatcher->hasListeners()); } public function testGetListenersWhenAddedCallbackListenerIsRemoved() { $listener = function () {}; $this->dispatcher->addListener('foo', $listener); $this->dispatcher->removeListener('foo', $listener); $this->assertSame(array(), $this->dispatcher->getListeners()); } public function testHasListenersWithoutEventsReturnsFalseAfterHasListenersWithEventHasBeenCalled() { $this->assertFalse($this->dispatcher->hasListeners('foo')); $this->assertFalse($this->dispatcher->hasListeners()); } } class CallableClass { public function __invoke() { } } class TestEventListener { public $preFooInvoked = false; public $postFooInvoked = false; /* Listener methods */ public function preFoo(Event $e) { $this->preFooInvoked = true; } public function postFoo(Event $e) { $this->postFooInvoked = true; $e->stopPropagation(); } } class TestWithDispatcher { public $name; public $dispatcher; public function foo(Event $e, $name, $dispatcher) { $this->name = $name; $this->dispatcher = $dispatcher; } } class TestEventSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() { return array('pre.foo' => 'preFoo', 'post.foo' => 'postFoo'); } } class TestEventSubscriberWithPriorities implements EventSubscriberInterface { public static function getSubscribedEvents() { return array( 'pre.foo' => array('preFoo', 10), 'post.foo' => array('postFoo'), ); } } class TestEventSubscriberWithMultipleListeners implements EventSubscriberInterface { public static function getSubscribedEvents() { return array('pre.foo' => array( array('preFoo1'), array('preFoo2', 10), )); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher\Tests; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\DependencyInjection\Scope; use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\EventDispatcher\EventSubscriberInterface; class ContainerAwareEventDispatcherTest extends AbstractEventDispatcherTest { protected function createEventDispatcher() { $container = new Container(); return new ContainerAwareEventDispatcher($container); } public function testAddAListenerService() { $event = new Event(); $service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service'); $service ->expects($this->once()) ->method('onEvent') ->with($event) ; $container = new Container(); $container->set('service.listener', $service); $dispatcher = new ContainerAwareEventDispatcher($container); $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent')); $dispatcher->dispatch('onEvent', $event); } public function testAddASubscriberService() { $event = new Event(); $service = $this->getMock('Symfony\Component\EventDispatcher\Tests\SubscriberService'); $service ->expects($this->once()) ->method('onEvent') ->with($event) ; $container = new Container(); $container->set('service.subscriber', $service); $dispatcher = new ContainerAwareEventDispatcher($container); $dispatcher->addSubscriberService('service.subscriber', 'Symfony\Component\EventDispatcher\Tests\SubscriberService'); $dispatcher->dispatch('onEvent', $event); } public function testPreventDuplicateListenerService() { $event = new Event(); $service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service'); $service ->expects($this->once()) ->method('onEvent') ->with($event) ; $container = new Container(); $container->set('service.listener', $service); $dispatcher = new ContainerAwareEventDispatcher($container); $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'), 5); $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'), 10); $dispatcher->dispatch('onEvent', $event); } /** * @expectedException \InvalidArgumentException */ public function testTriggerAListenerServiceOutOfScope() { $service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service'); $scope = new Scope('scope'); $container = new Container(); $container->addScope($scope); $container->enterScope('scope'); $container->set('service.listener', $service, 'scope'); $dispatcher = new ContainerAwareEventDispatcher($container); $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent')); $container->leaveScope('scope'); $dispatcher->dispatch('onEvent'); } public function testReEnteringAScope() { $event = new Event(); $service1 = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service'); $service1 ->expects($this->exactly(2)) ->method('onEvent') ->with($event) ; $scope = new Scope('scope'); $container = new Container(); $container->addScope($scope); $container->enterScope('scope'); $container->set('service.listener', $service1, 'scope'); $dispatcher = new ContainerAwareEventDispatcher($container); $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent')); $dispatcher->dispatch('onEvent', $event); $service2 = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service'); $service2 ->expects($this->once()) ->method('onEvent') ->with($event) ; $container->enterScope('scope'); $container->set('service.listener', $service2, 'scope'); $dispatcher->dispatch('onEvent', $event); $container->leaveScope('scope'); $dispatcher->dispatch('onEvent'); } public function testHasListenersOnLazyLoad() { $event = new Event(); $service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service'); $container = new Container(); $container->set('service.listener', $service); $dispatcher = new ContainerAwareEventDispatcher($container); $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent')); $event->setDispatcher($dispatcher); $event->setName('onEvent'); $service ->expects($this->once()) ->method('onEvent') ->with($event) ; $this->assertTrue($dispatcher->hasListeners()); if ($dispatcher->hasListeners('onEvent')) { $dispatcher->dispatch('onEvent'); } } public function testGetListenersOnLazyLoad() { $service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service'); $container = new Container(); $container->set('service.listener', $service); $dispatcher = new ContainerAwareEventDispatcher($container); $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent')); $listeners = $dispatcher->getListeners(); $this->assertTrue(isset($listeners['onEvent'])); $this->assertCount(1, $dispatcher->getListeners('onEvent')); } public function testRemoveAfterDispatch() { $service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service'); $container = new Container(); $container->set('service.listener', $service); $dispatcher = new ContainerAwareEventDispatcher($container); $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent')); $dispatcher->dispatch('onEvent', new Event()); $dispatcher->removeListener('onEvent', array($container->get('service.listener'), 'onEvent')); $this->assertFalse($dispatcher->hasListeners('onEvent')); } public function testRemoveBeforeDispatch() { $service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service'); $container = new Container(); $container->set('service.listener', $service); $dispatcher = new ContainerAwareEventDispatcher($container); $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent')); $dispatcher->removeListener('onEvent', array($container->get('service.listener'), 'onEvent')); $this->assertFalse($dispatcher->hasListeners('onEvent')); } } class Service { public function onEvent(Event $e) { } } class SubscriberService implements EventSubscriberInterface { public static function getSubscribedEvents() { return array( 'onEvent' => array('onEvent'), ); } public function onEvent(Event $e) { } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher\Tests\Debug; use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\Stopwatch\Stopwatch; class TraceableEventDispatcherTest extends \PHPUnit_Framework_TestCase { public function testAddRemoveListener() { $dispatcher = new EventDispatcher(); $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch()); $tdispatcher->addListener('foo', $listener = function () {; }); $listeners = $dispatcher->getListeners('foo'); $this->assertCount(1, $listeners); $this->assertSame($listener, $listeners[0]); $tdispatcher->removeListener('foo', $listener); $this->assertCount(0, $dispatcher->getListeners('foo')); } public function testGetListeners() { $dispatcher = new EventDispatcher(); $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch()); $tdispatcher->addListener('foo', $listener = function () {; }); $this->assertSame($dispatcher->getListeners('foo'), $tdispatcher->getListeners('foo')); } public function testHasListeners() { $dispatcher = new EventDispatcher(); $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch()); $this->assertFalse($dispatcher->hasListeners('foo')); $this->assertFalse($tdispatcher->hasListeners('foo')); $tdispatcher->addListener('foo', $listener = function () {; }); $this->assertTrue($dispatcher->hasListeners('foo')); $this->assertTrue($tdispatcher->hasListeners('foo')); } public function testAddRemoveSubscriber() { $dispatcher = new EventDispatcher(); $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch()); $subscriber = new EventSubscriber(); $tdispatcher->addSubscriber($subscriber); $listeners = $dispatcher->getListeners('foo'); $this->assertCount(1, $listeners); $this->assertSame(array($subscriber, 'call'), $listeners[0]); $tdispatcher->removeSubscriber($subscriber); $this->assertCount(0, $dispatcher->getListeners('foo')); } public function testGetCalledListeners() { $dispatcher = new EventDispatcher(); $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch()); $tdispatcher->addListener('foo', $listener = function () {; }); $this->assertEquals(array(), $tdispatcher->getCalledListeners()); $this->assertEquals(array('foo.closure' => array('event' => 'foo', 'type' => 'Closure', 'pretty' => 'closure')), $tdispatcher->getNotCalledListeners()); $tdispatcher->dispatch('foo'); $this->assertEquals(array('foo.closure' => array('event' => 'foo', 'type' => 'Closure', 'pretty' => 'closure')), $tdispatcher->getCalledListeners()); $this->assertEquals(array(), $tdispatcher->getNotCalledListeners()); } public function testGetCalledListenersNested() { $tdispatcher = null; $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); $dispatcher->addListener('foo', function (Event $event, $eventName, $dispatcher) use (&$tdispatcher) { $tdispatcher = $dispatcher; $dispatcher->dispatch('bar'); }); $dispatcher->addListener('bar', function (Event $event) {}); $dispatcher->dispatch('foo'); $this->assertSame($dispatcher, $tdispatcher); $this->assertCount(2, $dispatcher->getCalledListeners()); } public function testLogger() { $logger = $this->getMock('Psr\Log\LoggerInterface'); $dispatcher = new EventDispatcher(); $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch(), $logger); $tdispatcher->addListener('foo', $listener1 = function () {; }); $tdispatcher->addListener('foo', $listener2 = function () {; }); $logger->expects($this->at(0))->method('debug')->with("Notified event \"foo\" to listener \"closure\"."); $logger->expects($this->at(1))->method('debug')->with("Notified event \"foo\" to listener \"closure\"."); $tdispatcher->dispatch('foo'); } public function testLoggerWithStoppedEvent() { $logger = $this->getMock('Psr\Log\LoggerInterface'); $dispatcher = new EventDispatcher(); $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch(), $logger); $tdispatcher->addListener('foo', $listener1 = function (Event $event) { $event->stopPropagation(); }); $tdispatcher->addListener('foo', $listener2 = function () {; }); $logger->expects($this->at(0))->method('debug')->with("Notified event \"foo\" to listener \"closure\"."); $logger->expects($this->at(1))->method('debug')->with("Listener \"closure\" stopped propagation of the event \"foo\"."); $logger->expects($this->at(2))->method('debug')->with("Listener \"closure\" was not called for event \"foo\"."); $tdispatcher->dispatch('foo'); } public function testDispatchCallListeners() { $called = array(); $dispatcher = new EventDispatcher(); $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch()); $tdispatcher->addListener('foo', $listener1 = function () use (&$called) { $called[] = 'foo1'; }); $tdispatcher->addListener('foo', $listener2 = function () use (&$called) { $called[] = 'foo2'; }); $tdispatcher->dispatch('foo'); $this->assertEquals(array('foo1', 'foo2'), $called); } public function testDispatchNested() { $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); $loop = 1; $dispatcher->addListener('foo', $listener1 = function () use ($dispatcher, &$loop) { ++$loop; if (2 == $loop) { $dispatcher->dispatch('foo'); } }); $dispatcher->dispatch('foo'); } public function testDispatchReusedEventNested() { $nestedCall = false; $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch()); $dispatcher->addListener('foo', function (Event $e) use ($dispatcher) { $dispatcher->dispatch('bar', $e); }); $dispatcher->addListener('bar', function (Event $e) use (&$nestedCall) { $nestedCall = true; }); $this->assertFalse($nestedCall); $dispatcher->dispatch('foo'); $this->assertTrue($nestedCall); } } class EventSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() { return array('foo' => 'call'); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher\Tests\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass; class RegisterListenersPassTest extends \PHPUnit_Framework_TestCase { /** * Tests that event subscribers not implementing EventSubscriberInterface * trigger an exception. * * @expectedException \InvalidArgumentException */ public function testEventSubscriberWithoutInterface() { // one service, not implementing any interface $services = array( 'my_event_subscriber' => array(0 => array()), ); $definition = $this->getMock('Symfony\Component\DependencyInjection\Definition'); $definition->expects($this->atLeastOnce()) ->method('isPublic') ->will($this->returnValue(true)); $definition->expects($this->atLeastOnce()) ->method('getClass') ->will($this->returnValue('stdClass')); $builder = $this->getMock( 'Symfony\Component\DependencyInjection\ContainerBuilder', array('hasDefinition', 'findTaggedServiceIds', 'getDefinition') ); $builder->expects($this->any()) ->method('hasDefinition') ->will($this->returnValue(true)); // We don't test kernel.event_listener here $builder->expects($this->atLeastOnce()) ->method('findTaggedServiceIds') ->will($this->onConsecutiveCalls(array(), $services)); $builder->expects($this->atLeastOnce()) ->method('getDefinition') ->will($this->returnValue($definition)); $registerListenersPass = new RegisterListenersPass(); $registerListenersPass->process($builder); } public function testValidEventSubscriber() { $services = array( 'my_event_subscriber' => array(0 => array()), ); $definition = $this->getMock('Symfony\Component\DependencyInjection\Definition'); $definition->expects($this->atLeastOnce()) ->method('isPublic') ->will($this->returnValue(true)); $definition->expects($this->atLeastOnce()) ->method('getClass') ->will($this->returnValue('Symfony\Component\EventDispatcher\Tests\DependencyInjection\SubscriberService')); $builder = $this->getMock( 'Symfony\Component\DependencyInjection\ContainerBuilder', array('hasDefinition', 'findTaggedServiceIds', 'getDefinition', 'findDefinition') ); $builder->expects($this->any()) ->method('hasDefinition') ->will($this->returnValue(true)); // We don't test kernel.event_listener here $builder->expects($this->atLeastOnce()) ->method('findTaggedServiceIds') ->will($this->onConsecutiveCalls(array(), $services)); $builder->expects($this->atLeastOnce()) ->method('getDefinition') ->will($this->returnValue($definition)); $builder->expects($this->atLeastOnce()) ->method('findDefinition') ->will($this->returnValue($definition)); $registerListenersPass = new RegisterListenersPass(); $registerListenersPass->process($builder); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage The service "foo" must be public as event listeners are lazy-loaded. */ public function testPrivateEventListener() { $container = new ContainerBuilder(); $container->register('foo', 'stdClass')->setPublic(false)->addTag('kernel.event_listener', array()); $container->register('event_dispatcher', 'stdClass'); $registerListenersPass = new RegisterListenersPass(); $registerListenersPass->process($container); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage The service "foo" must be public as event subscribers are lazy-loaded. */ public function testPrivateEventSubscriber() { $container = new ContainerBuilder(); $container->register('foo', 'stdClass')->setPublic(false)->addTag('kernel.event_subscriber', array()); $container->register('event_dispatcher', 'stdClass'); $registerListenersPass = new RegisterListenersPass(); $registerListenersPass->process($container); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage The service "foo" must not be abstract as event listeners are lazy-loaded. */ public function testAbstractEventListener() { $container = new ContainerBuilder(); $container->register('foo', 'stdClass')->setAbstract(true)->addTag('kernel.event_listener', array()); $container->register('event_dispatcher', 'stdClass'); $registerListenersPass = new RegisterListenersPass(); $registerListenersPass->process($container); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage The service "foo" must not be abstract as event subscribers are lazy-loaded. */ public function testAbstractEventSubscriber() { $container = new ContainerBuilder(); $container->register('foo', 'stdClass')->setAbstract(true)->addTag('kernel.event_subscriber', array()); $container->register('event_dispatcher', 'stdClass'); $registerListenersPass = new RegisterListenersPass(); $registerListenersPass->process($container); } public function testEventSubscriberResolvableClassName() { $container = new ContainerBuilder(); $container->setParameter('subscriber.class', 'Symfony\Component\EventDispatcher\Tests\DependencyInjection\SubscriberService'); $container->register('foo', '%subscriber.class%')->addTag('kernel.event_subscriber', array()); $container->register('event_dispatcher', 'stdClass'); $registerListenersPass = new RegisterListenersPass(); $registerListenersPass->process($container); $definition = $container->getDefinition('event_dispatcher'); $expected_calls = array( array( 'addSubscriberService', array( 'foo', 'Symfony\Component\EventDispatcher\Tests\DependencyInjection\SubscriberService', ), ), ); $this->assertSame($expected_calls, $definition->getMethodCalls()); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessage You have requested a non-existent parameter "subscriber.class" */ public function testEventSubscriberUnresolvableClassName() { $container = new ContainerBuilder(); $container->register('foo', '%subscriber.class%')->addTag('kernel.event_subscriber', array()); $container->register('event_dispatcher', 'stdClass'); $registerListenersPass = new RegisterListenersPass(); $registerListenersPass->process($container); } } class SubscriberService implements \Symfony\Component\EventDispatcher\EventSubscriberInterface { public static function getSubscribedEvents() { } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher\Tests; use Symfony\Component\EventDispatcher\EventDispatcher; class EventDispatcherTest extends AbstractEventDispatcherTest { protected function createEventDispatcher() { return new EventDispatcher(); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher\Tests; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\EventDispatcher\EventDispatcher; /** * Test class for Event. */ class EventTest extends \PHPUnit_Framework_TestCase { /** * @var \Symfony\Component\EventDispatcher\Event */ protected $event; /** * @var \Symfony\Component\EventDispatcher\EventDispatcher */ protected $dispatcher; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { $this->event = new Event(); $this->dispatcher = new EventDispatcher(); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. */ protected function tearDown() { $this->event = null; $this->dispatcher = null; } public function testIsPropagationStopped() { $this->assertFalse($this->event->isPropagationStopped()); } public function testStopPropagationAndIsPropagationStopped() { $this->event->stopPropagation(); $this->assertTrue($this->event->isPropagationStopped()); } public function testLegacySetDispatcher() { $this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED); $this->event->setDispatcher($this->dispatcher); $this->assertSame($this->dispatcher, $this->event->getDispatcher()); } public function testLegacyGetDispatcher() { $this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED); $this->assertNull($this->event->getDispatcher()); } public function testLegacyGetName() { $this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED); $this->assertNull($this->event->getName()); } public function testLegacySetName() { $this->iniSet('error_reporting', -1 & ~E_USER_DEPRECATED); $this->event->setName('foo'); $this->assertEquals('foo', $this->event->getName()); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher\Tests; use Symfony\Component\EventDispatcher\GenericEvent; /** * Test class for Event. */ class GenericEventTest extends \PHPUnit_Framework_TestCase { /** * @var GenericEvent */ private $event; private $subject; /** * Prepares the environment before running a test. */ protected function setUp() { parent::setUp(); $this->subject = new \stdClass(); $this->event = new GenericEvent($this->subject, array('name' => 'Event')); } /** * Cleans up the environment after running a test. */ protected function tearDown() { $this->subject = null; $this->event = null; parent::tearDown(); } public function testConstruct() { $this->assertEquals($this->event, new GenericEvent($this->subject, array('name' => 'Event'))); } /** * Tests Event->getArgs(). */ public function testGetArguments() { // test getting all $this->assertSame(array('name' => 'Event'), $this->event->getArguments()); } public function testSetArguments() { $result = $this->event->setArguments(array('foo' => 'bar')); $this->assertAttributeSame(array('foo' => 'bar'), 'arguments', $this->event); $this->assertSame($this->event, $result); } public function testSetArgument() { $result = $this->event->setArgument('foo2', 'bar2'); $this->assertAttributeSame(array('name' => 'Event', 'foo2' => 'bar2'), 'arguments', $this->event); $this->assertEquals($this->event, $result); } public function testGetArgument() { // test getting key $this->assertEquals('Event', $this->event->getArgument('name')); } /** * @expectedException \InvalidArgumentException */ public function testGetArgException() { $this->event->getArgument('nameNotExist'); } public function testOffsetGet() { // test getting key $this->assertEquals('Event', $this->event['name']); // test getting invalid arg $this->setExpectedException('InvalidArgumentException'); $this->assertFalse($this->event['nameNotExist']); } public function testOffsetSet() { $this->event['foo2'] = 'bar2'; $this->assertAttributeSame(array('name' => 'Event', 'foo2' => 'bar2'), 'arguments', $this->event); } public function testOffsetUnset() { unset($this->event['name']); $this->assertAttributeSame(array(), 'arguments', $this->event); } public function testOffsetIsset() { $this->assertTrue(isset($this->event['name'])); $this->assertFalse(isset($this->event['nameNotExist'])); } public function testHasArgument() { $this->assertTrue($this->event->hasArgument('name')); $this->assertFalse($this->event->hasArgument('nameNotExist')); } public function testGetSubject() { $this->assertSame($this->subject, $this->event->getSubject()); } public function testHasIterator() { $data = array(); foreach ($this->event as $key => $value) { $data[$key] = $value; } $this->assertEquals(array('name' => 'Event'), $data); } } * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\EventDispatcher\Tests; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\EventDispatcher\ImmutableEventDispatcher; /** * @author Bernhard Schussek */ class ImmutableEventDispatcherTest extends \PHPUnit_Framework_TestCase { /** * @var \PHPUnit_Framework_MockObject_MockObject */ private $innerDispatcher; /** * @var ImmutableEventDispatcher */ private $dispatcher; protected function setUp() { $this->innerDispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface'); $this->dispatcher = new ImmutableEventDispatcher($this->innerDispatcher); } public function testDispatchDelegates() { $event = new Event(); $this->innerDispatcher->expects($this->once()) ->method('dispatch') ->with('event', $event) ->will($this->returnValue('result')); $this->assertSame('result', $this->dispatcher->dispatch('event', $event)); } public function testGetListenersDelegates() { $this->innerDispatcher->expects($this->once()) ->method('getListeners') ->with('event') ->will($this->returnValue('result')); $this->assertSame('result', $this->dispatcher->getListeners('event')); } public function testHasListenersDelegates() { $this->innerDispatcher->expects($this->once()) ->method('hasListeners') ->with('event') ->will($this->returnValue('result')); $this->assertSame('result', $this->dispatcher->hasListeners('event')); } /** * @expectedException \BadMethodCallException */ public function testAddListenerDisallowed() { $this->dispatcher->addListener('event', function () { return 'foo'; }); } /** * @expectedException \BadMethodCallException */ public function testAddSubscriberDisallowed() { $subscriber = $this->getMock('Symfony\Component\EventDispatcher\EventSubscriberInterface'); $this->dispatcher->addSubscriber($subscriber); } /** * @expectedException \BadMethodCallException */ public function testRemoveListenerDisallowed() { $this->dispatcher->removeListener('event', function () { return 'foo'; }); } /** * @expectedException \BadMethodCallException */ public function testRemoveSubscriberDisallowed() { $subscriber = $this->getMock('Symfony\Component\EventDispatcher\EventSubscriberInterface'); $this->dispatcher->removeSubscriber($subscriber); } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Json extends Printer implements Listener, Logger { /** * List of all debug messages * * @var array */ protected $debug = array(); /** * Setup the logger. * * @see \phpbu\Log\Logger::setup * @param array $options * @throws \phpbu\App\Exception */ public function setup(array $options) { if (empty($options['target'])) { throw new Exception('no target given'); } $this->setOut($options['target']); } /** * * @see \phpbu\App\Listener::phpbuStart() * @param array $settings */ public function phpbuStart($settings) { // do something fooish } /** * * @see \phpbu\App\Listener::phpbuEnd() * @param \phpbu\App\Result $result */ public function phpbuEnd(Result $result) { $output = array( 'status' => $result->allOk() ? 0 : 1, 'timestamp' => time(), 'errors' => $this->extractErrors($result), 'debug' => $this->debug, 'backups' => $this->extractBackups($result) ); $this->write($output); } /** * * @see \phpbu\App\Listener::backupStart() * @param array $backup */ public function backupStart($backup) { // do something fooish } /** * * @see \phpbu\App\Listener::backupEnd() * @param array $backup */ public function backupEnd($backup) { // do something fooish } /** * * @see \phpbu\App\Listener::backupFailed() * @param array $backup */ public function backupFailed($backup) { // do something fooish } /** * * @see \phpbu\App\Listener::checkStart() * @param array $check */ public function checkStart($check) { // do something fooish } /** * * @see \phpbu\App\Listener::checkEnd() * @param array $check */ public function checkEnd($check) { // do something fooish } /** * * @see \phpbu\App\Listener::checkFailed() * @param array $check */ public function checkFailed($check) { // do something fooish } /** * * @see \phpbu\App\Listener::syncStart() * @param array $sync */ public function syncStart($sync) { // do something fooish } /** * * @see \phpbu\App\Listener::syncEnd() * @param array $sync */ public function syncEnd($sync) { // do something fooish } /** * * @see \phpbu\App\Listener::syncSkipped() * @param array $sync */ public function syncSkipped($sync) { // do something fooish } /** * * @see \phpbu\App\Listener::syncFailed() * @param array $sync */ public function syncFailed($sync) { // do something fooish } /** * * @see \phpbu\App\Listener::cleanupStart() * @param array $cleanup */ public function cleanupStart($cleanup) { // do something fooish } /** * * @see \phpbu\App\Listener::cleanupEnd() * @param array $cleanup */ public function cleanupEnd($cleanup) { // do something fooish } /** * * @see \phpbu\App\Listener::cleanupSkipped() * @param array $cleanup */ public function cleanupSkipped($cleanup) { // do something fooish } /** * * @see \phpbu\App\Listener::cleanupFailed() * @param array $cleanup */ public function cleanupFailed($cleanup) { // do something fooish } /** * * @see \phpbu\App\Listener::debug() * @param string $msg */ public function debug($msg) { $this->debug[] = $msg; } /** * * @param array $buffer */ public function write($buffer) { parent::write(json_encode($buffer)); } /** * Get error information. * * @param \phpbu\App\Result $result * @return array */ protected function extractErrors(Result $result) { $errors = array(); /** @var \Exception $e */ foreach ($result->getErrors() as $e) { $errors[] = array( 'class' => get_class($e), 'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine() ); } return $errors; } /** * Return backup information. * * @param \phpbu\App\Result $result * @return array */ protected function extractBackups(Result $result) { $output = array(); $backups = $result->getBackups(); if (count($backups) > 0) { /** @var \phpbu\App\Result\Backup $backup */ foreach ($backups as $backup) { $output[] = array( 'name' => $backup->getName(), 'status' => $backup->wasSuccessful() ? 0 : 1, 'checks' => array( 'executed' => $backup->checkCount(), 'failed' => $backup->checkCountFailed() ), 'syncs' => array( 'executed' => $backup->syncCount(), 'skipped' => $backup->syncCountSkipped(), 'failed' => $backup->syncCountFailed() ), 'cleanups' => array( 'executed' => $backup->cleanupCount(), 'skipped' => $backup->cleanupCountSkipped(), 'failed' => $backup->cleanupCountFailed() ) ); } } return $output; } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ interface Logger { /** * Setup the logger. * * @param array $options */ public function setup(array $options); } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Mail implements Listener, Logger { /** * Mailer instance * * @var Swift_Mailer */ protected $mailer; /** * Mail subject * * @var string */ protected $subject; /** * From email address * * @var string */ protected $senderMail; /** * From name * * @var string */ protected $senderName; /** * Transport type [mail|smtp|null] * * @var string */ protected $transportType; /** * List of mail recipients * * @var array */ protected $recipients = array(); /** * Amount of executed backups * * @var integer */ private $numBackups = 0; /** * Amount of executed checks * * @var integer */ private $numChecks = 0; /** * Amount of executed Syncs * * @var integer */ private $numSyncs = 0; /** * Amount of executed Cleanups * * @var integer */ private $numCleanups = 0; /** * Send mail only if there was an error * * @var boolean */ private $sendOnlyOnError; /** * Setup the Logger. * * @see \phpbu\Log\Logger::setup * @param array $options * @throws \phpbu\App\Exception */ public function setup(array $options) { if (empty($options['recipients'])) { throw new Exception('no recipients given'); } $mails = $options['recipients']; $server = gethostname(); $this->sendOnlyOnError = String::toBoolean(Arr::getValue($options, 'sendOnlyOnError'), false); $this->subject = Arr::getValue($options, 'subject', 'PHPBU backup report from ' . $server); $this->senderMail = Arr::getValue($options, 'sender.mail', 'phpbu@' . $server); $this->senderName = Arr::getValue($options, 'sender.name'); $this->transportType = Arr::getValue($options, 'transport', 'mail'); $this->recipients = array_map('trim', explode(';', $mails)); // create transport an mailer $transport = $this->createTransport($this->transportType, $options); $this->mailer = Swift_Mailer::newInstance($transport); } /** * @see \phpbu\App\Listener::phpbuStart() * @param array $settings */ public function phpbuStart($settings) { // do something fooish } /** * @see \phpbu\App\Listener::phpbuEnd() * @param \phpbu\App\Result $result * @throws \phpbu\App\Exception */ public function phpbuEnd(Result $result) { $allGood = $result->wasSuccessful() && $result->noneSkipped() && $result->noneFailed(); if (!$this->sendOnlyOnError || !$allGood) { $header = $this->getHeaderHtml($result); $errors = $this->getErrorHtml($result); $info = $this->getInfoHtml($result); $footer = $this->getFooterHtml(); $body = $header . $errors . $info . $footer; $sent = null; try { /** @var Swift_Message $message */ $message = Swift_Message::newInstance(); $message->setSubject($this->subject) ->setFrom($this->senderMail, $this->senderName) ->setTo($this->recipients) ->setBody($body) ->addPart($body, 'text/html'); $sent = $this->mailer->send($message); } catch (\Exception $e) { throw new Exception($e->getMessage()); } if (!$sent) { throw new Exception('mail could not be sent'); } } } /** * @see \phpbu\App\Listener::backupStart() * @param array $backup */ public function backupStart($backup) { $this->numBackups++; } /** * @see \phpbu\App\Listener::backupEnd() * @param array $backup */ public function backupEnd($backup) { // do something fooish } /** * @see \phpbu\App\Listener::backupFailed() * @param array $backup */ public function backupFailed($backup) { // do something fooish } /** * @see \phpbu\App\Listener::checkStart() * @param array $check */ public function checkStart($check) { $this->numChecks++; } /** * @see \phpbu\App\Listener::checkEnd() * @param array $check */ public function checkEnd($check) { // do something fooish } /** * @see \phpbu\App\Listener::checkFailed() * @param array $check */ public function checkFailed($check) { // do something fooish } /** * @see \phpbu\App\Listener::syncStart() * @param array $sync */ public function syncStart($sync) { $this->numSyncs++; } /** * @see \phpbu\App\Listener::syncEnd() * @param array $sync */ public function syncEnd($sync) { // do something fooish } /** * @see \phpbu\App\Listener::syncSkipped() * @param array $sync */ public function syncSkipped($sync) { // do something fooish } /** * @see \phpbu\App\Listener::syncFailed() * @param array $sync */ public function syncFailed($sync) { // do something fooish } /** * @see \phpbu\App\Listener::cleanupStart() * @param array $cleanup */ public function cleanupStart($cleanup) { // do something fooish } /** * @see \phpbu\App\Listener::cleanupEnd() * @param array $cleanup */ public function cleanupEnd($cleanup) { // do something fooish } /** * @see \phpbu\App\Listener::cleanupSkipped() * @param array $cleanup */ public function cleanupSkipped($cleanup) { // do something fooish } /** * @see \phpbu\App\Listener::cleanupFailed() * @param array $cleanup */ public function cleanupFailed($cleanup) { // do something fooish } /** * @see \phpbu\App\Listener::debug() * @param string $msg */ public function debug($msg) { // do something fooish } /** * Create a Swift_Mailer_Transport. * * @param string $type * @param array $options * @throws \phpbu\App\Exception * @return \Swift_Transport */ protected function createTransport($type, array $options) { switch ($type) { // null transport, don't send any mails case 'null': /* @var $transport \Swift_NullTransport */ $transport = \Swift_NullTransport::newInstance(); break; case 'mail': /* @var $transport \Swift_MailTransport */ $transport = \Swift_MailTransport::newInstance(); break; case 'smtp': $transport = $this->getSmtpTransport($options); break; case 'sendmail': $transport = $this->getSendmailTransport($options); break; // UPS! no transport given default: throw new Exception(sprintf('mail transport not supported: \'%s\'', $type)); } return $transport; } /** * Create Swift Smtp Transport. * * @param array $options * @return \Swift_SmtpTransport * @throws \phpbu\App\Exception */ protected function getSmtpTransport(array $options) { if (!isset($options['smtp.host'])) { throw new Exception('option \'smtp.host\' ist missing'); } $host = $options['smtp.host']; $port = Arr::getValue($options, 'smtp.port', 25); $username = Arr::getValue($options, 'smtp.username'); $password = Arr::getValue($options, 'smtp.password'); $encryption = Arr::getValue($options, 'smtp.encryption'); /* @var $transport \Swift_SmtpTransport */ $transport = \Swift_SmtpTransport::newInstance($host, $port); if ($username && $password) { $transport->setUsername($username) ->setPassword($password); } if ($encryption) { $transport->setEncryption($encryption); } return $transport; } /** * Create a Swift Sendmail Transport. * * @param array $options * @return \Swift_SendmailTransport * @throws \phpbu\App\Exception */ protected function getSendmailTransport(array $options) { if (!isset($options['sendmail.path'])) { throw new Exception('option \'sendmail.path\' ist missing'); } $path = $options['sendmail.path']; $options = isset($options['sendmail.options']) ? ' ' . $options['sendmail.options'] : ''; /* @var $transport \Swift_SendmailTransport */ $transport = \Swift_SendmailTransport::newInstance($path . $options); return $transport; } /** * Return mail header html * * @param \phpbu\App\Result $result * @return string */ protected function getHeaderHtml(Result $result) { $html = ''; if (count($result->getBackups()) === 0) { $html = '

No backups executed!

'; } elseif ($result->allOk()) { $html .= '

' . sprintf( 'OK (%d %s, %d %s, %d %s, %d %s)', count($result->getBackups()), String::appendPluralS('backup', count($result->getBackups())), $this->numChecks, String::appendPluralS('check', $this->numChecks), $this->numSyncs, String::appendPluralS('sync', $this->numSyncs), $this->numCleanups, String::appendPluralS('cleanup', $this->numCleanups) ) . '

'; } elseif ($result->backupOkButSkipsOrFails()) { $html .= '

' . sprintf( 'OK, but skipped or failed Syncs or Cleanups!
' . 'Backups: %d, Syncs: skipped|failed %d|%d, Cleanups: skipped|failed %d|%d.', count($result->getBackups()), $result->syncsSkippedCount(), $result->syncsFailedCount(), $result->cleanupsSkippedCount(), $result->cleanupsFailedCount() ) . '

'; } else { $html .= '

' . sprintf( 'FAILURE!
' . 'Backups: %d, failed Checks: %d, failed Syncs: %d, failed Cleanups: %d.', count($result->getBackups()), $result->checksFailedCount(), $result->syncsFailedCount(), $result->cleanupsFailedCount() ) . '

'; } return $html; } /** * Get error information. * * @param \phpbu\App\Result $result * @return string */ protected function getErrorHtml(Result $result) { $html = ''; /* @var $e Exception */ foreach ($result->getErrors() as $e) { $html .= '

' . sprintf( "Exception '%s' with message '%s'
in %s:%d", get_class($e), $e->getMessage(), $e->getFile(), $e->getLine() ) . '

'; } return $html; } /** * Return backup html information. * * @param \phpbu\App\Result $result * @return string */ protected function getInfoHtml(Result $result) { $html = ''; $backups = $result->getBackups(); $amount = count($backups); if ($amount > 0) { $i = 0; $html .= ''; /** @var \phpbu\App\Result\Backup $backup */ foreach ($backups as $backup) { $html .= ''; $html .= '' . '' . '' . '' . '' . '' . '' . '' . '' . '' . '' . ''; // put spacing row between backups but not at the end of the table $i++; $html .= ($i < $amount ? '' : ''); } $html .= '
'; $html .= sprintf('backup %s ', $backup->getName()); if ($backup->allOk()) { $html .= 'OK'; } elseif (!$backup->okButSkipsOrFails()) { $html .= 'OK, but skipped or failed Syncs or Cleanups!'; } else { $html .= 'FAILED'; } $html .= '
executedskippedfailed
checks' . $backup->checkCount() . '' . $backup->checkCountFailed() . '
syncs' . $backup->syncCount() . '' . $backup->syncCountSkipped() . '' . $backup->syncCountFailed() . '
cleanups' . $backup->cleanupCount() . '' . $backup->cleanupCountSkipped() . '' . $backup->cleanupCountFailed() . '
 
'; } return $html; } /** * Return mail body footer. * * @return string */ protected function getFooterHtml() { return '

' . PHP_Timer::resourceUsage() . '

'; } } * @author Sebastian Feldmann * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ */ class Printer { /** * If true, flush output after every write. * * @var boolean */ protected $autoFlush = false; /** * @var resource */ protected $out; /** * @var mixed */ protected $outTarget; /** * @var boolean */ protected $printsHTML = false; /** * Constructor * * @param mixed $out */ public function __construct($out = null) { $this->setOut($out); } /** * Out setter. * * @param mixed $out * @throws InvalidArgumentException */ protected function setOut($out = null) { if ($out !== null) { if (is_string($out)) { if (strpos($out, 'socket://') === 0) { $out = explode(':', str_replace('socket://', '', $out)); if (count($out) != 2) { throw new InvalidArgumentException(sprintf('Invalid socket: %s', $out)); } $this->out = fsockopen($out[0], $out[1]); } else { if (strpos($out, 'php://') === false && !is_dir(dirname($out))) { mkdir(dirname($out), 0777, true); } $this->out = fopen($out, 'wt'); } $this->outTarget = $out; } else { $this->out = $out; } } } /** * Flush buffer, optionally tidy up HTML, and close output if it's not to a php stream */ public function flush() { if ($this->out && strncmp($this->outTarget, 'php://', 6) !== 0) { fclose($this->out); } if ($this->printsHTML === true && $this->outTarget !== null && strpos($this->outTarget, 'php://') !== 0 && strpos($this->outTarget, 'socket://') !== 0 && extension_loaded('tidy')) { file_put_contents( $this->outTarget, tidy_repair_file( $this->outTarget, array('indent' => true, 'wrap' => 0), 'utf8' ) ); } } /** * Performs a safe, incremental flush. * * Do not confuse this function with the flush() function of this class, * since the flush() function may close the file being written to, rendering * the current object no longer usable. */ public function incrementalFlush() { if ($this->out) { fflush($this->out); } else { flush(); } } /** * @param string $buffer */ public function write($buffer) { if ($this->out) { fwrite($this->out, $buffer); if ($this->autoFlush) { $this->incrementalFlush(); } } else { if (PHP_SAPI != 'cli') { $buffer = htmlspecialchars($buffer); } echo $buffer; if ($this->autoFlush) { $this->incrementalFlush(); } } } /** * Check auto-flush mode. * * @return boolean */ public function getAutoFlush() { return $this->autoFlush; } /** * Set auto-flushing mode. * * If set, *incremental* flushes will be done after each write. This should * not be confused with the different effects of this class' flush() method. * * @param boolean $autoFlush */ public function setAutoFlush($autoFlush) { if (is_bool($autoFlush)) { $this->autoFlush = $autoFlush; } else { throw new InvalidArgumentException('Invalid argument, boolean expected'); } } } phpbu/phpbu: master@25750344fe46fae261eddb2b63b226f6e85cb798 aws/aws-sdk-php: 2.7.21 barracuda/copy: 1.1.6 dropbox/dropbox-sdk: v1.1.5 eher/oauth: 1.0.7 guzzle/guzzle: v3.9.2 phpseclib/phpseclib: dev-php5@38e6196127d243d0ed25baf8cf69bc2b2a0b7b80 phpunit/php-timer: 1.0.5 sebastian/environment: 1.2.1 sebastian/version: 1.0.4 softlayer/objectstorage: dev-master@b7aa7332e0eabf897dcf6cf2334830091ca781aa swiftmailer/swiftmailer: v5.3.1 symfony/event-dispatcher: v2.6.4 * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Backup { /** * Backup name * * @var string */ protected $name; /** * Backup was successful * * @var boolean */ protected $wasSuccessful = true; /** * List of executed checks * * @var array */ protected $checks = array(); /** * List of failed checks * * @var array */ protected $checksFailed = array(); /** * List of executed syncs * * @var array */ protected $syncs = array(); /** * List of skipped syncs * * @var array */ protected $syncsSkipped = array(); /** * List of failed syncs * * @var array */ protected $syncsFailed = array(); /** * List of executed cleanups * * @var array */ protected $cleanups = array(); /** * List of skipped cleanups * * @var array */ protected $cleanupsSkipped = array(); /** * List of failed cleanups * * @var array */ protected $cleanupsFailed = array(); /** * Constructor * * @param string $name */ public function __construct($name) { $this->name = $name; } /** * Type getter * * @return string */ public function getName() { return $this->name; } /** * Backup successful and nothing skipped or failed. * * @return boolean */ public function allOk() { return $this->wasSuccessful() && $this->noneSkipped() && $this->noneFailed(); } /** * Backup successful but something was skipped or failed. * * @return boolean */ public function okButSkipsOrFails() { return $this->wasSuccessful() && (!$this->noneFailed() || !$this->noneSkipped()); } /** * Backup executed successfully and no checks failed * * @return boolean */ public function wasSuccessful() { return $this->wasSuccessful; } /** * No skipped syncs or cleanups * * @return boolean */ public function noneSkipped() { return count($this->syncsSkipped) + count($this->cleanupsSkipped) === 0; } /** * No failed syncs or cleanups * * @return boolean */ public function noneFailed() { return count($this->syncsFailed) + count($this->cleanupsFailed) === 0; } /** * Mark backup as failed */ public function fail() { $this->wasSuccessful = false; } /** * Add check to executed list * * @param array $check */ public function checkAdd($check) { $this->checks[] = $check; } /** * Return amount of executed checks * * @return number */ public function checkCount() { return count($this->checks); } /** * Add check to failed checks list * * @param array $check */ public function checkFailed($check) { $this->checksFailed[] = $check; } /** * Return amount of failed checks * * @return number */ public function checkCountFailed() { return count($this->checksFailed); } /** * Add sync to executed syncs list * * @param array $sync */ public function syncAdd($sync) { $this->syncs[] = $sync; } /** * Return count of executed syncs. * * @return number */ public function syncCount() { return count($this->syncs); } /** * Add sync to skipped syncs list. * * @param array $sync */ public function syncSkipped($sync) { $this->syncsSkipped[] = $sync; } /** * Return amount of skipped syncs. * * @return number */ public function syncCountSkipped() { return count($this->syncsSkipped); } /** * Add sync to failed syncs list. * * @param array $sync */ public function syncFailed($sync) { $this->syncsFailed[] = $sync; } /** * Return amount of failed syncs. * * @return number */ public function syncCountFailed() { return count($this->syncsFailed); } /** * Add cleanup to executed cleanups list. * * @param array $cleanup */ public function cleanupAdd($cleanup) { $this->cleanups[] = $cleanup; } /** * Return amount of executed cleanups. * * @return number */ public function cleanupCount() { return count($this->cleanups); } /** * Add cleanup to skipped cleanups list. * * @param array $cleanup */ public function cleanupSkipped($cleanup) { $this->cleanupsSkipped[] = $cleanup; } /** * Return amount of skipped cleanups * * @return number */ public function cleanupCountSkipped() { return count($this->cleanupsSkipped); } /** * Add cleanup to failed cleanups list. * * @param array $cleanup */ public function cleanupFailed($cleanup) { $this->cleanupsFailed[] = $cleanup; } /** * Return amount of failed cleanups. * * @return number */ public function cleanupCountFailed() { return count($this->cleanupsFailed); } } * @author Sebastian Feldmann * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class PrinterCli extends Printer implements Listener { /** * Verbose output * * @var boolean */ protected $verbose; /** * Output with colors * * @var boolean */ protected $colors; /** * Is debug active * * @var boolean */ protected $debug; /** * List of console color codes. * * @var array */ private static $ansiCodes = array( 'bold' => 1, 'fg-black' => 30, 'fg-red' => 31, 'fg-yellow' => 33, 'fg-cyan' => 36, 'fg-white' => 37, 'bg-red' => 41, 'bg-green' => 42, 'bg-yellow' => 43 ); /** * Amount of executed backups * * @var integer */ private $numBackups = 0; /** * Amount of executed checks * * @var integer */ private $numChecks = 0; /** * Amount of executed Syncs * * @var integer */ private $numSyncs = 0; /** * Amount of executed Cleanups * * @var integer */ private $numCleanups = 0; /** * Constructor * * @param string $out * @param boolean $verbose * @param boolean $colors * @param boolean $debug * @throws \InvalidArgumentException */ public function __construct($out = null, $verbose = false, $colors = false, $debug = false) { $this->setOut($out); if (is_bool($verbose)) { $this->verbose = $verbose; } else { throw new InvalidArgumentException('Expected $verbose to be of type boolean'); } if (is_bool($colors)) { $console = new Console; $this->colors = $colors && $console->hasColorSupport(); } else { throw new InvalidArgumentException('Expected $colors to be of type boolean'); } if (is_bool($debug)) { $this->debug = $debug; } else { throw new InvalidArgumentException('Expected $debug to be of type boolean'); } } /** * phpbu start event. * * @see \phpbu\App\Listener::phpbuStart() * @param array $settings */ public function phpbuStart($settings) { $this->write( Version::getVersionString() . PHP_EOL . PHP_EOL . 'Configuration read from ' . $settings['configuration'] . PHP_EOL . PHP_EOL ); } /** * phpbu end event. * * @see \phpbu\App\Listener::phpbuEnd() * @param \phpbu\App\Result $result */ public function phpbuEnd(Result $result) { // do something fooish } /** * Backup start event. * * @see \phpbu\App\Listener::backupStart() * @param array $backup */ public function backupStart($backup) { $this->numBackups++; if ($this->debug) { $this->write('create backup (' . $backup['source']['type'] . '): '); } } /** * Backup failed event. * * @see \phpbu\App\Listener::backupFailed() * @param array $backup */ public function backupFailed($backup) { if ($this->debug) { $this->writeWithColor( 'fg-white, bg-red, bold', 'failed' ); } } /** * Backup end event. * * @see \phpbu\App\Listener::backupEnd() * @param array $backup */ public function backupEnd($backup) { if ($this->debug) { $this->write('done' . PHP_EOL); } } /** * Check start event. * * @see \phpbu\App\Listener::checkStart() * @param array $check */ public function checkStart($check) { $this->numChecks++; if ($this->debug) { $this->write('check (' . $check['type'] . '): '); } } /** * Check failed event. * * @see \phpbu\App\Listener::checkFailed() * @param array $check */ public function checkFailed($check) { if ($this->debug) { $this->writeWithColor( 'fg-white, bg-red, bold', 'failed' ); } } /** * Check end event. * * @see \phpbu\App\Listener::checkEnd() * @param array $check */ public function checkEnd($check) { if ($this->debug) { $this->write('passed' . PHP_EOL); } } /** * Sync start event. * * @see \phpbu\App\Listener::syncStart() * @param array $sync */ public function syncStart($sync) { $this->numSyncs++; if ($this->debug) { $this->write('sync start (' . $sync['type'] . '): '); } } /** * Sync skipped event. * * @see \phpbu\App\Listener::syncSkipped() * @param array $sync */ public function syncSkipped($sync) { if ($this->debug) { $this->writeWithColor( 'fg-black, bg-yellow', 'skipped' ); } } /** * Sync failed event. * * @see \phpbu\App\Listener::syncFailed() * @param array $sync */ public function syncFailed($sync) { if ($this->debug) { $this->writeWithColor( 'fg-white, bg-red, bold', 'failed' ); } } /** * Sync end event. * * @see \phpbu\App\Listener::syncEnd() * @param array $sync */ public function syncEnd($sync) { if ($this->debug) { $this->write('done' . PHP_EOL); } } /** * Cleanup start event. * * @see \phpbu\App\Listener::cleanupStart() * @param array $cleanup */ public function cleanupStart($cleanup) { $this->numCleanups++; if ($this->debug) { $this->write('cleanup start (' . $cleanup['type'] . '): '); } } /** * Cleanup skipped event. * * @see \phpbu\App\Listener::cleanupSkipped() * @param array $cleanup */ public function cleanupSkipped($cleanup) { if ($this->debug) { $this->writeWithColor( 'fg-black, bg-yellow', 'skipped' ); } } /** * Cleanup failed event. * * @see \phpbu\App\Listener::cleanupFailed() * @param array $cleanup */ public function cleanupFailed($cleanup) { if ($this->debug) { $this->writeWithColor( 'fg-white, bg-red, bold', 'failed' ); } } /** * Cleanup end event. * * @see \phpbu\App\Listener::cleanupEnd() * @param array $cleanup */ public function cleanupEnd($cleanup) { if ($this->debug) { $this->write('done' . PHP_EOL); } } /** * Debugging. * * @see \phpbu\App\Listener::debug() * @param string $msg */ public function debug($msg) { if ($this->debug) { $this->write($msg . PHP_EOL); } } /** * Prints a result summary. * * @param \phpbu\App\Result $result */ public function printResult(Result $result) { $this->printHeader(); $this->printErrors($result); if ($this->verbose) { foreach ($result->getBackups() as $backup) { $this->printBackupVerbose($backup); } } $this->printFooter($result); } /** * Prints the result header with memory usage info. */ protected function printHeader() { $this->write(PHP_Timer::resourceUsage() . PHP_EOL . PHP_EOL); } /** * Print error information. * * @param \phpbu\App\Result $result */ protected function printErrors(Result $result) { /* @var $e \Exception */ foreach ($result->getErrors() as $e) { $this->write( sprintf( "Exception '%s' with message '%s'\nin %s:%d\n\n", get_class($e), $e->getMessage(), $e->getFile(), $e->getLine() ) ); } } /** * Prints verbose backup information. * * @param \phpbu\App\Result\Backup $backup */ protected function printBackupVerbose(Result\Backup $backup) { $this->write(sprintf('backup %s: ', $backup->getName())); if ($backup->allOk()) { $this->writeWithColor( 'fg-black, bg-green', 'OK' ); } elseif ($backup->okButSkipsOrFails()) { $this->writeWithColor( 'fg-black, bg-yellow', 'OK, but skipped or failed Syncs or Cleanups!' ); } else { $this->writeWithColor( 'fg-white, bg-red, bold', 'FAILED' ); } $chExecuted = str_pad($backup->checkCount(), 8, ' ', STR_PAD_LEFT); $chFailed = str_pad($backup->checkCountFailed(), 6, ' ', STR_PAD_LEFT); $syExecuted = str_pad($backup->syncCount(), 8, ' ', STR_PAD_LEFT); $sySkipped = str_pad($backup->syncCountSkipped(), 7, ' ', STR_PAD_LEFT); $syFailed = str_pad($backup->syncCountFailed(), 6, ' ', STR_PAD_LEFT); $clExecuted = str_pad($backup->cleanupCount(), 8, ' ', STR_PAD_LEFT); $clSkipped = str_pad($backup->cleanupCountSkipped(), 7, ' ', STR_PAD_LEFT); $clFailed = str_pad($backup->cleanupCountFailed(), 6, ' ', STR_PAD_LEFT); $out = ' | executed | skipped | failed |' . PHP_EOL . '----------+----------+---------+--------+' . PHP_EOL . ' checks | ' . $chExecuted . ' | | ' . $chFailed . ' |' . PHP_EOL . ' syncs | ' . $syExecuted . ' | ' . $sySkipped . ' | ' . $syFailed . ' |' . PHP_EOL . ' cleanups | ' . $clExecuted . ' | ' . $clSkipped . ' | ' . $clFailed . ' |' . PHP_EOL . '----------+----------+---------+--------+' . PHP_EOL . PHP_EOL; $this->write($out); } /** * Prints 'OK' or 'FAILURE' footer. * * @param Result $result */ protected function printFooter(Result $result) { if (count($result->getBackups()) === 0) { $this->writeWithColor( 'fg-black, bg-yellow', 'No backups executed!' ); } elseif ($result->allOk()) { $this->writeWithColor( 'fg-black, bg-green', sprintf( 'OK (%d %s, %d %s, %d %s, %d %s)', count($result->getBackups()), String::appendPluralS('backup', count($result->getBackups())), $this->numChecks, String::appendPluralS('check', $this->numChecks), $this->numSyncs, String::appendPluralS('sync', $this->numSyncs), $this->numCleanups, String::appendPluralS('cleanup', $this->numCleanups) ) ); } elseif ($result->backupOkButSkipsOrFails()) { $this->writeWithColor( 'fg-black, bg-yellow', sprintf( "OK, but skipped or failed Syncs or Cleanups!\n" . 'Backups: %d, Syncs: skipped|failed %d|%d, Cleanups: skipped|failed %d|%d.', count($result->getBackups()), $result->syncsSkippedCount(), $result->syncsFailedCount(), $result->cleanupsSkippedCount(), $result->cleanupsFailedCount() ) ); } else { $this->writeWithColor( 'fg-white, bg-red', sprintf( "FAILURE!\n" . 'Backups: %d, failed Checks: %d, failed Syncs: %d, failed Cleanups: %d.', count($result->getBackups()), $result->checksFailedCount(), $result->syncsFailedCount(), $result->cleanupsFailedCount() ) ); } } /** * Formats a buffer with a specified ANSI color sequence if colors are enabled. * * @author Sebastian Bergmann * @param string $color * @param string $buffer * @return string */ protected function formatWithColor($color, $buffer) { if (!$this->colors) { return $buffer; } $codes = array_map('trim', explode(',', $color)); $lines = explode("\n", $buffer); $padding = max(array_map('strlen', $lines)); $styles = array(); foreach ($codes as $code) { $styles[] = self::$ansiCodes[$code]; } $style = sprintf("\x1b[%sm", implode(';', $styles)); $styledLines = array(); foreach ($lines as $line) { $styledLines[] = $style . str_pad($line, $padding) . "\x1b[0m"; } return implode(PHP_EOL, $styledLines); } /** * Writes a buffer out with a color sequence if colors are enabled. * * @author Sebastian Bergmann * @param string $color * @param string $buffer */ protected function writeWithColor($color, $buffer) { $buffer = $this->formatWithColor($color, $buffer); $this->write($buffer . PHP_EOL); } } * @author Sebastian Feldmann * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Result { /** * List of Logging listeners * * @var array<\phpbu\App\Listener> */ protected $listeners = array(); /** * List of executed Backups * * @var array<\phpbu\App\Result\Backup> */ protected $backups = array(); /** * Currently running backup. * * @var \phpbu\App\Result\Backup */ protected $backupActive; /** * List of errors. * * @var array */ protected $errors = array(); /** * @var integer */ protected $backupsFailed = 0; /** * @var integer */ protected $checksFailed = 0; /** * @var integer */ protected $syncsSkipped = 0; /** * @var integer */ protected $syncsFailed = 0; /** * @var integer */ protected $cleanupsSkipped = 0; /** * @var integer */ protected $cleanupsFailed = 0; /** * @return boolean */ public function allOk() { return $this->wasSuccessful() && $this->noneSkipped() && $this->noneFailed(); } /** * @return boolean */ public function backupOkButSkipsOrFails() { return $this->wasSuccessful() && (!$this->noneSkipped() || !$this->noneFailed()); } /** * @return boolean */ public function wasSuccessful() { return $this->backupsFailed === 0; } /** * @return boolean */ public function noneSkipped() { return $this->syncsSkipped + $this->cleanupsSkipped === 0; } /** * @return boolean */ public function noneFailed() { return $this->syncsFailed + $this->cleanupsFailed === 0; } /** * Add Exception to error list * * @param \Exception $e */ public function addError(\Exception $e) { $this->errors[] = $e; } /** * Return current error count. * * @return integer */ public function errorCount() { return count($this->errors); } /** * Return list of errors. * * @return array */ public function getErrors() { return $this->errors; } /** * Return list of executed backups. * * @return array */ public function getBackups() { return $this->backups; } /** * phpbu start event. * * @param array $settings */ public function phpbuStart(array $settings) { /** @var \phpbu\App\Listener $l */ foreach ($this->listeners as $l) { $l->phpbuStart($settings); } } /** * phpbu end event. */ public function phpbuEnd() { /** @var \phpbu\App\Listener $l */ foreach ($this->listeners as $l) { $l->phpbuEnd($this); } } /** * Backup start event. * * @param array $backup */ public function backupStart($backup) { $this->backupActive = new Result\Backup(!empty($backup['name']) ? $backup['name'] : $backup['source']['type']); $this->backups[] = $this->backupActive; /** @var \phpbu\App\Listener $l */ foreach ($this->listeners as $l) { $l->backupStart($backup); } } /** * Backup failed event. * * @param array $backup */ public function backupFailed($backup) { $this->backupsFailed++; $this->backupActive->fail(); /** @var \phpbu\App\Listener $l */ foreach ($this->listeners as $l) { $l->backupFailed($backup); } } /** * Return amount of failed backups * * @return integer */ public function backupsFailedCount() { return $this->backupsFailed; } /** * Backup end event. * * @param array $backup */ public function backupEnd($backup) { /** @var \phpbu\App\Listener $l */ foreach ($this->listeners as $l) { $l->backupEnd($backup); } } /** * Check start event. * * @param array $check */ public function checkStart($check) { $this->backupActive->checkAdd($check); /** @var \phpbu\App\Listener $l */ foreach ($this->listeners as $l) { $l->checkStart($check); } } /** * Check failed event. * * @param array $check */ public function checkFailed($check) { $this->checksFailed++; $this->backupActive->fail(); $this->backupActive->checkFailed($check); /** @var \phpbu\App\Listener $l */ foreach ($this->listeners as $l) { $l->checkFailed($check); } } /** * Return amount of failed checks * * @return integer */ public function checksFailedCount() { return $this->checksFailed; } /** * Check end event. * * @param array $check */ public function checkEnd($check) { /** @var \phpbu\App\Listener $l */ foreach ($this->listeners as $l) { $l->checkEnd($check); } } /** * Sync start event. * * @param array $sync */ public function syncStart($sync) { $this->backupActive->syncAdd($sync); /** @var \phpbu\App\Listener $l */ foreach ($this->listeners as $l) { $l->syncStart($sync); } } /** * Sync skipped event. * * @param array $sync */ public function syncSkipped($sync) { $this->syncsSkipped++; $this->backupActive->syncSkipped($sync); /** @var \phpbu\App\Listener $l */ foreach ($this->listeners as $l) { $l->syncSkipped($sync); } } /** * Return amount of skipped syncs * * @return integer */ public function syncsSkippedCount() { return $this->syncsSkipped; } /** * Sync failed event. * * @param array $sync */ public function syncFailed($sync) { $this->syncsFailed++; $this->backupActive->syncFailed($sync); /** @var \phpbu\App\Listener $l */ foreach ($this->listeners as $l) { $l->syncFailed($sync); } } /** * Return amount of failed syncs * * @return integer */ public function syncsFailedCount() { return $this->syncsFailed; } /** * Sync end event. * * @param array $sync */ public function syncEnd($sync) { /** @var \phpbu\App\Listener $l */ foreach ($this->listeners as $l) { $l->syncEnd($sync); } } /** * Cleanup start event. * * @param array $cleanup */ public function cleanupStart($cleanup) { $this->backupActive->cleanupAdd($cleanup); /** @var \phpbu\App\Listener $l */ foreach ($this->listeners as $l) { $l->cleanupStart($cleanup); } } /** * Cleanup skipped event. * * @param array $cleanup */ public function cleanupSkipped($cleanup) { $this->cleanupsSkipped++; $this->backupActive->cleanupSkipped($cleanup); /** @var \phpbu\App\Listener $l */ foreach ($this->listeners as $l) { $l->cleanupSkipped($cleanup); } } /** * Return amount of skipped cleanups * * @return integer */ public function cleanupsSkippedCount() { return $this->cleanupsSkipped; } /** * Cleanup failed event. * * @param array $cleanup */ public function cleanupFailed($cleanup) { $this->cleanupsFailed++; $this->backupActive->cleanupFailed($cleanup); /** @var \phpbu\App\Listener $l */ foreach ($this->listeners as $l) { $l->cleanupFailed($cleanup); } } /** * Return amount of failed cleanups * * @return integer */ public function cleanupsFailedCount() { return $this->cleanupsFailed; } /** * Cleanup end event. * * @param array $cleanup */ public function cleanupEnd($cleanup) { /** @var \phpbu\App\Listener $l */ foreach ($this->listeners as $l) { $l->cleanupEnd($cleanup); } } /** * Debug. * * @param string $msg */ public function debug($msg) { /** @var \phpbu\App\Listener $l */ foreach ($this->listeners as $l) { $l->debug($msg); } } /** * Registers a Listener. * * @param \phpbu\App\Listener */ public function addListener(Listener $listener) { $this->listeners[] = $listener; } /** * Remove a Listener. * * @author Sebastian Bergmann * @param \phpbu\App\Listener $listener */ public function removeListener(Listener $listener) { /** @var \phpbu\App\Listener $l */ foreach ($this->listeners as $key => $l) { if ($listener === $l) { unset($this->listeners[$key]); } } } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Runner { /** * Application output * * @var \phpbu\App\Listener */ protected $printer; /** * Run all backups configured * * @param array $arguments * @return \phpbu\App\Result */ public function run(array $arguments) { $this->handleConfiguration($arguments); $this->printer = $this->createPrinter($arguments); $stop = false; $result = new Result(); $result->addListener($this->printer); foreach ($this->createLoggers($arguments) as $listener) { $result->addListener($listener); } $result->phpbuStart($arguments); // create backups foreach ($arguments['backups'] as $backup) { if ($stop) { break; } // create target $checkFailed = false; $syncFailed = false; $target = new Backup\Target($backup['target']['dirname'], $backup['target']['filename']); $target->setupPath(); // compressor if (!empty($backup['target']['compress'])) { $compressor = Backup\Compressor::create($backup['target']['compress']); $target->setCompressor($compressor); } /* * __ __ * / /_ ____ ______/ /____ ______ * / __ \/ __ `/ ___/ //_/ / / / __ \ * / /_/ / /_/ / /__/ ,< / /_/ / /_/ / * /_.___/\__,_/\___/_/|_|\__,_/ .___/ * /_/ */ try { $result->backupStart($backup); $source = Factory::createSource($backup['source']['type'], $backup['source']['options']); $source->backup($target, $result); $result->backupEnd($backup); // setup the collector for this backup $collector = new Backup\Collector($target); /* * __ __ * _____/ /_ ___ _____/ /_______ * / ___/ __ \/ _ \/ ___/ //_/ ___/ * / /__/ / / / __/ /__/ ,< (__ ) * \___/_/ /_/\___/\___/_/|_/____/ * */ foreach ($backup['checks'] as $check) { try { $result->checkStart($check); $c = Factory::createCheck($check['type']); if ($c->pass($target, $check['value'], $collector, $result)) { $result->checkEnd($check); } else { $checkFailed = true; $result->checkFailed($check); } } catch (Backup\Check\Exception $e) { $checkFailed = true; $result->addError($e); $result->checkFailed($check); } } /* * _______ ______ __________ * / ___/ / / / __ \/ ___/ ___/ * (__ ) /_/ / / / / /__(__ ) * /____/\__, /_/ /_/\___/____/ * /____/ */ foreach ($backup['syncs'] as $sync) { try { $result->syncStart($sync); if ($checkFailed && $sync['skipOnCheckFail']) { $result->syncSkipped($sync); } else { $s = Factory::createSync($sync['type'], $sync['options']); $s->sync($target, $result); $result->syncEnd($sync); } } catch (Backup\Sync\Exception $e) { $syncFailed = true; $result->addError($e); $result->syncFailed($sync); } } /* * __ * _____/ /__ ____ _____ __ ______ * / ___/ / _ \/ __ `/ __ \/ / / / __ \ * / /__/ / __/ /_/ / / / / /_/ / /_/ / * \___/_/\___/\__,_/_/ /_/\__,_/ .___/ * /_/ */ if (!empty($backup['cleanup'])) { $cleanup = $backup['cleanup']; try { $result->cleanupStart($cleanup); if (($checkFailed && $cleanup['skipOnCheckFail']) || ($syncFailed && $cleanup['skipOnSyncFail'])) { $result->cleanupSkipped($cleanup); } else { $cleaner = Factory::createCleaner($cleanup['type'], $cleanup['options']); $cleaner->cleanup($target, $collector, $result); $result->cleanupEnd($cleanup); } } catch (Backup\Cleaner\Exception $e) { $result->debug('exception: ' . $e->getMessage()); $result->addError($e); $result->cleanupFailed($cleanup); } } } catch (\Exception $e) { $result->debug('exception: ' . $e->getMessage()); $result->addError($e); $result->backupFailed($backup); if (true == $backup['stopOnError']) { $stop = true; } } } $result->phpbuEnd(); $this->printer->printResult($result); return $result; } /** * Make sure the config is valid. * * @param array $arguments */ protected function handleConfiguration(array &$arguments) { $arguments['colors'] = isset($arguments['colors']) ? $arguments['colors'] : false; $arguments['debug'] = isset($arguments['debug']) ? $arguments['debug'] : false; $arguments['verbose'] = isset($arguments['verbose']) ? $arguments['verbose'] : false; } /** * Creates the output printer. * * @param array $arguments * @return \phpbu\App\Result\PrinterCli */ protected function createPrinter(array $arguments) { $printer = new Result\PrinterCli( isset($arguments['stderr']) ? 'php://stderr' : null, $arguments['verbose'], $arguments['colors'], $arguments['debug'] ); return $printer; } /** * Create all configured loggers. * * @param array $arguments * @return array */ protected function createLoggers(array $arguments) { $loggers = array(); foreach ($arguments['logging'] as $log) { $logger = Factory::createLogger($log['type'], $log['options']); $loggers[] = $logger; } return $loggers; } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.1.5 */ abstract class Arr { /** * Check array key for existence and value that is not the empty string. * * @param array $arr * @param string $key * @return boolean */ public static function isSetAndNotEmptyString(array $arr, $key) { return isset($arr[$key]) && '' !== $arr[$key]; } /** * Return an array key if it exists, null or given default otherwise. * * @param array $arr * @param string $key * @param mixed $default * @return mixed */ public static function getValue(array $arr, $key, $default = null) { return isset($arr[$key]) ? $arr[$key] : $default; } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ abstract class Cli { /** * Detect a given commands location. * * @param string $cmd The command to be located * @param string $path Directory where the command should be located * @param array $optionalLocations Some fallback locations where to investigate * @return string Absolute path to detected command including command itself * @throws \RuntimeException */ public static function detectCmdLocation($cmd, $path = null, $optionalLocations = array()) { // explicit path given, so check it out if (null !== $path) { $command = $path . DIRECTORY_SEPARATOR . $cmd; if (!is_executable($command)) { throw new RuntimeException(sprintf('wrong path specified for \'%s\': %s', $cmd, $path)); } return $command; } // on nx systems use 'which' command. if (!defined('PHP_WINDOWS_VERSION_BUILD')) { $command = `which $cmd`; if (is_executable($command)) { return $command; } } // checking environment variable. $pathList = explode(PATH_SEPARATOR, $_SERVER['PATH']); foreach ($pathList as $path) { $command = $path . DIRECTORY_SEPARATOR . $cmd; if (is_executable($command)) { return $command; } } // some more paths we came across that where added manually foreach ($optionalLocations as $path) { $command = $path . DIRECTORY_SEPARATOR . $cmd; if (is_executable($command)) { return $command; } } throw new RuntimeException(sprintf('\'%s\' was nowhere to be found please specify the correct path', $cmd)); } /** * Is given path absolute. * * @param string $path * @return boolean */ public static function isAbsolutePath($path) { // path already absolute? if ($path[0] === '/') { return true; } // Matches the following on Windows: // - \\NetworkComputer\Path // - \\.\D: // - \\.\c: // - C:\Windows // - C:\windows // - C:/windows // - c:/windows if (defined('PHP_WINDOWS_VERSION_BUILD') && self::isAbsoluteWindowsPath($path)) { return true; } // Stream if (strpos($path, '://') !== false) { return true; } return false; } /** * Is given path an absolute windows path. * * @param string $path * @return bool */ public static function isAbsoluteWindowsPath($path) { return ($path[0] === '\\' || (strlen($path) >= 3 && preg_match('#^[A-Z]\:[/\\\]#i', substr($path, 0, 3)))); } /** * Converts a path to an absolute one if necessary relative to a given base path. * * @param string $path * @param string $base * @param boolean $useIncludePath * @return string */ public static function toAbsolutePath($path, $base, $useIncludePath = false) { if (self::isAbsolutePath($path)) { return $path; } $file = $base . DIRECTORY_SEPARATOR . $path; if ($useIncludePath && !file_exists($file)) { $includePathFile = stream_resolve_include_path($path); if ($includePathFile) { $file = $includePathFile; } } return $file; } /** * Removes a directory that is not empty. * * @param $dir */ public static function removeDir($dir) { foreach(scandir($dir) as $file) { if ('.' === $file || '..' === $file) { continue; } if (is_dir($dir . '/' . $file)) { self::removeDir($dir . '/' . $file); } else { unlink($dir . '/' . $file); } } rmdir($dir); } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Math { /** * Calculates the difference of two values in percent * * @param integer $a * @param integer $b * @return integer */ public static function getDiffInPercent($a, $b) { if ($a > $b) { $whole = $a; $part = $b; } else { $whole = $b; $part = $a; } return 100 - ceil(($part / $whole) * 100); } } * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class String { /** * Date placeholder replacement. * Replaces %{somevalue} with date({somevalue}). * * @param string $string * @param mixed $time * @return string */ public static function replaceDatePlaceholders($string, $time = null) { $time = $time === null ? time() : $time; return preg_replace_callback( '#%([a-zA-Z])#', function($match) use ($time) { return date($match[1], $time); }, $string ); } /** * Create a regex that matches the raw path considering possible date placeholders. * * @param string $stringWithDatePlaceholders * @return string */ public static function datePlaceholdersToRegex($stringWithDatePlaceholders) { $regex = preg_quote($stringWithDatePlaceholders, '#'); return preg_replace('#%[a-z]#i', '[0-9a-z]+', $regex); } /** * Converts a given value to boolean. * * @param string $value * @param boolean $default * @return boolean */ public static function toBoolean($value, $default) { if (strtolower($value) == 'false') { return false; } elseif (strtolower($value) == 'true') { return true; } return $default; } /** * Return given size in bytes. * Allowed units: * B => byte * K => kilo byte * M => mega byte * G => giga byte * T => terra byte * P => peta byte * * e.g. * 1K => 1024 * 2K => 2048 * ... * * @param string $value * @throws \RuntimeException * @return integer */ public static function toBytes($value) { if (!preg_match('#^[0-9]*[BKMGT]$#i', $value)) { throw new RuntimeException('Invalid size value'); } $units = array('B' => 0, 'K' => 1, 'M' => 2, 'G' => 3, 'T' => 4, 'P' => 5); $unit = strtoupper(substr($value, -1)); $number = intval(substr($value, 0, -1)); return $number * pow(1024, $units[$unit]); } /** * Return time in seconds for a given value. * Allowed units: * S => second * I => minute * D => day * W => week * M => month * Y => year * * e.g. * 2I => 120 * 10D => 864000 * ... * * @param string $offset * @throws \RuntimeException * @return integer */ public static function toTime($offset) { if (!preg_match('#^[1-9]+[0-9]*[SIHDWMY]$#i', $offset)) { throw new RuntimeException(sprintf('Invalid value for offset: %s', $offset)); } $units = array('S' => 1, 'I' => 60, 'H' => 3600, 'D' => 86400, 'W' => 604800, 'M' => 2678400, 'Y' => 31536000); $unit = strtoupper(substr($offset, -1)); $number = intval(substr($offset, 0, -1)); return $number * $units[$unit]; } /** * Pads all given strings to given length. * * @param array $strings * @param integer $length * @param string $pad * @param integer $mode * @return array */ public static function padAll(array $strings, $length, $pad = ' ', $mode = STR_PAD_LEFT) { $result = array(); foreach ($strings as $key => $s) { $result[$key] = str_pad($s, $length, $pad, $mode); } return $result; } /** * Explodes string to array but empty string results in empty array not array with empty string in it. * * @param string $separated * @param string $separator * @param boolean $trim * @return array */ public static function toList($separated, $separator = ',', $trim = true) { $list = empty($separated) ? array() : explode($separator, $separated); if ($trim) { $list = array_map('trim', $list); } return $list; } /** * Adds trailing slash to a string/path if not already there. * * @param string $string * @return string */ public static function withTrailingSlash($string) { return $string . (substr($string, -1) !== '/' ? '/' : ''); } /** * Removes the trailing slash from a string/path. * * @param string $string * @return string */ public static function withoutTrailingSlash($string) { return strlen($string) > 1 && substr($string, -1) === '/' ? substr($string, 0, -1) : $string; } /** * Adds leading slash to a string/path if not already there. * * @param string $string * @return string */ public static function withLeadingSlash($string) { return (substr($string, 0, 1) !== '/' ? '/' : '') . $string; } /** * Removes the leading slash from a string/path. * * @param string $string * @return string */ public static function withoutLeadingSlash($string) { return substr($string, 0, 1) === '/' ? substr($string, 1) : $string; } /** * Appends a plural "s" or "'s". * * @param string $subject * @param integer $amount * @return string */ public static function appendPluralS($subject, $amount) { return $subject . ($amount == 1 ? '' : (substr($subject, -1) == 's' ? '\'s' : 's')); } } * @author Sebastian Feldmann * @copyright Sebastian Feldmann * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://phpbu.de/ * @since Class available since Release 1.0.0 */ class Version { /** * Version of the phar file. * Is getting set via the phar build process. * * @var string */ private static $pharVersion = "1.2.0"; /** * Current version * * @var string */ private static $version; /** * Return the current version of PHPUnit. * * @return string */ public static function id() { if (self::$pharVersion !== null) { return self::$pharVersion; } if (self::$version === null) { $version = new SebastianBergmann\Version('1.2.0', dirname(dirname(__DIR__))); self::$version = $version->getVersion(); } return self::$version; } /** * Return the version string. * * @return string */ public static function getVersionString() { return 'phpbu ' . self::id(); } /** * Return the current release channel ('alpha', 'beta', '') * * @return string */ public static function getReleaseChannel() { if (strpos(self::$pharVersion, 'alpha') !== false) { return '-alpha'; } if (strpos(self::$pharVersion, 'beta') !== false) { return '-beta'; } return ''; } } Íù¦‰UK³¥&@6¦+¬Æ¼ÙGBMB