idx
int64
0
60.3k
question
stringlengths
64
4.24k
target
stringlengths
5
618
52,700
private function hasToken ( ) { $ token = $ this -> _scopeConfig -> getValue ( 'payment/pagseguro/token' ) ; if ( ! isset ( $ token ) ) return false ; if ( $ this -> isValidToken ( $ token ) ) return true ; return false ; }
Check if has a valid token
52,701
private function holder ( ) { $ this -> _paymentRequest -> setHolder ( ) -> setName ( $ this -> _data [ 'holder' ] [ 'name' ] ) ; $ this -> _paymentRequest -> setHolder ( ) -> setBirthdate ( $ this -> _data [ 'holder' ] [ 'birth_date' ] ) ; $ this -> _paymentRequest -> setHolder ( ) -> setDocument ( ) -> withParameters ( $ this -> _data [ 'sender_document' ] [ 'type' ] , $ this -> _data [ 'sender_document' ] [ 'number' ] ) ; $ this -> setHolderPhone ( ) ; }
Set the holder informartion
52,702
private function setHolderPhone ( ) { $ addressData = ( $ this -> getBillingAddress ( ) ) ? $ this -> getBillingAddress ( ) : $ this -> _order -> getShippingAddress ( ) ; if ( ! empty ( $ addressData [ 'telephone' ] ) ) { $ phone = \ UOL \ PagSeguro \ Helper \ Data :: formatPhone ( $ addressData [ 'telephone' ] ) ; $ this -> _paymentRequest -> setHolder ( ) -> setPhone ( ) -> withParameters ( $ phone [ 'areaCode' ] , $ phone [ 'number' ] ) ; } }
Set the holder phone
52,703
private function updateOrderStatus ( ) { $ this -> _library -> setEnvironment ( ) ; $ this -> _library -> setCharset ( ) ; $ this -> _library -> setLog ( ) ; $ transaction = $ this -> getTransaction ( ) ; $ order = $ this -> _order -> get ( $ this -> _helperData -> getReferenceDecryptOrderID ( $ transaction -> getReference ( ) ) ) ; $ status = $ this -> _helperData -> getStatusFromKey ( $ transaction -> getStatus ( ) ) ; if ( ! $ this -> compareStatus ( $ status , $ order -> getStatus ( ) ) ) { $ history = array ( 'status' => $ this -> _history -> setStatus ( $ status ) , 'comment' => $ this -> _history -> setComment ( 'PagSeguro Notification' ) ) ; $ transactionCode = $ transaction -> getCode ( ) ; $ orderId = $ order -> getId ( ) ; $ order -> setStatus ( $ status ) ; $ order -> setStatusHistories ( $ history ) ; $ order -> save ( ) ; $ this -> updateSalesOrderGridTransactionCode ( $ orderId , $ transactionCode ) ; $ this -> updatePagSeguroOrdersTransactionCode ( $ orderId , $ transactionCode ) ; } return true ; }
Update status in Magento2 Order
52,704
public function getConfig ( ) { $ this -> _library -> setEnvironment ( ) ; $ config = [ 'library' => [ 'session' => $ this -> _library -> getSession ( ) , 'directPaymentJs' => $ this -> _library -> getDirectPaymentUrl ( ) ] , 'brazilFlagPath' => $ this -> _library -> getImageUrl ( 'UOL_PagSeguro::images/flag-origin-country.png' ) , 'payment' => [ 'pagseguro' => [ 'isDirect' => $ this -> method -> isDirectCheckout ( ) , 'isLightbox' => $ this -> method -> isLightboxCheckoutType ( ) , 'checkout' => [ 'lightbox' => $ this -> method -> getLightboxCheckoutPaymentUrl ( ) , 'standard' => $ this -> method -> getStandardCheckoutPaymentUrl ( ) , 'direct' => $ this -> method -> getDirectCheckoutPaymentUrl ( ) ] ] ] , 'pagseguro_boleto' => $ this -> boletoMethod -> getStandardCheckoutPaymentUrl ( ) , ] ; return $ config ; }
Get payment config
52,705
public function url ( $ id = null , $ additionalEndpoint = null ) { $ endpoint = $ this -> endpoint ( ) ; if ( ! is_null ( $ id ) ) { $ endpoint .= '/' . $ id ; } if ( ! is_null ( $ additionalEndpoint ) ) { $ endpoint .= '/' . $ additionalEndpoint ; } return $ endpoint ; }
Build url that will hit the API .
52,706
public function update ( $ id = null , array $ form_params = [ ] ) { return $ this -> apiRequester -> request ( 'PUT' , $ this -> url ( $ id ) , [ 'json' => $ form_params ] ) ; }
Update a specific resource .
52,707
public function delete ( $ id = null , array $ form_params = [ ] ) { return $ this -> apiRequester -> request ( 'DELETE' , $ this -> url ( $ id ) , [ 'json' => $ form_params ] ) ; }
Delete a specific resource .
52,708
public function get ( $ id = null , $ additionalEndpoint = null ) { return $ this -> apiRequester -> request ( 'GET' , $ this -> url ( $ id , $ additionalEndpoint ) ) ; }
Make a GET request to an additional endpoint for a specific resource .
52,709
public function post ( $ id = null , $ additionalEndpoint = null , array $ form_params = [ ] ) { return $ this -> apiRequester -> request ( 'POST' , $ this -> url ( $ id , $ additionalEndpoint ) , [ 'json' => $ form_params ] ) ; }
Make a POST request to an additional endpoint for a specific resource .
52,710
private function getHeaderValue ( $ response , $ name ) { $ header = $ response -> getHeader ( $ name ) ; if ( ! $ header || ! count ( $ header ) ) { return 0 ; } return ( int ) array_shift ( $ header ) ; }
Get first array value from specified header as integer .
52,711
public static function getApiUri ( ) { if ( null !== self :: $ vindi_api_uri ) { return self :: $ vindi_api_uri ; } if ( ! empty ( getenv ( static :: VINDI_API_URI ) ) ) { return getenv ( static :: VINDI_API_URI ) ; } return 'https://app.vindi.com.br/api/v1/' ; }
Get Vindi API URI from environment .
52,712
protected function hexToRgb ( $ hex ) { if ( ! isset ( $ this -> colorCache [ $ hex ] ) ) { $ this -> colorCache [ $ hex ] = [ 'r' => hexdec ( substr ( $ hex , 0 , 2 ) ) , 'g' => hexdec ( substr ( $ hex , 2 , 2 ) ) , 'b' => hexdec ( substr ( $ hex , 4 , 2 ) ) ] ; } return $ this -> colorCache [ $ hex ] ; }
Color converter - HEX to RGB .
52,713
protected function drawScratch ( $ img , $ imageWidth , $ imageHeight , $ hex ) { $ rgb = $ this -> hexToRgb ( $ hex ) ; imageline ( $ img , mt_rand ( 0 , floor ( $ imageWidth / 2 ) ) , mt_rand ( 1 , $ imageHeight ) , mt_rand ( floor ( $ imageWidth / 2 ) , $ imageWidth ) , mt_rand ( 1 , $ imageHeight ) , imagecolorallocate ( $ img , $ rgb [ 'r' ] , $ rgb [ 'g' ] , $ rgb [ 'b' ] ) ) ; }
Draw scratches .
52,714
public function getImage ( ) { $ code = $ this -> code -> generate ( $ this -> params [ 'chars' ] , $ this -> params [ 'length' ] [ 0 ] , $ this -> params [ 'length' ] [ 1 ] ) ; $ this -> storage -> push ( $ code ) ; return $ this -> generator -> render ( $ code , $ this -> params ) ; }
Output a PNG image .
52,715
public function validate ( $ code ) { $ correctCode = $ this -> storage -> pull ( ) ; if ( ! empty ( $ correctCode ) ) { return mb_strtolower ( $ correctCode ) === mb_strtolower ( $ code ) ; } return false ; }
Captcha validation .
52,716
protected function registerRoutes ( ) { $ this -> app [ 'router' ] -> group ( [ 'middleware' => config ( 'bone.captcha.middleware' , 'web' ) , 'namespace' => 'Igoshev\Captcha\Controllers' , 'as' => 'bone.captcha.' ] , function ( $ router ) { $ router -> get ( config ( 'bone.captcha.routes.image' ) , 'CaptchaController@image' ) -> name ( 'image' ) ; $ router -> get ( config ( 'bone.captcha.routes.image_tag' ) , 'CaptchaController@imageTag' ) -> name ( 'image.tag' ) ; } ) ; }
Register captcha routes .
52,717
protected function registerValidator ( ) { Validator :: extend ( config ( 'bone.captcha.validator' ) , function ( $ attribute , $ value , $ parameters , $ validator ) { return $ this -> app [ Captcha :: class ] -> validate ( $ value ) ; } , trans ( 'bone::captcha.incorrect_code' ) ) ; }
Register captcha validator .
52,718
public function setCurlDefaultOption ( $ key , $ value ) { $ this -> curlOptions [ $ key ] = $ value ; $ this -> guzzle = $ this -> createGuzzleClient ( ) ; }
set cURL default option on Guzzle client
52,719
protected function processBlocktrailPubKeys ( ) { if ( ! isset ( $ this -> backupInfo [ 'blocktrail_public_keys' ] ) ) { return ; } foreach ( $ this -> backupInfo [ 'blocktrail_public_keys' ] as $ keyIndex => $ key ) { $ key = $ key instanceof BIP32Key ? $ key : BIP32Key :: create ( HierarchicalKeyFactory :: fromExtended ( $ key [ 0 ] ) , $ key [ 1 ] ) ; $ qrCode = new QrCode ( ) ; $ qrCode -> setText ( $ key -> key ( ) -> toExtendedKey ( ) ) -> setSize ( self :: QR_CODE_SIZE - 20 ) -> setPadding ( 10 ) -> setErrorCorrection ( 'high' ) -> setForegroundColor ( array ( 'r' => 0 , 'g' => 0 , 'b' => 0 , 'a' => 0 ) ) -> setBackgroundColor ( array ( 'r' => 255 , 'g' => 255 , 'b' => 255 , 'a' => 0 ) ) -> setLabel ( "KeyIndex: " . $ keyIndex . " Path: " . $ key -> path ( ) ) -> setLabelFontSize ( 10 ) ; $ this -> blocktrailPubKeyQRs [ ] = array ( 'keyIndex' => $ keyIndex , 'path' => $ key -> path ( ) , 'qr' => $ qrCode -> getDataUri ( ) , 'qrImg' => $ qrCode -> getImage ( ) , ) ; } }
process the blocktrail public keys and create qr codes for each one
52,720
public function generateHTML ( ) { if ( ! $ this -> blocktrailPubKeyQRs ) { $ this -> processBlocktrailPubKeys ( ) ; } $ pubKeysHtml = "" ; foreach ( $ this -> blocktrailPubKeyQRs as $ pubKey ) { $ pubKeysHtml .= "<img src='{$pubKey['qr']}' />" ; } $ totalPubKeys = count ( $ this -> blocktrailPubKeyQRs ) ; $ backupInfo = $ this -> prepareBackupInfo ( ) ; $ extraInfo = $ this -> prepareExtraInfo ( ) ; $ passwordEncryptedSecret = null ; if ( isset ( $ this -> backupInfo [ 'encrypted_secret' ] ) ) { $ passwordEncryptedSecret = $ this -> backupInfo [ 'encrypted_secret' ] ; } $ html = self :: renderTemplate ( __DIR__ . "/../resources/templates/recovery_sheet.html.php" , [ 'identifier' => $ this -> identifier , 'totalPubKeys' => $ totalPubKeys , 'pubKeysHtml' => $ pubKeysHtml , 'backupInfo' => $ backupInfo , 'extraInfo' => $ extraInfo , 'passwordEncryptedSecret' => $ passwordEncryptedSecret , 'options' => $ this -> options , ] ) ; return $ html ; }
generate html document of backup details
52,721
public function generatePDF ( ) { $ dompdf = new \ DOMPDF ( ) ; $ html = $ this -> generateHTML ( ) ; $ dompdf -> load_html ( $ html ) ; $ dompdf -> render ( ) ; $ pdfStream = $ dompdf -> output ( ) ; return $ pdfStream ; }
generate PDF document of backup details
52,722
public function addOutput ( $ output ) { $ output = $ this -> outputNormalizer -> normalize ( [ $ output ] ) [ 0 ] ; $ this -> outputs [ ] = $ output ; return $ this ; }
add a raw output normally addRecipient or addOpReturn should be used
52,723
public function addOpReturn ( $ data , $ allowNonStandard = false ) { if ( ! $ allowNonStandard && strlen ( $ data ) / 2 > 79 ) { throw new BlocktrailSDKException ( "OP_RETURN data should be <= 79 bytes to remain standard!" ) ; } $ script = ScriptFactory :: create ( ) -> op ( 'OP_RETURN' ) -> push ( new Buffer ( $ data ) ) -> getScript ( ) ; $ this -> addOutput ( [ 'scriptPubKey' => $ script , 'value' => 0 ] ) ; return $ this ; }
add OP_RETURN output
52,724
protected function setBitcoinLibMagicBytes ( $ network , $ testnet , $ regtest ) { if ( $ network === "bitcoin" ) { if ( $ regtest ) { $ useNetwork = NetworkFactory :: bitcoinRegtest ( ) ; } else if ( $ testnet ) { $ useNetwork = NetworkFactory :: bitcoinTestnet ( ) ; } else { $ useNetwork = NetworkFactory :: bitcoin ( ) ; } } else if ( $ network === "bitcoincash" ) { if ( $ regtest ) { $ useNetwork = new BitcoinCashRegtest ( ) ; } else if ( $ testnet ) { $ useNetwork = new BitcoinCashTestnet ( ) ; } else { $ useNetwork = new BitcoinCash ( ) ; } } Bitcoin :: setNetwork ( $ useNetwork ) ; }
set BitcoinLib to the correct magic - byte defaults for the selected network
52,725
public function setVerboseErrors ( $ verboseErrors = true ) { $ this -> blocktrailClient -> setVerboseErrors ( $ verboseErrors ) ; $ this -> dataClient -> setVerboseErrors ( $ verboseErrors ) ; }
enable verbose errors
52,726
public function address ( $ address ) { $ response = $ this -> dataClient -> get ( $ this -> converter -> getUrlForAddress ( $ address ) ) ; return $ this -> converter -> convertAddress ( $ response -> body ( ) ) ; }
get a single address
52,727
public function verifyAddress ( $ address , $ signature ) { if ( $ this -> verifyMessage ( $ address , $ address , $ signature ) ) { return [ 'result' => true , 'msg' => 'Successfully verified' ] ; } else { return [ 'result' => false ] ; } }
verify ownership of an address
52,728
public function allWebhooks ( $ page = 1 , $ limit = 20 ) { $ queryString = [ 'page' => $ page , 'limit' => $ limit ] ; $ response = $ this -> blocktrailClient -> get ( "webhooks" , $ this -> converter -> paginationParams ( $ queryString ) ) ; return self :: jsonDecode ( $ response -> body ( ) , true ) ; }
get a paginated list of all webhooks associated with the api user
52,729
public function getWebhook ( $ identifier ) { $ response = $ this -> blocktrailClient -> get ( "webhook/" . $ identifier ) ; return self :: jsonDecode ( $ response -> body ( ) , true ) ; }
get an existing webhook by it s identifier
52,730
public function updateWebhook ( $ identifier , $ newUrl = null , $ newIdentifier = null ) { $ putData = [ 'url' => $ newUrl , 'identifier' => $ newIdentifier ] ; $ response = $ this -> blocktrailClient -> put ( "webhook/{$identifier}" , null , $ putData , RestClient :: AUTH_HTTP_SIG ) ; return self :: jsonDecode ( $ response -> body ( ) , true ) ; }
update an existing webhook
52,731
public function subscribeTransaction ( $ identifier , $ transaction , $ confirmations = 6 ) { $ postData = [ 'event_type' => 'transaction' , 'transaction' => $ transaction , 'confirmations' => $ confirmations , ] ; $ response = $ this -> blocktrailClient -> post ( "webhook/{$identifier}/events" , null , $ postData , RestClient :: AUTH_HTTP_SIG ) ; return self :: jsonDecode ( $ response -> body ( ) , true ) ; }
subscribes a webhook to transaction events of one particular transaction
52,732
public function subscribeAddressTransactions ( $ identifier , $ address , $ confirmations = 6 ) { $ postData = [ 'event_type' => 'address-transactions' , 'address' => $ address , 'confirmations' => $ confirmations , ] ; $ response = $ this -> blocktrailClient -> post ( "webhook/{$identifier}/events" , null , $ postData , RestClient :: AUTH_HTTP_SIG ) ; return self :: jsonDecode ( $ response -> body ( ) , true ) ; }
subscribes a webhook to transaction events on a particular address
52,733
public function batchSubscribeAddressTransactions ( $ identifier , $ batchData ) { $ postData = [ ] ; foreach ( $ batchData as $ record ) { $ postData [ ] = [ 'event_type' => 'address-transactions' , 'address' => $ record [ 'address' ] , 'confirmations' => isset ( $ record [ 'confirmations' ] ) ? $ record [ 'confirmations' ] : 6 , ] ; } $ response = $ this -> blocktrailClient -> post ( "webhook/{$identifier}/events/batch" , null , $ postData , RestClient :: AUTH_HTTP_SIG ) ; return self :: jsonDecode ( $ response -> body ( ) , true ) ; }
batch subscribes a webhook to multiple transaction events
52,734
public function subscribeNewBlocks ( $ identifier ) { $ postData = [ 'event_type' => 'block' , ] ; $ response = $ this -> blocktrailClient -> post ( "webhook/{$identifier}/events" , null , $ postData , RestClient :: AUTH_HTTP_SIG ) ; return self :: jsonDecode ( $ response -> body ( ) , true ) ; }
subscribes a webhook to a new block event
52,735
public function upgradeKeyIndex ( $ identifier , $ keyIndex , $ primaryPublicKey ) { $ data = [ 'key_index' => $ keyIndex , 'primary_public_key' => $ primaryPublicKey ] ; $ response = $ this -> blocktrailClient -> post ( "wallet/{$identifier}/upgrade" , null , $ data , RestClient :: AUTH_HTTP_SIG ) ; return self :: jsonDecode ( $ response -> body ( ) , true ) ; }
upgrade wallet to use a new account number the account number specifies which blocktrail cosigning key is used
52,736
public function updateWallet ( $ identifier , $ data ) { $ response = $ this -> blocktrailClient -> post ( "wallet/{$identifier}" , null , $ data , RestClient :: AUTH_HTTP_SIG ) ; return self :: jsonDecode ( $ response -> body ( ) , true ) ; }
update the wallet data on the server
52,737
public function deleteWallet ( $ identifier , $ checksumAddress , $ signature , $ force = false ) { $ response = $ this -> blocktrailClient -> delete ( "wallet/{$identifier}" , [ 'force' => $ force ] , [ 'checksum' => $ checksumAddress , 'signature' => $ signature ] , RestClient :: AUTH_HTTP_SIG , 360 ) ; return self :: jsonDecode ( $ response -> body ( ) , true ) ; }
delete a wallet from the server the checksum address and a signature to verify you ownership of the key of that checksum address is required to be able to delete a wallet
52,738
protected function newV1BackupSeed ( ) { list ( $ backupMnemonic , $ backupSeed , $ backupPrivateKey ) = $ this -> generateNewSeed ( "" ) ; return [ $ backupMnemonic , $ backupSeed , $ backupPrivateKey ] ; }
create new backup key ; 1 ) a BIP39 mnemonic 2 ) a seed from that mnemonic with a blank password 3 ) a private key from that seed
52,739
protected function newV1PrimarySeed ( $ passphrase ) { list ( $ primaryMnemonic , $ primarySeed , $ primaryPrivateKey ) = $ this -> generateNewSeed ( $ passphrase ) ; return [ $ primaryMnemonic , $ primarySeed , $ primaryPrivateKey ] ; }
create new primary key ; 1 ) a BIP39 mnemonic 2 ) a seed from that mnemonic with the password 3 ) a private key from that seed
52,740
protected function generateNewSeed ( $ passphrase = "" , $ forceEntropy = null ) { do { $ mnemonic = $ this -> generateNewMnemonic ( $ forceEntropy ) ; $ seed = ( new Bip39SeedGenerator ) -> getSeed ( $ mnemonic , $ passphrase ) ; $ key = null ; try { $ key = HierarchicalKeyFactory :: fromEntropy ( $ seed ) ; } catch ( \ Exception $ e ) { } } while ( ! $ key ) ; return [ $ mnemonic , $ seed , $ key ] ; }
create a new key ; 1 ) a BIP39 mnemonic 2 ) a seed from that mnemonic with the password 3 ) a private key from that seed
52,741
public function getWalletBalance ( $ identifier ) { $ response = $ this -> blocktrailClient -> get ( "wallet/{$identifier}/balance" , null , RestClient :: AUTH_HTTP_SIG ) ; return self :: jsonDecode ( $ response -> body ( ) , true ) ; }
get the balance for the wallet
52,742
public function coinSelection ( $ identifier , $ outputs , $ lockUTXO = false , $ allowZeroConf = false , $ feeStrategy = Wallet :: FEE_STRATEGY_OPTIMAL , $ forceFee = null ) { $ args = [ 'lock' => ( int ) ! ! $ lockUTXO , 'zeroconf' => ( int ) ! ! $ allowZeroConf , 'fee_strategy' => $ feeStrategy , ] ; if ( $ forceFee !== null ) { $ args [ 'forcefee' ] = ( int ) $ forceFee ; } $ response = $ this -> blocktrailClient -> post ( "wallet/{$identifier}/coin-selection" , $ args , $ outputs , RestClient :: AUTH_HTTP_SIG ) ; \ var_export ( self :: jsonDecode ( $ response -> body ( ) , true ) ) ; return self :: jsonDecode ( $ response -> body ( ) , true ) ; }
use the API to get the best inputs to use based on the outputs
52,743
public function setupWalletWebhook ( $ identifier , $ webhookIdentifier , $ url ) { $ response = $ this -> blocktrailClient -> post ( "wallet/{$identifier}/webhook" , null , [ 'url' => $ url , 'identifier' => $ webhookIdentifier ] , RestClient :: AUTH_HTTP_SIG ) ; return self :: jsonDecode ( $ response -> body ( ) , true ) ; }
setup webhook for wallet
52,744
public function deleteWalletWebhook ( $ identifier , $ webhookIdentifier ) { $ response = $ this -> blocktrailClient -> delete ( "wallet/{$identifier}/webhook/{$webhookIdentifier}" , null , null , RestClient :: AUTH_HTTP_SIG ) ; return self :: jsonDecode ( $ response -> body ( ) , true ) ; }
delete webhook for wallet
52,745
public function allWallets ( $ page = 1 , $ limit = 20 ) { $ queryString = [ 'page' => $ page , 'limit' => $ limit ] ; $ response = $ this -> blocktrailClient -> get ( "wallets" , $ this -> converter -> paginationParams ( $ queryString ) , RestClient :: AUTH_HTTP_SIG ) ; return self :: jsonDecode ( $ response -> body ( ) , true ) ; }
get a paginated list of all wallets associated with the api user
52,746
public function sendRawTransaction ( $ txHex ) { $ response = $ this -> blocktrailClient -> post ( "send-raw-tx" , null , [ 'hex' => $ txHex ] , RestClient :: AUTH_HTTP_SIG ) ; return self :: jsonDecode ( $ response -> body ( ) , true ) ; }
send raw transaction
52,747
public function faucetWithdrawal ( $ address , $ amount = 10000 ) { $ response = $ this -> blocktrailClient -> post ( "faucet/withdrawl" , null , [ 'address' => $ address , 'amount' => $ amount , ] , RestClient :: AUTH_HTTP_SIG ) ; return self :: jsonDecode ( $ response -> body ( ) , true ) ; }
testnet only ; - )
52,748
public function verifyMessage ( $ message , $ address , $ signature ) { $ adapter = Bitcoin :: getEcAdapter ( ) ; $ addr = \ BitWasp \ Bitcoin \ Address \ AddressFactory :: fromString ( $ address ) ; if ( ! $ addr instanceof PayToPubKeyHashAddress ) { throw new \ InvalidArgumentException ( 'Can only verify a message with a pay-to-pubkey-hash address' ) ; } $ csSerializer = EcSerializer :: getSerializer ( CompactSignatureSerializerInterface :: class , $ adapter ) ; $ signedMessage = new SignedMessage ( $ message , $ csSerializer -> parse ( new Buffer ( base64_decode ( $ signature ) ) ) ) ; $ signer = new MessageSigner ( $ adapter ) ; return $ signer -> verify ( $ signedMessage , $ addr ) ; }
verify a message signed bitcoin - core style
52,749
public function getLegacyBitcoinCashAddress ( $ input ) { if ( $ this -> network === "bitcoincash" ) { $ address = $ this -> makeAddressReader ( [ "use_cashaddress" => true ] ) -> fromString ( $ input ) ; if ( $ address instanceof CashAddress ) { $ address = $ address -> getLegacyAddress ( ) ; } return $ address -> getAddress ( ) ; } throw new BlocktrailSDKException ( "Only request a legacy address when using bitcoin cash" ) ; }
Take a base58 or cashaddress and return only the cash address . This function only works on bitcoin cash .
52,750
public static function jsonDecode ( $ json , $ assoc = false ) { if ( ! $ json ) { throw new \ Exception ( "Can't json_decode empty string [{$json}]" ) ; } $ data = json_decode ( $ json , $ assoc ) ; if ( $ data === null ) { throw new \ Exception ( "Failed to json_decode [{$json}]" ) ; } return $ data ; }
json_decode helper that throws exceptions when it fails to decode
52,751
public static function sortMultisigKeys ( array $ pubKeys ) { $ result = array_values ( $ pubKeys ) ; usort ( $ result , function ( PublicKeyInterface $ a , PublicKeyInterface $ b ) { $ av = $ a -> getHex ( ) ; $ bv = $ b -> getHex ( ) ; return $ av == $ bv ? 0 : $ av > $ bv ? 1 : - 1 ; } ) ; return $ result ; }
sort public keys for multisig script
52,752
public static function getWebhookPayload ( $ returnObject = false ) { $ data = file_get_contents ( "php://input" ) ; if ( $ data ) { return self :: jsonDecode ( $ data , ! $ returnObject ) ; } else { return null ; } }
read and decode the json payload from a webhook s POST request .
52,753
public function upgradeKeyIndex ( $ keyIndex ) { if ( $ this -> locked ) { throw new \ Exception ( "Wallet needs to be unlocked to upgrade key index" ) ; } $ walletPath = WalletPath :: create ( $ keyIndex ) ; $ primaryPublicKey = $ this -> primaryPrivateKey -> buildKey ( ( string ) $ walletPath -> keyIndexPath ( ) -> publicPath ( ) ) ; $ result = $ this -> sdk -> upgradeKeyIndex ( $ this -> identifier , $ keyIndex , $ primaryPublicKey -> tuple ( ) ) ; $ this -> primaryPublicKeys [ $ keyIndex ] = $ primaryPublicKey ; $ this -> keyIndex = $ keyIndex ; foreach ( $ result [ 'blocktrail_public_keys' ] as $ keyIndex => $ pubKey ) { if ( ! isset ( $ this -> blocktrailPublicKeys [ $ keyIndex ] ) ) { $ path = $ pubKey [ 1 ] ; $ pubKey = $ pubKey [ 0 ] ; $ this -> blocktrailPublicKeys [ $ keyIndex ] = BIP32Key :: create ( HierarchicalKeyFactory :: fromExtended ( $ pubKey ) , $ path ) ; } } return true ; }
upgrade wallet to different blocktrail cosign key
52,754
public function getAddressByPath ( $ path ) { $ path = ( string ) BIP32Path :: path ( $ path ) -> privatePath ( ) ; if ( ! isset ( $ this -> derivations [ $ path ] ) ) { list ( $ address , ) = $ this -> getRedeemScriptByPath ( $ path ) ; $ this -> derivations [ $ path ] = $ address ; $ this -> derivationsByAddress [ $ address ] = $ path ; } return $ this -> derivations [ $ path ] ; }
get address for the specified path
52,755
public function getRedeemScriptByPath ( $ path ) { $ walletScript = $ this -> getWalletScriptByPath ( $ path ) ; $ redeemScript = $ walletScript -> isP2SH ( ) ? $ walletScript -> getRedeemScript ( ) : null ; $ witnessScript = $ walletScript -> isP2WSH ( ) ? $ walletScript -> getWitnessScript ( ) : null ; return [ $ walletScript -> getAddress ( ) -> getAddress ( ) , $ redeemScript , $ witnessScript ] ; }
get address and redeemScript for specified path
52,756
public function getNewAddressPair ( $ chainIndex = null ) { $ path = $ this -> getNewDerivation ( $ chainIndex ) ; $ address = $ this -> getAddressByPath ( $ path ) ; return [ $ path , $ address ] ; }
generate a new derived key and return the new path and address for it
52,757
public function pay ( array $ outputs , $ changeAddress = null , $ allowZeroConf = false , $ randomizeChangeIdx = true , $ feeStrategy = self :: FEE_STRATEGY_OPTIMAL , $ forceFee = null , $ apiCheckFee = true ) { if ( $ this -> locked ) { throw new \ Exception ( "Wallet needs to be unlocked to pay" ) ; } if ( $ forceFee && $ feeStrategy !== self :: FEE_STRATEGY_FORCE_FEE ) { throw new \ InvalidArgumentException ( "feeStrategy should be set to force_fee to set a forced fee" ) ; } $ outputs = ( new OutputsNormalizer ( $ this -> getAddressReader ( ) ) ) -> normalize ( $ outputs ) ; $ txBuilder = new TransactionBuilder ( $ this -> addressReader ) ; $ txBuilder -> randomizeChangeOutput ( $ randomizeChangeIdx ) ; $ txBuilder -> setFeeStrategy ( $ feeStrategy ) ; $ txBuilder -> setChangeAddress ( $ changeAddress ) ; foreach ( $ outputs as $ output ) { $ txBuilder -> addOutput ( $ output ) ; } $ this -> coinSelectionForTxBuilder ( $ txBuilder , true , $ allowZeroConf , $ forceFee ) ; if ( $ forceFee !== null ) { $ apiCheckFee = true ; } return $ this -> sendTx ( $ txBuilder , $ apiCheckFee ) ; }
create sign and send a transaction
52,758
public function getMaxSpendable ( $ allowZeroConf = false , $ feeStrategy = self :: FEE_STRATEGY_OPTIMAL , $ forceFee = null , $ outputCnt = 1 ) { return $ this -> sdk -> walletMaxSpendable ( $ this -> identifier , $ allowZeroConf , $ feeStrategy , $ forceFee , $ outputCnt ) ; }
determine max spendable from wallet after fees
52,759
public static function normalizeOutputsStruct ( array $ outputs ) { $ result = [ ] ; foreach ( $ outputs as $ k => $ v ) { if ( is_numeric ( $ k ) ) { if ( ! is_array ( $ v ) ) { throw new \ InvalidArgumentException ( "outputs should be [address => value, ] or [[address, value], ] or [['address' => address, 'value' => value], ]" ) ; } if ( isset ( $ v [ 'address' ] ) && isset ( $ v [ 'value' ] ) ) { $ address = $ v [ 'address' ] ; $ value = $ v [ 'value' ] ; } elseif ( count ( $ v ) == 2 && isset ( $ v [ 0 ] ) && isset ( $ v [ 1 ] ) ) { $ address = $ v [ 0 ] ; $ value = $ v [ 1 ] ; } else { throw new \ InvalidArgumentException ( "outputs should be [address => value, ] or [[address, value], ] or [['address' => address, 'value' => value], ]" ) ; } } else { $ address = $ k ; $ value = $ v ; } $ result [ ] = [ 'address' => $ address , 'value' => $ value ] ; } return $ result ; }
parse outputs into normalized struct
52,760
public function sendTx ( TransactionBuilder $ txBuilder , $ apiCheckFee = true ) { list ( $ tx , $ signInfo ) = $ this -> buildTx ( $ txBuilder ) ; return $ this -> _sendTx ( $ tx , $ signInfo , $ apiCheckFee ) ; }
create sign and send transction based on TransactionBuilder
52,761
public function _sendTx ( Transaction $ tx , array $ signInfo , $ apiCheckFee = true ) { if ( $ this -> locked ) { throw new \ Exception ( "Wallet needs to be unlocked to pay" ) ; } assert ( Util :: all ( function ( $ signInfo ) { return $ signInfo instanceof SignInfo ; } , $ signInfo ) , '$signInfo should be SignInfo[]' ) ; $ signed = $ this -> signTransaction ( $ tx , $ signInfo ) ; $ txs = [ 'signed_transaction' => $ signed -> getHex ( ) , 'base_transaction' => $ signed -> getBaseSerialization ( ) -> getHex ( ) , ] ; return $ this -> sendTransaction ( $ txs , array_map ( function ( SignInfo $ r ) { return ( string ) $ r -> path ; } , $ signInfo ) , $ apiCheckFee ) ; }
!! INTERNAL METHOD public for testing purposes !! create sign and send transction based on inputs and outputs
52,762
public static function estimateSizeUTXOs ( $ utxoCnt ) { $ txinSize = 0 ; for ( $ i = 0 ; $ i < $ utxoCnt ; $ i ++ ) { $ multisig = "2of3" ; if ( $ multisig ) { $ sigCnt = 2 ; $ msig = explode ( "of" , $ multisig ) ; if ( count ( $ msig ) == 2 && is_numeric ( $ msig [ 0 ] ) ) { $ sigCnt = $ msig [ 0 ] ; } $ txinSize += array_sum ( [ 32 , 4 , 3 , ( ( 1 + 72 ) * $ sigCnt ) , ( 2 + 105 ) + 1 , 4 , ] ) ; } else { $ txinSize += array_sum ( [ 32 , 4 , 73 , 34 , 4 , ] ) ; } } return $ txinSize ; }
only supports estimating size for 2of3 multsig UTXOs
52,763
protected function determineFee ( $ utxos , $ outputs , $ feeStrategy , $ highPriorityFeePerKB , $ optimalFeePerKB , $ lowPriorityFeePerKB ) { $ size = SizeEstimation :: estimateVsize ( $ utxos , $ outputs ) ; switch ( $ feeStrategy ) { case self :: FEE_STRATEGY_BASE_FEE : return self :: baseFeeForSize ( $ size ) ; case self :: FEE_STRATEGY_HIGH_PRIORITY : return ( int ) round ( ( $ size / 1000 ) * $ highPriorityFeePerKB ) ; case self :: FEE_STRATEGY_OPTIMAL : return ( int ) round ( ( $ size / 1000 ) * $ optimalFeePerKB ) ; case self :: FEE_STRATEGY_LOW_PRIORITY : return ( int ) round ( ( $ size / 1000 ) * $ lowPriorityFeePerKB ) ; case self :: FEE_STRATEGY_FORCE_FEE : throw new BlocktrailSDKException ( "Can't determine when for force_fee" ) ; default : throw new BlocktrailSDKException ( "Unknown feeStrategy [{$feeStrategy}]" ) ; } }
determine how much fee is required based on the inputs and outputs this is an estimation not a proper 100% correct calculation
52,764
protected function determineChange ( $ utxos , $ outputs , $ fee ) { $ inputsTotal = array_sum ( array_map ( function ( UTXO $ utxo ) { return $ utxo -> value ; } , $ utxos ) ) ; $ outputsTotal = array_sum ( array_column ( $ outputs , 'value' ) ) ; return $ inputsTotal - $ outputsTotal - $ fee ; }
determine how much change is left over based on the inputs and outputs and the fee
52,765
public function deleteWallet ( $ force = false ) { if ( $ this -> locked ) { throw new \ Exception ( "Wallet needs to be unlocked to delete wallet" ) ; } list ( $ checksumAddress , $ signature ) = $ this -> createChecksumVerificationSignature ( ) ; return $ this -> sdk -> deleteWallet ( $ this -> identifier , $ checksumAddress , $ signature , $ force ) [ 'deleted' ] ; }
delete the wallet
52,766
protected function createChecksumVerificationSignature ( ) { $ privKey = $ this -> primaryPrivateKey -> key ( ) ; $ pubKey = $ this -> primaryPrivateKey -> publicKey ( ) ; $ address = $ pubKey -> getAddress ( ) -> getAddress ( ) ; $ signer = new MessageSigner ( Bitcoin :: getEcAdapter ( ) ) ; $ signed = $ signer -> sign ( $ address , $ privKey -> getPrivateKey ( ) ) ; return [ $ address , base64_encode ( $ signed -> getCompactSignature ( ) -> getBuffer ( ) -> getBinary ( ) ) ] ; }
create checksum to verify ownership of the master primary key
52,767
public function setupWebhook ( $ url , $ identifier = null ) { $ identifier = $ identifier ? : "WALLET-{$this->identifier}" ; return $ this -> sdk -> setupWalletWebhook ( $ this -> identifier , $ identifier , $ url ) ; }
setup a webhook for our wallet
52,768
public function unlockUTXO ( $ txHash , $ txIdx ) { return $ this -> sdk -> unlockWalletUTXO ( $ this -> identifier , $ txHash , $ txIdx ) ; }
unlock a specific unspent output
52,769
public function publicKeyHex ( ) { if ( ! $ this -> path -> isPublicPath ( ) ) { return $ this -> buildKey ( $ this -> path -> publicPath ( ) ) -> publicKey ( ) -> getHex ( ) ; } else { if ( is_null ( $ this -> publicKeyHex ) ) { $ this -> publicKeyHex = $ this -> key -> getPublicKey ( ) -> getHex ( ) ; } return $ this -> publicKeyHex ; } }
get the HEX of the plain public key for the current BIP32 key
52,770
public function buildKey ( $ path ) { $ path = BIP32Path :: path ( $ path ) ; $ originalPath = ( string ) $ path ; if ( ! isset ( $ this -> derivations [ $ originalPath ] ) ) { $ key = $ this -> key ; $ toPublic = $ path [ 0 ] === "M" && $ this -> path [ 0 ] === "m" ; if ( $ toPublic ) { $ path = $ path -> privatePath ( ) ; } assert ( strpos ( strtolower ( ( string ) $ path ) , strtolower ( ( string ) $ this -> path ) ) === 0 ) ; $ path = substr ( ( string ) $ path , strlen ( ( string ) $ this -> path ) ) ; if ( substr ( $ path , 0 , 1 ) == "/" ) { $ path = substr ( $ path , 1 ) ; } if ( strlen ( $ path ) ) { $ key = $ key -> derivePath ( $ path ) ; } if ( $ toPublic ) { $ key = $ key -> toPublic ( ) ; } $ this -> derivations [ $ originalPath ] = BIP32Key :: create ( $ key , $ originalPath ) ; } return $ this -> derivations [ $ originalPath ] ; }
build child key
52,771
protected function getUnspentOutputs ( $ address ) { $ utxos = array ( ) ; try { $ page = 1 ; do { $ results = $ this -> client -> addressUnspentOutputs ( $ address , $ page , $ this -> paginationLimit ) ; $ utxos = array_merge ( $ utxos , $ results [ 'data' ] ) ; $ page ++ ; } while ( count ( $ results [ 'data' ] ) > 0 ) ; } catch ( \ Exception $ e ) { if ( $ this -> retries < $ this -> retryLimit ) { $ this -> retries ++ ; sleep ( $ this -> sleepTime ) ; return $ this -> getUnspentOutputs ( $ address ) ; } else { throw $ e ; } } $ this -> retries = 0 ; $ result = array_map ( function ( $ utxo ) { return array ( 'hash' => $ utxo [ 'hash' ] , 'index' => $ utxo [ 'index' ] , 'value' => $ utxo [ 'value' ] , 'script_hex' => $ utxo [ 'script_hex' ] , ) ; } , $ utxos ) ; return $ result ; }
gets unspent outputs for an address returning and array of outputs with hash index value and script pub hex
52,772
public static function normalizeNetwork ( $ network , $ testnet ) { $ regtest = false ; switch ( strtolower ( $ network ) ) { case 'btc' : case 'bitcoin' : $ network = 'bitcoin' ; break ; case 'tbtc' : case 'bitcoin-testnet' : $ network = 'bitcoin' ; $ testnet = true ; break ; case 'bcc' : case 'bch' : case 'bitcoincash' : $ network = 'bitcoincash' ; break ; case 'tbch' : case 'tbcc' : case 'bitcoincash-testnet' : $ network = 'bitcoincash' ; $ testnet = true ; break ; case 'rbtc' : case 'bitcoin-regtest' : $ network = 'bitcoin' ; $ testnet = true ; $ regtest = true ; break ; case 'rbch' : case 'bitcoincash-regtest' : $ network = 'bitcoincash' ; $ testnet = true ; $ regtest = true ; break ; default : throw new \ Exception ( "Unknown network [{$network}]" ) ; } return [ $ network , $ testnet , $ regtest ] ; }
normalize network string
52,773
public function next ( ) { $ path = $ this -> path ; $ last = array_pop ( $ path ) ; if ( $ hardened = ( strpos ( $ last , "'" ) !== false ) ) { $ last = str_replace ( "'" , "" , $ last ) ; } $ last = ( int ) $ last ; $ last += 1 ; if ( $ hardened ) { $ last .= "'" ; } $ path [ ] = $ last ; return new static ( $ path ) ; }
increase the last level of the path by 1 and return the new path
52,774
public function parent ( ) { $ path = $ this -> path ; array_pop ( $ path ) ; if ( empty ( $ path ) ) { throw new \ RuntimeException ( "Can't get parent of root path" ) ; } return new static ( $ path ) ; }
pop off one level of the path and return the new path
52,775
public function hardened ( ) { $ path = $ this -> path ; $ last = array_pop ( $ path ) ; if ( strpos ( $ last , "'" ) !== false ) { return $ this ; } $ last .= "'" ; $ path [ ] = $ last ; return new static ( $ path ) ; }
harden the last level of the path and return the new path
52,776
public function unhardenedLast ( ) { $ path = $ this -> path ; $ last = array_pop ( $ path ) ; $ last = str_replace ( "'" , "" , $ last ) ; $ path [ ] = $ last ; return new static ( $ path ) ; }
unharden the last level of the path and return the new path
52,777
public function unhardenedPath ( ) { $ path = $ this -> path ; foreach ( $ path as $ i => $ level ) { $ path [ $ i ] = str_replace ( "'" , "" , $ level ) ; } return new static ( $ path ) ; }
unharden all levels of the path and return the new path
52,778
public function isHardened ( ) { $ path = $ this -> path ; $ last = array_pop ( $ path ) ; return strpos ( $ last , "'" ) !== false ; }
check if the last level of the path is hardened
52,779
public function isParentOf ( $ path ) { $ path = BIP32Path :: path ( $ path ) ; return strlen ( ( string ) $ path ) > strlen ( ( string ) $ this ) && strpos ( ( string ) $ path , ( string ) $ this ) === 0 ; }
check if this path is parent path of the provided path
52,780
protected function createAddress ( $ path ) { $ path = BIP32Path :: path ( $ path ) -> publicPath ( ) ; $ multisig = ScriptFactory :: scriptPubKey ( ) -> multisig ( 2 , BlocktrailSDK :: sortMultisigKeys ( [ $ this -> primaryPrivateKey -> buildKey ( $ path ) -> publicKey ( ) , $ this -> backupPrivateKey -> buildKey ( $ path -> unhardenedPath ( ) ) -> publicKey ( ) , $ this -> getBlocktrailPublicKey ( $ path ) -> buildKey ( $ path ) -> publicKey ( ) ] ) , false ) ; if ( $ this -> network !== "bitcoincash" && ( int ) $ path [ 2 ] === 2 ) { $ witnessScript = new WitnessScript ( $ multisig ) ; $ redeemScript = new P2shScript ( $ witnessScript ) ; $ address = $ this -> addressReader -> fromOutputScript ( $ redeemScript -> getOutputScript ( ) ) -> getAddress ( ) ; } else { $ witnessScript = null ; $ redeemScript = new P2shScript ( $ multisig ) ; $ address = $ this -> addressReader -> fromOutputScript ( $ redeemScript -> getOutputScript ( ) ) -> getAddress ( ) ; } return [ $ address , $ redeemScript , $ witnessScript ] ; }
generate multisig address for given path
52,781
protected function createBatchAddresses ( $ start , $ count , $ keyIndex ) { $ addresses = array ( ) ; for ( $ i = 0 ; $ i < $ count ; $ i ++ ) { $ path = ( string ) WalletPath :: create ( $ keyIndex , $ _chain = 0 , $ start + $ i ) -> path ( ) -> publicPath ( ) ; list ( $ address , $ redeem , $ witness ) = $ this -> createAddress ( $ path ) ; $ addresses [ $ address ] = array ( 'redeem' => $ redeem , 'witness' => $ witness , 'path' => $ path ) ; if ( $ this -> debug ) { echo "." ; } } return $ addresses ; }
create a batch of multisig addresses
52,782
protected function getBlocktrailPublicKey ( $ path ) { $ path = BIP32Path :: path ( $ path ) ; $ keyIndex = str_replace ( "'" , "" , $ path [ 1 ] ) ; if ( ! isset ( $ this -> blocktrailPublicKeys [ $ keyIndex ] ) ) { throw new \ Exception ( "No blocktrail publickey for key index [{$keyIndex}]" ) ; } return $ this -> blocktrailPublicKeys [ $ keyIndex ] ; }
gets the blocktrail pub key for the given path from the stored array of pub keys
52,783
public function discoverWalletFunds ( $ increment = 200 ) { $ totalBalance = 0 ; $ totalUTXOs = 0 ; $ totalAddressesGenerated = 0 ; $ addressUTXOs = array ( ) ; foreach ( $ this -> blocktrailPublicKeys as $ keyIndex => $ blocktrailPubKey ) { $ i = 0 ; do { if ( $ this -> debug ) { echo "\ngenerating $increment addresses using blocktrail key index $keyIndex\n" ; } $ addresses = $ this -> createBatchAddresses ( $ i , $ increment , $ keyIndex ) ; $ totalAddressesGenerated += count ( $ addresses ) ; if ( $ this -> debug ) { echo "\nstarting fund discovery for $increment addresses" ; } $ utxos = $ this -> utxoFinder -> getUTXOs ( array_keys ( $ addresses ) ) ; foreach ( $ utxos as $ utxo ) { if ( ! isset ( $ utxo [ 'address' ] , $ utxo [ 'value' ] ) ) { throw new BlocktrailSDKException ( "Missing data" ) ; } $ address = $ utxo [ 'address' ] ; if ( ! isset ( $ addressUTXOs [ $ address ] ) ) { $ addressUTXOs [ $ address ] = [ 'path' => $ addresses [ $ address ] [ 'path' ] , 'redeem' => $ addresses [ $ address ] [ 'redeem' ] , 'witness' => $ addresses [ $ address ] [ 'witness' ] , 'utxos' => [ ] , ] ; } $ addressUTXOs [ $ address ] [ 'utxos' ] [ ] = $ utxo ; $ totalUTXOs ++ ; $ totalBalance += $ utxo [ 'value' ] ; } if ( $ this -> debug ) { echo "\nfound " . count ( $ utxos ) . " unspent outputs" ; } $ i += $ increment ; } while ( count ( $ utxos ) > 0 ) ; } if ( $ this -> debug ) { echo "\nfinished fund discovery: $totalBalance Satoshi (in $totalUTXOs outputs) found when searching $totalAddressesGenerated addresses" ; } $ this -> sweepData = [ 'utxos' => $ addressUTXOs , 'count' => $ totalUTXOs , 'balance' => $ totalBalance , 'addressesSearched' => $ totalAddressesGenerated ] ; return $ this -> sweepData ; }
discover funds in the wallet
52,784
public function sweepWallet ( $ destinationAddress , $ sweepBatchSize = 200 ) { if ( $ this -> debug ) { echo "\nstarting wallet sweeping to address $destinationAddress" ; } if ( ! isset ( $ this -> sweepData ) ) { $ this -> discoverWalletFunds ( $ sweepBatchSize ) ; } if ( $ this -> sweepData [ 'balance' ] === 0 ) { throw new \ Exception ( "No funds found after searching through {$this->sweepData['addressesSearched']} addresses" ) ; } $ transaction = $ this -> createTransaction ( $ destinationAddress ) ; return $ transaction -> getHex ( ) ; }
sweep the wallet of all funds and send to a single address
52,785
protected function signTransaction ( TransactionInterface $ tx , array $ signInfo ) { $ signer = new Signer ( $ tx , Bitcoin :: getEcAdapter ( ) ) ; $ sigHash = SigHash :: ALL ; if ( $ this -> network === "bitcoincash" ) { $ sigHash |= SigHash :: BITCOINCASH ; $ signer -> redeemBitcoinCash ( true ) ; } assert ( Util :: all ( function ( $ signInfo ) { return $ signInfo instanceof SignInfo ; } , $ signInfo ) , '$signInfo should be SignInfo[]' ) ; foreach ( $ signInfo as $ idx => $ info ) { if ( $ info -> mode === SignInfo :: MODE_SIGN ) { $ path = BIP32Path :: path ( $ info -> path ) -> privatePath ( ) ; $ redeemScript = $ info -> redeemScript ; $ output = $ info -> output ; $ key = $ this -> primaryPrivateKey -> buildKey ( $ path ) -> key ( ) -> getPrivateKey ( ) ; $ backupKey = $ this -> backupPrivateKey -> buildKey ( $ path -> unhardenedPath ( ) ) -> key ( ) -> getPrivateKey ( ) ; $ signData = ( new SignData ( ) ) -> p2sh ( $ redeemScript ) ; if ( $ info -> witnessScript ) { $ signData -> p2wsh ( $ info -> witnessScript ) ; } $ input = $ signer -> input ( $ idx , $ output , $ signData ) ; $ input -> sign ( $ key , $ sigHash ) ; $ input -> sign ( $ backupKey , $ sigHash ) ; } } return $ signer -> get ( ) ; }
sign a raw transaction with the private keys that we have
52,786
public function actionUpload ( ) { Yii :: $ app -> response -> format = Response :: FORMAT_JSON ; $ model = new Mediafile ( ) ; $ routes = $ this -> module -> routes ; $ rename = $ this -> module -> rename ; $ tagIds = Yii :: $ app -> request -> post ( 'tagIds' ) ; if ( $ tagIds !== 'undefined' ) { $ model -> setTagIds ( explode ( ',' , $ tagIds ) ) ; } $ model -> saveUploadedFile ( $ routes , $ rename ) ; $ bundle = FilemanagerAsset :: register ( $ this -> view ) ; if ( $ model -> isImage ( ) ) { $ model -> createThumbs ( $ routes , $ this -> module -> thumbs ) ; } $ response [ 'files' ] [ ] = [ 'url' => $ model -> url , 'thumbnailUrl' => $ model -> getDefaultThumbUrl ( $ bundle -> baseUrl ) , 'name' => $ model -> filename , 'type' => $ model -> type , 'size' => $ model -> file -> size , 'deleteUrl' => Url :: to ( [ 'file/delete' , 'id' => $ model -> id ] ) , 'deleteType' => 'POST' , ] ; return $ response ; }
Provides upload file
52,787
public function actionUpdate ( $ id ) { $ model = Mediafile :: findOne ( $ id ) ; $ message = Module :: t ( 'main' , 'Changes not saved.' ) ; if ( $ model -> load ( Yii :: $ app -> request -> post ( ) ) && $ model -> save ( ) ) { $ message = Module :: t ( 'main' , 'Changes saved!' ) ; } Yii :: $ app -> session -> setFlash ( 'mediafileUpdateResult' , $ message ) ; Yii :: $ app -> assetManager -> bundles = false ; return $ this -> renderAjax ( 'info' , [ 'model' => $ model , 'strictThumb' => null , ] ) ; }
Updated mediafile by id
52,788
public function actionDelete ( $ id ) { Yii :: $ app -> response -> format = Response :: FORMAT_JSON ; $ routes = $ this -> module -> routes ; $ model = Mediafile :: findOne ( $ id ) ; if ( $ model -> isImage ( ) ) { $ model -> deleteThumbs ( $ routes ) ; } $ model -> deleteFile ( $ routes ) ; $ model -> delete ( ) ; return [ 'success' => 'true' ] ; }
Delete model with files
52,789
public function actionResize ( ) { $ models = Mediafile :: findByTypes ( Mediafile :: $ imageFileTypes ) ; $ routes = $ this -> module -> routes ; foreach ( $ models as $ model ) { if ( $ model -> isImage ( ) ) { $ model -> deleteThumbs ( $ routes ) ; $ model -> createThumbs ( $ routes , $ this -> module -> thumbs ) ; } } Yii :: $ app -> session -> setFlash ( 'successResize' ) ; $ this -> redirect ( Url :: to ( [ 'default/settings' ] ) ) ; }
Resize all thumbnails
52,790
public function actionInfo ( $ id , $ strictThumb = null ) { $ model = Mediafile :: findOne ( $ id ) ; Yii :: $ app -> assetManager -> bundles = false ; return $ this -> renderAjax ( 'info' , [ 'model' => $ model , 'strictThumb' => $ strictThumb , ] ) ; }
Render model info
52,791
public function saveUploadedFile ( array $ routes , $ rename = false ) { $ year = date ( 'Y' , time ( ) ) ; $ month = date ( 'm' , time ( ) ) ; $ structure = "$routes[baseUrl]/$routes[uploadPath]/$year/$month" ; $ basePath = Yii :: getAlias ( $ routes [ 'basePath' ] ) ; $ absolutePath = "$basePath/$structure" ; if ( ! file_exists ( $ absolutePath ) ) { mkdir ( $ absolutePath , 0777 , true ) ; } $ this -> file = UploadedFile :: getInstance ( $ this , 'file' ) ; $ counter = 0 ; do { if ( $ counter == 0 ) $ filename = Inflector :: slug ( $ this -> file -> baseName ) . '.' . $ this -> file -> extension ; else { if ( $ rename == false ) return false ; $ filename = Inflector :: slug ( $ this -> file -> baseName ) . $ counter . '.' . $ this -> file -> extension ; } $ url = "$structure/$filename" ; $ counter ++ ; } while ( self :: findByUrl ( $ url ) ) ; $ this -> file -> saveAs ( "$absolutePath/$filename" ) ; $ this -> filename = $ filename ; $ this -> type = $ this -> file -> type ; $ this -> size = $ this -> file -> size ; $ this -> url = $ url ; return $ this -> save ( ) ; }
Save just uploaded file
52,792
public function createDefaultThumb ( array $ routes ) { $ originalFile = pathinfo ( $ this -> url ) ; $ dirname = $ originalFile [ 'dirname' ] ; $ filename = $ originalFile [ 'filename' ] ; $ extension = $ originalFile [ 'extension' ] ; Image :: $ driver = [ Image :: DRIVER_GD2 , Image :: DRIVER_GMAGICK , Image :: DRIVER_IMAGICK ] ; $ size = Module :: getDefaultThumbSize ( ) ; $ width = $ size [ 0 ] ; $ height = $ size [ 1 ] ; $ thumbUrl = "$dirname/" . $ this -> getThumbFilename ( $ filename , $ extension , Module :: DEFAULT_THUMB_ALIAS , $ width , $ height ) ; $ basePath = Yii :: getAlias ( $ routes [ 'basePath' ] ) ; Image :: thumbnail ( "$basePath/{$this->url}" , $ width , $ height ) -> save ( "$basePath/$thumbUrl" ) ; }
Create default thumbnail
52,793
public function addOwner ( $ owner_id , $ owner , $ owner_attribute ) { $ mediafiles = new Owners ( ) ; $ mediafiles -> mediafile_id = $ this -> id ; $ mediafiles -> owner = $ owner ; $ mediafiles -> owner_id = $ owner_id ; $ mediafiles -> owner_attribute = $ owner_attribute ; return $ mediafiles -> save ( ) ; }
Add owner to mediafiles table
52,794
public static function removeOwner ( $ owner_id , $ owner , $ owner_attribute ) { $ mediafiles = Owners :: findOne ( [ 'owner_id' => $ owner_id , 'owner' => $ owner , 'owner_attribute' => $ owner_attribute , ] ) ; if ( $ mediafiles ) { return $ mediafiles -> delete ( ) ; } return false ; }
Remove this mediafile owner
52,795
protected function getThumbFilename ( $ original , $ extension , $ alias , $ width , $ height ) { $ module = Module :: getInstance ( ) ; return strtr ( $ module -> thumbFilenameTemplate , [ '{width}' => $ width , '{height}' => $ height , '{alias}' => $ alias , '{original}' => $ original , '{extension}' => $ extension , ] ) ; }
Returns thumbnail name
52,796
public function getThumbImage ( $ alias , $ options = [ ] ) { $ url = $ this -> getThumbUrl ( $ alias ) ; if ( empty ( $ url ) ) { return '' ; } if ( empty ( $ options [ 'alt' ] ) ) { $ options [ 'alt' ] = $ this -> alt ; } return Html :: img ( $ url , $ options ) ; }
Thumbnail image html tag
52,797
public function deleteOwners ( ) { foreach ( $ this -> attributes as $ attr ) { Mediafile :: removeOwner ( $ this -> owner -> primaryKey , $ this -> name , $ attr ) ; } }
Delete owners of mediafile
52,798
public function getServices ( ) { $ services = false ; if ( ! empty ( $ this -> cache ) && Yii :: $ app -> has ( $ this -> cache ) ) { $ cache = Yii :: $ app -> get ( $ this -> cache ) ; $ services = $ cache -> get ( 'EAuth.services' ) ; } if ( false === $ services || ! is_array ( $ services ) ) { $ services = [ ] ; foreach ( $ this -> services as $ service => $ options ) { $ class = $ this -> getIdentity ( $ service ) ; $ services [ $ service ] = ( object ) [ 'id' => $ class -> getServiceName ( ) , 'title' => $ class -> getServiceTitle ( ) , 'type' => $ class -> getServiceType ( ) , 'jsArguments' => $ class -> getJsArguments ( ) , ] ; } if ( isset ( $ cache ) ) { $ cache -> set ( 'EAuth.services' , $ services , $ this -> cacheExpire ) ; } } return $ services ; }
Returns services settings declared in the authorization classes . For perfomance reasons it uses cache to store settings array .
52,799
public function retrieveResponse ( UriInterface $ endpoint , $ requestBody , array $ extraHeaders = [ ] , $ method = 'POST' ) { $ this -> endpoint = $ endpoint ; $ this -> requestBody = $ requestBody ; $ this -> extraHeaders = $ extraHeaders ; $ this -> method = $ method ; if ( $ this -> useStreamsFallback && ! $ this -> allowFollowLocation ( ) ) { return $ this -> streams ( ) ; } return $ this -> curl ( ) ; }
Any implementing HTTP providers should send a request to the provided endpoint with the parameters . They should return in string form the response body and throw an exception on error .